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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
29c8f958e06471849d08e589231426cf53e10c9e | 1,328 | c | C | src/operators/ai.onnx/Pad/11/free_operator__ai_onnx__pad__11.c | ChenHuaYou/cONNXr | aa80322ec1f53d87644ba15d5c5663e726824c95 | [
"MIT"
] | null | null | null | src/operators/ai.onnx/Pad/11/free_operator__ai_onnx__pad__11.c | ChenHuaYou/cONNXr | aa80322ec1f53d87644ba15d5c5663e726824c95 | [
"MIT"
] | null | null | null | src/operators/ai.onnx/Pad/11/free_operator__ai_onnx__pad__11.c | ChenHuaYou/cONNXr | aa80322ec1f53d87644ba15d5c5663e726824c95 | [
"MIT"
] | null | null | null | //this file was generated by ../../../../../../scripts/onnx_generator/OperatorTemplate.py
#include "operator__ai_onnx__pad__11.h"
#include "tracing.h"
#include "utils.h"
void
free_operator__ai_onnx__pad__11(
Onnx__NodeProto *ctx
)
{
TRACE_ENTRY(1);
TRACE_NODE(2, true, ctx->onnx_node);
/* UNCOMMENT AS NEEDED */
//Onnx__TensorProto *i_data = searchInputByIndex(ctx, 0);
//Onnx__TensorProto *i_pads = searchInputByIndex(ctx, 1);
//Onnx__TensorProto *i_constant_value = searchInputByIndex(ctx, 2);
// TRACE_TENSOR(2, true, i_data);
// TRACE_TENSOR(2, true, i_pads);
// TRACE_TENSOR(2, constant_value, i_constant_value);
// Onnx__AttributeProto *a_mode = searchAttributeNyName(ctx->onnx_node->n_attribute,ctx->onnx_node->attribute,"mode");
// TRACE_ATTRIBUTE(2, a_mode, a_mode);
//Onnx__TensorProto *o_output = searchOutputByIndex(ctx, 0);
// TRACE_TENSOR(2, true, o_output);
/* FREE CONTEXT HERE IF NEEDED */
// context_operator__ai_onnx__pad__11 *op_ctx = ctx->executer_context;
// TRACE_VAR(2, true, op_ctx->mode, "\"%s\"");
// free(op_ctx->mode);
// free(op_ctx);
/* FREE OUTPUT DATA_TYPE AND SHAPE HERE */
/* DO NOT FREE THE TENSOR ITSELF */
// freeTensorData(o_output);
// free(o_output->dims);
TRACE_EXIT(1);
} | 26.039216 | 122 | 0.675452 | [
"shape"
] |
29cd8bede7f2cd368b14c56ccd24eeb6a3076887 | 3,605 | h | C | Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Document/AtomToolsDocumentRequestBus.h | Perpixel/o3de | b1df4c90d54839c44a6236d6fd3853e7e2af6404 | [
"Apache-2.0",
"MIT"
] | 1 | 2022-02-24T08:49:30.000Z | 2022-02-24T08:49:30.000Z | Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Document/AtomToolsDocumentRequestBus.h | Perpixel/o3de | b1df4c90d54839c44a6236d6fd3853e7e2af6404 | [
"Apache-2.0",
"MIT"
] | null | null | null | Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Document/AtomToolsDocumentRequestBus.h | Perpixel/o3de | b1df4c90d54839c44a6236d6fd3853e7e2af6404 | [
"Apache-2.0",
"MIT"
] | null | null | null | /*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#pragma once
#include <AzCore/std/any.h>
#include <AtomToolsFramework/DynamicProperty/DynamicProperty.h>
#include <AtomToolsFramework/DynamicProperty/DynamicPropertyGroup.h>
#include <AzCore/EBus/EBus.h>
namespace AtomToolsFramework
{
//! Structure used as an opaque description of objects reflected inside of a document.
//! An example use would be semi automatic handling of serialization or reflection to a property editor.
struct DocumentObjectInfo
{
bool m_visible = true;
AZStd::string m_name;
AZStd::string m_displayName;
AZStd::string m_description;
AZ::Uuid m_objectType = AZ::Uuid::CreateNull();
void* m_objectPtr = {};
};
//! This bus provides the most basic interface for implementing a document that works with the document system.
//! Any extensions or application specific functionality should be added using a domain specific buses.
class AtomToolsDocumentRequests
: public AZ::EBusTraits
{
public:
static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple;
static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::ById;
typedef AZ::Uuid BusIdType;
//! Get absolute path of document
virtual AZStd::string_view GetAbsolutePath() const = 0;
//! Returns a container describing all reflected objects contained in a document
virtual AZStd::vector<DocumentObjectInfo> GetObjectInfo() const = 0;
//! Load document and related data
//! @param loadPath absolute path of document to load
virtual bool Open(AZStd::string_view loadPath) = 0;
//! Reopen document preserving edits
virtual bool Reopen() = 0;
//! Save document to file
virtual bool Save() = 0;
//! Save document copy
//! @param savePath absolute path where document is saved
virtual bool SaveAsCopy(AZStd::string_view savePath) = 0;
//! Save document to a new source file derived from of the open document
//! @param savePath absolute path where document is saved
virtual bool SaveAsChild(AZStd::string_view savePath) = 0;
//! Close document and reset its data
virtual bool Close() = 0;
//! Document is loaded
virtual bool IsOpen() const = 0;
//! Document has changes pending
virtual bool IsModified() const = 0;
//! Can the document be saved
virtual bool IsSavable() const = 0;
//! Returns true if there are reversible modifications to the document
virtual bool CanUndo() const = 0;
//! Returns true if there are changes that were reversed and can be re-applied to the document
virtual bool CanRedo() const = 0;
//! Restores the previous state of the document
virtual bool Undo() = 0;
//! Restores the next state of the document
virtual bool Redo() = 0;
//! Signal that editing is about to begin, like beginning to drag a slider control
virtual bool BeginEdit() = 0;
//! Signal that editing has completed, like after releasing the mouse button after continuously dragging a slider control
virtual bool EndEdit() = 0;
};
using AtomToolsDocumentRequestBus = AZ::EBus<AtomToolsDocumentRequests>;
} // namespace AtomToolsFramework
| 37.552083 | 129 | 0.67767 | [
"vector",
"3d"
] |
29d02faef703fd59a640c5c69d5249b0dee87d0f | 10,876 | c | C | Testing/Marlin-2.0.x/Marlin/src/HAL/DUE/usb/usb_task.c | qisback/Geeetech-i3-B-pro-configs | a2c309923c4e68103addda677fda190238a1abe0 | [
"CC-BY-4.0"
] | 5 | 2020-05-17T21:16:41.000Z | 2021-06-11T04:46:31.000Z | Testing/Marlin-2.0.x/Marlin/src/HAL/DUE/usb/usb_task.c | qisback/Geeetech-i3-B-pro-configs | a2c309923c4e68103addda677fda190238a1abe0 | [
"CC-BY-4.0"
] | 1 | 2020-09-27T14:53:34.000Z | 2020-09-27T14:53:34.000Z | src/HAL/HAL_DUE/usb/usb_task.c | Sundancer78/Marlin-2.0.4_SKR_14_turbo_ender3 | d9dbef52e6fb4e110908a6d09d0af00fc0ac9b20 | [
"MIT"
] | 2 | 2020-10-05T15:08:13.000Z | 2020-10-20T06:21:59.000Z | /**
* \file
*
* \brief Main functions for USB composite example
*
* Copyright (c) 2011-2015 Atmel Corporation. All rights reserved.
*
* \asf_license_start
*
* \page License
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name of Atmel may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* 4. This software may only be redistributed and used in connection with an
* Atmel microcontroller product.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
*
* \asf_license_stop
*
*/
// Support and FAQ: visit <a href="http://www.atmel.com/design-support/">Atmel Support</a>
#ifdef ARDUINO_ARCH_SAM
#include <Arduino.h>
#include <Reset.h>
#include "conf_usb.h"
#include "udc.h"
#if ENABLED(SDSUPPORT)
static volatile bool main_b_msc_enable = false;
#endif
static volatile bool main_b_cdc_enable = false;
static volatile bool main_b_dtr_active = false;
void usb_task_idle(void) {
#if ENABLED(SDSUPPORT)
// Attend SD card access from the USB MSD -- Prioritize access to improve speed
int delay = 2;
while (main_b_msc_enable && --delay > 0) {
if (udi_msc_process_trans()) delay = 10000;
// Reset the watchdog, just to be sure
REG_WDT_CR = WDT_CR_WDRSTT | WDT_CR_KEY(0xA5);
}
#endif
}
#if ENABLED(SDSUPPORT)
bool usb_task_msc_enable(void) { return ((main_b_msc_enable = true)); }
void usb_task_msc_disable(void) { main_b_msc_enable = false; }
bool usb_task_msc_isenabled(void) { return main_b_msc_enable; }
#endif
bool usb_task_cdc_enable(const uint8_t port) { UNUSED(port); return ((main_b_cdc_enable = true)); }
void usb_task_cdc_disable(const uint8_t port) { UNUSED(port); main_b_cdc_enable = false; main_b_dtr_active = false; }
bool usb_task_cdc_isenabled(void) { return main_b_cdc_enable; }
/*! \brief Called by CDC interface
* Callback running when CDC device have received data
*/
void usb_task_cdc_rx_notify(const uint8_t port) { UNUSED(port); }
/*! \brief Configures communication line
*
* \param cfg line configuration
*/
static uint16_t dwDTERate = 0;
void usb_task_cdc_config(const uint8_t port, usb_cdc_line_coding_t *cfg) {
UNUSED(port);
// Store last DTE rate
dwDTERate = cfg->dwDTERate;
}
void usb_task_cdc_set_dtr(const uint8_t port, const bool b_enable) {
UNUSED(port);
// Keep DTR status
main_b_dtr_active = b_enable;
// Implement Arduino-Compatible kludge to enter programming mode from
// the native port:
// "Auto-reset into the bootloader is triggered when the port, already
// open at 1200 bps, is closed."
if (1200 == dwDTERate) {
// We check DTR state to determine if host port is open (bit 0 of lineState).
if (!b_enable) {
// Set RST pin to go low for 65535 clock cycles on reset
// This helps restarting when firmware flash ends
RSTC->RSTC_MR = 0xA5000F01;
// Schedule delayed reset
initiateReset(250);
}
else
cancelReset();
}
}
bool usb_task_cdc_dtr_active(void) { return main_b_dtr_active; }
/// Microsoft WCID descriptor
typedef struct USB_MicrosoftCompatibleDescriptor_Interface {
uint8_t bFirstInterfaceNumber;
uint8_t reserved1;
uint8_t compatibleID[8];
uint8_t subCompatibleID[8];
uint8_t reserved2[6];
} __attribute__((packed)) USB_MicrosoftCompatibleDescriptor_Interface;
typedef struct USB_MicrosoftCompatibleDescriptor {
uint32_t dwLength;
uint16_t bcdVersion;
uint16_t wIndex;
uint8_t bCount;
uint8_t reserved[7];
USB_MicrosoftCompatibleDescriptor_Interface interfaces[];
} __attribute__((packed)) USB_MicrosoftCompatibleDescriptor;
// 3D Printer compatible descriptor
static USB_MicrosoftCompatibleDescriptor microsoft_compatible_id_descriptor = {
.dwLength = sizeof(USB_MicrosoftCompatibleDescriptor) +
1*sizeof(USB_MicrosoftCompatibleDescriptor_Interface),
.bcdVersion = 0x0100,
.wIndex = 0x0004,
.bCount = 1,
.reserved = {0, 0, 0, 0, 0, 0, 0},
.interfaces = {
{
.bFirstInterfaceNumber = 0,
.reserved1 = 1,
.compatibleID = "3DPRINT",
.subCompatibleID = {0, 0, 0, 0, 0, 0, 0, 0},
.reserved2 = {0, 0, 0, 0, 0, 0},
}
}
};
#define xstr(s) str(s)
#define str(s) #s
#define MS3DPRINT_CONFIG u"MS3DPrintConfig"
#define MS3DPRINT_CONFIG_DATA \
u"Base=SD\0"\
u"Job3DOutputAreaWidth=" xstr(X_BED_SIZE) "000\0"\
u"Job3DOutputAreaDepth=" xstr(Y_BED_SIZE) "000\0"\
u"Job3DOutputAreaHeight=" xstr(Z_MAX_POS) "000\0"\
u"filamentdiameter=1750\0"
typedef struct USB_MicrosoftExtendedPropertiesDescriptor {
uint32_t dwLength;
uint16_t bcdVersion;
uint16_t wIndex;
uint16_t bCount;
uint32_t dwPropertySize;
uint32_t dwPropertyDataType;
uint16_t wPropertyNameLength;
uint16_t PropertyName[sizeof(MS3DPRINT_CONFIG)/sizeof(uint16_t)];
uint32_t dwPropertyDataLength;
uint16_t PropertyData[sizeof(MS3DPRINT_CONFIG_DATA)/sizeof(uint16_t)];
} __attribute__((packed)) USB_MicrosoftExtendedPropertiesDescriptor;
static USB_MicrosoftExtendedPropertiesDescriptor microsoft_extended_properties_descriptor = {
.dwLength = sizeof(USB_MicrosoftExtendedPropertiesDescriptor),
.bcdVersion = 0x0100,
.wIndex = 0x0005,
.bCount = 1,
.dwPropertySize = 4 + 4 + 2 + 4 + sizeof(MS3DPRINT_CONFIG) + sizeof(MS3DPRINT_CONFIG_DATA),
.dwPropertyDataType = 7, // (1=REG_SZ, 4=REG_DWORD, 7=REG_MULTI_SZ)
.wPropertyNameLength = sizeof(MS3DPRINT_CONFIG),
.PropertyName = MS3DPRINT_CONFIG,
.dwPropertyDataLength = sizeof(MS3DPRINT_CONFIG_DATA),
.PropertyData = MS3DPRINT_CONFIG_DATA
};
/**************************************************************************************************
** WCID configuration information
** Hooked into UDC via UDC_GET_EXTRA_STRING #define.
*/
bool usb_task_extra_string(void) {
static uint8_t udi_msft_magic[] = "MSFT100\xEE";
static uint8_t udi_cdc_name[] = "CDC interface";
#if ENABLED(SDSUPPORT)
static uint8_t udi_msc_name[] = "MSC interface";
#endif
struct extra_strings_desc_t {
usb_str_desc_t header;
#if ENABLED(SDSUPPORT)
le16_t string[Max(Max(sizeof(udi_cdc_name) - 1, sizeof(udi_msc_name) - 1), sizeof(udi_msft_magic) - 1)];
#else
le16_t string[Max(sizeof(udi_cdc_name) - 1, sizeof(udi_msft_magic) - 1)];
#endif
};
static UDC_DESC_STORAGE struct extra_strings_desc_t extra_strings_desc = {
.header.bDescriptorType = USB_DT_STRING
};
uint8_t *str;
uint8_t str_lgt = 0;
// Link payload pointer to the string corresponding at request
switch (udd_g_ctrlreq.req.wValue & 0xFF) {
case UDI_CDC_IAD_STRING_ID:
str_lgt = sizeof(udi_cdc_name) - 1;
str = udi_cdc_name;
break;
#if ENABLED(SDSUPPORT)
case UDI_MSC_STRING_ID:
str_lgt = sizeof(udi_msc_name) - 1;
str = udi_msc_name;
break;
#endif
case 0xEE:
str_lgt = sizeof(udi_msft_magic) - 1;
str = udi_msft_magic;
break;
default:
return false;
}
for (uint8_t i = 0; i < str_lgt; i++)
extra_strings_desc.string[i] = cpu_to_le16((le16_t)str[i]);
extra_strings_desc.header.bLength = 2 + str_lgt * 2;
udd_g_ctrlreq.payload_size = extra_strings_desc.header.bLength;
udd_g_ctrlreq.payload = (uint8_t*)&extra_strings_desc;
// if the string is larger than request length, then cut it
if (udd_g_ctrlreq.payload_size > udd_g_ctrlreq.req.wLength) {
udd_g_ctrlreq.payload_size = udd_g_ctrlreq.req.wLength;
}
return true;
}
/**************************************************************************************************
** Handle device requests that the ASF stack doesn't
*/
bool usb_task_other_requests(void) {
uint8_t* ptr = 0;
uint16_t size = 0;
if (Udd_setup_type() == USB_REQ_TYPE_VENDOR) {
//if (udd_g_ctrlreq.req.bRequest == 0x30)
if (1) {
if (udd_g_ctrlreq.req.wIndex == 0x04) {
ptr = (uint8_t*)µsoft_compatible_id_descriptor;
size = (udd_g_ctrlreq.req.wLength);
if (size > microsoft_compatible_id_descriptor.dwLength)
size = microsoft_compatible_id_descriptor.dwLength;
}
else if (udd_g_ctrlreq.req.wIndex == 0x05) {
ptr = (uint8_t*)µsoft_extended_properties_descriptor;
size = (udd_g_ctrlreq.req.wLength);
if (size > microsoft_extended_properties_descriptor.dwLength)
size = microsoft_extended_properties_descriptor.dwLength;
}
else
return false;
}
}
udd_g_ctrlreq.payload_size = size;
if (size == 0) {
udd_g_ctrlreq.callback = 0;
udd_g_ctrlreq.over_under_run = 0;
}
else
udd_g_ctrlreq.payload = ptr;
return true;
}
void usb_task_init(void) {
uint16_t *ptr;
// Disable USB peripheral so we start clean and avoid lockups
otg_disable();
udd_disable();
// Set the USB interrupt to our stack
UDD_SetStack(&USBD_ISR);
// Start USB stack to authorize VBus monitoring
udc_start();
// Patch in filament diameter - Be careful: String is in UNICODE (2bytes per char)
ptr = µsoft_extended_properties_descriptor.PropertyData[0];
while (ptr[0] || ptr[1]) { // Double 0 flags end of resource
// Found the filamentdiameter= unicode string
if (ptr[0] == 'r' && ptr[1] == '=') {
char diam[16];
char *sptr;
// Patch in the filament diameter
sprintf_P(diam, PSTR("%d"), (int)((DEFAULT_NOMINAL_FILAMENT_DIA) * 1000.0));
// And copy it to the proper place, expanding it to unicode
sptr = &diam[0];
ptr += 2;
while (*sptr) *ptr++ = *sptr++;
// Done!
break;
}
// Go to the next character
ptr++;
}
}
#endif // ARDUINO_ARCH_SAM
| 31.80117 | 117 | 0.698051 | [
"3d"
] |
29ddc0dae4c35a93d113307e6d6e7b751a284b77 | 4,602 | h | C | NaoTHSoccer/Source/Representations/Infrastructure/FieldInfo.h | BerlinUnited/NaoTH | 02848ac10c16a5349f1735da8122a64d601a5c75 | [
"ECL-2.0",
"Apache-2.0"
] | 15 | 2015-01-12T10:46:29.000Z | 2022-03-28T05:13:14.000Z | NaoTHSoccer/Source/Representations/Infrastructure/FieldInfo.h | BerlinUnited/NaoTH | 02848ac10c16a5349f1735da8122a64d601a5c75 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2019-01-20T21:07:50.000Z | 2020-01-22T14:00:28.000Z | NaoTHSoccer/Source/Representations/Infrastructure/FieldInfo.h | BerlinUnited/NaoTH | 02848ac10c16a5349f1735da8122a64d601a5c75 | [
"ECL-2.0",
"Apache-2.0"
] | 5 | 2018-02-07T18:18:10.000Z | 2019-10-15T17:01:41.000Z | /**
* @file FieldInfo.h
*
* Declaration of class FieldInfo
*
* @author <a href="mailto:goehring@informatik.hu-berlin.de">Daniel Goehring</a>
* @author <a href="mailto:xu@informatik.hu-berlin.de">Xu, Yuan</a>
*/
#ifndef _FieldInfo_h_
#define _FieldInfo_h_
#include <Tools/Math/Vector2.h>
#include <Tools/Math/Geometry.h>
#include <Tools/DataStructures/ParameterList.h>
#include <Tools/DataStructures/Printable.h>
#include "Tools/LinesTable.h"
class FieldInfo : public ParameterList, public naoth::Printable
{
private:
void calculateValues();
/** */
void createLinesTable();
/** */
void calculateCrossings();
public:
FieldInfo();
void draw(DrawingCanvas2D& canvas) const;
virtual void print(std::ostream& stream) const;
// some tools
inline bool insideCarpet(const Vector2d& p) const {
return carpetRect.inside(p);
}
//////////////// basic values from configuration ////////////////
double ballRadius;
// Rolling resistance / rolling friction coefficient
double ballRRCoefficient;
double ballDeceleration; // mm/s^2
// size of the whole field (including the green area outside the lines)
double xFieldLength;
double yFieldLength;
// size of the field lines
double xLength;
double yLength;
// penalty area
double xPenaltyAreaLength;
double yPenaltyAreaLength;
double centerCircleRadius;
double fieldLinesWidth;
// goal
double goalWidth;
double goalHeight;
double goalDepth;
double goalpostRadius;
// white goal box is treated as lines
bool goalBoxAsLines;
/////////////// pre-calculated values from basic values //////////////
double xPosHalfWayLine;
double xPosOwnGoal;
double xPosOpponentGoal;
double xPosOwnGroundline;
double xPosOpponentGroundline;
double xPosOpponentPenaltyArea;
double xPosOwnPenaltyArea;
double yPosLeftSideline;
double yPosRightSideline;
double yPosLeftPenaltyArea;
double yPosRightPenaltyArea;
double xPenaltyMarkDistance;
double yPosRightGoalpost;
double yPosLeftGoalpost;
//Extra Stuff for the Simulator
double xThrowInLineOwn;
double xThrowInLineOpp;
double yThrowInLineLeft;
double yThrowInLineRight;
Vector2d leftThrowInPointOwn;
Vector2d rightThrowInPointOwn;
Vector2d leftThrowInPointOpp;
Vector2d rightThrowInPointOpp;
//Should be done differently
Math::LineSegment leftLineSegment;
Math::LineSegment rightLineSegment;
Math::LineSegment ownLineSegment;
Math::LineSegment oppLineSegment;
//End extra stuff
Geometry::Rect2d fieldRect;
Geometry::Rect2d carpetRect;
Geometry::Rect2d ownHalfRect;
Geometry::Rect2d oppHalfRect;
Geometry::Rect2d ownGoalRect;
Geometry::Rect2d oppGoalRect;
enum LineCrossingsId
{
// L crossings
opponentCornerLeft,
opponentCornerRight,
ownCornerLeft,
ownCornerRight,
opponentPenaltyCornerLeft,
opponentPenaltyCornerRight,
ownPenaltyCornerLeft,
ownPenaltyCornerRight,
// T crossings
opponentGoalTCrossingLeft,
opponentGoalTCrossingRight,
ownGoalTCrossingLeft,
ownGoalTCrossingRight,
centerTCrossingLeft,
centerTCrossingRight,
// X crossings
crossingCenterCircleLeft,
crossingCenterCircleRight,
numberLineCrossingsId
};
class Crossing
{
public:
Crossing() : id(numberLineCrossingsId) {}
LineCrossingsId id;
//Type type; // TODO: L, T, X
Vector2d position;
};
Crossing crossings[numberLineCrossingsId];
/*
// L crossings
Vector2<double> opponentCornerLeft;
Vector2<double> opponentCornerRight;
Vector2<double> ownCornerLeft;
Vector2<double> ownCornerRight;
Vector2<double> opponentPenaltyCornerLeft;
Vector2<double> opponentPenaltyCornerRight;
Vector2<double> ownPenaltyCornerLeft;
Vector2<double> ownPenaltyCornerRight;
// T crossings
Vector2<double> opponentGoalTCrossingLeft;
Vector2<double> opponentGoalTCrossingRight;
Vector2<double> ownGoalTCrossingLeft;
Vector2<double> ownGoalTCrossingRight;
Vector2<double> centerTCrossingLeft;
Vector2<double> centerTCrossingRight;
// X Crossings
Vector2<double> crossingCenterCircleLeft;
Vector2<double> crossingCenterCircleRight;
*/
// goal post positions
Vector2d opponentGoalPostLeft;
Vector2d opponentGoalPostRight;
Vector2d opponentGoalCenter;
Vector2d ownGoalPostLeft;
Vector2d ownGoalPostRight;
Vector2d ownGoalCenter;
/** */
LinesTable fieldLinesTable;
// Moved from Simulation.cpp
Vector2d oppGoalBackLeft;
Vector2d oppGoalBackRight;
Vector2d ownGoalBackLeft;
Vector2d ownGoalBackRight;
};
#endif //__FieldInfo_h_
| 22.019139 | 79 | 0.747066 | [
"geometry"
] |
29f0fd4203e1318abc1ae68672bafc8ca802fd80 | 23,115 | h | C | wpilibNewCommands/src/main/native/include/frc2/command/MecanumControllerCommand.h | jasondaming/allwpilib | 3ef2dab465a1da7f060f0bcc9663095d9f29b91c | [
"BSD-3-Clause"
] | 707 | 2016-05-11T16:54:13.000Z | 2022-03-30T13:03:15.000Z | wpilibNewCommands/src/main/native/include/frc2/command/MecanumControllerCommand.h | jasondaming/allwpilib | 3ef2dab465a1da7f060f0bcc9663095d9f29b91c | [
"BSD-3-Clause"
] | 2,308 | 2016-05-12T00:17:17.000Z | 2022-03-30T20:08:10.000Z | wpilibNewCommands/src/main/native/include/frc2/command/MecanumControllerCommand.h | jasondaming/allwpilib | 3ef2dab465a1da7f060f0bcc9663095d9f29b91c | [
"BSD-3-Clause"
] | 539 | 2016-05-11T20:33:26.000Z | 2022-03-28T20:20:25.000Z | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include <cmath>
#include <functional>
#include <initializer_list>
#include <memory>
#include <frc/Timer.h>
#include <frc/controller/HolonomicDriveController.h>
#include <frc/controller/PIDController.h>
#include <frc/controller/ProfiledPIDController.h>
#include <frc/controller/SimpleMotorFeedforward.h>
#include <frc/geometry/Pose2d.h>
#include <frc/kinematics/ChassisSpeeds.h>
#include <frc/kinematics/MecanumDriveKinematics.h>
#include <frc/kinematics/MecanumDriveWheelSpeeds.h>
#include <frc/trajectory/Trajectory.h>
#include <units/angle.h>
#include <units/length.h>
#include <units/velocity.h>
#include <units/voltage.h>
#include <wpi/span.h>
#include "CommandBase.h"
#include "CommandHelper.h"
#pragma once
namespace frc2 {
/**
* A command that uses two PID controllers (PIDController) and a profiled PID
* controller (ProfiledPIDController) to follow a trajectory (Trajectory) with a
* mecanum drive.
*
* <p>The command handles trajectory-following,
* Velocity PID calculations, and feedforwards internally. This
* is intended to be a more-or-less "complete solution" that can be used by
* teams without a great deal of controls expertise.
*
* <p>Advanced teams seeking more flexibility (for example, those who wish to
* use the onboard PID functionality of a "smart" motor controller) may use the
* secondary constructor that omits the PID and feedforward functionality,
* returning only the raw wheel speeds from the PID controllers.
*
* <p>The robot angle controller does not follow the angle given by
* the trajectory but rather goes to the angle given in the final state of the
* trajectory.
*/
class MecanumControllerCommand
: public CommandHelper<CommandBase, MecanumControllerCommand> {
public:
/**
* Constructs a new MecanumControllerCommand that when executed will follow
* the provided trajectory. PID control and feedforward are handled
* internally. Outputs are scaled from -12 to 12 as a voltage output to the
* motor.
*
* <p>Note: The controllers will *not* set the outputVolts to zero upon
* completion of the path this is left to the user, since it is not
* appropriate for paths with nonstationary endstates.
*
* @param trajectory The trajectory to follow.
* @param pose A function that supplies the robot pose,
* provided by the odometry class.
* @param feedforward The feedforward to use for the drivetrain.
* @param kinematics The kinematics for the robot drivetrain.
* @param xController The Trajectory Tracker PID controller
* for the robot's x position.
* @param yController The Trajectory Tracker PID controller
* for the robot's y position.
* @param thetaController The Trajectory Tracker PID controller
* for angle for the robot.
* @param desiredRotation The angle that the robot should be facing.
* This is sampled at each time step.
* @param maxWheelVelocity The maximum velocity of a drivetrain wheel.
* @param frontLeftController The front left wheel velocity PID.
* @param rearLeftController The rear left wheel velocity PID.
* @param frontRightController The front right wheel velocity PID.
* @param rearRightController The rear right wheel velocity PID.
* @param currentWheelSpeeds A MecanumDriveWheelSpeeds object containing
* the current wheel speeds.
* @param output The output of the velocity PIDs.
* @param requirements The subsystems to require.
*/
MecanumControllerCommand(
frc::Trajectory trajectory, std::function<frc::Pose2d()> pose,
frc::SimpleMotorFeedforward<units::meters> feedforward,
frc::MecanumDriveKinematics kinematics, frc2::PIDController xController,
frc2::PIDController yController,
frc::ProfiledPIDController<units::radians> thetaController,
std::function<frc::Rotation2d()> desiredRotation,
units::meters_per_second_t maxWheelVelocity,
std::function<frc::MecanumDriveWheelSpeeds()> currentWheelSpeeds,
frc2::PIDController frontLeftController,
frc2::PIDController rearLeftController,
frc2::PIDController frontRightController,
frc2::PIDController rearRightController,
std::function<void(units::volt_t, units::volt_t, units::volt_t,
units::volt_t)>
output,
std::initializer_list<Subsystem*> requirements);
/**
* Constructs a new MecanumControllerCommand that when executed will follow
* the provided trajectory. PID control and feedforward are handled
* internally. Outputs are scaled from -12 to 12 as a voltage output to the
* motor.
*
* <p>Note: The controllers will *not* set the outputVolts to zero upon
* completion of the path this is left to the user, since it is not
* appropriate for paths with nonstationary endstates.
*
* <p>Note 2: The final rotation of the robot will be set to the rotation of
* the final pose in the trajectory. The robot will not follow the rotations
* from the poses at each timestep. If alternate rotation behavior is desired,
* the other constructor with a supplier for rotation should be used.
*
* @param trajectory The trajectory to follow.
* @param pose A function that supplies the robot pose,
* provided by the odometry class.
* @param feedforward The feedforward to use for the drivetrain.
* @param kinematics The kinematics for the robot drivetrain.
* @param xController The Trajectory Tracker PID controller
* for the robot's x position.
* @param yController The Trajectory Tracker PID controller
* for the robot's y position.
* @param thetaController The Trajectory Tracker PID controller
* for angle for the robot.
* @param maxWheelVelocity The maximum velocity of a drivetrain wheel.
* @param frontLeftController The front left wheel velocity PID.
* @param rearLeftController The rear left wheel velocity PID.
* @param frontRightController The front right wheel velocity PID.
* @param rearRightController The rear right wheel velocity PID.
* @param currentWheelSpeeds A MecanumDriveWheelSpeeds object containing
* the current wheel speeds.
* @param output The output of the velocity PIDs.
* @param requirements The subsystems to require.
*/
MecanumControllerCommand(
frc::Trajectory trajectory, std::function<frc::Pose2d()> pose,
frc::SimpleMotorFeedforward<units::meters> feedforward,
frc::MecanumDriveKinematics kinematics, frc2::PIDController xController,
frc2::PIDController yController,
frc::ProfiledPIDController<units::radians> thetaController,
units::meters_per_second_t maxWheelVelocity,
std::function<frc::MecanumDriveWheelSpeeds()> currentWheelSpeeds,
frc2::PIDController frontLeftController,
frc2::PIDController rearLeftController,
frc2::PIDController frontRightController,
frc2::PIDController rearRightController,
std::function<void(units::volt_t, units::volt_t, units::volt_t,
units::volt_t)>
output,
std::initializer_list<Subsystem*> requirements);
/**
* Constructs a new MecanumControllerCommand that when executed will follow
* the provided trajectory. PID control and feedforward are handled
* internally. Outputs are scaled from -12 to 12 as a voltage output to the
* motor.
*
* <p>Note: The controllers will *not* set the outputVolts to zero upon
* completion of the path this is left to the user, since it is not
* appropriate for paths with nonstationary endstates.
*
* @param trajectory The trajectory to follow.
* @param pose A function that supplies the robot pose,
* provided by the odometry class.
* @param feedforward The feedforward to use for the drivetrain.
* @param kinematics The kinematics for the robot drivetrain.
* @param xController The Trajectory Tracker PID controller
* for the robot's x position.
* @param yController The Trajectory Tracker PID controller
* for the robot's y position.
* @param thetaController The Trajectory Tracker PID controller
* for angle for the robot.
* @param desiredRotation The angle that the robot should be facing.
* This is sampled at each time step.
* @param maxWheelVelocity The maximum velocity of a drivetrain wheel.
* @param frontLeftController The front left wheel velocity PID.
* @param rearLeftController The rear left wheel velocity PID.
* @param frontRightController The front right wheel velocity PID.
* @param rearRightController The rear right wheel velocity PID.
* @param currentWheelSpeeds A MecanumDriveWheelSpeeds object containing
* the current wheel speeds.
* @param output The output of the velocity PIDs.
* @param requirements The subsystems to require.
*/
MecanumControllerCommand(
frc::Trajectory trajectory, std::function<frc::Pose2d()> pose,
frc::SimpleMotorFeedforward<units::meters> feedforward,
frc::MecanumDriveKinematics kinematics, frc2::PIDController xController,
frc2::PIDController yController,
frc::ProfiledPIDController<units::radians> thetaController,
std::function<frc::Rotation2d()> desiredRotation,
units::meters_per_second_t maxWheelVelocity,
std::function<frc::MecanumDriveWheelSpeeds()> currentWheelSpeeds,
frc2::PIDController frontLeftController,
frc2::PIDController rearLeftController,
frc2::PIDController frontRightController,
frc2::PIDController rearRightController,
std::function<void(units::volt_t, units::volt_t, units::volt_t,
units::volt_t)>
output,
wpi::span<Subsystem* const> requirements = {});
/**
* Constructs a new MecanumControllerCommand that when executed will follow
* the provided trajectory. PID control and feedforward are handled
* internally. Outputs are scaled from -12 to 12 as a voltage output to the
* motor.
*
* <p>Note: The controllers will *not* set the outputVolts to zero upon
* completion of the path this is left to the user, since it is not
* appropriate for paths with nonstationary endstates.
*
* <p>Note 2: The final rotation of the robot will be set to the rotation of
* the final pose in the trajectory. The robot will not follow the rotations
* from the poses at each timestep. If alternate rotation behavior is desired,
* the other constructor with a supplier for rotation should be used.
*
* @param trajectory The trajectory to follow.
* @param pose A function that supplies the robot pose,
* provided by the odometry class.
* @param feedforward The feedforward to use for the drivetrain.
* @param kinematics The kinematics for the robot drivetrain.
* @param xController The Trajectory Tracker PID controller
* for the robot's x position.
* @param yController The Trajectory Tracker PID controller
* for the robot's y position.
* @param thetaController The Trajectory Tracker PID controller
* for angle for the robot.
* @param maxWheelVelocity The maximum velocity of a drivetrain wheel.
* @param frontLeftController The front left wheel velocity PID.
* @param rearLeftController The rear left wheel velocity PID.
* @param frontRightController The front right wheel velocity PID.
* @param rearRightController The rear right wheel velocity PID.
* @param currentWheelSpeeds A MecanumDriveWheelSpeeds object containing
* the current wheel speeds.
* @param output The output of the velocity PIDs.
* @param requirements The subsystems to require.
*/
MecanumControllerCommand(
frc::Trajectory trajectory, std::function<frc::Pose2d()> pose,
frc::SimpleMotorFeedforward<units::meters> feedforward,
frc::MecanumDriveKinematics kinematics, frc2::PIDController xController,
frc2::PIDController yController,
frc::ProfiledPIDController<units::radians> thetaController,
units::meters_per_second_t maxWheelVelocity,
std::function<frc::MecanumDriveWheelSpeeds()> currentWheelSpeeds,
frc2::PIDController frontLeftController,
frc2::PIDController rearLeftController,
frc2::PIDController frontRightController,
frc2::PIDController rearRightController,
std::function<void(units::volt_t, units::volt_t, units::volt_t,
units::volt_t)>
output,
wpi::span<Subsystem* const> requirements = {});
/**
* Constructs a new MecanumControllerCommand that when executed will follow
* the provided trajectory. The user should implement a velocity PID on the
* desired output wheel velocities.
*
* <p>Note: The controllers will *not* set the outputVolts to zero upon
* completion of the path - this is left to the user, since it is not
* appropriate for paths with non-stationary end-states.
*
* @param trajectory The trajectory to follow.
* @param pose A function that supplies the robot pose - use one
* of the odometry classes to provide this.
* @param kinematics The kinematics for the robot drivetrain.
* @param xController The Trajectory Tracker PID controller
* for the robot's x position.
* @param yController The Trajectory Tracker PID controller
* for the robot's y position.
* @param thetaController The Trajectory Tracker PID controller
* for angle for the robot.
* @param desiredRotation The angle that the robot should be facing.
* This is sampled at each time step.
* @param maxWheelVelocity The maximum velocity of a drivetrain wheel.
* @param output The output of the position PIDs.
* @param requirements The subsystems to require.
*/
MecanumControllerCommand(
frc::Trajectory trajectory, std::function<frc::Pose2d()> pose,
frc::MecanumDriveKinematics kinematics, frc2::PIDController xController,
frc2::PIDController yController,
frc::ProfiledPIDController<units::radians> thetaController,
std::function<frc::Rotation2d()> desiredRotation,
units::meters_per_second_t maxWheelVelocity,
std::function<void(units::meters_per_second_t, units::meters_per_second_t,
units::meters_per_second_t,
units::meters_per_second_t)>
output,
std::initializer_list<Subsystem*> requirements);
/**
* Constructs a new MecanumControllerCommand that when executed will follow
* the provided trajectory. The user should implement a velocity PID on the
* desired output wheel velocities.
*
* <p>Note: The controllers will *not* set the outputVolts to zero upon
* completion of the path - this is left to the user, since it is not
* appropriate for paths with non-stationary end-states.
*
* <p>Note 2: The final rotation of the robot will be set to the rotation of
* the final pose in the trajectory. The robot will not follow the rotations
* from the poses at each timestep. If alternate rotation behavior is desired,
* the other constructor with a supplier for rotation should be used.
*
* @param trajectory The trajectory to follow.
* @param pose A function that supplies the robot pose - use one
* of the odometry classes to provide this.
* @param kinematics The kinematics for the robot drivetrain.
* @param xController The Trajectory Tracker PID controller
* for the robot's x position.
* @param yController The Trajectory Tracker PID controller
* for the robot's y position.
* @param thetaController The Trajectory Tracker PID controller
* for angle for the robot.
* @param maxWheelVelocity The maximum velocity of a drivetrain wheel.
* @param output The output of the position PIDs.
* @param requirements The subsystems to require.
*/
MecanumControllerCommand(
frc::Trajectory trajectory, std::function<frc::Pose2d()> pose,
frc::MecanumDriveKinematics kinematics, frc2::PIDController xController,
frc2::PIDController yController,
frc::ProfiledPIDController<units::radians> thetaController,
units::meters_per_second_t maxWheelVelocity,
std::function<void(units::meters_per_second_t, units::meters_per_second_t,
units::meters_per_second_t,
units::meters_per_second_t)>
output,
std::initializer_list<Subsystem*> requirements);
/**
* Constructs a new MecanumControllerCommand that when executed will follow
* the provided trajectory. The user should implement a velocity PID on the
* desired output wheel velocities.
*
* <p>Note: The controllers will *not* set the outputVolts to zero upon
* completion of the path - this is left to the user, since it is not
* appropriate for paths with non-stationary end-states.
*
* @param trajectory The trajectory to follow.
* @param pose A function that supplies the robot pose - use one
* of the odometry classes to provide this.
* @param kinematics The kinematics for the robot drivetrain.
* @param xController The Trajectory Tracker PID controller
* for the robot's x position.
* @param yController The Trajectory Tracker PID controller
* for the robot's y position.
* @param thetaController The Trajectory Tracker PID controller
* for angle for the robot.
* @param desiredRotation The angle that the robot should be facing.
* This is sampled at every time step.
* @param maxWheelVelocity The maximum velocity of a drivetrain wheel.
* @param output The output of the position PIDs.
* @param requirements The subsystems to require.
*/
MecanumControllerCommand(
frc::Trajectory trajectory, std::function<frc::Pose2d()> pose,
frc::MecanumDriveKinematics kinematics, frc2::PIDController xController,
frc2::PIDController yController,
frc::ProfiledPIDController<units::radians> thetaController,
std::function<frc::Rotation2d()> desiredRotation,
units::meters_per_second_t maxWheelVelocity,
std::function<void(units::meters_per_second_t, units::meters_per_second_t,
units::meters_per_second_t,
units::meters_per_second_t)>
output,
wpi::span<Subsystem* const> requirements = {});
/**
* Constructs a new MecanumControllerCommand that when executed will follow
* the provided trajectory. The user should implement a velocity PID on the
* desired output wheel velocities.
*
* <p>Note: The controllers will *not* set the outputVolts to zero upon
* completion of the path - this is left to the user, since it is not
* appropriate for paths with non-stationary end-states.
*
* <p>Note2: The final rotation of the robot will be set to the rotation of
* the final pose in the trajectory. The robot will not follow the rotations
* from the poses at each timestep. If alternate rotation behavior is desired,
* the other constructor with a supplier for rotation should be used.
*
* @param trajectory The trajectory to follow.
* @param pose A function that supplies the robot pose - use one
* of the odometry classes to provide this.
* @param kinematics The kinematics for the robot drivetrain.
* @param xController The Trajectory Tracker PID controller
* for the robot's x position.
* @param yController The Trajectory Tracker PID controller
* for the robot's y position.
* @param thetaController The Trajectory Tracker PID controller
* for angle for the robot.
* @param maxWheelVelocity The maximum velocity of a drivetrain wheel.
* @param output The output of the position PIDs.
* @param requirements The subsystems to require.
*/
MecanumControllerCommand(
frc::Trajectory trajectory, std::function<frc::Pose2d()> pose,
frc::MecanumDriveKinematics kinematics, frc2::PIDController xController,
frc2::PIDController yController,
frc::ProfiledPIDController<units::radians> thetaController,
units::meters_per_second_t maxWheelVelocity,
std::function<void(units::meters_per_second_t, units::meters_per_second_t,
units::meters_per_second_t,
units::meters_per_second_t)>
output,
wpi::span<Subsystem* const> requirements = {});
void Initialize() override;
void Execute() override;
void End(bool interrupted) override;
bool IsFinished() override;
private:
frc::Trajectory m_trajectory;
std::function<frc::Pose2d()> m_pose;
frc::SimpleMotorFeedforward<units::meters> m_feedforward;
frc::MecanumDriveKinematics m_kinematics;
frc::HolonomicDriveController m_controller;
std::function<frc::Rotation2d()> m_desiredRotation;
const units::meters_per_second_t m_maxWheelVelocity;
std::unique_ptr<frc2::PIDController> m_frontLeftController;
std::unique_ptr<frc2::PIDController> m_rearLeftController;
std::unique_ptr<frc2::PIDController> m_frontRightController;
std::unique_ptr<frc2::PIDController> m_rearRightController;
std::function<frc::MecanumDriveWheelSpeeds()> m_currentWheelSpeeds;
std::function<void(units::meters_per_second_t, units::meters_per_second_t,
units::meters_per_second_t, units::meters_per_second_t)>
m_outputVel;
std::function<void(units::volt_t, units::volt_t, units::volt_t,
units::volt_t)>
m_outputVolts;
bool m_usePID;
frc::Timer m_timer;
frc::MecanumDriveWheelSpeeds m_prevSpeeds;
units::second_t m_prevTime;
};
} // namespace frc2
| 51.139381 | 80 | 0.68289 | [
"geometry",
"object"
] |
29fca598f602e4780452e16e62bb72be6f8e25f3 | 2,606 | c | C | src/wallbreaker/main.c | AndyMender/raylib-games | d7fc2c1ce36914243f41ec7b37b2f841b8e7f891 | [
"MIT"
] | 1 | 2021-02-16T13:58:21.000Z | 2021-02-16T13:58:21.000Z | src/wallbreaker/main.c | AndyMender/raylib-games | d7fc2c1ce36914243f41ec7b37b2f841b8e7f891 | [
"MIT"
] | null | null | null | src/wallbreaker/main.c | AndyMender/raylib-games | d7fc2c1ce36914243f41ec7b37b2f841b8e7f891 | [
"MIT"
] | null | null | null |
#include <stdio.h>
#include <stdlib.h>
#include <raylib.h>
#include "main.h"
// TODO: move global state init to main.h to an 'init' function?
const int screenWidth = 800;
const int screenHeight = 450;
int main(const int argc, char *const *argv)
{
/* Process command-line args */
enum CmdlineCode exit_code = process_cmdline_args(argc, argv);
/* Triggered 'help' message */
if (exit_code == CMDLINE_HELP) return EXIT_SUCCESS;
/* Processing failed */
else if (exit_code == CMDLINE_ERROR) {
log_message("Processing command-line arguments failed. Exiting!", APP_LOG_ERROR);
return EXIT_FAILURE;
}
// Create window (and OpenGL context in the background)
InitWindow(screenWidth, screenHeight, "raylib [core] example - 3d camera mode");
// Define the camera to look into our 3d world
Camera3D camera = { 0 };
camera.position = (Vector3){ 0.0f, 10.0f, 10.0f }; // Camera position
camera.target = (Vector3){ 0.0f, 0.0f, 0.0f }; // Camera looking at point
camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; // Camera up vector (rotation towards target)
camera.fovy = 45.0f; // Camera field-of-view Y
camera.type = CAMERA_PERSPECTIVE; // Camera mode type
Vector3 cubePosition = { 0.0f, 0.0f, 0.0f };
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
// Update
//----------------------------------------------------------------------------------
// TODO: Update your variables here
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(RAYWHITE);
BeginMode3D(camera);
DrawCube(cubePosition, 2.0f, 2.0f, 2.0f, RED);
DrawCubeWires(cubePosition, 2.0f, 2.0f, 2.0f, MAROON);
DrawGrid(10, 1.0f);
EndMode3D();
DrawText("Welcome to the third dimension!", 10, 40, 20, DARKGRAY);
DrawFPS(10, 10);
EndDrawing();
//----------------------------------------------------------------------------------
}
// Destroy window (and backend OpenGL context)
CloseWindow();
return EXIT_SUCCESS;
} | 33.844156 | 101 | 0.491174 | [
"vector",
"3d"
] |
4b0185924ea891554ccf9943ea9f91197c00d39a | 2,871 | c | C | gamess/ddi/src/ddi_recv.c | andremirt/v_cond | 6b5c364d7cd4243686488b2bd4318be3927e07ea | [
"Unlicense"
] | null | null | null | gamess/ddi/src/ddi_recv.c | andremirt/v_cond | 6b5c364d7cd4243686488b2bd4318be3927e07ea | [
"Unlicense"
] | null | null | null | gamess/ddi/src/ddi_recv.c | andremirt/v_cond | 6b5c364d7cd4243686488b2bd4318be3927e07ea | [
"Unlicense"
] | null | null | null | /* -------------------------------------------------------------------- *\
* Distributed Data Interface
* ==========================
*
* Global objects
*
* Author: Ryan M. Olson
* CVS $Id: ddi_recv.c,v 1.1.1.1 2007/05/26 01:42:29 andrey Exp $
\* -------------------------------------------------------------------- */
# include "ddi_base.h"
/* ------------------------------------------------------------------------- *\
DDI_Recv_request(buff,from)
===========================
[OUT] buff - address in which incoming data is passed.
[IN] from - rank of process sending data stream.
Used to receive a data request sent by DDI_Send_request. This subroutine
is only called from a data server.
\* ------------------------------------------------------------------------- */
void DDI_Recv_request(void *buff,int *from) {
# if defined DDI_SOC
char ack=37;
size_t size = sizeof(DDI_Patch);
DDI_Recvany(buff,size,from);
Send(gv(sockets)[*from],&ack,1,0);
# endif
/* ---------------------------------- *\
The stand-alone MPI version of DDI
\* ---------------------------------- */
/*
This routine is the one that is responsible for the poor
performance of a 100% MPI-1 model. The "receive from anywhere"
option caused by MPI_ANY_SOURCE typically is implemented by
repeated checking (polling) on all open MPI processes. This
can sometimes be influenced by looking for options to control
the polling mechanism, at the "mpirun" time. However, a more
practical solution is to use the "mixed" model, which uses
our TCP/IP code for handling the small control messages, which
do no polling at all. If your adapter allows TCP/IP to coexist
with the MPI-1, by all means try "mixed" over "mpi" for DDI.
Here's a short note from Ryan,
Having talking to some MPI people at past SC conferences,
it seems that the Irecv/wait combination has the best
chance to be implemented in a blocking fashion. However,
I never worked out all the details to make it happen.
What I think this means is that you set up an IRECV on every
possible source, and then loop around "polling" with the wait
yourself, perhaps with a delay from "sleep" added before the
loop repeats itself.
*/
# if defined DDI_MPI && !defined DDI_SOC & !defined DDI_LAPI
const DDI_Comm *comm = (const DDI_Comm *) Comm_find(DDI_WORKING_COMM);
MPI_Status status;
size_t size = sizeof(DDI_Patch);
DEBUG_OUT(LVL4,(stdout,"%s: call mpi_recv from any source.\n",DDI_Id()))
MPI_Recv(buff,size,MPI_BYTE,MPI_ANY_SOURCE,0,comm->world_comm,&status);
*from = status.MPI_SOURCE;
DEBUG_OUT(LVL4,(stdout,"%s: received request from %i.\n",DDI_Id(),*from))
# endif
}
| 40.43662 | 79 | 0.56914 | [
"model"
] |
4b0218b6db161163e43a7bacad98847a833b9a1a | 2,036 | h | C | iPhoneOS14.2.sdk/System/Library/Frameworks/CoreTelephony.framework/Headers/CTSubscriber.h | Zi0P4tch0/sdks | 96951a2b5a0c0a58963a8f9c37bc44ec9991153b | [
"MIT"
] | 416 | 2016-08-20T03:40:59.000Z | 2022-03-30T14:27:47.000Z | iPhoneOS14.4.sdk/System/Library/Frameworks/CoreTelephony.framework/Headers/CTSubscriber.h | haoict/sdks | 40a7cee1dc15ae097d867ae0c5133709fa103040 | [
"MIT"
] | 41 | 2016-08-22T14:41:42.000Z | 2022-02-25T11:38:16.000Z | iPhoneOS14.4.sdk/System/Library/Frameworks/CoreTelephony.framework/Headers/CTSubscriber.h | haoict/sdks | 40a7cee1dc15ae097d867ae0c5133709fa103040 | [
"MIT"
] | 173 | 2016-08-28T15:09:18.000Z | 2022-03-23T15:42:52.000Z | /*
* CTSubscriber.h
* CoreTelephony
*
* Copyright 2012 Apple, Inc.. All rights reserved.
*
*/
#import <Foundation/Foundation.h>
#import <CoreTelephony/CoreTelephonyDefines.h>
NS_ASSUME_NONNULL_BEGIN
/*
* CTSubscriberTokenRefreshed
*
* Description:
* The name of the NSNotification sent when the carrier token is available.
* The `object' argument is set to the CTSubscriber instance for which the token was refreshed.
*/
CORETELEPHONY_EXTERN NSString * const CTSubscriberTokenRefreshed
API_UNAVAILABLE(macos)
API_DEPRECATED_WITH_REPLACEMENT("-[CTSubscriberDelegate subscriberTokenRefreshed:]", ios(7.0, 12.1))
;
@class CTSubscriber;
API_AVAILABLE(ios(12.1)) API_UNAVAILABLE(macCatalyst, watchos) API_UNAVAILABLE(macos, tvos)
@protocol CTSubscriberDelegate
- (void)subscriberTokenRefreshed:(CTSubscriber *)subscriber;
@end
CORETELEPHONY_CLASS_AVAILABLE(7_0) API_UNAVAILABLE(macCatalyst, watchos) API_UNAVAILABLE(macos, tvos)
@interface CTSubscriber : NSObject
/*
* carrierToken
*
* Description:
* A data blob containing authorization information about the subscriber.
* This API is deprecated without replacement. Starting in iOS 11.3, this API returns nil.
*/
@property (nonatomic, readonly, retain, nullable) NSData* carrierToken
API_UNAVAILABLE(macos, watchos, tvos)
API_DEPRECATED("Deprecated; returns nil starting in iOS 11.3.", ios(7.0, 11.0))
;
/*
* identifier
*
* Description:
* An implementation-defined identifier that can be used to correlate this CTSubscriber
* with information vended by other API's.
* The format of the identifier can change across software releases. Therefore, applications
* should not persist it.
*/
@property (nonatomic, readonly) NSString* identifier
API_UNAVAILABLE(macos, tvos)
API_AVAILABLE(ios(12.1))
API_UNAVAILABLE(macCatalyst, watchos)
;
@property (nonatomic, weak) id<CTSubscriberDelegate> delegate
API_UNAVAILABLE(macos, tvos)
API_AVAILABLE(ios(12.1))
API_UNAVAILABLE(macCatalyst, watchos)
;
@end
NS_ASSUME_NONNULL_END
| 27.890411 | 101 | 0.77112 | [
"object"
] |
4b09bb8f280e0d0691ac40e66e893cb4ce95a54f | 30,500 | h | C | GenericMatrix.h | shaoguangwu/GenericMatrix | 905dc6663a15037286d2b0af8abdc4596571c395 | [
"Apache-2.0"
] | null | null | null | GenericMatrix.h | shaoguangwu/GenericMatrix | 905dc6663a15037286d2b0af8abdc4596571c395 | [
"Apache-2.0"
] | null | null | null | GenericMatrix.h | shaoguangwu/GenericMatrix | 905dc6663a15037286d2b0af8abdc4596571c395 | [
"Apache-2.0"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2019 Shaoguang. All rights reserved.
**
** GenericMatrix, a generic template matrix class,
** the matrix elements are managed by a one-dimension pointer.
**
** 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
**
** https://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 __GERNERICMATRIX_H__
#define __GERNERICMATRIX_H__
#include <ostream>
#include <utility> // std::move, std::pair
#include <algorithm> // std::fill_n, std::copy_n
/*!
\class GenericMatrix
\brief The GenericMatrix class defines a generic template matrix class,
the matrix elements are managed by a one-dimension pointer.
The GenericMatrix template has one parameter:
\li \b Elem Element type that is visible to users of the class.
*/
template<typename Elem = float>
class GenericMatrix
{
public:
using size_type = std::size_t;
using value_type = Elem;
using iterator = value_type *;
using const_iterator = const iterator;
GenericMatrix();
GenericMatrix(size_type row, size_type col);
GenericMatrix(size_type row, size_type col, const Elem &initialValue);
GenericMatrix(size_type row, size_type col, Elem *data);
GenericMatrix(const GenericMatrix &other);
GenericMatrix(GenericMatrix &&other) noexcept;
~GenericMatrix();
GenericMatrix &operator=(const GenericMatrix &other);
GenericMatrix &operator=(GenericMatrix &&other) noexcept;
iterator begin() noexcept;
const_iterator begin() const noexcept;
const_iterator cbegin() const noexcept;
iterator end() noexcept;
const_iterator end() const noexcept;
const_iterator cend() const noexcept;
size_type rows() const;
size_type columns() const;
size_type size() const;
Elem *data() noexcept;
const Elem *data() const noexcept;
const Elem *constData() const noexcept;
Elem *data(size_type row, size_type col) noexcept;
const Elem *data(size_type row, size_type col) const noexcept;
const Elem *constData(size_type row, size_type col) const noexcept;
Elem *dataAt(size_type row, size_type col) noexcept;
const Elem *dataAt(size_type row, size_type col) const noexcept;
const Elem *constDataAt(size_type row, size_type col) const noexcept;
Elem &operator()(size_type row, size_type col);
const Elem &operator()(size_type row, size_type col) const;
Elem &at(size_type row, size_type col);
const Elem &at(size_type row, size_type col) const;
bool empty() const;
bool isValid() const;
bool isIdentity() const;
inline bool isHomomorphicTo(const GenericMatrix<Elem> &m);
static inline bool isHomomorphic(const GenericMatrix<Elem> &m1, const GenericMatrix<Elem> &m2);
void resize(size_type row, size_type col);
void resize(size_type row, size_type col, const Elem &initialValue);
void reset(size_type row, size_type col, Elem *data);
void setToIdentity();
void fill(const Elem &value);
void swap(GenericMatrix<Elem> &other);
GenericMatrix<Elem> reverse() const;
GenericMatrix<Elem> transposed() const;
void doHadamardProduct(const GenericMatrix<Elem> &m);
static GenericMatrix<Elem> hadamardProduct(const GenericMatrix<Elem> &m1, const GenericMatrix<Elem> &m2);
GenericMatrix<Elem> roi(size_type row1, size_type col1, size_type row2, size_type col2);
GenericMatrix<Elem> &operator+=(const GenericMatrix<Elem> &m);
GenericMatrix<Elem> &operator-=(const GenericMatrix<Elem> &m);
GenericMatrix<Elem> &operator*=(const GenericMatrix<Elem> &m);
GenericMatrix<Elem> &operator*=(const Elem &factor);
GenericMatrix<Elem> &operator/=(const Elem &divisor);
bool operator==(const GenericMatrix<Elem> &m) const;
bool operator!=(const GenericMatrix<Elem> &m) const;
template<typename __ElemDTo, typename __Elem>
friend GenericMatrix<__ElemDTo> matrix_cast(const GenericMatrix<__Elem> &m);
template<typename __Elem>
friend GenericMatrix<__Elem> operator+(const GenericMatrix<__Elem> &m1, const GenericMatrix<__Elem> &m2);
template<typename __Elem>
friend GenericMatrix<__Elem> operator-(const GenericMatrix<__Elem> &m1, const GenericMatrix<__Elem> &m2);
template<typename __Elem>
friend GenericMatrix<__Elem> operator*(const GenericMatrix<__Elem> &m1, const GenericMatrix<__Elem> &m2);
template<typename __Elem>
friend GenericMatrix<__Elem> operator*(const GenericMatrix<__Elem> &matrix, const __Elem &factor);
template<typename __Elem>
friend GenericMatrix<__Elem> operator*(const __Elem &factor, const GenericMatrix<__Elem> &matrix);
template<typename __Elem>
friend GenericMatrix<__Elem> operator/(const GenericMatrix<__Elem> &matrix, const __Elem &divisor);
template<typename __Elem>
friend GenericMatrix<__Elem> operator-(const GenericMatrix<__Elem> &matrix);
template<typename __Elem>
friend std::ostream &operator<<(std::ostream &os, const GenericMatrix<__Elem> &matrix);
private:
void alloc();
void alloc(size_type row, size_type col);
void free();
void setSize(size_type row, size_type col);
size_type computeOffset(size_type row, size_type col) const;
bool containsIndex(size_type row, size_type col) const;
private:
size_type m_rows;
size_type m_cols;
Elem *m_data;
};
/*!
\typedef GenericMatrix::size_type
Type for declaring the matrix's rows and columns.
*/
/*!
\typedef GenericMatrix::value_type
The value type of the template parameter \a Elem.
*/
/*!
\typedef GenericMatrix::iterator
An STL-style non-const iterator for GenericMatrix.
*/
/*!
\typedef GenericMatrix::const_iterator
An STL-style const iterator for GenericMatrix.
*/
/*!
Constructs a invalid matrix.
\sa isValid()
*/
template<typename Elem>
GenericMatrix<Elem>::GenericMatrix()
: m_rows(0), m_cols(0), m_data(nullptr)
{
}
/*!
Constructs a \a row x \a col matrix without initializing the contents.
*/
template<typename Elem>
GenericMatrix<Elem>::GenericMatrix(size_type row, size_type col)
: m_rows(row), m_cols(col), m_data(nullptr)
{
alloc();
}
/*!
Constructs a \a row x \a col matrix and set the element pointer to \a data.
\note \a data pointer will be free when destroy this matrix.
\sa reset()
*/
template<typename Elem>
GenericMatrix<Elem>::GenericMatrix(size_type row, size_type col, Elem *data)
: m_rows(row), m_cols(col), m_data(data)
{
}
/*!
Constructs a \a row x \a col matrix and initialize all values with \a initialValue.
\sa fill()
*/
template<typename Elem>
GenericMatrix<Elem>::GenericMatrix(size_type row, size_type col, const Elem &initialValue)
: m_rows(row), m_cols(col), m_data(nullptr)
{
alloc();
fill(initialValue);
}
/*!
Destroys the matrix.
*/
template<typename Elem>
GenericMatrix<Elem>::~GenericMatrix()
{
free();
}
/*!
\internal
Alloc the matrix memory from \a m_rows and \a m_cols.
*/
template<typename Elem>
void GenericMatrix<Elem>::alloc()
{
if (m_rows > 0 && m_cols > 0) {
m_data = new Elem[m_rows * m_cols];
}
}
/*!
\internal
Alloc the matrix memory from \a row and \a col.
*/
template<typename Elem>
void GenericMatrix<Elem>::alloc(size_type row, size_type col)
{
if (row > 0 && col > 0) {
m_data = new Elem[row * col];
}
}
/*!
\internal
Frees the matrix memory.
*/
template<typename Elem>
void GenericMatrix<Elem>::free()
{
if (m_data) {
delete[] m_data;
m_data = nullptr;
}
}
/*!
\internal
Sets this matrix's rows and columns with parameter \a row and \a col.
*/
template<typename Elem>
void GenericMatrix<Elem>::setSize(size_type row, size_type col)
{
m_rows = row;
m_cols = col;
}
/*!
\internal
Compute internal data offset by \a row index and \a col index.
*/
template<typename Elem>
typename GenericMatrix<Elem>::size_type GenericMatrix<Elem>::computeOffset(size_type row, size_type col) const
{
return row * m_cols + col;
}
/*!
\internal
Returns true if \a row index is less than this matrix rows
and \a col index is less than this matrix cols, otherwise return false.
*/
template<typename Elem>
bool GenericMatrix<Elem>::containsIndex(size_type row, size_type col) const
{
return (row < m_rows && col < m_cols);
}
/*!
Constructs a copy of \a other.
*/
template<typename Elem>
GenericMatrix<Elem>::GenericMatrix(const GenericMatrix &other)
: m_rows(other.m_rows), m_cols(other.m_cols), m_data(nullptr)
{
alloc();
std::copy_n(other.data(), other.size(), m_data);
}
/*!
Move-constructs a GenericMatrix instance, making it point at the same object that \a other was pointing to.
*/
template<typename Elem>
GenericMatrix<Elem>::GenericMatrix(GenericMatrix &&other) noexcept
: m_rows(other.m_rows), m_cols(other.m_cols), m_data(other.m_data)
{
other.m_data = nullptr;
other.setSize(0, 0);
}
/*!
Assigns \a other to this matrix and returns a reference to this matrix.
*/
template<typename Elem>
GenericMatrix<Elem> &GenericMatrix<Elem>::operator=(const GenericMatrix &other)
{
if (this == &other) {
return *this;
}
resize(other.rows(), other.columns());
std::copy_n(other.m_data, other.size(), m_data);
return *this;
}
/*!
Move-assigns \a other to this GenericMatrix instance.
*/
template<typename Elem>
GenericMatrix<Elem> &GenericMatrix<Elem>::operator=(GenericMatrix &&other) noexcept
{
if (this == &other) {
return *this;
}
free();
setSize(other.m_rows, other.m_cols);
other.setSize(0, 0);
std::swap(m_data. other.m_data);
return *this;
}
template<typename Elem>
typename GenericMatrix<Elem>::iterator GenericMatrix<Elem>::begin() noexcept
{
return m_data;
}
template<typename Elem>
typename GenericMatrix<Elem>::const_iterator GenericMatrix<Elem>::begin() const noexcept
{
return m_data;
}
template<typename Elem>
typename GenericMatrix<Elem>::const_iterator GenericMatrix<Elem>::cbegin() const noexcept
{
return m_data;
}
template<typename Elem>
typename GenericMatrix<Elem>::iterator GenericMatrix<Elem>::end() noexcept
{
return m_data + size();
}
template<typename Elem>
typename GenericMatrix<Elem>::const_iterator GenericMatrix<Elem>::end() const noexcept
{
return m_data + size();
}
template<typename Elem>
typename GenericMatrix<Elem>::const_iterator GenericMatrix<Elem>::cend() const noexcept
{
return m_data + size();
}
/*!
Returns the number of matrix rows.
\sa columns(), size()
*/
template<typename Elem>
typename GenericMatrix<Elem>::size_type GenericMatrix<Elem>::rows() const
{
return m_rows;
}
/*!
Returns the number of matrix columns.
\sa rows(), size()
*/
template<typename Elem>
typename GenericMatrix<Elem>::size_type GenericMatrix<Elem>::columns() const
{
return m_cols;
}
/*!
Returns the number of matrix elements.
\sa rows(), columns()
*/
template<typename Elem>
typename GenericMatrix<Elem>::size_type GenericMatrix<Elem>::size() const
{
return m_rows * m_cols;
}
/*!
Returns a pointer to the raw data of this matrix.
\sa constData()
*/
template<typename Elem>
Elem *GenericMatrix<Elem>::data() noexcept
{
return m_data;
}
/*!
Returns a constant pointer to the raw data of this matrix.
\sa constData()
*/
template<typename Elem>
const Elem *GenericMatrix<Elem>::data() const noexcept
{
return m_data;
}
/*!
Returns a constant pointer to the raw data of this matrix.
\sa data()
*/
template<typename Elem>
const Elem *GenericMatrix<Elem>::constData() const noexcept
{
return m_data;
}
/*!
Returns a offset \a row and \a col pointer to the raw data of this matrix.
\note No bounds checking is performed.
\sa dataAt()
*/
template<typename Elem>
Elem *GenericMatrix<Elem>::data(size_type row, size_type col) noexcept
{
return m_data + computeOffset(row, col);
}
/*!
Returns a constant offset \a row and \a col pointer to the raw data of this matrix.
\note No bounds checking is performed.
\sa dataAt()
*/
template<typename Elem>
const Elem *GenericMatrix<Elem>::data(size_type row, size_type col) const noexcept
{
return m_data + computeOffset(row, col);
}
/*!
Returns a constant offset \a row and \a col pointer to the raw data of this matrix.
\note No bounds checking is performed.
\sa constDataAt()
*/
template<typename Elem>
const Elem *GenericMatrix<Elem>::constData(size_type row, size_type col) const noexcept
{
return m_data + computeOffset(row, col);
}
/*!
Returns a offset \a row and \a col pointer to the raw data of this matrix.
If \a row or \a col out of range, returns end();
\sa constDataAt()
*/
template<typename Elem>
Elem *GenericMatrix<Elem>::dataAt(size_type row, size_type col) noexcept
{
if (row > m_rows || col > m_cols)
return end();
return m_data + computeOffset(row, col);
}
/*!
Returns a constant offset \a row and \a col pointer to the raw data of this matrix.
If \a row or \a col out of range, returns end();
\sa constDataAt()
*/
template<typename Elem>
const Elem *GenericMatrix<Elem>::dataAt(size_type row, size_type col) const noexcept
{
if (row > m_rows || col > m_cols)
return end();
return m_data + computeOffset(row, col);
}
/*!
Returns a constant offset \a row and \a col pointer to the raw data of this matrix.
If \a row or \a col out of range, returns end();
\sa dataAt()
*/
template<typename Elem>
const Elem *GenericMatrix<Elem>::constDataAt(size_type row, size_type col) const noexcept
{
if (row > m_rows || col > m_cols)
return end();
return m_data + computeOffset(row, col);
}
/*!
Returns a constant reference to the element at position (\a row, \a column) in this matrix.
\note No bounds checking is performed.
\sa at()
*/
template<typename Elem>
const Elem &GenericMatrix<Elem>::operator()(size_type row, size_type column) const
{
return m_data[computeOffset(row, column)];
}
/*!
Returns a reference to the element at position (\a row, \a column)
in this matrix so that the element can be assigned to.
\note No bounds checking is performed.
\sa at()
*/
template<typename Elem>
Elem &GenericMatrix<Elem>::operator()(size_type row, size_type column)
{
return m_data[computeOffset(row, column)];
}
/*!
Returns a constant reference to the element at position (\a row, \a column)
in this matrix, with bounds checking.
\exception std::out_of_range if position (\a row, \a col) is not within the range of the matrix.
\sa operator()()
*/
template<typename Elem>
const Elem &GenericMatrix<Elem>::at(size_type row, size_type col) const
{
if (row >= 0 && row < m_rows && col >= 0 && col < m_cols)
return m_data[computeOffset(row, col)];
throw std::out_of_range("out of range.");
}
/*!
Returns a reference to the element at position (\a row, \a column)
in this matrix, with bounds checking.
\exception std::out_of_range if position (\a row, \a col) is not within the range of the matrix.
\sa operator()()
*/
template<typename Elem>
Elem &GenericMatrix<Elem>::at(size_type row, size_type col)
{
if (row >= 0 && row < m_rows && col >= 0 && col < m_cols)
return m_data[computeOffset(row, col)];
throw std::out_of_range("out of range.");
}
/*!
Returns \c true if this matrix element's size equal to 0,
otherwise returns \c false.
*/
template<typename Elem>
bool GenericMatrix<Elem>::empty() const
{
return 0 == size();
}
/*!
Returns \c true if this matrix internal data is not null pointer
and matrix rows/cols greater than 0, otherwise returns \c false.
*/
template<typename Elem>
bool GenericMatrix<Elem>::isValid() const
{
return m_data && size() > 0;
}
/*!
Returns \c true if this matrix is the identity; false otherwise.
\sa setToIdentity()
*/
template<typename Elem>
bool GenericMatrix<Elem>::isIdentity() const
{
for (size_type i = 0; i < m_rows; ++i) {
for (size_type j = 0; j < m_cols; ++j) {
if (i == j) {
if (m_data[computeOffset(i, j)] != 1)
return false;
} else {
if (m_data[computeOffset(i, j)] != 0)
return false;
}
}
}
return true;
}
/*!
Reconstructs a \a row x \a col identity matrix without initializing the contents.
*/
template<typename Elem>
void GenericMatrix<Elem>::resize(size_type row, size_type col)
{
if (this->size() != row * col) {
free();
alloc(row, col);
}
setSize(row, col);
}
/*!
Reconstructs a \a row x \a col identity matrix and initialize all values with \a initialValue.
*/
template<typename Elem>
void GenericMatrix<Elem>::resize(size_type row, size_type col, const Elem &initialValue)
{
resize(row, col);
fill(initialValue);
}
/*!
Reset this matrix to \a row x \a col matrix and set the elments pointer to \a data.
\note \a data pointer will be free when destroy this matrix.
*/
template<typename Elem>
void GenericMatrix<Elem>::reset(size_type row, size_type col, Elem *data)
{
free();
m_rows = row;
m_cols = col;
m_data = data;
}
/*!
Sets this matrix to the identity.
\sa isIdentity()
*/
template<typename Elem>
void GenericMatrix<Elem>::setToIdentity()
{
for (size_type i = 0; i < m_rows; ++i) {
for (size_type j = 0; j < m_cols; ++j) {
if (j == i) {
m_data[computeOffset(i, j)] = 1;
} else {
m_data[computeOffset(i, j)] = 0;
}
}
}
}
/*!
Returns a new matrix reversed by this matrix.
*/
template<typename Elem>
GenericMatrix<Elem> GenericMatrix<Elem>::reverse() const
{
GenericMatrix<Elem> result(m_rows, m_cols);
auto reverse_it = m_data + size() - 1;
auto reverse_it_end = m_data - 1;
auto its = result.begin();
while (reverse_it != reverse_it_end) {
*its++ = *reverse_it--;
}
return result;
}
/*!
Returns this matrix, transposed about its diagonal.
*/
template<typename Elem>
GenericMatrix<Elem> GenericMatrix<Elem>::transposed() const
{
GenericMatrix<Elem> result(m_cols, m_rows);
for (size_type i = 0; i < m_cols; ++i) {
for (size_type j = 0; j < m_rows; ++j) {
result(i, j) = m_data[computeOffset(j, i)];
}
}
return result;
}
/*!
Fills all elements of this matrix with \a value.
*/
template<typename Elem>
void GenericMatrix<Elem>::fill(const Elem &value)
{
std::fill_n(m_data, m_rows * m_cols, value);
}
/*!
Do the hadamard product of this matrix and the matrix \a m.
\exception std::invalid_argument if \a m1 and \a m2 are not homomorphic.
\sa hadamardProduct()
*/
template<typename Elem>
void GenericMatrix<Elem>::doHadamardProduct(const GenericMatrix<Elem> &m)
{
if (!GenericMatrix<Elem>::isHomomorphic(*this, m))
throw std::invalid_argument("invalid argument.");
for (size_type i = 0; i < m_rows; ++i) {
for (size_type j = 0; i < m_cols; ++j) {
m_data[computeOffset(i, j)] *= m(i, j);
}
}
}
/*!
Returns the hadamard product of the matrix \a m1 and the matrix \a m2.
\exception std::invalid_argument if \a m1 and \a m2 are not homomorphic.
\sa doHadamardProduct()
*/
template<typename Elem>
GenericMatrix<Elem> GenericMatrix<Elem>::hadamardProduct(const GenericMatrix<Elem> &m1, const GenericMatrix<Elem> &m2)
{
if (!GenericMatrix<Elem>::isHomomorphic(m1, m2))
throw std::invalid_argument("invalid argument.");
GenericMatrix<Elem> result(m1.rows(), m1.columns());
for (size_type i = 0; i < m1.rows(); ++i) {
for (size_type j = 0; i < m2.columns(); ++j) {
result(i, j) = m1(i, j) * m2(i, j);
}
}
return result;
}
/*!
Extracts region of interest of this matrix.
\note No bounds checking is performed.
*/
template<typename Elem>
GenericMatrix<Elem> GenericMatrix<Elem>::roi(size_type row1, size_type col1, size_type row2, size_type col2)
{
if (!containsIndex(row1, col1) || !containsIndex(row2, col2)) {
return GenericMatrix<Elem>();
}
std::pair<size_type, size_type> rowMinMax = std::minmax(row1, row2);
std::pair<size_type, size_type> colMinMax = std::minmax(col1, col2);
GenericMatrix<Elem> result(rowMinMax.second - rowMinMax.first + 1, colMinMax.second - colMinMax.first + 1);
for (size_type i = rowMinMax.first; i <= rowMinMax.second; ++i) {
std::copy_n(constData(i, colMinMax.first), result.columns(), result.data((i - rowMinMax.first), 0));
}
return result;
}
/*!
Returns \c true if this matrix and matrix \a m are homomorphic; false otherwise.
\sa isHomomorphic()
*/
template<typename Elem>
inline bool GenericMatrix<Elem>::isHomomorphicTo(const GenericMatrix<Elem> &m)
{
return((m_rows == m.m_rows) && (m_cols == m.m_cols));
}
/*!
Returns \c true if matrix \a m1 and matrix \a m2 are homomorphic; false otherwise.
\sa isHomomorphicTo()
*/
template<typename Elem>
inline bool GenericMatrix<Elem>::isHomomorphic(const GenericMatrix<Elem> &m1, const GenericMatrix<Elem> &m2)
{
return ((m1.m_rows == m2.m_rows) && (m1.m_cols == m2.m_cols));
}
/*!
Swaps matrix \a other with this matrix.
*/
template<typename Elem>
void GenericMatrix<Elem>::swap(GenericMatrix<Elem> &other)
{
std::swap(*this, other);
}
/*!
Adds the contents of \a m to this matrix.
\exception std::invalid_argument if this matrix and matrix \a m are not homomorphic.
\sa operator-=()
*/
template<typename Elem>
GenericMatrix<Elem> &GenericMatrix<Elem>::operator+=(const GenericMatrix<Elem> &m)
{
if (!isHomomorphicTo(m))
throw std::invalid_argument("invalid argument.");
for (size_type i = 0; i < m.size(); ++i) {
m_data[i] += m.m_data[i];
}
return *this;
}
/*!
Subtracts the contents of \a m from this matrix.
\exception std::invalid_argument if this matrix and matrix \a m are not homomorphic.
\sa operator+=()
*/
template<typename Elem>
GenericMatrix<Elem> &GenericMatrix<Elem>::operator-=(const GenericMatrix<Elem> &m)
{
if (!isHomomorphicTo(m))
throw std::invalid_argument("invalid argument.");
for (size_type i = 0; i < m.size(); ++i) {
m_data[i] -= m.m_data[i];
}
return *this;
}
/*!
Multiplies this matrix and matrix \a m, in format: this = this * m.
\exception std::invalid_argument if this matrix's columns is not equal to matrix \a m's rows.
*/
template<typename Elem>
GenericMatrix<Elem> &GenericMatrix<Elem>::operator*=(const GenericMatrix<Elem> &m)
{
if (m_cols != m.m_rows)
throw std::invalid_argument("invalid argument.");
GenericMatrix<Elem> result(m_rows, m.m_cols, 0);
for (size_type i = 0; i < result.m_rows; ++i) {
for (size_type j = 0; j < result.m_cols; ++j) {
for (size_type k = 0; k < m_cols; ++k) {
result(i, j) += m_data[computeOffset(i, k)] * m(k, j);
}
}
}
return (*this = std::move(result));
}
/*!
Multiplies all elements of this matrix by \a factor.
\sa operator/=()
*/
template<typename Elem>
GenericMatrix<Elem> &GenericMatrix<Elem>::operator*=(const Elem &factor)
{
for (size_type i = 0; i < size(); ++i) {
m_data[i] *= factor;
}
return *this;
}
/*!
Divides all elements of this matrix by \a divisor.
\sa operator*=()
*/
template<typename Elem>
GenericMatrix<Elem> &GenericMatrix<Elem>::operator/=(const Elem &divisor)
{
for (size_type i = 0; i < size(); ++i) {
m_data[i] /= divisor;
}
return *this;
}
/*!
Returns \c true if this matrix is identical to \a m; false otherwise.
\sa operator!=()
*/
template<typename Elem>
bool GenericMatrix<Elem>::operator==(const GenericMatrix<Elem> &m) const
{
for (size_type i = 0; i < size(); ++i) {
if (m_data[i] != m.m_data[i])
return false;
}
return true;
}
/*!
Returns \c true if this matrix is not identical to \a m; false otherwise.
\sa operator==()
*/
template<typename Elem>
bool GenericMatrix<Elem>::operator!=(const GenericMatrix<Elem> &m) const
{
for (size_type i = 0; i < size(); ++i) {
if (m_data[i] != m.m_data[i])
return true;
}
return false;
}
/*****************************************************************************
friend functions
*****************************************************************************/
/*!
\relates GenericMatrix
Converts a matrix to a different type matrix.
\note The \b __ElemDst must can do \c static_cast<__ElemDst>(__Elem).
*/
template<typename __ElemDTo, typename __Elem>
GenericMatrix<__ElemDTo> matrix_cast(const GenericMatrix<__Elem> &m)
{
GenericMatrix<__ElemDTo> result(m.rows(), m.columns());
auto itm = m.begin();
auto its = result.begin();
while (itm != m.end()) {
*its++ = static_cast<__ElemDTo>(*itm++);
}
return result;
}
/*!
\relates GenericMatrix
Returns the sum of \a m1 and \a m2.
\exception std::invalid_argument if this matrix and matrix \a m are not homomorphic.
*/
template<typename __Elem>
GenericMatrix<__Elem> operator+(const GenericMatrix<__Elem> &m1, const GenericMatrix<__Elem> &m2)
{
if (!GenericMatrix<__Elem>::isHomomorphic(m1, m2))
throw std::invalid_argument("invalid argument.");
using size_type = typename GenericMatrix<__Elem>::size_type;
GenericMatrix<__Elem> result(m1.m_rows, m1.m_cols);
for (size_type i = 0; i < result.size(); ++i) {
result.m_data[i] = m1.m_data[i] + m2.m_data[i];
}
return result;
}
/*!
\relates GenericMatrix
Returns the difference of \a m1 and \a m2.
\exception std::invalid_argument if this matrix and matrix \a m are not homomorphic.
*/
template<typename __Elem>
GenericMatrix<__Elem> operator-(const GenericMatrix<__Elem> &m1, const GenericMatrix<__Elem> &m2)
{
if (!GenericMatrix<__Elem>::isHomomorphic(m1, m2))
throw std::invalid_argument("invalid argument.");
using size_type = typename GenericMatrix<__Elem>::size_type;
GenericMatrix<__Elem> result(m1.m_rows, m1.m_cols);
for (size_type i = 0; i < result.size(); ++i) {
result.m_data[i] = m1.m_data[i] - m2.m_data[i];
}
return result;
}
/*!
\relates GenericMatrix
Returns the product of the \c M1xNN matrix \a m1 and the \c NNxM2 matrix \a m2
to produce a \c M1xM2 matrix result.
\exception std::invalid_argument if \a m1's columns is not equal to matrix \a m2's rows.
*/
template<typename __Elem>
GenericMatrix<__Elem> operator*(const GenericMatrix<__Elem> &m1, const GenericMatrix<__Elem> &m2)
{
if (m1.m_cols != m2.m_rows)
throw std::invalid_argument("invalid argument.");
using size_type = typename GenericMatrix<__Elem>::size_type;
GenericMatrix<__Elem> result(m1.m_rows, m2.m_cols, 0);
for (size_type i = 0; i < result.m_rows; ++i) {
for (size_type j = 0; j < result.m_cols; ++j) {
for (size_type k = 0; k < m1.m_cols; ++k) {
result(i, j) += m1(i, k) * m2(k, j);
}
}
}
return result;
}
/*!
\relates GenericMatrix
Returns the result of multiplying all elements of \a matrix by \a factor.
*/
template<typename __Elem>
GenericMatrix<__Elem> operator*(const GenericMatrix<__Elem> &matrix, const __Elem &factor)
{
using size_type = typename GenericMatrix<__Elem>::size_type;
GenericMatrix<__Elem> result(matrix.m_rows, matrix.m_cols);
for (size_type i = 0; i < matrix.size(); ++i) {
result.m_data[i] = matrix.m_data[i] * factor;
}
return result;
}
/*!
\relates GenericMatrix
Returns the result of multiplying all elements of \a matrix by \a factor.
*/
template<typename __Elem>
GenericMatrix<__Elem> operator*(const __Elem &factor, const GenericMatrix<__Elem> &matrix)
{
using size_type = typename GenericMatrix<__Elem>::size_type;
GenericMatrix<__Elem> result(matrix.m_rows, matrix.m_cols);
for (size_type i = 0; i < matrix.size(); ++i) {
result.m_data[i] = matrix.m_data[i] * factor;
}
return result;
}
/*!
\relates GenericMatrix
Returns the result of dividing all elements of \a matrix by \a divisor.
*/
template<typename __Elem>
GenericMatrix<__Elem> operator/(const GenericMatrix<__Elem> &matrix, const __Elem &divisor)
{
using size_type = typename GenericMatrix<__Elem>::size_type;
GenericMatrix<__Elem> result(matrix.m_rows, matrix.m_cols);
for (size_type i = 0; i < matrix.size(); ++i) {
result.m_data[i] = matrix.m_data[i] / divisor;
}
return result;
}
/*!
\relates GenericMatrix
Returns the negation of \a matrix.
*/
template<typename __Elem>
GenericMatrix<__Elem> operator-(const GenericMatrix<__Elem> &matrix)
{
using size_type = typename GenericMatrix<__Elem>::size_type;
GenericMatrix<__Elem> result(matrix.m_rows, matrix.m_cols);
for (size_type i = 0; i < matrix.size(); ++i) {
result.m_data[i] = -matrix.m_data[i];
}
return result;
}
/*!
\relates GenericMatrix
Writes the given \a matrix to the given \a stream and returns a
reference to the stream.
*/
template<typename __Elem>
std::ostream &operator<<(std::ostream &stream, const GenericMatrix<__Elem> &matrix)
{
using size_type = typename GenericMatrix<__Elem>::size_type;
stream << "GenericMatrix<" << matrix.m_rows << ", " << matrix.m_cols << ", " << typeid(__Elem).name() << ">(" << std::endl;
for (size_type i = 0; i < matrix.m_rows; ++i) {
for (size_type j = 0; j < matrix.m_cols; ++j) {
stream << stream.width(10) << matrix(i, j);
}
stream << std::endl;
}
stream << ')';
return stream;
}
#endif // __GERNERICMATRIX_H__
| 27.159394 | 127 | 0.661246 | [
"object"
] |
4b0a61a83dabd517f1a22e9e09204ebf1baf800d | 2,331 | h | C | Source/GeneratedFiles/ui_mainwindow.h | alexmohr/VolumePopup | f0b36923813e26d64c7b00d33c7503d3b16d90be | [
"WTFPL"
] | null | null | null | Source/GeneratedFiles/ui_mainwindow.h | alexmohr/VolumePopup | f0b36923813e26d64c7b00d33c7503d3b16d90be | [
"WTFPL"
] | 1 | 2015-07-19T13:10:14.000Z | 2015-07-20T16:42:37.000Z | Source/GeneratedFiles/ui_mainwindow.h | alexmohr/VolumePopup | f0b36923813e26d64c7b00d33c7503d3b16d90be | [
"WTFPL"
] | null | null | null | /********************************************************************************
** Form generated from reading UI file 'mainwindow.ui'
**
** Created by: Qt User Interface Compiler version 5.5.0
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_MAINWINDOW_H
#define UI_MAINWINDOW_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QProgressBar>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_MainWindow
{
public:
QWidget *centralWidget;
QLabel *label;
QProgressBar *progressBar;
void setupUi(QMainWindow *MainWindow)
{
if (MainWindow->objectName().isEmpty())
MainWindow->setObjectName(QStringLiteral("MainWindow"));
MainWindow->resize(526, 362);
MainWindow->setStyleSheet(QStringLiteral(""));
centralWidget = new QWidget(MainWindow);
centralWidget->setObjectName(QStringLiteral("centralWidget"));
label = new QLabel(centralWidget);
label->setObjectName(QStringLiteral("label"));
label->setGeometry(QRect(110, 70, 47, 13));
progressBar = new QProgressBar(centralWidget);
progressBar->setObjectName(QStringLiteral("progressBar"));
progressBar->setGeometry(QRect(90, 230, 118, 23));
progressBar->setStyleSheet(QLatin1String("QProgressBar {\n"
" border: 2px solid grey;\n"
" border-radius: 5px;\n"
"}\n"
"\n"
"QProgressBar::chunk {\n"
" background-color: white;\n"
" width: 1px;\n"
"}"));
progressBar->setValue(24);
MainWindow->setCentralWidget(centralWidget);
retranslateUi(MainWindow);
QMetaObject::connectSlotsByName(MainWindow);
} // setupUi
void retranslateUi(QMainWindow *MainWindow)
{
MainWindow->setWindowTitle(QApplication::translate("MainWindow", "MainWindow", 0));
label->setText(QApplication::translate("MainWindow", "TextLabel", 0));
} // retranslateUi
};
namespace Ui {
class MainWindow: public Ui_MainWindow {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_MAINWINDOW_H
| 30.272727 | 91 | 0.647362 | [
"solid"
] |
4b0eb09a7d0c7cb910e3af24c295635cb3aafc30 | 6,349 | h | C | FDPS-5.0g/src/particle_mesh/param.h | subarutaro/GPLUM | 89b1dadb08a0c6adcdc48879ddf2b7b0fb02912f | [
"MIT"
] | 77 | 2015-02-12T02:35:40.000Z | 2022-03-11T01:10:31.000Z | FDPS-5.0g/src/particle_mesh/param.h | subarutaro/GPLUM | 89b1dadb08a0c6adcdc48879ddf2b7b0fb02912f | [
"MIT"
] | 9 | 2015-03-24T09:44:29.000Z | 2021-11-30T19:42:58.000Z | FDPS-5.0g/src/particle_mesh/param.h | subarutaro/GPLUM | 89b1dadb08a0c6adcdc48879ddf2b7b0fb02912f | [
"MIT"
] | 28 | 2015-03-17T06:58:09.000Z | 2022-02-14T07:16:25.000Z | #ifndef __PPPM__
#define __PPPM__
#include "openmp_param.h"
#include "gadget_param.h"
// A. Tanikawa add this.
#include "param_fdps.h"
namespace ParticleSimulator{
namespace ParticleMesh{
typedef const char *const cchar;
/* Run ---------------------------------------------------------- */
//const int MAX_STEPS = 100000000; /* max steps for calculation */
const int MAX_STEPS = 0; /* max steps for calculation */
const double MAX_CPUTIME = 1e30; /* max cputime (second)*/
//const double Z_FIN = 0.0;
const double Z_FIN = 1e30;
cchar MODEL="Test";
cchar SNAPSHOT="Snapshot";
/* Tree ---------------------------------------------------------- */
const int NJMAX = 130000; /* j-particle buffer size (g5_get_jmemsize) */
const double Z_SWITCH_THETA = 5.0; /* redshift to switch opening angle */
#if 1
const double THETA_HIGHZ = 0.5; /* opening angle at high z*/
const double THETA = 0.5; /* opening angle */
#else
const double THETA_HIGHZ = 0.0; /* opening angle at high z*/
const double THETA = 0.0; /* opening angle */
#endif
const int NCRIT = 300; /* critical number of particles to share interaction list */
const int NLEAF = 10; /* minimum number of particle not to divide tree further */
// A. Tanikawa comments out this.
const double CUTOFF_RADIUS = 3.0;
/* Timestep ------------------------------------------------ */
const double Z_SWITCH_ETA = 0.0;
const double ETA_HIGHZ = 0.3; /* accuracy parameter */
const double ETA_TIMESTEP = 0.3; /* accuracy parameter */
const double MAX_DLOGA = 0.03;
const double constant_timestep = 5e-3;
/* Softening ------------------------------------------------ */
const double CONST_Z_VALUE = 0.0; /* redshift to switch softening shape */
/* load balance ----------------------------------------------------------------------- */
const int LOADBALANCE_METHOD = 1; /* 0:interaction 1:pp+pm 2:n 3:1+lowerlimit 4:pp*/
const double SAMPLING_LOWER_LIMIT_FACTOR = 1.2;
const int NRATE_EXCHANGE = 2500; /* sampling interval to decide area of each domain */
const int SORT_STEP = 10; /* step interval to sort particle using morton ordering */
const int nstep_smoothing_boundary = 5;
const int nstep_decompose_x = 3;
/* IO --------------------------------------------------------------------------*/
const int NUMBER_OF_COMM_PER_ALLTOALLV_FOR_INPUT_IC = 16;
const int LOADBALANCELOG_ON = 0;
const int BOUNDARYLOG_ON = 0;
cchar STOPFILE = "stop";
const int fmerge = 2;
cchar DUMPDIR = "Dump";
cchar DUMPDIR0 = "Dump0"; // for initial dump;
cchar DUMPFILE = "dump";
const int ONELOGFLAG = 1; /* 0: each node outputs log 1: root node outputs log */
const int IO_CACHE_SIZE = 2097152; /* cache number of io (*3) */
/* Buffer ---------------------------------------------------------- */
const int CHARMAX = 256;
const int MAXNNODE = 16384;
const int MAXNNODE3 = MAXNNODE*3;
const int NXMAX = 100;
const int NSAMPMAX = 30000000;
const int bufsize_largemem0 = 10000000;
const int bufsize_largemem = 10000000;
/* PM ---------------------------------------------------------- */
const int _ndiv_fft[3] = {2, 4, 2};
const int _pm_reduce_nx = 1;
const int _pm_reduce_ny = 2;
const int _pm_reduce_nz = 1;
const int _flag_wisdom = 0;
cchar FFTW_WISDOM_FILENAME_F = "wisdom_f";
cchar FFTW_WISDOM_FILENAME_B = "wisdom_b";
const int PMLOG_ON = 0;
cchar PMLOG = "pm.log";
#ifdef FFT3D
#ifndef RMM_PM
#error
#endif
#ifndef FIX_FFTNODE
#error
#endif
#endif
/* Misc ---------------------------------------------------------- */
#define NOACC /* debug */
// A. Tanikawa comments out this.
//#define UNIFORM /* uniform mass mode */
/*cannot use multi mass mode in the case of n>2^31 */
#define LONG_ID
#define IDTYPE long long int
#define MPI_IDTYPE MPI_LONG_LONG_INT
cchar TORUSINFOFILE = "torus.dat";
#ifdef TREE2
#ifndef TREE_PARTICLE_CACHE
#error
#endif
#endif
/* on the fly analysis ---------------------------------------------------------- */
cchar IMAGEDIR = "Image"; /* relative path of image directory */
cchar NEWEST_IMAGEFILE = "newest.bmp";
const int IMAGESTEP = 32; /* step interval to output image (0:no output image) */
const int IMAGEWIDTH = 768; /* image width (px) */
const int IMAGEHEIGHT= 768; /* image height (px) */
const double IMAGEFACA = 1.098612; /* luminosity = s*(density-a) + b */
const double IMAGEFACB = 0.0;
const double IMAGEFACS = 22.77958;
const int COLORMAP = 0; /* others:gray 1:blue 2:red */
/* NUMBER_OF_PART_ALL -> number of particle of system */
/* NUMBER_OF_PART -> cache number to allocate particle array */
/* SIZE_OF_MESH -> number of mesh of pm part (2*NUMBER_OF_PART**(1/3))*/
/* SFT_FOR_PP -> softening parameter (ref evolve.c:get_eps) (1.0/(10*NUMBER_OF_PART**(1/3))) */
// A. Tanikawa defines this.
#define N32_2H
#ifdef N32_2H
#define NUMBER_OF_PART_ALL (32768)
#define NUMBER_OF_PART (32768)
// A. Tanikawa comments out this.
//#define SIZE_OF_MESH (16)
#define SFT_FOR_PP (2.5e-4)
#endif
#ifdef N128_2H
#define NUMBER_OF_PART_ALL (2097152)
#define NUMBER_OF_PART (2097152)
#define SIZE_OF_MESH (64)
#define SFT_FOR_PP (2.5e-4)
#endif
#ifdef N256_H
#define NUMBER_OF_PART_ALL (16777216)
#define NUMBER_OF_PART (16777216)
#define SIZE_OF_MESH (256)
#define SFT_FOR_PP (2.5e-4)
#endif
#ifdef N256_2H
#define NUMBER_OF_PART_ALL (16777216)
#define NUMBER_OF_PART (16777216)
#define SIZE_OF_MESH (128)
#define SFT_FOR_PP (2.5e-4)
#endif
#ifdef N512_2H
#define NUMBER_OF_PART_ALL (134217728)
#define NUMBER_OF_PART (20000000)
#define SIZE_OF_MESH (256)
#define SFT_FOR_PP (6.25e-5)
#endif
#define SIZE_OF_MESH_P2 (SIZE_OF_MESH+2)
#define SIZE_OF_GREEN (SIZE_OF_MESH/2+1)
#define SFT_FOR_PM (CUTOFF_RADIUS/SIZE_OF_MESH)
#define RADIUS_FOR_PP (SFT_FOR_PM)
#define RADIUS_FOR_PP2 (RADIUS_FOR_PP*RADIUS_FOR_PP)
#define _MIN_(a,b) ( ((a)<(b)) ? (a) : (b) )
#define _MAX_(a,b) ( ((a)>(b)) ? (a) : (b) )
const static long long int nleafmax =
(long long int)NUMBER_OF_PART * (long long int)NLEAF / (long long int)NLEAF_PARALLEL_TREE_CONSTRUCTION;
} // namespace ParticleMesh
} // namespace ParticleSimulator
#endif /* __PPPM__ */
| 30.233333 | 105 | 0.621358 | [
"mesh",
"shape",
"model"
] |
4b109d06b10269096ecd115363124732659ae1dd | 4,890 | c | C | ext/test/properties/staticprotectedproperties.zep.c | yejune/zephir | d6070c2ebd8d7bea319671bec978b55ffb96f395 | [
"MIT"
] | null | null | null | ext/test/properties/staticprotectedproperties.zep.c | yejune/zephir | d6070c2ebd8d7bea319671bec978b55ffb96f395 | [
"MIT"
] | 1 | 2019-10-08T02:14:55.000Z | 2019-10-08T02:14:55.000Z | ext/test/properties/staticprotectedproperties.zep.c | yejune/zephir | d6070c2ebd8d7bea319671bec978b55ffb96f395 | [
"MIT"
] | 3 | 2019-05-17T19:26:59.000Z | 2020-11-08T07:49:34.000Z |
#ifdef HAVE_CONFIG_H
#include "../../ext_config.h"
#endif
#include <php.h>
#include "../../php_ext.h"
#include "../../ext.h"
#include <Zend/zend_operators.h>
#include <Zend/zend_exceptions.h>
#include <Zend/zend_interfaces.h>
#include "kernel/main.h"
#include "kernel/object.h"
#include "kernel/memory.h"
ZEPHIR_INIT_CLASS(Test_Properties_StaticProtectedProperties) {
ZEPHIR_REGISTER_CLASS(Test\\Properties, StaticProtectedProperties, test, properties_staticprotectedproperties, test_properties_staticprotectedproperties_method_entry, 0);
/**
* This is a protected property with no initial value
*/
zend_declare_property_null(test_properties_staticprotectedproperties_ce, SL("someNull"), ZEND_ACC_PROTECTED|ZEND_ACC_STATIC);
/**
* This is a protected property with initial null value
*/
zend_declare_property_null(test_properties_staticprotectedproperties_ce, SL("someNullInitial"), ZEND_ACC_PROTECTED|ZEND_ACC_STATIC);
/**
* This is a protected property with initial boolean false
*/
zend_declare_property_bool(test_properties_staticprotectedproperties_ce, SL("someFalse"), 0, ZEND_ACC_PROTECTED|ZEND_ACC_STATIC);
/**
* This is a protected property with initial boolean true
*/
zend_declare_property_bool(test_properties_staticprotectedproperties_ce, SL("someTrue"), 1, ZEND_ACC_PROTECTED|ZEND_ACC_STATIC);
/**
* This is a protected property with an initial integer value
*/
zend_declare_property_long(test_properties_staticprotectedproperties_ce, SL("someInteger"), 10, ZEND_ACC_PROTECTED|ZEND_ACC_STATIC);
/**
* This is a protected property with an initial double value
*/
zend_declare_property_double(test_properties_staticprotectedproperties_ce, SL("someDouble"), 10.25, ZEND_ACC_PROTECTED|ZEND_ACC_STATIC);
/**
* This is a protected property with an initial string value
*/
zend_declare_property_string(test_properties_staticprotectedproperties_ce, SL("someString"), "test", ZEND_ACC_PROTECTED|ZEND_ACC_STATIC);
zend_declare_property_null(test_properties_staticprotectedproperties_ce, SL("someVar"), ZEND_ACC_PROTECTED|ZEND_ACC_STATIC);
return SUCCESS;
}
PHP_METHOD(Test_Properties_StaticProtectedProperties, setSomeVar) {
zval *someVar, someVar_sub;
zval *this_ptr = getThis();
ZVAL_UNDEF(&someVar_sub);
zephir_fetch_params_without_memory_grow(1, 0, &someVar);
zephir_update_property_zval(this_ptr, SL("someVar"), someVar);
RETURN_THISW();
}
PHP_METHOD(Test_Properties_StaticProtectedProperties, getSomeVar) {
zval *this_ptr = getThis();
RETURN_MEMBER(getThis(), "someVar");
}
PHP_METHOD(Test_Properties_StaticProtectedProperties, getSomeNull) {
zval _0;
zval *this_ptr = getThis();
ZVAL_UNDEF(&_0);
zephir_read_static_property_ce(&_0, test_properties_staticprotectedproperties_ce, SL("someNull"), PH_NOISY_CC | PH_READONLY);
RETURN_CTORW(&_0);
}
PHP_METHOD(Test_Properties_StaticProtectedProperties, setSomeNull) {
zval *param, param_sub;
zval *this_ptr = getThis();
ZVAL_UNDEF(¶m_sub);
zephir_fetch_params_without_memory_grow(1, 0, ¶m);
zephir_update_static_property_ce(test_properties_staticprotectedproperties_ce, ZEND_STRL("someNull"), param);
}
PHP_METHOD(Test_Properties_StaticProtectedProperties, getSomeNullInitial) {
zval _0;
zval *this_ptr = getThis();
ZVAL_UNDEF(&_0);
zephir_read_static_property_ce(&_0, test_properties_staticprotectedproperties_ce, SL("someNullInitial"), PH_NOISY_CC | PH_READONLY);
RETURN_CTORW(&_0);
}
PHP_METHOD(Test_Properties_StaticProtectedProperties, getSomeFalse) {
zval _0;
zval *this_ptr = getThis();
ZVAL_UNDEF(&_0);
zephir_read_static_property_ce(&_0, test_properties_staticprotectedproperties_ce, SL("someFalse"), PH_NOISY_CC | PH_READONLY);
RETURN_CTORW(&_0);
}
PHP_METHOD(Test_Properties_StaticProtectedProperties, getSomeTrue) {
zval _0;
zval *this_ptr = getThis();
ZVAL_UNDEF(&_0);
zephir_read_static_property_ce(&_0, test_properties_staticprotectedproperties_ce, SL("someTrue"), PH_NOISY_CC | PH_READONLY);
RETURN_CTORW(&_0);
}
PHP_METHOD(Test_Properties_StaticProtectedProperties, getSomeInteger) {
zval _0;
zval *this_ptr = getThis();
ZVAL_UNDEF(&_0);
zephir_read_static_property_ce(&_0, test_properties_staticprotectedproperties_ce, SL("someInteger"), PH_NOISY_CC | PH_READONLY);
RETURN_CTORW(&_0);
}
PHP_METHOD(Test_Properties_StaticProtectedProperties, getSomeDouble) {
zval _0;
zval *this_ptr = getThis();
ZVAL_UNDEF(&_0);
zephir_read_static_property_ce(&_0, test_properties_staticprotectedproperties_ce, SL("someDouble"), PH_NOISY_CC | PH_READONLY);
RETURN_CTORW(&_0);
}
PHP_METHOD(Test_Properties_StaticProtectedProperties, getSomeString) {
zval _0;
zval *this_ptr = getThis();
ZVAL_UNDEF(&_0);
zephir_read_static_property_ce(&_0, test_properties_staticprotectedproperties_ce, SL("someString"), PH_NOISY_CC | PH_READONLY);
RETURN_CTORW(&_0);
}
| 25.076923 | 171 | 0.793456 | [
"object"
] |
4b1fa54105ca910fddc0a2a27078aa3363406446 | 19,098 | h | C | Examples/include/asposecpplib/drawing/image.h | kashifiqb/Aspose.PDF-for-C | 13d49bba591c5704685820185741e64a462a5bdc | [
"MIT"
] | null | null | null | Examples/include/asposecpplib/drawing/image.h | kashifiqb/Aspose.PDF-for-C | 13d49bba591c5704685820185741e64a462a5bdc | [
"MIT"
] | null | null | null | Examples/include/asposecpplib/drawing/image.h | kashifiqb/Aspose.PDF-for-C | 13d49bba591c5704685820185741e64a462a5bdc | [
"MIT"
] | null | null | null | /// @file drawing/image.h
#ifndef _aspose_system_drawing_image_h_
#define _aspose_system_drawing_image_h_
#include "system/object.h"
#include "system/nullable.h"
#include "drawing/imaging/image_attributes.h"
#include "drawing/imaging/image_format.h"
#include "drawing/imaging/image_codec_info.h"
#include "drawing/imaging/encoder_parameters.h"
#include "drawing/imaging/encoder_value.h"
#include "drawing/imaging/pixel_format.h"
#include "drawing/imaging/color_palette.h"
#include "drawing/imaging/frame_dimension.h"
#include "drawing/rotate_flip_type.h"
#include "drawing/graphics_unit.h"
#include "drawing/size.h"
#include "drawing/rectangle_f.h"
#include "system/io/stream.h"
#include "system/string.h"
#include "imaging/image_flags.h"
// skia headers and forwards
#if defined(ASPOSECPP_SHARED_EXPORTS) || defined(ASPOSECPP_SKIA_EXTERNAL_USAGE)
#include <core/SkImage.h>
#include <core/SkData.h>
#include <codec/SkEncodedFormat.h>
#endif
#define ASPOSE_DUMMY_META_FILE
/// Forward declaration of SkBitmap class.
ASPOSECPP_3RD_PARTY_CLASS(SkBitmap);
/// Forward declaration of SkCanvas class.
ASPOSECPP_3RD_PARTY_CLASS(SkCanvas);
/// Forward declaration of SkData class.
ASPOSECPP_3RD_PARTY_CLASS(SkData);
/// Forward declaration of SkMatrix class.
ASPOSECPP_3RD_PARTY_CLASS(SkMatrix);
/// Forward declaration of SkImageEncoder class.
ASPOSECPP_3RD_PARTY_CLASS(SkImageEncoder);
/// Forward declaration of SkRWStream class.
ASPOSECPP_3RD_PARTY_CLASS(SkRWStream);
/// Static checks of SkEncodedFormat enum.
ASPOSECPP_3RD_PARTY_STRUCT(SkImageInfo);
/// Forward declaration of SkRect struct.
ASPOSECPP_3RD_PARTY_STRUCT(SkRect);
/// Forward declaration of SkFilterQuality enum.
#if defined(ASPOSECPP_SHARED_EXPORTS) || !defined(ASPOSECPP_SKIA_EXTERNAL_USAGE)
ASPOSECPP_3RD_PARTY_ENUM(SkEncodedFormat);
/// Forward declaration of SkImageInfo struct.
ASPOSECPP_3RD_PARTY_ENUM(SkFilterQuality);
/// Forward declaration of SkBlendMode enum.
ASPOSECPP_3RD_PARTY_ENUM_CLASS(SkBlendMode);
#endif
template <typename T> class sk_sp;
namespace System { namespace Drawing {
class Bitmap;
class TextureBrush;
/// A base class for System::Drawing::Bitmap and System::Drawing::Metafile classes providing basic functionality.
/// Objects of this class should only be allocated using System::MakeObject() function.
/// Never create instance of this type on stack or using operator new, as it will result in runtime errors and/or assertion faults.
/// Always wrap this class into System::SmartPtr pointer and use this pointer to pass it to functions as argument.
class ASPOSECPP_SHARED_CLASS Image: virtual public Object
{
RTTI_INFO(System::Drawing::Image, ::System::BaseTypesInfo<System::Object>)
public:
/// Saves the image represented by the current object to the specified file in PNG format.
/// @param filename The name of the file to save the image to
ASPOSECPP_SHARED_API void Save(const String & filename);
/// Saves the image represented by the current object to the specified file in the specified format.
/// @param filename The name of the file to save the image to
/// @param format A format to save the image in
ASPOSECPP_SHARED_API void Save(const String & filename, const Imaging::ImageFormatPtr& format);
/// Saves the image represented by the current object to the specified stream in the specified format.
/// @param stream A stream to save the image to
/// @param format A format to save the image in
ASPOSECPP_SHARED_API void Save(const SharedPtr<System::IO::Stream>& stream, const Imaging::ImageFormatPtr& format);
/// Saves the image represented by the current object to the specified file using the specified encoder and encoder parameters.
/// @param filename The name of the file to save the image to
/// @param encoder The encoder to use
/// @param encoder_params The parameters of the encoder to use
ASPOSECPP_SHARED_API void Save(const String & filename, const Imaging::ImageCodecInfoPtr& encoder, const Imaging::EncoderParametersPtr& encoder_params);
/// Saves the image represented by the current object to the specified stream using the specified encoder and encoder parameters.
/// @param stream A stream to save the image to
/// @param encoder The encoder to use
/// @param encoder_params The parameters of the encoder to used
ASPOSECPP_SHARED_API void Save(const SharedPtr<System::IO::Stream>& stream, const Imaging::ImageCodecInfoPtr& encoder, const Imaging::EncoderParametersPtr& encoder_params);
/// Adds a frame to the file or stream specified in a previous call to the Save() method.
/// @param encoder_params The parameters of the encoder to use
ASPOSECPP_SHARED_API void SaveAdd(const Imaging::EncoderParametersPtr& encoder_params);
/// Adds a frame to the file or stream specified in a previous call to the Save() method.
/// @param image An Image object that contains the frame to be added
/// @param encoder_params The parameters of the encoder to use
ASPOSECPP_SHARED_API void SaveAdd(const SharedPtr<Image>& image, const Imaging::EncoderParametersPtr& encoder_params);
/// Creates a copy of the current object.
/// @returns A copy of the current object.
virtual ASPOSECPP_SHARED_API SharedPtr<Image> Clone() = 0;
/// Rotate image to multiple of 90 degrees and flip.
/// @param rotate_flip_type Type of rotation and flip.
virtual ASPOSECPP_SHARED_API void RotateFlip(RotateFlipType rotate_flip_type);
/// Returns the image bounds in the specified measurement units.
/// @param page_unit Measurement unit
/// @returns An instance of RectangleF class that represents the image bound in the specified
/// measurement units
ASPOSECPP_SHARED_API RectangleF GetBounds(GraphicsUnit & page_unit);
/// Returns the width of the image in pixels.
virtual ASPOSECPP_SHARED_API int get_Width() const = 0;
/// Returns the height of the image in pixels.
virtual ASPOSECPP_SHARED_API int get_Height() const = 0;
/// Returns a bit-wise combination of ImageFlags enum values that represents the attributes
/// of the image.
virtual Imaging::ImageFlags get_Flags() const
{
throw System::NotImplementedException(ASPOSE_CURRENT_FUNCTION);
}
/// Returns a Size object that represents the width and height of the image
/// in pixels.
ASPOSECPP_SHARED_API Size get_Size() const;
/// Returns the file format of the image represented by the current object.
virtual ASPOSECPP_SHARED_API Imaging::ImageFormatPtr get_RawFormat() const = 0;
/// Returns the pixel format of the image represented by the current object.
virtual ASPOSECPP_SHARED_API Imaging::PixelFormat get_PixelFormat() const = 0;
/// Returns the horizontal resolution of the image represented by the current object in pixels per inch.
ASPOSECPP_SHARED_API float get_HorizontalResolution() const;
/// Returns the vertical resolution of the image represented by the current object in pixels per inch.
ASPOSECPP_SHARED_API float get_VerticalResolution() const;
/// Returns the color palette used by the image represented by the current object.
virtual ASPOSECPP_SHARED_API Imaging::ColorPalettePtr get_Palette() const;
/// Sets the color palette used by the image represented by the current object.
/// @param value The value to set
virtual ASPOSECPP_SHARED_API void set_Palette(Imaging::ColorPalettePtr value);
/// Returns whether the original format is a multi-image.
virtual ASPOSECPP_SHARED_API bool IsMultiImage() const;
/// Returns an array of GUIDs that represent the dimensions of frames within the image
/// represented by the current object.
ASPOSECPP_SHARED_API ArrayPtr<Guid> get_FrameDimensionsList() const;
/// Returns the number of frames of the specified frame dimension.
/// @param dimension A frame dimension
/// @returns The number of frames of the @p dimension frame dimension.
ASPOSECPP_SHARED_API int GetFrameCount(const Imaging::FrameDimensionPtr& dimension);
/// Selects the specified frame.
/// @param dimension The dimension of the frame to select
/// @param frameIndex The index of the frame to select
/// returns Always 0
ASPOSECPP_SHARED_API int SelectActiveFrame(const Imaging::FrameDimensionPtr& dimension, int frameIndex);
/// Creates an Image object from the specified stream.
/// @param stream A stream that contains image data
/// @param use_embedded_color_management IGNORED
/// @param validate_image_data IGNORED
/// @returns A shared pointer to the created Image object.
static ASPOSECPP_SHARED_API SharedPtr<Image> FromStream(const SharedPtr<System::IO::Stream>& stream, bool use_embedded_color_management = false, bool validate_image_data = true);
/// Creates an Image object from the specified file.
/// @param filename A name of the file that contains image data
/// @param use_embedded_color_management IGNORED
/// @returns A shared pointer to the created Image object.
static ASPOSECPP_SHARED_API SharedPtr<Image> FromFile(const String & filename, bool use_embedded_color_management = false);
/// Determines if the specified pixel format contains alpha information.
/// @param pixfmt A pixel format to test
/// @returns True if @p pixfmt contains alpha information, otherwise - false
static ASPOSECPP_SHARED_API bool IsAlphaPixelFormat(Imaging::PixelFormat pixfmt);
/// Returns the number of bits used to represent the color depth in the specified pixel format.
/// @param pixfmt A pixel format for which to determine the size
/// @returns The color depth in @p pixfmt
static ASPOSECPP_SHARED_API int GetPixelFormatSize(Imaging::PixelFormat pixfmt);
/// Constructs a Bitmap object from the specified GDI bitmap.
/// @param hbitmap A handle to a GDI bitmap from which to create a Bitmap object
/// @returns A shared pointer to the created Bitmap object
static ASPOSECPP_SHARED_API SharedPtr<Bitmap> FromHbitmap(IntPtr hbitmap);
/// Releases all resources aquired by the current object.
void Dispose() { };
/// Returns an underlying SkBitmap object.
virtual ASPOSECPP_SHARED_API const SkBitmap* GetSkBitmap() const = 0;
protected:
/// Default quality level used when encoding an image.
static const int s_default_save_quality = 80;
friend class Graphics;
friend class TextureBrush;
friend class Bitmap;
/// Structure that represents save options
struct SaveOptions
{
/// The quality level used when encoding an image.
Nullable<int> Quality;
/// Specifies the parameter value passed to a JPEG or TIFF image encoder.
Nullable<Imaging::EncoderValue> Flag;
};
/// Converts a set of encoder parameters into a SaveOptions structure
/// @param encoder_params The parameters of the encoder
static SaveOptions ParseEncoderParameters(const Imaging::EncoderParametersPtr& encoder_params);
/// Returns the drawing canvas object.
virtual ASPOSECPP_SHARED_API SkCanvas * GetDrawingCanvas() const = 0;
/// Saves an image represented by the current object in the specified format using the specified
/// image quality level setting when encoding the image to the momory buffer.
/// @param encoder_type The image format to save the image in
/// @param quality The quality level setting used when encoding the image
/// @returns An SkData object that represents a memory buffer to which the image was saved
virtual ASPOSECPP_SHARED_API sk_sp<SkData> GetRawBytes(SkEncodedFormat encoder_type, int quality) = 0;
/// Saves the image represented by the current object to the specified stream in the specified format.
/// @param stream A stream to save the image to
/// @param encoder_type A format to save the image in
/// @param quality The quality to save the image in; is used only if @p encoder_type format supports this setting
ASPOSECPP_SHARED_API void InternalSave(const SharedPtr<System::IO::Stream>& stream, SkEncodedFormat encoder_type, int quality = s_default_save_quality);
/// Saves the image represented by the current object to the specified stream in the specified format.
/// @param stream A stream to save the image to
/// @param encoder_type A format to save the image in
/// @param options The options used to save the image in; is used only if @p encoder_type format supports this options
void InternalSave(const SharedPtr<IO::Stream>& stream, SkEncodedFormat encoder_type, const SaveOptions& options);
/// Saves the bitmap as a part of a multipage image
/// @param bitmap The bitmap to save
/// @param options The options used to save the bitmap
void InternalSavePage(const SkBitmap* bitmap, const SaveOptions& options);
/// Checks if the specified image format is supported and returns a SkEncodedFormat value that represents the specified image format.
/// @param image_format The format to check
/// @returns A value of SkEncodedFormat that specifies the same image format as @p image_format specifies
/// @throws System::Runtime::InteropServices::ExternalException If the specified format is not supported
ASPOSECPP_SHARED_API SkEncodedFormat CheckOutputFormat(const Imaging::ImageFormatPtr& image_format) const;
/// Checks if the specified encoder is supported and returns a SkEncodedFormat value that represents an image format of the specified encoder.
/// @param encoder The ImageCodecInfo object that represents the encoder to check
/// @returns A SkEncodedFormat value that represents @p encoder's image format
/// @throws System::Runtime::InteropServices::ExternalException If the specified encoder is not supported
static ASPOSECPP_SHARED_API SkEncodedFormat CheckOutputFormat(const Imaging::ImageCodecInfoPtr& encoder);
/// Checks if the specified format is among supported.
/// @param encoded_format The format to check
/// @returns A copy of @p encoded_format value if it is among supported formats
/// @throws System::Runtime::InteropServices::ExternalException If the specified format is not supported
static ASPOSECPP_SHARED_API SkEncodedFormat CheckOutputFormat(SkEncodedFormat encoded_format);
/// Returns an underlying SkEncodedFormat object.
virtual ASPOSECPP_SHARED_API const SkEncodedFormat GetSkEncodedFormat() const = 0;
/// Returns the original image format.
virtual ASPOSECPP_SHARED_API Imaging::PixelFormat GetOriginalFormat() const = 0;
/// Draws the specified region of the image to the specified region on the specified canvas.
/// The source bitmap region is scaled and translated to fill the destination region.
/// @param sk_canvas The canvas to draw on
/// @param dest_rect The rectangle on the canvas to draw to
/// @param src_rect The rectangle specifying the portion of the image to draw
/// @param matrix The matrix that specifies how to traslate and scale the source image region
/// @param quality The quality of image interpolation
/// @param blend_mode Specifies how the source colors are combined with the background colors
virtual void Draw(SkCanvas* sk_canvas, const SkRect& dest_rect, const SkRect&src_rect, SkMatrix* matrix, SkFilterQuality quality, SkBlendMode blend_mode) const = 0;
/// Draws the the image to the specified region on the specified canvas.
/// The source image is scaled and translated to fill the destination region.
/// @param sk_canvas The canvas to draw on
/// @param dest_rect The rectangle in the canvas to draw to
/// @param matrix The matrix that specifies how to traslate and scale the source image region
/// @param quality The quality of image interpolation
/// @param blend_mode Specifies how the source colors are combined with the background colors
virtual void Draw(SkCanvas* sk_canvas, const SkRect& dest_rect, SkMatrix* matrix, SkFilterQuality quality, SkBlendMode blend_mode) const = 0;
/// Draws the specified region of the image to the specified region on the specified canvas.
/// The source bitmap region is scaled and translated to fill the destination region.
/// @param sk_canvas The canvas to draw on
/// @param dest_points Array of 3 PointF objects representing points that define the rectangular region on the canvas to draw to
/// @param src_rect The rectangle specifying the portion of the image to draw
/// @param matrix The matrix that specifies how to traslate and scale the source image region
/// @param quality The quality of image interpolation
/// @param blend_mode Specifies how the source colors are combined with the background colors
virtual void Draw(SkCanvas* sk_canvas, ArrayPtr<PointF> dest_points, const SkRect& src_rect, SkMatrix* matrix, SkFilterQuality quality, SkBlendMode blend_mode) const = 0;
/// Determines if the data in the specified stream starts with the WMF format marker.
/// @param stream The stream containing the data to check
/// @returns True if the data in the @p stream begins with WMF format marker, otherwise - false
static ASPOSECPP_SHARED_API bool IsWmf(const System::SharedPtr<System::IO::Stream>& stream);
/// Determines if the data in the specified stream starts with the EMF format marker.
/// @param stream The stream containing the data to check
/// @returns True if the data in the @p stream begins with EMF format marker, otherwise - false
static ASPOSECPP_SHARED_API bool IsEmf(const System::SharedPtr<System::IO::Stream>& stream);
/// The color palette used by the image represented by the current object.
Imaging::ColorPalettePtr m_palette;
/// The horizontal resolution of the image represented by the current object in pixels per inch.
float m_horizontal_resolution = 96.f; //only default 96dpi is supported
/// The vertical resolution of the image represented by the current object in pixels per inch.
float m_vertical_resolution = 96.f; //only default 96dpi is supported
private:
std::unique_ptr<SkRWStream> m_stream;
std::unique_ptr<SkImageEncoder> m_encoder;
};
}}
#endif
| 61.015974 | 186 | 0.723374 | [
"object"
] |
4b21338e106537544e0f2ab76bb9b79f1a648b79 | 9,434 | h | C | gmm/itkInitializeTransform.h | sMedX/GMMPointSetRegistration | ea9b3a26eaee70ee4692dc26c17d366e8f730ac5 | [
"Apache-2.0"
] | 4 | 2017-07-31T18:57:56.000Z | 2020-09-07T11:13:03.000Z | gmm/itkInitializeTransform.h | sMedX/GMMPointSetRegistration | ea9b3a26eaee70ee4692dc26c17d366e8f730ac5 | [
"Apache-2.0"
] | 2 | 2017-06-17T21:08:22.000Z | 2017-06-29T23:05:50.000Z | gmm/itkInitializeTransform.h | sMedX/GMMPointSetRegistration | ea9b3a26eaee70ee4692dc26c17d366e8f730ac5 | [
"Apache-2.0"
] | 2 | 2020-04-23T06:46:38.000Z | 2021-06-29T10:36:03.000Z | #pragma once
#include <itkObject.h>
#include <itkTranslationTransform.h>
#include <itkVersorRigid3DTransform.h>
#include <itkSimilarity3DTransform.h>
#include <itkScaleSkewVersor3DTransform.h>
namespace itk
{
template<typename TParametersValueType>
class InitializeTransform : public Object
{
public:
/** Standard class typedefs. */
typedef InitializeTransform Self;
typedef Object Superclass;
typedef SmartPointer<Self> Pointer;
typedef SmartPointer<const Self> ConstPointer;
/** Method for creation through the object factory. */
itkNewMacro(Self);
itkTypeMacro(InitializeTransform, Object);
enum class Transform
{
Translation,
Versor3D,
Similarity,
ScaleSkewVersor3D
};
/** typedefs */
itkStaticConstMacro(PointDimension, unsigned int, 3U);
static_assert(PointDimension == 3U, "Invalid dimension. Dimension 3 is supported.");
typedef typename itk::Transform<TParametersValueType, PointDimension> TransformType;
typedef typename TransformType::InputPointType InputPointType;
typedef typename TransformType::OutputPointType OutputPointType;
typedef typename TransformType::OutputVectorType OutputVectorType;
typedef itk::Array<double> ParametersType;
typedef itk::Array<unsigned int> ModeBoundsType;
typedef itk::Array<double> BoundsType;
// Get transform
itkGetObjectMacro(Transform, TransformType);
// Set/Get type of transform
itkSetEnumMacro(TypeOfTransform, Transform);
itkGetEnumMacro(TypeOfTransform, Transform);
void SetTypeOfTransform(const size_t & type) { this->SetTypeOfTransform(static_cast<Transform>(type)); }
itkSetMacro(RotationScale, double);
itkGetMacro(RotationScale, double);
itkSetMacro(TranslationScale, double);
itkGetMacro(TranslationScale, double);
itkSetMacro(ScalingScale, double);
itkGetMacro(ScalingScale, double);
itkSetMacro(SkewScale, double);
itkGetMacro(SkewScale, double);
// Get scales and bounds
itkGetMacro(Scales, ParametersType);
itkGetMacro(ModeBounds, ModeBoundsType);
itkGetMacro(LowerBounds, ParametersType);
itkGetMacro(UpperBounds, ParametersType);
// Set/Get moving and fixed landmarks
itkSetMacro(MovingLandmark, InputPointType);
itkSetMacro(FixedLandmark, OutputPointType);
void Update()
{
m_Center = m_MovingLandmark;
m_Translation = m_FixedLandmark - m_MovingLandmark;
switch (m_TypeOfTransform) {
case Transform::Translation: {
// Translation transform
typedef typename itk::TranslationTransform<TParametersValueType, PointDimension> TranslationTransformType;
typename TranslationTransformType::Pointer transform = TranslationTransformType::New();
transform->Translate(m_Translation);
m_Transform = transform;
this->Allocate();
// define scales
m_NumberOfTranslationComponents = 3;
size_t count = 0;
for (size_t i = 0; i < m_NumberOfTranslationComponents; ++i, ++count) {
m_Scales[count] = m_TranslationScale;
m_ModeBounds[count] = 0;
}
break;
}
case Transform::Versor3D: {
// VersorRigid3DTransform
typedef itk::VersorRigid3DTransform<TParametersValueType> VersorRigid3DTransformType;
typename VersorRigid3DTransformType::Pointer transform = VersorRigid3DTransformType::New();
transform->SetIdentity();
transform->SetCenter(m_Center);
transform->SetTranslation(m_Translation);
m_Transform = transform;
this->Allocate();
// define scales
m_NumberOfRotationComponents = 3;
m_NumberOfTranslationComponents = 3;
size_t count = 0;
for (size_t i = 0; i < m_NumberOfRotationComponents; ++i, ++count) {
m_Scales[count] = m_RotationScale;
m_ModeBounds[count] = 2;
m_LowerBounds[count] = -1;
m_UpperBounds[count] = 1;
}
for (size_t i = 0; i < m_NumberOfTranslationComponents; ++i, ++count) {
m_Scales[count] = m_TranslationScale;
m_ModeBounds[count] = 0;
}
break;
}
case Transform::Similarity:{
// Similarity3DTransform
typedef itk::Similarity3DTransform<TParametersValueType> Similarity3DTransformType;
typename Similarity3DTransformType::Pointer transform = Similarity3DTransformType::New();
transform->SetIdentity();
transform->SetCenter(m_Center);
transform->SetTranslation(m_Translation);
m_Transform = transform;
this->Allocate();
// define scales
m_NumberOfRotationComponents = 3;
m_NumberOfTranslationComponents = 3;
m_NumberOfScalingComponents = 1;
size_t count = 0;
for (size_t i = 0; i < m_NumberOfRotationComponents; ++i, ++count) {
m_Scales[count] = m_RotationScale;
m_ModeBounds[count] = 2;
m_LowerBounds[count] = -1;
m_UpperBounds[count] = 1;
}
for (size_t i = 0; i < m_NumberOfTranslationComponents; ++i, ++count) {
m_Scales[count] = m_TranslationScale;
m_ModeBounds[count] = 0;
}
for (size_t i = 0; i < m_NumberOfScalingComponents; ++i, ++count) {
m_Scales[count] = m_ScalingScale;
m_ModeBounds[count] = 0;
}
break;
}
case Transform::ScaleSkewVersor3D:{
typedef itk::ScaleSkewVersor3DTransform<TParametersValueType> ScaleSkewVersor3DTransformType;
typename ScaleSkewVersor3DTransformType::Pointer transform = ScaleSkewVersor3DTransformType::New();
transform->SetIdentity();
transform->SetCenter(m_Center);
transform->SetTranslation(m_Translation);
m_Transform = transform;
this->Allocate();
// define scales
m_NumberOfRotationComponents = 3;
m_NumberOfTranslationComponents = 3;
m_NumberOfScalingComponents = 3;
m_NumberOfSkewComponents = 6;
size_t count = 0;
for (size_t i = 0; i < m_NumberOfRotationComponents; ++i, ++count) {
m_Scales[count] = m_RotationScale;
m_ModeBounds[count] = 2;
m_LowerBounds[count] = -1;
m_UpperBounds[count] = 1;
}
for (size_t i = 0; i < m_NumberOfTranslationComponents; ++i, ++count) {
m_Scales[count] = m_TranslationScale;
m_ModeBounds[count] = 0;
}
for (size_t i = 0; i < m_NumberOfScalingComponents; ++i, ++count) {
m_Scales[count] = m_ScalingScale;
m_ModeBounds[count] = 0;
}
for (size_t i = 0; i < m_NumberOfSkewComponents; ++i, ++count) {
m_Scales[count] = m_SkewScale;
m_ModeBounds[count] = 0;
}
break;
}
}
}
void PrintReport() const
{
std::cout << this->GetNameOfClass() << std::endl;
std::cout << "spatial transform " << m_Transform->GetTransformTypeAsString() << std::endl;
std::cout << "center " << m_Center << std::endl;
std::cout << "translation " << m_Translation << std::endl;
std::cout << "fixed parameters " << m_Transform->GetFixedParameters() << " " << m_Transform->GetNumberOfFixedParameters() << std::endl;
std::cout << "parameters " << m_Transform->GetParameters() << " " << m_Transform->GetNumberOfParameters() << std::endl;
std::cout << "scales " << std::endl << m_Scales << std::endl;
std::cout << "mode bounds " << std::endl << m_ModeBounds << std::endl;
std::cout << "lower bounds " << std::endl << m_LowerBounds << std::endl;
std::cout << "upper bounds " << std::endl << m_UpperBounds << std::endl;
std::cout << std::endl;
}
protected:
Transform m_TypeOfTransform = Transform::Similarity;
typename TransformType::Pointer m_Transform = nullptr;
InputPointType m_Center;
OutputVectorType m_Translation;
InputPointType m_MovingLandmark;
OutputPointType m_FixedLandmark;
/** Set the boundary condition for each variable, where
* select[i] = 0 if x[i] is unbounded,
* = 1 if x[i] has only a lower bound,
* = 2 if x[i] has both lower and upper bounds, and
* = 3 if x[1] has only an upper bound */
ModeBoundsType m_ModeBounds;
BoundsType m_LowerBounds;
BoundsType m_UpperBounds;
ParametersType m_Scales;
double m_TranslationScale = 1;
double m_RotationScale = 0.1;
double m_ScalingScale = 0.1;
double m_SkewScale = 0.1;
size_t m_NumberOfComponents = 0;
size_t m_NumberOfTranslationComponents = 0;
size_t m_NumberOfRotationComponents = 0;
size_t m_NumberOfScalingComponents = 0;
size_t m_NumberOfSkewComponents = 0;
size_t m_NumberOfParameters = 0;
void Allocate()
{
m_NumberOfParameters = m_Transform->GetNumberOfParameters();
m_Scales.set_size(m_NumberOfParameters);
m_Scales.Fill(0);
m_ModeBounds.set_size(m_NumberOfParameters);
m_ModeBounds.Fill(0);
m_LowerBounds.set_size(m_NumberOfParameters);
m_LowerBounds.Fill(0);
m_UpperBounds.set_size(m_NumberOfParameters);
m_UpperBounds.Fill(0);
}
InitializeTransform() {}
~InitializeTransform() {}
};
}
| 32.986014 | 145 | 0.650201 | [
"object",
"transform"
] |
4b255e218b4e6b0c2967d4f156a0164c0f80811d | 7,783 | h | C | include/IMessage.h | Watch-Later/mfcmapi | 72c2b46ec13ed2e2170a71fb65636234b049fb8a | [
"MIT"
] | 655 | 2016-10-13T20:18:52.000Z | 2022-03-28T21:25:14.000Z | include/IMessage.h | anthonysfo/mfcmapi | 72c2b46ec13ed2e2170a71fb65636234b049fb8a | [
"MIT"
] | 285 | 2016-10-18T19:03:31.000Z | 2022-03-10T11:02:33.000Z | include/IMessage.h | youtiaocoder/mfcmapi-1 | f2e58e7153b033b92c0b3989010428a2291d8527 | [
"MIT"
] | 129 | 2016-10-14T14:27:24.000Z | 2022-03-30T12:34:01.000Z | /*
* I M E S S A G E . H
*
* External definitions for MAPI's IMessage-on-IStorage facility
*
* Copyright 1986-1999 Microsoft Corporation. All Rights Reserved.
*/
#ifndef _IMESSAGE_H_
#define _IMESSAGE_H_
#if _MSC_VER > 1000
#pragma once
#endif
#ifdef __cplusplus
extern "C"
{
#endif
typedef struct _MSGSESS FAR * LPMSGSESS;
/* Typedef of optional callback routine to be called on last release of
* top-level messages opened with OpenIMsgOnIStg
*/
typedef void (STDAPICALLTYPE MSGCALLRELEASE)(
ULONG ulCallerData,
LPMESSAGE lpMessage );
/* DLL Entry Points (found in mapiu.dll) */
/* OpenIMsgSession
* CloseIMsgSession
*
* These entry points allow the caller to "wrap" the creation of messages
* inside a session, so that when the session is closed, all messages
* created within that session are closed as well. Use of IMSG sessions
* is optional. If OpenIMsgOnIStg is called with a NULL for the lpmsgsess
* parameter, the message is created independent of any session, and has
* no way to be shutdown. If the caller forgets to release the message, or
* to release open tables within the message, the memory will be leaked until
* the external application terminates.
*/
STDAPI_(SCODE) OpenIMsgSession(
LPMALLOC lpMalloc, /* -> Co malloc object */
ULONG ulFlags, /* reserved. Must be zero. */
LPMSGSESS FAR *lppMsgSess ); /* <- message session object */
STDAPI_(void) CloseIMsgSession(
LPMSGSESS lpMsgSess ); /* -> message session object */
/* OpenIMsgOnIStg - Main entry point
*
* NOTE 1: The IStg must be opened with STGM_TRANSACTED if STGM_READWRITE
* is specified. Since messages don't support a write only mode, IMessage
* doesn't allow a storage object opened in write only mode. If the storage
* is opened STGM_READ, then STGM_TRANSACTED is NOT required.
*
* NOTE 2: The lpMapiSup parameter is optional. If supplied then IMessage
* will support the MAPI_DIALOG and ATTACH_DIALOG flags (by calling
* support method: DoMCDialog) on CopyTo and DeleteAttach methods.
* If lpMapiSup is not supplied (i.e. passed 0) then dialog flags will be
* ignored. If supplied then ModifyRecipients will attempt to convert
* short term entryids to long term entryids (by calling support method
* OpenAddressBook and calls on the returned object). If not supplied
* then short term entryid's will be stored without conversion.
*
* NOTE 3: The lpfMsgCallRelease parameter is optional. If supplied then
* IMessage will call the routine when the last release on (the toplevel only)
* message is called. It is intended to allow the callee to free the IStorage
* that contains the message. IMessage will not use the IStorage object after
* making this call.
*
* NOTE 4: Behavior of multiple opens of sub-objects (Attachments, Streams,
* Storages, Messages, etc.) within a message is deliberately undefined in
* MAPI. This implementation allows them, but will do it by AddRef'ing the
* existing open and returning it to the caller of OpenAttachment or
* OpenProperty. This means that whatever access mode the first open on a
* specific Attachment or Property had is what all others will get regardless
* of what the subsequent opens asked for.
*
* NOTE 5: There is currently one flag defined for use with the ulFlags
* parameter. The IMSG_NO_ISTG_COMMIT flag controls whether the commit
* method of IStorage is called when the client calls SaveChanges on the
* IMessage object. Some clients of IMessage may wish to commit the IStorage
* themselves after writing additional data to the storage (beyond what
* IMessage itself writes). To aid in this, the IMessage implementation
* guarantees to name all sub-storages starting with "__". Therefore,
* if the client keeps its names out of that namespace, there will be no
* accidental collisions.
*
* WARNING:
*
* This implementation of IMessage will support OpenProperty w/MAPI_CREATE
* where the source interface is IID_IStorage if the property id is
* 'PR_ATTACH_DATA'. Once this has been done, the caller has an IStorage
* interface on this property. This is ok and should allow for
* easier implementation of OLE 2.0 Server functionality. However, if you
* pass in the new IStorage ptr (to the attachment data) through the
* OpenIMsgOnIStg entry point and then proceed to release things in the
* wrong order we will make no attempt to behave in a predictable fashion.
* Keep in mind that the correct method for placing a message into an
* attachment is to call OpenProperty where the source interface is
* IID_IMessage. The IStorage interface is supported to allow an easy way
* to stick a WWord doc. into an attachment w/o converting to/from IStream.
*
*/
STDAPI_(SCODE) OpenIMsgOnIStg(
LPMSGSESS lpMsgSess, /* -> message session obj (optional) */
LPALLOCATEBUFFER lpAllocateBuffer, /* -> AllocateBuffer memory routine */
LPALLOCATEMORE lpAllocateMore, /* -> AllocateMore memory routine */
LPFREEBUFFER lpFreeBuffer, /* -> FreeBuffer memory routine */
LPMALLOC lpMalloc, /* -> Co malloc object */
LPVOID lpMapiSup, /* -> MAPI Support Obj (optional) */
LPSTORAGE lpStg, /* -> open IStorage containing msg */
MSGCALLRELEASE FAR *lpfMsgCallRelease, /* -> release callback rtn (opt) */
ULONG ulCallerData, /* caller data returned in callback */
ULONG ulFlags, /* -> flags (controls istg commit) */
LPMESSAGE FAR *lppMsg ); /* <- open message object */
#define IMSG_NO_ISTG_COMMIT ((ULONG) 0x00000001)
/* NOTE: Property Attributes are specific to this IMessage on IStorage */
/* implementation and are not a part of standard MAPI 1.0 property methods */
/* Property Attributes */
#define PROPATTR_MANDATORY ((ULONG) 0x00000001)
#define PROPATTR_READABLE ((ULONG) 0x00000002)
#define PROPATTR_WRITEABLE ((ULONG) 0x00000004)
#define PROPATTR_NOT_PRESENT ((ULONG) 0x00000008)
/* Attribute Array */
typedef struct _SPropAttrArray
{
ULONG cValues;
ULONG aPropAttr[MAPI_DIM];
} SPropAttrArray, FAR * LPSPropAttrArray;
#define CbNewSPropAttrArray(_cattr) \
(offsetof(SPropAttrArray,aPropAttr) + (_cattr)*sizeof(ULONG))
#define CbSPropAttrArray(_lparray) \
(offsetof(SPropAttrArray,aPropAttr) + \
(UINT)((_lparray)->cValues)*sizeof(ULONG))
#define SizedSPropAttrArray(_cattr, _name) \
struct _SPropAttrArray_ ## _name \
{ \
ULONG cValues; \
ULONG aPropAttr[_cattr]; \
} _name
/* GetAttribIMsgOnIStg - To get attributes on properties
*
* This call is provided because there is no method of IMAPIPropSet to allow
* getting attributes.
*/
STDAPI GetAttribIMsgOnIStg(
LPVOID lpObject,
LPSPropTagArray lpPropTagArray,
LPSPropAttrArray FAR *lppPropAttrArray );
/* SetAttribIMsgOnIStg - To set attributes on properties
*
* This call is provided because there is no method of IMAPIPropSet to allow
* setting of attributes.
*/
STDAPI SetAttribIMsgOnIStg(
LPVOID lpObject,
LPSPropTagArray lpPropTags,
LPSPropAttrArray lpPropAttrs,
LPSPropProblemArray FAR *lppPropProblems );
/* MapStorageSCode - To map an IStorage hResult to a MAPI sCode value
*
* This call is provided for the internal use of PDK components that base
* their message implementations on IMessage. Since these components must
* open the storage themselves, there is a common need to map OLE 2.0
* Storage error returns to MAPI sCodes.
*
* WARNING: There is no guarantee that this entry point will exist in
* shipped versions of mapiu.dll.
*/
STDAPI_(SCODE) MapStorageSCode( SCODE StgSCode );
#ifdef __cplusplus
}
#endif
#endif /* _IMESSAGE_H_ */
| 39.110553 | 79 | 0.73031 | [
"object"
] |
4b26c5b6944edb523b3d35bb9039c89da1a3f772 | 13,740 | c | C | xdk-asf-3.51.0/avr32/applications/evk1100-control-panel/actuators/cpled.c | j3270/SAMD_Experiments | 5c242aff44fc8d7092322d7baf2dda450a78a9b7 | [
"MIT"
] | null | null | null | xdk-asf-3.51.0/avr32/applications/evk1100-control-panel/actuators/cpled.c | j3270/SAMD_Experiments | 5c242aff44fc8d7092322d7baf2dda450a78a9b7 | [
"MIT"
] | null | null | null | xdk-asf-3.51.0/avr32/applications/evk1100-control-panel/actuators/cpled.c | j3270/SAMD_Experiments | 5c242aff44fc8d7092322d7baf2dda450a78a9b7 | [
"MIT"
] | null | null | null | /*****************************************************************************
*
* \file
*
* \brief AVR32 UC3 Control Panel leds actuators module.
*
* - Supported boards: EVK1100
*
*
* Copyright (c) 2014-2018 Microchip Technology Inc. and its subsidiaries.
*
* \asf_license_start
*
* \page License
*
* Subject to your compliance with these terms, you may use Microchip
* software and any derivatives exclusively with Microchip products.
* It is your responsibility to comply with third party license terms applicable
* to your use of third party software (including open source software) that
* may accompany Microchip software.
*
* THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES,
* WHETHER EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE,
* INCLUDING ANY IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY,
* AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT WILL MICROCHIP BE
* LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE, INCIDENTAL OR CONSEQUENTIAL
* LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND WHATSOEVER RELATED TO THE
* SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS BEEN ADVISED OF THE
* POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE FULLEST EXTENT
* ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN ANY WAY
* RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY,
* THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE.
*
* \asf_license_stop
*
*****************************************************************************/
/*
* Support and FAQ: visit <a href="https://www.microchip.com/support/">Microchip Support</a>
*/
//_____ I N C L U D E S ___________________________________________________
#include <string.h>
#include "compiler.h"
#include "FreeRTOS.h"
#include "datalog.h"
#include "shell.h"
#include "board.h"
#include "supervisor.h"
#include "cptime.h"
#include "actuator.h"
#include "cpled.h"
//_____ M A C R O S ________________________________________________________
//_____ D E F I N I T I O N S ______________________________________________
const signed portCHAR *const CPLED_OFF_STR = (signed portCHAR *)"off";
const signed portCHAR *const CPLED_ON_STR = (signed portCHAR *)"on";
extern int sprintf(char *out, const char *format, ...); // From printf-stdarg.c
//_____ D E C L A R A T I O N S ____________________________________________
/*!
* \brief Get the ledm1 current value.
*
* \param pxLog a Log structure.
*
* \return true upon success, false if error.
*/
bool b_ledm1_get_value( xLogDef *pxLog )
{
// Build the log string.
if( LED_Test( LEDM1 ) )
pxLog->pcStringLog = (char *)CPLED_ON_STR;
else
pxLog->pcStringLog = (char *)CPLED_OFF_STR;
pxLog->pfFreeStringLog = NULL; // We use a constant
return( true );
}
/*!
* \brief Get the ledm2 current value.
*
* \param pxLog a Log structure.
*
* \return true upon success, false if error.
*/
bool b_ledm2_get_value( xLogDef *pxLog )
{
// Build the log string.
if( LED_Test( LEDM2 ) )
pxLog->pcStringLog = (char *)CPLED_ON_STR;
else
pxLog->pcStringLog = (char *)CPLED_OFF_STR;
pxLog->pfFreeStringLog = NULL; // We use a constant
return( true );
}
/*!
* \brief Get the ledb1 current value.
*
* \param pxLog a Log structure.
*
* \return true upon success, false if error.
*/
bool b_ledb1_get_value( xLogDef *pxLog )
{
// Alloc memory for the log string.
pxLog->pcStringLog = pvPortMalloc( 8*sizeof( char ) );
if( NULL == pxLog->pcStringLog )
{
return( false );
}
pxLog->pfFreeStringLog = vPortFree; // Because pvPortMalloc() was used to
// alloc the log string.
// Build the log string.
sprintf( pxLog->pcStringLog, "%d,%d", LED_Get_Intensity( LEDB1G ),
LED_Get_Intensity( LEDB1R ) );
return( true );
}
/*!
* \brief Get the ledb2 current value.
*
* \param pxLog a Log structure.
*
* \return true upon success, false if error.
*/
bool b_ledb2_get_value( xLogDef *pxLog )
{
// Alloc memory for the log string.
pxLog->pcStringLog = pvPortMalloc( 8*sizeof( char ) );
if( NULL == pxLog->pcStringLog )
{
return( false );
}
pxLog->pfFreeStringLog = vPortFree; // Because pvPortMalloc() was used to
// alloc the log string.
// Build the log string.
sprintf( pxLog->pcStringLog, "%d,%d", LED_Get_Intensity( LEDB2G ),
LED_Get_Intensity( LEDB2R ) );
return( true );
}
/* \brief The set monocolor led1 value command: set the value of the monocolor led1.
* Takes up to four parameters
* the first parameter is the state parameter, the second parameter is its value(on/off),
* the third is the time parameter(optional), the fourth is the time value(optional).
* Format: set_actuator_value actuator=actuatorname state=value [time=date]
*
* \note This function must be of the type pfShellCmd defined by the shell module.
*
* \param xModId Input. The module that is calling this function.
* \param ac Input. The argument counter. For this command, should be
* at least 2, at most 4.
* \param av Input. The argument vector.
* \param ppcStringReply Input/Output. The response string.
* If Input is NULL, no response string will be output.
* Else a malloc for the response string is performed here;
* the caller must free this string.
*
* \return the status of the command execution.
*/
eExecStatus e_ledm1_set_value( eModId xModId, int ac, signed portCHAR *av[],
signed portCHAR **ppcStringReply )
{
/* 1) Check the input. */
// i) Arguments: at least 2, at most 4.
if( ( 2 > ac ) || ( 4 < ac ) )
{ // Syntax error.
*ppcStringReply = (signed portCHAR *)ACTUATOR_ERRMSG_SETVAL_SYNTAXERROR;
return( SHELL_EXECSTATUS_KO );
}
// ii) Check that the 1st arg is state.
if( strcmp( (char *)av[0], "state" ) )
{
*ppcStringReply = (signed portCHAR *)ACTUATOR_ERRMSG_SETVAL_SYNTAXERROR;
return( SHELL_EXECSTATUS_KO );
}
// iii) If there is a third parameter, check that it is equal to "time" and
// record a new scheduling.
if( 4 == ac )
{
return( e_actuator_ScheduleCmdSet( CPTIME_SCHEDCMDID_SETLEDM1VAL, ac, av, ppcStringReply ) );
}
if( !strcmp( (char *)av[1], (char *)CPLED_ON_STR ) )
{
LED_On( LEDM1 );
}
else if( !strcmp( (char *)av[1], (char *)CPLED_OFF_STR ) )
{
LED_Off( LEDM1 );
}
else
{
*ppcStringReply = (signed portCHAR *)ACTUATOR_ERRMSG_SETVAL_SYNTAXERROR;
return( SHELL_EXECSTATUS_KO );
}
return( SHELL_EXECSTATUS_OK );
}
/*!
* \brief The set monocolor led2 value command: set the value of the monocolor led2.
* Takes up to four parameters
* the first parameter is the state parameter, the second parameter is its value(on/off),
* the third is the time parameter(optional), the fourth is the time value(optional).
* Format: set_actuator_value actuator=actuatorname state=value [time=date]
*
* \note This function must be of the type pfShellCmd defined by the shell module.
*
* \param xModId Input. The module that is calling this function.
* \param ac Input. The argument counter. For this command, should be
* at least 2, at most 4.
* \param av Input. The argument vector.
* \param ppcStringReply Input/Output. The response string.
* If Input is NULL, no response string will be output.
* Else a malloc for the response string is performed here;
* the caller must free this string.
*
* \return the status of the command execution.
*/
eExecStatus e_ledm2_set_value( eModId xModId, int ac, signed portCHAR *av[],
signed portCHAR **ppcStringReply )
{
/* 1) Check the input. */
// i) Arguments: at least 2, at most 4.
if( ( 2 > ac ) || ( 4 < ac ) )
{ // Syntax error.
*ppcStringReply = (signed portCHAR *)ACTUATOR_ERRMSG_SETVAL_SYNTAXERROR;
return( SHELL_EXECSTATUS_KO );
}
// ii) Check that the 1st arg is state.
if( strcmp( (char *)av[0], "state" ) )
{
*ppcStringReply = (signed portCHAR *)ACTUATOR_ERRMSG_SETVAL_SYNTAXERROR;
return( SHELL_EXECSTATUS_KO );
}
// iii) If there is a third parameter, check that it is equal to "time" and
// record a new scheduling.
if( 4 == ac )
{
return( e_actuator_ScheduleCmdSet( CPTIME_SCHEDCMDID_SETLEDM2VAL, ac, av, ppcStringReply ) );
}
if( !strcmp( (char *)av[1], (char *)CPLED_ON_STR ) )
{
LED_On( LEDM2 );
}
else if( !strcmp( (char *)av[1], (char *)CPLED_OFF_STR ) )
{
LED_Off( LEDM2 );
}
else
{
*ppcStringReply = (signed portCHAR *)ACTUATOR_ERRMSG_SETVAL_SYNTAXERROR;
return( SHELL_EXECSTATUS_KO );
}
return( SHELL_EXECSTATUS_OK );
}
/*!
* \brief The set bicolor ledb1 value command: set the value of the bicolor ledb1.
* Takes up to six parameters
* the first parameter is the green parameter, the second parameter is its value in [0,255],
* the third parameter is the red parameter, the fourth parameter is its value in [0,255],
* the fifth is the time parameter(optional), the sixth is the time value(optional) expressed in seconds.
* Format: set_actuator_value actuator=actuatorname green=value red=value [time=date]
*
* \note This function must be of the type pfShellCmd defined by the shell module.
*
* \param xModId Input. The module that is calling this function.
* \param ac Input. The argument counter. For this command, should be
* at least 4, at most 6.
* \param av Input. The argument vector.
* \param ppcStringReply Input/Output. The response string.
* If Input is NULL, no response string will be output.
* Else a malloc for the response string is performed here;
* the caller must free this string.
*
* \return the status of the command execution.
*/
eExecStatus e_ledb1_set_value( eModId xModId, int ac, signed portCHAR *av[],
signed portCHAR **ppcStringReply )
{
/* 1) Check the input. */
// i) Arguments: at least 4, at most 6.
if( ( 4 > ac ) || ( 6 < ac ) )
{ // Syntax error.
*ppcStringReply = (signed portCHAR *)ACTUATOR_ERRMSG_SETVAL_SYNTAXERROR;
return( SHELL_EXECSTATUS_KO );
}
// ii) Check that the 1st arg is 'green' and that the 3rd is 'red'.
if( strcmp( (char *)av[0], "green" ) || strcmp( (char *)av[2], "red" ))
{
*ppcStringReply = (signed portCHAR *)ACTUATOR_ERRMSG_SETVAL_SYNTAXERROR;
return( SHELL_EXECSTATUS_KO );
}
// iii) If there is a fifth parameter, check that it is equal to "time" and
// record a new scheduling.
if( 6 == ac )
{
return( e_actuator_ScheduleCmdSet( CPTIME_SCHEDCMDID_SETLEDB1VAL, ac, av, ppcStringReply ) );
}
/* 2) Set the val. */
LED_Set_Intensity( LEDB1G, atoi( (char *)av[1] ) );
LED_Set_Intensity( LEDB1R, atoi( (char *)av[3] ) );
return( SHELL_EXECSTATUS_OK );
}
/*!
* \brief The set bicolor ledb2 value command: set the value of the bicolor ledb2.
* Takes up to six parameters
* the first parameter is the green parameter, the second parameter is its value in [0,255],
* the third parameter is the red parameter, the fourth parameter is its value in [0,255],
* the fifth is the time parameter(optional), the sixth is the time value(optional) expressed in seconds.
* Format: set_actuator_value actuator=actuatorname green=value red=value [time=date]
*
* \note This function must be of the type pfShellCmd defined by the shell module.
*
* \param xModId Input. The module that is calling this function.
* \param ac Input. The argument counter. For this command, should be
* at least 4, at most 6.
* \param av Input. The argument vector.
* \param ppcStringReply Input/Output. The response string.
* If Input is NULL, no response string will be output.
* Else a malloc for the response string is performed here;
* the caller must free this string.
*
* \return the status of the command execution.
*/
eExecStatus e_ledb2_set_value( eModId xModId, int ac, signed portCHAR *av[],
signed portCHAR **ppcStringReply )
{
/* 1) Check the input. */
// i) Arguments: at least 4, at most 6.
if( ( 4 > ac ) || ( 6 < ac ) )
{ // Syntax error.
*ppcStringReply = (signed portCHAR *)ACTUATOR_ERRMSG_SETVAL_SYNTAXERROR;
return( SHELL_EXECSTATUS_KO );
}
// ii) Check that the 1st arg is 'green' and that the 3rd is 'red'.
if( strcmp( (char *)av[0], "green" ) || strcmp( (char *)av[2], "red" ))
{
*ppcStringReply = (signed portCHAR *)ACTUATOR_ERRMSG_SETVAL_SYNTAXERROR;
return( SHELL_EXECSTATUS_KO );
}
// iii) If there is a fifth parameter, check that it is equal to "time" and
// record a new scheduling.
if( 6 == ac )
{
return( e_actuator_ScheduleCmdSet( CPTIME_SCHEDCMDID_SETLEDB2VAL, ac, av, ppcStringReply ) );
}
/* 2) Set the val. */
LED_Set_Intensity( LEDB2G, atoi( (char *)av[1] ) );
LED_Set_Intensity( LEDB2R, atoi( (char *)av[3] ) );
return( SHELL_EXECSTATUS_OK );
}
| 35.230769 | 113 | 0.633552 | [
"vector"
] |
4b285cf9f6d0f23f4623d10c0afc30f8d54921fd | 618 | h | C | omp_prog/optimal_split_graph/Graph.h | alexanderflegontov/OpenMPAnalyzer | 609ad47699384b802b4d8307fab55b63e749f84c | [
"MIT"
] | null | null | null | omp_prog/optimal_split_graph/Graph.h | alexanderflegontov/OpenMPAnalyzer | 609ad47699384b802b4d8307fab55b63e749f84c | [
"MIT"
] | null | null | null | omp_prog/optimal_split_graph/Graph.h | alexanderflegontov/OpenMPAnalyzer | 609ad47699384b802b4d8307fab55b63e749f84c | [
"MIT"
] | null | null | null | #include <vector>
#include <iostream>
#include <algorithm>
#include "time.h"
#include "math.h"
using namespace std;
class Graph {
int last_a, last_b, totalGain, half;
int v_size, e_size;
bool **edge;
int *part, *gain;
vector <pair<int, int> > def_a, def_b;
public:
Graph(int size, int probty);
~Graph();
void print_matrix();
void print_parts();
void print_defs();
void print_gains();
void def_calc();
void def_recalc();
void def_balance();
bool exchange_pair(int stage);
int max_gain();
int total_gain();
void create_parts();
int* create_result();
int cut_size();
}; | 19.935484 | 40 | 0.660194 | [
"vector"
] |
4b2e6fbe41379d5717b3699ddf1934b1e4b8ea0e | 16,893 | c | C | services/amfapp.c | ystk/debian-openais | 9be5d9d1dfa5d189346270525febdd3b0447e854 | [
"BSD-3-Clause"
] | 3 | 2021-06-21T17:50:35.000Z | 2021-11-17T11:12:42.000Z | services/amfapp.c | ystk/debian-openais | 9be5d9d1dfa5d189346270525febdd3b0447e854 | [
"BSD-3-Clause"
] | null | null | null | services/amfapp.c | ystk/debian-openais | 9be5d9d1dfa5d189346270525febdd3b0447e854 | [
"BSD-3-Clause"
] | 1 | 2016-11-15T14:02:19.000Z | 2016-11-15T14:02:19.000Z | /** @file amfapp.c
*
* Copyright (c) 2006 Ericsson AB.
* Author: Hans Feldt, Anders Eriksson, Lars Holm
* - Refactoring of code into several AMF files
* - Constructors/destructors
* - Serializers/deserializers
*
* All rights reserved.
*
*
* This software licensed under BSD license, the text of which follows:
*
* 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 MontaVista Software, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*
* AMF Application Class implementation
*
* This file contains functions for handling the AMF Applications. It can
* be viewed as the implementation of the AMF Application class
* as described in SAI-Overview-B.02.01. The SA Forum specification
* SAI-AIS-AMF-B.02.01 has been used as specification of the behaviour
* and is referred to as 'the spec' below.
*
* The functions in this file are responsible for:
* - on request start the service groups it contains
* - on request order the service groups to assign workload to all
* service units contained in the service group, level by level
* - to handle administrative operation support for the application (FUTURE)
*
* The application class contains the following state machines:
* - administrative state machine (ADSM)
* - availability control state machine (ACSM)
*
* The administrative state machine will be implemented in the future.
*
* ACSM handles initial start of an Application. In the future it will also
* handle administrative commands on the application as described in paragraph
* 7.4 of the spec. ACSM includes two stable states (UNINSTANTIATED and
* WORKLOAD_ASSIGNED) and a number of states to control the transition between
* the stable states.
*
* The application is in state UNINSTANTIATED when the application starts.
* (In the future this state will also be assumed after the LOCK_INSTANTIATION
* administrative command.)
*
* State WORKLOAD_ASSIGNED is assumed when the Application has been initially
* started and will in the future be re-assumed after the administrative
* command RESTART have been executed.
*
* 1. AMF Application Availability Control State Machine
* =====================================================
*
* 1.1 State Transition Table
*
* State: Event: Action: New state:
* ===========================================================================
* UNINSTANTIATED start A6,A1 STARTING_SGS
* STARTING_SGS start [C4] A7
* STARTING_SGS sg_started [C1] A8,A9 STARTED
* STARTING_SGS assign_workload [C4] A3 ASSIGNING_WORKLOAD
* STARTED start A6,A1 STARTING_SGS
* STARTED start [!C4] A7 STARTED
* STARTED assign_workload A3 ASSIGNING_WORKLOAD
* ASSIGNING_WORKLOAD assign_workload A7 ASSIGNING_WORKLOAD
* ASSIGNING_WORKLOAD start A7 ASSIGNING_WORKLOAD
* ASSIGNING_WORKLOAD sg_assigned [C2] A10,A9 WORKLOAD_ASSIGNED
* WORKLOAD_ASSIGNED start A6,A1 STARTING_SGS
* WORKLOAD_ASSIGNED assign_workload A3 ASSIGNING_WORKLOAD
*
* 1.2 State Description
* =====================
* UNINSTANTIATED - No SUs within the SGs contained in the Application have been
* instantiated.
* STARTING_SGS - Waiting for the contained SGs to start.
* STARTED - No SUs within the SGs contained in the Application are in the
* process of beein instantiated. Either the SUs are instantiated or
* instantiation was not possible or instantiation has failed.
* ASSIGNING_WORKLOAD - Waiting for the contained SGs to indicate they have
* assigned workload to its SUs.
* WORKLOAD_ASSIGNED - at least some workload has been assigned to the SUs that
* are in-service.
*
* 1.3 Actions
* ===========
* A1 - [foreach SG in Application] sg_start
* A2 -
* A3 - [foreach SG in Application] sg_assign
* A4 -
* A5 -
* A6 - save value of received node parameter
* A7 - defer the event
* A8 - [node == NULL] cluster_application_started else node_application_started
* A9 - recall deferred events
* A10 - [node == NULL] cluster_application_assigned else
* node_application_assigned
*
* 1.4 Guards
* ==========
* C1 - No SU has presence state == INSTANTIATING
* C2 - All SGs have availability control state == IDLE
* C3 -
* C4 - Sender is Cluster
*/
#include <config.h>
#include <assert.h>
#include <stdlib.h>
#include "amf.h"
#include <corosync/engine/logsys.h>
LOGSYS_DECLARE_SUBSYS ("AMF");
typedef struct application_event {
amf_application_event_type_t event_type;
amf_application_t *app;
amf_node_t *node;
} application_event_t;
/******************************************************************************
* Internal (static) utility functions
*****************************************************************************/
static int is_cluster_start(amf_node_t *node_to_start)
{
return node_to_start == NULL;
}
void amfapp_init (void)
{
#ifdef OPENAIS_SOLARIS
logsys_subsys_init();
#endif
}
static void application_defer_event (
amf_application_event_type_t event_type, amf_application_t *app,
amf_node_t *node)
{
application_event_t app_event = {event_type, app, node};
ENTER();
amf_fifo_put (event_type, &app->deferred_events,
sizeof (application_event_t), &app_event);
}
static void application_recall_deferred_events (amf_application_t *app)
{
application_event_t application_event;
if (amf_fifo_get (&app->deferred_events, &application_event)) {
switch (application_event.event_type) {
case APPLICATION_ASSIGN_WORKLOAD_EV: {
log_printf (LOGSYS_LEVEL_NOTICE,
"Recall APPLICATION_ASSIGN_WORKLOAD_EV");
amf_application_assign_workload (
application_event.app,
application_event.node);
break;
}
case APPLICATION_START_EV: {
log_printf (LOGSYS_LEVEL_NOTICE,
"Recall APPLICATION_START_EV");
amf_application_start (application_event.app,
application_event.node);
break;
}
default:
assert (0);
break;
}
}
}
static void timer_function_application_recall_deferred_events (void *data)
{
amf_application_t *app = (amf_application_t*)data;
ENTER ();
application_recall_deferred_events (app);
}
static int no_su_is_instantiating (struct amf_application *app)
{
struct amf_sg *sg;
struct amf_su *su;
int all_su_instantiated = 1;
for (sg = app->sg_head; sg != NULL; sg = sg->next) {
for (su = sg->su_head; su != NULL; su = su->next) {
if (su->saAmfSUPresenceState == SA_AMF_PRESENCE_INSTANTIATING) {
all_su_instantiated = 0;
break;
}
}
}
return all_su_instantiated;
}
static int all_sg_assigned (struct amf_application *app)
{
struct amf_sg *sg;
int all_assigned = 1;
for (sg = app->sg_head; sg != NULL; sg = sg->next) {
if (sg->avail_state != SG_AC_Idle) {
all_assigned = 0;
break;
}
}
return all_assigned;
}
static void start_all_sg_for_cluster (amf_application_t *app)
{
amf_sg_t *sg;
int su_to_instantiate = 0;
for (sg = app->sg_head; sg != NULL; sg = sg->next) {
su_to_instantiate += amf_sg_start (sg, NULL);
}
if (su_to_instantiate == 0) {
amf_cluster_application_started (app->cluster, app);
}
}
static void timer_function_cluster_application_started (void* app)
{
amf_application_t *application = (amf_application_t*)app;
ENTER();
amf_cluster_application_started (application->cluster, application);
}
static void timer_function_node_application_started (void* app)
{
amf_application_t *application = (amf_application_t*)app;
ENTER();
amf_node_application_started (application->node_to_start, application);
}
static void application_enter_starting_sgs (struct amf_application *app,
struct amf_node *node)
{
amf_sg_t *sg = 0;
int su_to_instantiate = 0;
app->node_to_start = node;
app->acsm_state = APP_AC_STARTING_SGS;
ENTER ();
for (sg = app->sg_head; sg != NULL; sg = sg->next) {
su_to_instantiate += amf_sg_start (sg, node);
}
if (su_to_instantiate == 0) {
app->acsm_state = APP_AC_STARTED;
if (is_cluster_start (app->node_to_start)) {
amf_call_function_asynchronous (
timer_function_cluster_application_started, app);
} else {
amf_call_function_asynchronous (
timer_function_node_application_started, app);
}
}
}
static void application_enter_assigning_workload (amf_application_t *app)
{
amf_sg_t *sg = 0;
int posible_to_assign_si = 0;
ENTER ();
app->acsm_state = APP_AC_ASSIGNING_WORKLOAD;
for (sg = app->sg_head; sg != NULL; sg = sg->next) {
if (amf_sg_assign_si_req (sg, 0)) {
posible_to_assign_si = 1;
}
}
if (posible_to_assign_si == 0) {
app->acsm_state = APP_AC_WORKLOAD_ASSIGNED;
}
}
static void application_enter_workload_assigned (amf_application_t *app)
{
ENTER ();
if (all_sg_assigned (app)){
app->acsm_state = APP_AC_WORKLOAD_ASSIGNED;
if (app->node_to_start == NULL){
amf_cluster_application_workload_assigned (
app->cluster, app);
} else {
TRACE1("%s",app->node_to_start->name.value);
amf_node_application_workload_assigned(
app->node_to_start, app);
}
amf_call_function_asynchronous (
timer_function_application_recall_deferred_events, app);
}
}
/******************************************************************************
* Event methods
*****************************************************************************/
void amf_application_start (
struct amf_application *app, struct amf_node *node)
{
ENTER ();
assert (app != NULL);
switch (app->acsm_state) {
case APP_AC_UNINSTANTIATED:
application_enter_starting_sgs (app, node);
break;
case APP_AC_STARTING_SGS:
if (is_cluster_start (app->node_to_start)) {
start_all_sg_for_cluster (app);
} else { /*is_not_cluster_start*/
application_defer_event (APPLICATION_START_EV, app , node);
}
break;
case APP_AC_STARTED:
if (is_cluster_start (app->node_to_start)) {
app->acsm_state = APP_AC_STARTING_SGS;
start_all_sg_for_cluster (app);
} else { /*is_not_cluster_start*/
application_defer_event (APPLICATION_START_EV, app , node);
}
break;
case APP_AC_ASSIGNING_WORKLOAD:
log_printf (LOGSYS_LEVEL_ERROR, "Request to start application"
" =%s in state APP_AC_ASSIGNING_WORKLOAD(should be deferred)",
app->name.value);
application_defer_event (APPLICATION_START_EV, app , node);
break;
case APP_AC_WORKLOAD_ASSIGNED:
application_enter_starting_sgs (app, node);
break;
default:
assert (0);
break;
}
}
void amf_application_assign_workload (struct amf_application *app,
struct amf_node *node)
{
/*
* TODO: dependency level ignored. Each dependency level should
* be looped and amf_sg_assign_si called several times.
*/
assert (app != NULL);
app->node_to_start = node;
ENTER();
switch (app->acsm_state) {
case APP_AC_STARTING_SGS:
if (is_cluster_start (node)) {
application_enter_assigning_workload (app);
}
break;
case APP_AC_WORKLOAD_ASSIGNED:
application_enter_assigning_workload (app);
break;
case APP_AC_STARTED:
application_enter_assigning_workload (app);
break;
case APP_AC_ASSIGNING_WORKLOAD:
if (app->node_to_start == node) {
/*
* Calling object has violated the contract !
*/
assert (0);
} else {
log_printf (LOGSYS_LEVEL_ERROR, "Request to assign workload to"
" application =%s in state APP_AC_ASSIGNING_WORKLOAD "
"(should be deferred)", app->name.value);
application_defer_event (APPLICATION_ASSIGN_WORKLOAD_EV, app,
node);
}
break;
default:
/*
* Calling object has violated the contract !
*/
TRACE1 ("acsm_state = %d",app->acsm_state);
assert (0);
break;
}
}
/******************************************************************************
* Event response methods
*****************************************************************************/
void amf_application_sg_started (struct amf_application *app, struct amf_sg *sg,
struct amf_node *node)
{
ENTER ();
assert (app != NULL);
switch (app->acsm_state) {
case APP_AC_STARTING_SGS:
if (no_su_is_instantiating (app)) {
app->acsm_state = APP_AC_STARTED;
if (app->node_to_start == NULL) {
amf_cluster_application_started (app->cluster, app);
} else {
amf_node_application_started (app->node_to_start, app);
}
}
break;
default:
log_printf (LOGSYS_LEVEL_ERROR, "amf_application_sg_started()"
" called in state = %d", app->acsm_state);
corosync_fatal_error (COROSYNC_FATAL_ERR);
break;
}
}
void amf_application_sg_assigned (
struct amf_application *app, struct amf_sg *sg)
{
ENTER ();
assert (app != NULL);
switch (app->acsm_state) {
case APP_AC_ASSIGNING_WORKLOAD:
application_enter_workload_assigned (app);
break;
default:
log_printf (LOGSYS_LEVEL_ERROR,
"amf_application_sg_assigned()"
" called in state = %d", app->acsm_state);
corosync_fatal_error (COROSYNC_FATAL_ERR);
break;
}
}
/******************************************************************************
* General methods
*****************************************************************************/
struct amf_application *amf_application_new (struct amf_cluster *cluster) {
struct amf_application *app = amf_calloc (1,
sizeof (struct amf_application));
app->cluster = cluster;
app->next = cluster->application_head;
cluster->application_head = app;
app->acsm_state = APP_AC_UNINSTANTIATED;
app->node_to_start = NULL;
return app;
}
void amf_application_delete (struct amf_application *app)
{
struct amf_sg *sg;
struct amf_si *si;
assert (app != NULL);
for (sg = app->sg_head; sg != NULL;) {
struct amf_sg *tmp = sg;
sg = sg->next;
amf_sg_delete (tmp);
}
for (si = app->si_head; si != NULL;) {
struct amf_si *tmp = si;
si = si->next;
amf_si_delete (tmp);
}
free (app);
}
void *amf_application_serialize (
struct amf_application *app, int *len)
{
char *buf = NULL;
int offset = 0, size = 0;
assert (app != NULL);
TRACE8 ("%s", app->name.value);
buf = amf_serialize_SaNameT (buf, &size, &offset, &app->name);
buf = amf_serialize_SaUint32T (
buf, &size, &offset, app->saAmfApplicationAdminState);
buf = amf_serialize_SaUint32T (
buf, &size, &offset, app->saAmfApplicationCurrNumSG);
buf = amf_serialize_SaStringT (
buf, &size, &offset, app->clccli_path);
buf = amf_serialize_SaUint32T (
buf, &size, &offset, app->acsm_state);
*len = offset;
return buf;
}
struct amf_application *amf_application_deserialize (
struct amf_cluster *cluster, char *buf)
{
char *tmp = buf;
struct amf_application *app = amf_application_new (cluster);
tmp = amf_deserialize_SaNameT (tmp, &app->name);
tmp = amf_deserialize_SaUint32T (tmp, &app->saAmfApplicationAdminState);
tmp = amf_deserialize_SaUint32T (tmp, &app->saAmfApplicationCurrNumSG);
tmp = amf_deserialize_SaStringT (tmp, &app->clccli_path);
tmp = amf_deserialize_SaUint32T (tmp, &app->acsm_state);
return app;
}
struct amf_application *amf_application_find (
struct amf_cluster *cluster, char *name)
{
struct amf_application *app;
assert (cluster != NULL);
for (app = cluster->application_head; app != NULL; app = app->next) {
if (app->name.length == strlen(name) &&
strncmp (name, (char*)app->name.value, app->name.length)
== 0) {
break;
}
}
if (app == NULL) {
TRACE1 ("App %s not found!", name);
}
return app;
}
| 30.112299 | 80 | 0.679394 | [
"object"
] |
4b35baa14d308c229eca570daafbab461b917fd2 | 4,794 | h | C | openeuler-kernel/include/linux/mfd/core.h | Ddnirvana/test-CI | dd7a0a71281075e8ab300bddbab4a9fa039958f0 | [
"MulanPSL-1.0"
] | 31 | 2021-04-27T08:50:40.000Z | 2022-03-01T02:26:21.000Z | openeuler-kernel/include/linux/mfd/core.h | Ddnirvana/test-CI | dd7a0a71281075e8ab300bddbab4a9fa039958f0 | [
"MulanPSL-1.0"
] | 13 | 2021-07-10T04:36:17.000Z | 2022-03-03T10:50:05.000Z | openeuler-kernel/include/linux/mfd/core.h | Ddnirvana/test-CI | dd7a0a71281075e8ab300bddbab4a9fa039958f0 | [
"MulanPSL-1.0"
] | 12 | 2021-04-06T02:23:10.000Z | 2022-02-28T11:43:19.000Z | /* SPDX-License-Identifier: GPL-2.0-only */
/*
* drivers/mfd/mfd-core.h
*
* core MFD support
* Copyright (c) 2006 Ian Molton
* Copyright (c) 2007 Dmitry Baryshkov
*/
#ifndef MFD_CORE_H
#define MFD_CORE_H
#include <linux/platform_device.h>
#define MFD_RES_SIZE(arr) (sizeof(arr) / sizeof(struct resource))
#define MFD_CELL_ALL(_name, _res, _pdata, _pdsize, _id, _compat, _of_reg, _use_of_reg, _match) \
{ \
.name = (_name), \
.resources = (_res), \
.num_resources = MFD_RES_SIZE((_res)), \
.platform_data = (_pdata), \
.pdata_size = (_pdsize), \
.of_compatible = (_compat), \
.of_reg = (_of_reg), \
.use_of_reg = (_use_of_reg), \
.acpi_match = (_match), \
.id = (_id), \
}
#define OF_MFD_CELL_REG(_name, _res, _pdata, _pdsize, _id, _compat, _of_reg) \
MFD_CELL_ALL(_name, _res, _pdata, _pdsize, _id, _compat, _of_reg, true, NULL)
#define OF_MFD_CELL(_name, _res, _pdata, _pdsize, _id, _compat) \
MFD_CELL_ALL(_name, _res, _pdata, _pdsize, _id, _compat, 0, false, NULL)
#define ACPI_MFD_CELL(_name, _res, _pdata, _pdsize, _id, _match) \
MFD_CELL_ALL(_name, _res, _pdata, _pdsize, _id, NULL, 0, false, _match)
#define MFD_CELL_BASIC(_name, _res, _pdata, _pdsize, _id) \
MFD_CELL_ALL(_name, _res, _pdata, _pdsize, _id, NULL, 0, false, NULL)
#define MFD_CELL_RES(_name, _res) \
MFD_CELL_ALL(_name, _res, NULL, 0, 0, NULL, 0, false, NULL)
#define MFD_CELL_NAME(_name) \
MFD_CELL_ALL(_name, NULL, NULL, 0, 0, NULL, 0, false, NULL)
#define MFD_DEP_LEVEL_NORMAL 0
#define MFD_DEP_LEVEL_HIGH 1
struct irq_domain;
struct property_entry;
/* Matches ACPI PNP id, either _HID or _CID, or ACPI _ADR */
struct mfd_cell_acpi_match {
const char *pnpid;
const unsigned long long adr;
};
/*
* This struct describes the MFD part ("cell").
* After registration the copy of this structure will become the platform data
* of the resulting platform_device
*/
struct mfd_cell {
const char *name;
int id;
int level;
int (*enable)(struct platform_device *dev);
int (*disable)(struct platform_device *dev);
int (*suspend)(struct platform_device *dev);
int (*resume)(struct platform_device *dev);
/* platform data passed to the sub devices drivers */
void *platform_data;
size_t pdata_size;
/* device properties passed to the sub devices drivers */
const struct property_entry *properties;
/*
* Device Tree compatible string
* See: Documentation/devicetree/usage-model.rst Chapter 2.2 for details
*/
const char *of_compatible;
/*
* Address as defined in Device Tree. Used to compement 'of_compatible'
* (above) when matching OF nodes with devices that have identical
* compatible strings
*/
const u64 of_reg;
/* Set to 'true' to use 'of_reg' (above) - allows for of_reg=0 */
bool use_of_reg;
/* Matches ACPI */
const struct mfd_cell_acpi_match *acpi_match;
/*
* These resources can be specified relative to the parent device.
* For accessing hardware you should use resources from the platform dev
*/
int num_resources;
const struct resource *resources;
/* don't check for resource conflicts */
bool ignore_resource_conflicts;
/*
* Disable runtime PM callbacks for this subdevice - see
* pm_runtime_no_callbacks().
*/
bool pm_runtime_no_callbacks;
/* A list of regulator supplies that should be mapped to the MFD
* device rather than the child device when requested
*/
const char * const *parent_supplies;
int num_parent_supplies;
};
/*
* Convenience functions for clients using shared cells. Refcounting
* happens automatically, with the cell's enable/disable callbacks
* being called only when a device is first being enabled or no other
* clients are making use of it.
*/
extern int mfd_cell_enable(struct platform_device *pdev);
extern int mfd_cell_disable(struct platform_device *pdev);
/*
* Given a platform device that's been created by mfd_add_devices(), fetch
* the mfd_cell that created it.
*/
static inline const struct mfd_cell *mfd_get_cell(struct platform_device *pdev)
{
return pdev->mfd_cell;
}
extern int mfd_add_devices(struct device *parent, int id,
const struct mfd_cell *cells, int n_devs,
struct resource *mem_base,
int irq_base, struct irq_domain *irq_domain);
static inline int mfd_add_hotplug_devices(struct device *parent,
const struct mfd_cell *cells, int n_devs)
{
return mfd_add_devices(parent, PLATFORM_DEVID_AUTO, cells, n_devs,
NULL, 0, NULL);
}
extern void mfd_remove_devices(struct device *parent);
extern void mfd_remove_devices_late(struct device *parent);
extern int devm_mfd_add_devices(struct device *dev, int id,
const struct mfd_cell *cells, int n_devs,
struct resource *mem_base,
int irq_base, struct irq_domain *irq_domain);
#endif
| 29.231707 | 96 | 0.720484 | [
"model"
] |
4b39a861337d784e7304238ed1afe7f46593edc8 | 281 | h | C | iomanager.h | Kepler-Br/Game-of-life | a7ce90654912f6574b72c136012b2eee4f9d0964 | [
"MIT"
] | 4 | 2019-01-21T14:15:54.000Z | 2020-10-01T09:47:40.000Z | iomanager.h | Kepler-Br/Game-of-life | a7ce90654912f6574b72c136012b2eee4f9d0964 | [
"MIT"
] | null | null | null | iomanager.h | Kepler-Br/Game-of-life | a7ce90654912f6574b72c136012b2eee4f9d0964 | [
"MIT"
] | null | null | null | #ifndef IOMANAGER_H
#define IOMANAGER_H
#include <GL/glew.h>
#include <string>
#include <vector>
class IOManager
{
public:
static std::string readTextFile(const std::string& path);
static std::vector<char> readBinFile(const std::string& path);
};
#endif // IOMANAGER_H
| 16.529412 | 66 | 0.72242 | [
"vector"
] |
af3ed6abcc9b3adc7123d46baa02916d58c4d37b | 704 | h | C | switcher_controller/src/switchmatrix.h | effectspcbs/platformio-avr | 09b2feffb63424de20020f46f988ce0e00b1cb8e | [
"MIT"
] | null | null | null | switcher_controller/src/switchmatrix.h | effectspcbs/platformio-avr | 09b2feffb63424de20020f46f988ce0e00b1cb8e | [
"MIT"
] | null | null | null | switcher_controller/src/switchmatrix.h | effectspcbs/platformio-avr | 09b2feffb63424de20020f46f988ce0e00b1cb8e | [
"MIT"
] | 1 | 2021-12-09T11:45:01.000Z | 2021-12-09T11:45:01.000Z | #include <Arduino.h>
#include <SPI.h>
#ifndef SWITCHMATRIX_H
#define SWITCHMATRIX_H
class SwitchMatrix
{
private:
uint8_t m_csPin;
uint16_t m_switchArray[16] = { 0 }; // array[y]
void select();
void deselect();
public:
SwitchMatrix(uint8_t pin) : m_csPin(pin) {}
void switchMatrixSetup();
void resetSwitchMatrix();
/**
* @brief Set the Switch Array object
*
* @param y Row
* @param x Column
* @param value
*/
void setSwitchArray(uint8_t y, uint8_t x, uint8_t value);
uint8_t getSwitchArray(uint8_t y, uint8_t x);
void sendSwitchArray();
};
#endif | 20.114286 | 65 | 0.571023 | [
"object"
] |
af4a28f00b7b476a2dfc2face7cc7d3666ecd71e | 6,178 | h | C | sys/vax/uba/vsreg.h | weiss/original-bsd | b44636d7febc9dcf553118bd320571864188351d | [
"Unlicense"
] | 114 | 2015-01-18T22:55:52.000Z | 2022-02-17T10:45:02.000Z | sys/vax/uba/vsreg.h | JamesLinus/original-bsd | b44636d7febc9dcf553118bd320571864188351d | [
"Unlicense"
] | null | null | null | sys/vax/uba/vsreg.h | JamesLinus/original-bsd | b44636d7febc9dcf553118bd320571864188351d | [
"Unlicense"
] | 29 | 2015-11-03T22:05:22.000Z | 2022-02-08T15:36:37.000Z | /* @(#)vsreg.h 7.1 (MIT) 06/05/86 */
/****************************************************************************
* *
* Copyright (c) 1983, 1984 by *
* DIGITAL EQUIPMENT CORPORATION, Maynard, Massachusetts. *
* All rights reserved. *
* *
* This software is furnished on an as-is basis and may be used and copied *
* only with inclusion of the above copyright notice. This software or any *
* other copies thereof may be provided or otherwise made available to *
* others only for non-commercial purposes. No title to or ownership of *
* the software is hereby transferred. *
* *
* The information in this software is subject to change without notice *
* and should not be construed as a commitment by DIGITAL EQUIPMENT *
* CORPORATION. *
* *
* DIGITAL assumes no responsibility for the use or reliability of its *
* software on equipment which is not supplied by DIGITAL. *
* *
* *
****************************************************************************/
/*
* vsreg.h - VS100 Registers and Bits
*
* Author: Christopher A. Kent
* Digital Equipment Corporation
* Western Research Lab
* Date: Tue Jun 14 1983
*/
struct vsdevice{
u_short vs_csr0; /* Control and Status */
u_short vs_csr1; /* Interrupt Reason */
u_short vs_csr2; /* Keyboard Receive */
u_short vs_csr3; /* Function Parameter Low */
u_short vs_csr4; /* Function Parameter High */
u_short vs_csr5; /* Cursor Position X */
u_short vs_csr6; /* Cursor Position Y */
u_short vs_csr7; /* Interrupt Vector */
u_short vs_csr8; /* Spare 1 */
u_short vs_csr9; /* Spare 2 */
u_short vs_csra; /* Spare 3 */
u_short vs_csrb; /* Spare 4 */
u_short vs_csrc; /* Spare 5 */
u_short vs_csrd; /* Spare 6 */
u_short vs_csre; /* Spare 7 */
u_short vs_csrf; /* Interrupt Vector (2Bs) */
};
/*
* CSR0 - Control and Status
*/
#define VS_LNK_TRNS 0100000 /* Link Transition */
#define VS_LNK_AVL 0040000 /* Link Available */
#define VS_LNK_ERR 0020000 /* Link Error */
#define VS_XMIT_ON 0010000 /* Transmitter On */
#define VS_MNT_MODE 0004000 /* Maintenance Mode */
#define VS_CRC_DIS 0002000 /* CRC Disable */
#define VS_MNT_DONE 0001000 /* Maintenance Done */
#define VS_SPARE 0000400 /* Spare */
#define VS_OWN 0000200 /* Owner */
#define VS_IE 0000100 /* Interrupt Enable */
#define VS_FCN 0000076 /* Function Code */
#define VS_GO 0000001 /* GO! */
struct vs_csr{
union{
u_short _register;
struct{
unsigned _go : 1;
unsigned _function : 5;
unsigned _ie : 1;
unsigned _own : 1;
unsigned _spare : 1;
unsigned _mainDone : 1;
unsigned _CRCdisable : 1;
unsigned _mainMode : 1;
unsigned _xmitOn : 1;
unsigned _linkErr : 1;
unsigned _linkAvail : 1;
unsigned _linkTran : 1;
}_bits;
}_X;
};
#define csr_reg _X._register
#define csr_go _X._bits._go
#define csr_ie _X._bits._ie
#define csr_own _X._bits._own
#define csr_mainDone _X._bits._mainDone
#define csr_CRCdisable _X._bits._CRCdisable
#define csr_mainMode _X._bits._mainMode
#define csr_xmitOn _X._bits._xmitOn
#define csr_linkErr _X._bits._linkErr
#define csr_linkAvail _X._bits._linkAvail
#define csr_linkTran _X._bits._linkTran
/* Function Codes */
#define VS_INIT 01 /* Initialize Display */
#define VS_SEND 02 /* Send Packet */
#define VS_START 03 /* Start Microcode */
#define VS_ABORT 04 /* Abort Command Chain */
#define VS_PWRUP 05 /* Power Up Reset */
/**/
#define VS_ENABBA 020 /* Enable BBA */
#define VS_DISBBA 021 /* Disable BBA */
#define VS_INFINITE 022 /* Inifinite Retries */
#define VS_FINITE 023 /* Finite Retries */
/* amount to shift to get function code into right place */
#define VS_FCSHIFT 01
/*
* CSR1 - Interrupt Reason
*/
#define vs_irr vs_csr1
#define VS_ERROR 0100000 /* Any error */
#define VS_REASON 0077777 /* Reason Mask */
#define VSIRR_BITS \
"\20\20ERROR\10PWRUP\6TABLET\5MOUSE\4BUTTON\3START\2DONE\1INIT"
#define VS_INT_US 0
#define VS_INT_ID 01
#define VS_INT_CD 02
#define VS_INT_SE 04
#define VS_INT_BE 010
#define VS_INT_MM 020
#define VS_INT_TM 040
#define VS_INT_PWR 0200
struct vs_intr{
union{
u_short _register; /* whole register */
struct{
unsigned _reason : 14; /* Reason bits */
unsigned _diagnostic : 1; /* Diagnostic Error bit */
unsigned _error : 1; /* Error bit */
}_bits;
}_X;
};
#define intr_reg _X._register
#define intr_reason _X._bits._reason
#define intr_diagnostic _X._bits._diagnostic /* not in rev 2b */
#define intr_error _X._bits._error
/*
* CSR2 - Keyboard Receive
*/
#define vs_krr vs_csr2
#define VS_KBDEV 0007000 /* Device mask */
#define VS_KBT 0000400 /* Transition direction */
#define VS_KBKEY 0000377 /* Key mask */
struct vs_kbd{
union{
u_short _register; /* whole register */
struct{
unsigned _key : 8; /* Key number */
unsigned _transition : 1; /* Transition direction */
unsigned _device : 3; /* Device */
unsigned _x : 4; /* Unused */
}_bits;
}_X;
};
#define kbd_reg _X._register
#define kbd_key _X._bits._key
#define kbd_transition _X._bits._transition
#define kbd_device _X._bits._device
#define VS_KBTUP 0 /* up */
#define VS_KBTDOWN 1 /* down */
/*
* CSR3/4 Function Parameter Address
*/
#define vs_pr1 vs_csr3
#define vs_pr2 vs_csr4
struct vs_fparm{
union{
struct{
u_short _plow; /* low 16 bits of address */
u_short _phigh; /* high 16 bits of address */
}_parts;
caddr_t _pall;
}_X;
};
#define fparm_low _X._parts._plow
#define fparm_high _X._parts._phigh
#define fparm_all _X._pall
/*
* CSR5/6 - Cursor position
*/
#define vs_cxr vs_csr5
#define vs_cyr vs_csr6
/*
* CSR 7 - Interrupt vector in fiber cable machines
*/
#define vs_ivr vs_csr7
/*
* CSR 8 through 14 Spare
*/
#define vs_spr2 vs_csr8
#define vs_spr3 vs_csr9
#define vs_spr4 vs_csra
#define vs_spr5 vs_csrb
#define vs_spr6 vs_csrc
#define vs_spr7 vs_csrd
#define vs_spr8 vs_csre
/*
* CSR 15 - Interrupt vector in rev 2B
*/
#define vs_ivr2 vs_csrf
| 26.289362 | 78 | 0.657494 | [
"vector"
] |
af4cd7f5e3a942abf2eaae0597bc7fba94607da5 | 11,038 | h | C | src/spencer_people_tracking/detection/rgbd_detectors/pcl_people_detector/src/pcl/people/person_cluster.h | CodeToPoem/HumanAwareRobotNavigation | d44eb7e5acd73a5a7bf8bf1cd88c23d6a4a3c330 | [
"BSD-3-Clause"
] | 20 | 2017-10-26T05:58:24.000Z | 2021-06-13T11:18:54.000Z | src/spencer_people_tracking/detection/rgbd_detectors/pcl_people_detector/src/pcl/people/person_cluster.h | dmr-goncalves/HumanAwareRobotNavigation | d44eb7e5acd73a5a7bf8bf1cd88c23d6a4a3c330 | [
"BSD-3-Clause"
] | null | null | null | src/spencer_people_tracking/detection/rgbd_detectors/pcl_people_detector/src/pcl/people/person_cluster.h | dmr-goncalves/HumanAwareRobotNavigation | d44eb7e5acd73a5a7bf8bf1cd88c23d6a4a3c330 | [
"BSD-3-Clause"
] | 6 | 2018-02-05T09:31:42.000Z | 2022-02-07T22:05:57.000Z | /*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2013-, Open Perception, 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 the copyright holder(s) nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* person_cluster.h
* Created on: Nov 30, 2012
* Author: Matteo Munaro
*/
#ifndef PCL_PEOPLE_PERSON_CLUSTER_H_
#define PCL_PEOPLE_PERSON_CLUSTER_H_
#include <pcl/point_types.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <opencv2/opencv.hpp>
namespace pcl
{
namespace people
{
/** \brief @b PersonCluster represents a class for representing information about a cluster containing a person.
* \author Filippo Basso, Matteo Munaro
* \ingroup people
*/
template <typename PointT> class PersonCluster;
template <typename PointT> bool operator<(const PersonCluster<PointT>& c1, const PersonCluster<PointT>& c2);
template <typename PointT>
class PersonCluster
{
protected:
bool head_centroid_;
/** \brief Minimum x coordinate of the cluster points. */
float min_x_;
/** \brief Minimum y coordinate of the cluster points. */
float min_y_;
/** \brief Minimum z coordinate of the cluster points. */
float min_z_;
/** \brief Maximum x coordinate of the cluster points. */
float max_x_;
/** \brief Maximum y coordinate of the cluster points. */
float max_y_;
/** \brief Maximum z coordinate of the cluster points. */
float max_z_;
/** \brief Sum of x coordinates of the cluster points. */
float sum_x_;
/** \brief Sum of y coordinates of the cluster points. */
float sum_y_;
/** \brief Sum of z coordinates of the cluster points. */
float sum_z_;
/** \brief Number of cluster points. */
int n_;
/** \brief x coordinate of the cluster centroid. */
float c_x_;
/** \brief y coordinate of the cluster centroid. */
float c_y_;
/** \brief z coordinate of the cluster centroid. */
float c_z_;
/** \brief Cluster height from the ground plane. */
float height_;
/** \brief Cluster distance from the sensor. */
float distance_;
/** \brief Cluster centroid horizontal angle with respect to z axis. */
float angle_;
/** \brief Maximum angle of the cluster points. */
float angle_max_;
/** \brief Minimum angle of the cluster points. */
float angle_min_;
/** \brief Cluster top point. */
Eigen::Vector3f top_;
/** \brief Cluster bottom point. */
Eigen::Vector3f bottom_;
/** \brief Cluster centroid. */
Eigen::Vector3f center_;
/** \brief Theoretical cluster top. */
Eigen::Vector3f ttop_;
/** \brief Theoretical cluster bottom (lying on the ground plane). */
Eigen::Vector3f tbottom_;
/** \brief Theoretical cluster center (between ttop_ and tbottom_). */
Eigen::Vector3f tcenter_;
/** \brief Vector containing the minimum coordinates of the cluster. */
Eigen::Vector3f min_;
/** \brief Vector containing the maximum coordinates of the cluster. */
Eigen::Vector3f max_;
/** \brief Point cloud indices of the cluster points. */
pcl::PointIndices points_indices_;
/** \brief Region in the 2D image where the detection has been made. */
cv::Rect imageRegion_;
/** \brief If true, the sensor is considered to be vertically placed (portrait mode). */
bool vertical_;
/** \brief PersonCluster HOG confidence. */
float person_confidence_;
public:
typedef pcl::PointCloud<PointT> PointCloud;
typedef boost::shared_ptr<PointCloud> PointCloudPtr;
typedef boost::shared_ptr<const PointCloud> PointCloudConstPtr;
/** \brief Constructor. */
PersonCluster (
const PointCloudPtr& input_cloud,
const pcl::PointIndices& indices,
const Eigen::VectorXf& ground_coeffs,
float sqrt_ground_coeffs,
bool head_centroid,
bool vertical = false);
/** \brief Destructor. */
virtual ~PersonCluster ();
/**
* \brief Returns the height of the cluster.
* \return the height of the cluster.
*/
float
getHeight ();
/**
* \brief Update the height of the cluster.
* \param[in] ground_coeffs The coefficients of the ground plane.
* \return the height of the cluster.
*/
float
updateHeight (const Eigen::VectorXf& ground_coeffs);
/**
* \brief Update the height of the cluster.
* \param[in] ground_coeffs The coefficients of the ground plane.
* \param[in] sqrt_ground_coeffs The norm of the vector [a, b, c] where a, b and c are the first
* three coefficients of the ground plane (ax + by + cz + d = 0).
* \return the height of the cluster.
*/
float
updateHeight (const Eigen::VectorXf& ground_coeffs, float sqrt_ground_coeffs);
/**
* \brief Returns the distance of the cluster from the sensor.
* \return the distance of the cluster (its centroid) from the sensor without considering the
* y dimension.
*/
float
getDistance ();
/**
* \brief Returns the angle formed by the cluster's centroid with respect to the sensor (in radians).
* \return the angle formed by the cluster's centroid with respect to the sensor (in radians).
*/
float
getAngle ();
/**
* \brief Returns the minimum angle formed by the cluster with respect to the sensor (in radians).
* \return the minimum angle formed by the cluster with respect to the sensor (in radians).
*/
float
getAngleMin ();
/**
* \brief Returns the maximum angle formed by the cluster with respect to the sensor (in radians).
* \return the maximum angle formed by the cluster with respect to the sensor (in radians).
*/
float
getAngleMax ();
/**
* \brief Returns the indices of the point cloud points corresponding to the cluster.
* \return the indices of the point cloud points corresponding to the cluster.
*/
pcl::PointIndices&
getIndices ();
/**
* \brief Returns the theoretical top point.
* \return the theoretical top point.
*/
Eigen::Vector3f&
getTTop ();
/**
* \brief Returns the theoretical bottom point.
* \return the theoretical bottom point.
*/
Eigen::Vector3f&
getTBottom ();
/**
* \brief Returns the theoretical centroid (at half height).
* \return the theoretical centroid (at half height).
*/
Eigen::Vector3f&
getTCenter ();
/**
* \brief Returns the top point.
* \return the top point.
*/
Eigen::Vector3f&
getTop ();
/**
* \brief Returns the bottom point.
* \return the bottom point.
*/
Eigen::Vector3f&
getBottom ();
/**
* \brief Returns the centroid.
* \return the centroid.
*/
Eigen::Vector3f&
getCenter ();
//Eigen::Vector3f& getTMax();
/**
* \brief Returns the point formed by min x, min y and min z.
* \return the point formed by min x, min y and min z.
*/
Eigen::Vector3f&
getMin ();
/**
* \brief Returns the point formed by max x, max y and max z.
* \return the point formed by max x, max y and max z.
*/
Eigen::Vector3f&
getMax ();
/**
* \brief Returns the HOG confidence.
* \return the HOG confidence.
*/
float
getPersonConfidence ();
/**
* \brief Returns the number of points of the cluster.
* \return the number of points of the cluster.
*/
int
getNumberPoints ();
/**
* \brief Returns the detection rectangle in the properly rotated RGB image.
* \return rectangle
*/
const cv::Rect&
getImageRegion();
/**
* \brief Sets the cluster height.
* \param[in] height
*/
void
setHeight (float height);
/**
* \brief Sets the HOG confidence.
* \param[in] confidence
*/
void
setPersonConfidence (float confidence);
/**
* \brief Sets the detection rectangle in the properly rotated RGB image.
* \param[in] detection rectangle in RGB image
*/
void
setImageRegion(cv::Rect& imageRegion);
/**
* \brief Draws the theoretical 3D bounding box of the cluster in the PCL visualizer.
* \param[in] viewer PCL visualizer.
* \param[in] person_numbers progressive number representing the person.
*/
void
drawTBoundingBox (pcl::visualization::PCLVisualizer& viewer, int person_number);
/**
* \brief For sorting purpose: sort by distance.
*/
friend bool operator< <>(const PersonCluster<PointT>& c1, const PersonCluster<PointT>& c2);
protected:
/**
* \brief PersonCluster initialization.
*/
void init(
const PointCloudPtr& input_cloud,
const pcl::PointIndices& indices,
const Eigen::VectorXf& ground_coeffs,
float sqrt_ground_coeffs,
bool head_centroid,
bool vertical);
};
} /* namespace people */
} /* namespace pcl */
#include <pcl/people/impl/person_cluster.hpp>
#endif /* PCL_PEOPLE_PERSON_CLUSTER_H_ */
| 31.447293 | 116 | 0.630187 | [
"vector",
"3d"
] |
af5bfdc5fff8b37052de9424ae76d948d16af616 | 1,867 | h | C | src/algorithms/FeatureTD.h | olethrosdc/beliefbox | 44c0c160732b875f294a3f6d7f27e8f4cdf9602c | [
"OLDAP-2.3"
] | 4 | 2015-12-02T23:16:44.000Z | 2018-01-07T10:54:36.000Z | src/algorithms/FeatureTD.h | olethrosdc/beliefbox | 44c0c160732b875f294a3f6d7f27e8f4cdf9602c | [
"OLDAP-2.3"
] | 2 | 2015-12-02T19:47:57.000Z | 2018-10-14T13:08:40.000Z | src/algorithms/FeatureTD.h | olethrosdc/beliefbox | 44c0c160732b875f294a3f6d7f27e8f4cdf9602c | [
"OLDAP-2.3"
] | 4 | 2018-01-14T14:23:18.000Z | 2018-10-29T12:46:41.000Z | // -*- Mode: c++ -*-
// copyright (c) 2008 by Christos Dimitrakakis <christos.dimitrakakis@gmail.com>
// $Revision$
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#ifndef FEATURE_TD_H
#define FEATURE_TD_H
#include "DiscreteMDP.h"
#include "DiscretePolicy.h"
#include "ExplorationPolicy.h"
#include "Matrix.h"
#include "real.h"
#include "OnlineAlgorithm.h"
#include "BasisSet.h"
#include "Critic.h"
#include <vector>
class FeatureTD : public Critic<Vector, int>
{
protected:
const int n_states; ///< number of states
const int n_actions; ///< number
real gamma; ///< discount factor
real alpha; ///< learning rate
BasisSet<Vector, int>& features;
Vector params; ///< parameters
Vector state; ///< current state
int action; ///< current action
bool valid_state; ///< are we at the start of an episode?
public:
FeatureTD(int n_states_,
int n_actions_,
BasisSet<Vector, int>& features_,
real gamma_,
real alpha_=0.5);
virtual ~FeatureTD();
virtual void Reset();
/// Partial observation
virtual real Observe (real reward,
const Vector& next_state,
const int& next_action);
virtual real getValue (const Vector& state, const int& action) const;
virtual real getValue (const Vector& state) const;
};
#endif
| 32.754386 | 80 | 0.558115 | [
"vector"
] |
af5eac118a7666df8b97d4135393396789ee82d2 | 4,814 | h | C | lib/include/impl/MapGenerator.h | ford442/GlobeViewer | f9c990322e5d1c9c4beae29b3fb7ff0fb70ce587 | [
"MIT"
] | 6 | 2018-12-09T20:06:39.000Z | 2022-03-04T02:37:58.000Z | lib/include/impl/MapGenerator.h | ford442/GlobeViewer | f9c990322e5d1c9c4beae29b3fb7ff0fb70ce587 | [
"MIT"
] | 51 | 2018-09-26T13:05:33.000Z | 2019-09-18T17:07:09.000Z | lib/include/impl/MapGenerator.h | ford442/GlobeViewer | f9c990322e5d1c9c4beae29b3fb7ff0fb70ce587 | [
"MIT"
] | 5 | 2018-12-09T20:06:50.000Z | 2022-03-04T05:51:56.000Z | #pragma once
#include <atomic>
#include <mutex>
#include <thread>
#include <vector>
#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/signals2.hpp>
#include "type/TileServer.h"
#include "type/TileTexture.h"
#include "type/ViewData.h"
namespace gv {
class Projector;
/*!
* \brief Generates a single texture from several map tiles.
*
* MapGenerator gets signal that something is changed and map texture
* needs to be regenerated. First of all it determines which map tiles
* are currently visible at the view and requests them from the system.
* Once they arrive MapGenerator generates new texture in memory
* (which is a simple vector of chars) and fills it with new tiles.
* Then it send texture in memory to the system.
*
* MapGenerator is one of few classes that do a lot of work in a separate
* thread. That allows for non-blocking behaviour but also leads to
* delays in displaying the map.
*/
class MapGenerator
{
public:
MapGenerator();
~MapGenerator();
//! Initialize MapGenerator.
void init( ViewData );
//! Notification of rotating the Globe.
void updateGlobe();
//! Notification of updating viewport.
void updateViewData( ViewData );
//! Notification of changing tile server.
void updateTileServer( TileServer );
//! Receiving new map tiles.
void getTiles( const std::vector<TileImage>& );
//! Request for pointer to Projector instance.
boost::signals2::signal<std::shared_ptr<Projector>()> getProjector;
//! Request for map tiles from particular tile server.
boost::signals2::signal<void( std::vector<TileHead>, TileServer )> requestTiles;
//! Signal that map is not ready for rendering.
boost::signals2::signal<void()> mapNotReady;
//! Send new texture data.
boost::signals2::signal<void( std::vector<GLfloat> /*vbo*/, int /*texW*/, int /*texH*/,
std::vector<unsigned char> /*data*/)> updateMapTexture;
private:
//! Check and modify active_ and pending_ states before generating new map texture.
void checkStates();
//! Check and modify active_ and pending_ states after generating new map texture.
void cleanupCheck();
//! Generate new map texture.
void regenerateMap();
//! Convert longitude to tile coordinate x.
int lonToTileX( double lon, int z ) const;
//! Convert latitude to tile coordinate y.
int latToTileY( double lat, int z ) const;
//! Convert tile coordinate x to longitude.
double tileXToLon( int x, int z ) const;
//! Convert tile coordinate y to latitude.
double tileYToLat( int y, int z ) const;
//! Check if a point is visible in current projection.
bool visiblePoint( double& lon, double& lat );
//! Find all map tiles that need to be requested for further processing.
std::vector<TileHead> findTilesToProcess( int z, int x, int y );
//! Check if a tile is visible in current projection.
bool tileVisible( TileHead );
//! Build meta data of a new map texture based on tile headers.
void composeTileTexture( const std::vector<TileHead>& );
//! Create vertex buffer object for a new map texture.
void vboFromTileTexture( TileTexture );
//! Check if everything is ready for a new map texture.
void finalize();
boost::asio::io_context ioc_; //!< Allows implementing task queue.
boost::asio::executor_work_guard<boost::asio::io_context::executor_type> work_; //!< Provides work to ioc and doesn't let it stop.
std::vector<std::thread> threads_; //!< Vector of worker thread.
std::shared_ptr<Projector> projector_; //!< Pointer to Projector instance.
ViewData viewData_; //!< Current viewport dimensions data.
ViewData newViewData_; //!< Newly arrived viewport dimensions data.
TileServer tileServerType_; //!< Current server of map tiles.
TileServer newTileServerType_; //!< Newly arrived server of map tiles.
TileTexture tileTex_; //!< Meta data of texture currently being generated.
std::vector<GLfloat> vbo_; //!< Vertex buffer object for new texture.
std::vector<unsigned char> data_; //!< New texture data (plain bytes).
std::mutex mutexState_; //!< For state synchronization.
bool active_; //!< Indicator of new texture being generated.
bool pending_; //!< Indicator of existence of new texture generate request.
std::atomic<bool> gotTiles_; //!< Indicator of readiness of map tiles for currently generating texture.
std::atomic<bool> calcedVbo_; //!< Indicator of readiness of vertex buffer object for currently generating texture.
};
}
| 35.925373 | 134 | 0.674283 | [
"object",
"vector"
] |
af6ccacefde6165d21f2a8b7438ca67ee0bdeab0 | 1,689 | h | C | include/Experiment.h | nicoleorzan/RL-second-practical | ffdc8b816bf0a65030083d9b377fff186d59fce8 | [
"MIT"
] | 1 | 2021-02-18T21:46:03.000Z | 2021-02-18T21:46:03.000Z | include/Experiment.h | nicoleorzan/RL-second-practical | ffdc8b816bf0a65030083d9b377fff186d59fce8 | [
"MIT"
] | null | null | null | include/Experiment.h | nicoleorzan/RL-second-practical | ffdc8b816bf0a65030083d9b377fff186d59fce8 | [
"MIT"
] | null | null | null | #ifndef EXPERIMENT
#define EXPERIMENT
#include "Agent.h"
#include "Environment.h"
class Experiment{
public:
int n_runs;
int n_experiments;
int* num_steps_runs;
int* num_steps_each_experiment;
double* returns_each_experiment;
double* average_steps;
double* std_average_steps;
double* average_returns;
double* std_average_returns;
double T;
double retur = 0;
int reward_strategy = 0;
Experiment(int n_r, int n_exp, double Ti);
~Experiment();
void set_reward_strategy(int r);
void set_T(int t);
int single_run_SARSA(Agent &ag, Environment & env, int exploration_strategy);
int single_run_QL(Agent &ag, Environment & env, int exploration_strategy);
int single_run_double_QL(Agent &ag, Environment &env, int exploration_strategy);
int single_run_QV(Agent &ag, Environment &env, int exploration_strategy);
int take_action(Agent &ag, int s, std::vector<int> allow_act, int algoithm, int exploration_strategy);
void learning(Agent &ag, Environment & env, int experiment_number, int algorithm, int exploration_strategy);
int single_eval(Agent &ag, Environment & env, double epsilon_evaluation, int algorithm, int starting_state);
std::vector<int> evaluation(Agent &ag, Environment & env, int algorithm, int epsilon_evaluation, std::vector<int> starting_states);
void more_experiments(Agent &ag, Environment & env, int algorithm, int exploration_strategy);
double* compute_average_steps();
double* compute_average_returns();
double* get_std_average_steps();
double* get_std_average_returns();
};
#endif
| 26.809524 | 135 | 0.706927 | [
"vector"
] |
af6e924fa476f419978ff7d57810c14fe5f3b978 | 1,257 | h | C | rovers/fastdownward/src/search/heuristics/cg_heuristic.h | mehrdadzakershahrak/Online-Explanation-Generation | e41ad9b5a390abdaf271562a56105c191e33b74d | [
"MIT"
] | null | null | null | rovers/fastdownward/src/search/heuristics/cg_heuristic.h | mehrdadzakershahrak/Online-Explanation-Generation | e41ad9b5a390abdaf271562a56105c191e33b74d | [
"MIT"
] | null | null | null | rovers/fastdownward/src/search/heuristics/cg_heuristic.h | mehrdadzakershahrak/Online-Explanation-Generation | e41ad9b5a390abdaf271562a56105c191e33b74d | [
"MIT"
] | null | null | null | #ifndef HEURISTICS_CG_HEURISTIC_H
#define HEURISTICS_CG_HEURISTIC_H
#include "../heuristic.h"
#include "../algorithms/priority_queues.h"
#include <string>
#include <vector>
namespace domain_transition_graph {
class DomainTransitionGraph;
struct ValueNode;
}
class GlobalState;
class State;
namespace cg_heuristic {
class CGCache;
class CGHeuristic : public Heuristic {
std::vector<priority_queues::AdaptiveQueue<domain_transition_graph::ValueNode *> *> prio_queues;
std::vector<domain_transition_graph::DomainTransitionGraph *> transition_graphs;
CGCache *cache;
int cache_hits;
int cache_misses;
int helpful_transition_extraction_counter;
int min_action_cost;
void setup_domain_transition_graphs();
int get_transition_cost(
const State &state,
domain_transition_graph::DomainTransitionGraph *dtg,
int start_val,
int goal_val);
void mark_helpful_transitions(
const State &state,
domain_transition_graph::DomainTransitionGraph *dtg,
int to);
protected:
virtual int compute_heuristic(const GlobalState &state);
public:
CGHeuristic(const options::Options &opts);
~CGHeuristic();
virtual bool dead_ends_are_reliable() const;
};
}
#endif
| 23.277778 | 100 | 0.74463 | [
"vector"
] |
af7f5ece7dcee613e35c42243fc02b104dc97ff3 | 606 | h | C | certain/default/route_impl.h | mehrdad-shokri/paxosstore | 120ce539ef4fef18b3bef512cec28e3e0e3b241c | [
"BSD-3-Clause"
] | 1,567 | 2017-08-30T07:58:14.000Z | 2022-03-28T07:46:54.000Z | certain/default/route_impl.h | tomjobs/paxosstore | 120ce539ef4fef18b3bef512cec28e3e0e3b241c | [
"BSD-3-Clause"
] | 21 | 2017-08-31T01:21:30.000Z | 2021-08-31T12:55:39.000Z | certain/default/route_impl.h | tomjobs/paxosstore | 120ce539ef4fef18b3bef512cec28e3e0e3b241c | [
"BSD-3-Clause"
] | 352 | 2017-08-30T15:25:40.000Z | 2022-03-18T10:02:57.000Z | #pragma once
#include <vector>
#include "certain/route.h"
class RouteImpl : public certain::Route {
public:
RouteImpl(std::string local_addr, std::vector<std::string> addrs);
virtual std::string GetLocalAddr() override;
virtual int GetLocalAcceptorId(uint64_t entity_id,
uint32_t* acceptor_id) override;
virtual int GetServerAddrId(uint64_t entity_id, uint32_t acceptor_id,
uint64_t* addr_id) override;
private:
std::string local_addr_;
std::vector<std::string> addrs_;
std::vector<uint64_t> addr_ids_;
int index_;
};
| 24.24 | 71 | 0.676568 | [
"vector"
] |
af85433e3f48074d7803859de7b88b7eb9577ba6 | 14,583 | c | C | protocol/zigbee/app/framework/plugin-soc/configuration-server/configuration-server.c | lenloe1/v2.7 | 9ac9c4a7bb37987af382c80647f42d84db5f2e1d | [
"Zlib"
] | null | null | null | protocol/zigbee/app/framework/plugin-soc/configuration-server/configuration-server.c | lenloe1/v2.7 | 9ac9c4a7bb37987af382c80647f42d84db5f2e1d | [
"Zlib"
] | null | null | null | protocol/zigbee/app/framework/plugin-soc/configuration-server/configuration-server.c | lenloe1/v2.7 | 9ac9c4a7bb37987af382c80647f42d84db5f2e1d | [
"Zlib"
] | null | null | null | /***************************************************************************//**
* @file
* @brief Definitions for the Configuration Server plugin.
*******************************************************************************
* # License
* <b>Copyright 2018 Silicon Laboratories Inc. www.silabs.com</b>
*******************************************************************************
*
* The licensor of this software is Silicon Laboratories Inc. Your use of this
* software is governed by the terms of Silicon Labs Master Software License
* Agreement (MSLA) available at
* www.silabs.com/about-us/legal/master-software-license-agreement. This
* software is distributed to you in Source Code format and is governed by the
* sections of the MSLA applicable to Source Code.
*
******************************************************************************/
// this file contains all the common includes for clusters in the util
#include "app/framework/include/af.h"
#include "app/framework/util/attribute-storage.h"
#if defined (EMBER_AF_PLUGIN_POWER_METER_CS5463)
#include EMBER_AF_API_POWER_METER
#endif
#define FALSE_UINT8_T 0
#define TRUE_UINT8_T 1
#define TOKEN_DATA_OFFSET 1
#define TOKEN_DATA_LENGTH 0
#define STRING_TERMINATOR 0
void emAfPluginConfigurationServerReadTokenDataFromCreator(uint16_t creator,
uint8_t *data);
bool emAfPluginConfigurationServerLocked(void)
{
uint8_t lockTokenWrite;
halCommonGetToken((uint8_t *) (&lockTokenWrite), TOKEN_OTA_CONFIG_LOCK);
if (lockTokenWrite == FALSE_UINT8_T) {
return false;
} else {
return true;
}
}
void emberAfOtaConfigurationClusterServerInitCallback(uint8_t endpoint)
{
uint8_t returnData[OTA_CONFIG_MAX_TOKEN_LENGTH + 1];
#if defined (EMBER_AF_PLUGIN_POWER_METER_CS5463)
uint16_t currentMultiplier;
#endif
// configure the model name here.
MEMSET(returnData, 0, OTA_CONFIG_MAX_TOKEN_LENGTH + 1);
halCommonGetToken((returnData + TOKEN_DATA_OFFSET),
TOKEN_OTA_CONFIG_MODEL_NAME);
returnData[0] = strlen(returnData + TOKEN_DATA_OFFSET);
if (returnData[1] != 0xff && returnData[0] != 0) {
emberAfWriteServerAttribute(endpoint,
ZCL_BASIC_CLUSTER_ID,
ZCL_MODEL_IDENTIFIER_ATTRIBUTE_ID,
returnData,
ZCL_CHAR_STRING_ATTRIBUTE_TYPE);
}
halCommonGetToken((returnData + TOKEN_DATA_OFFSET),
TOKEN_OTA_CONFIG_MANUFACTURER_NAME);
returnData[0] = strlen(returnData + TOKEN_DATA_OFFSET);
if (returnData[1] != 0xff && returnData[0] != 0) {
emberAfWriteServerAttribute(endpoint,
ZCL_BASIC_CLUSTER_ID,
ZCL_MANUFACTURER_NAME_ATTRIBUTE_ID,
returnData,
ZCL_CHAR_STRING_ATTRIBUTE_TYPE);
}
halCommonGetToken(returnData, TOKEN_OTA_CONFIG_HW_VERSION);
if (returnData[0] != 0xff) {
emberAfWriteServerAttribute(endpoint,
ZCL_BASIC_CLUSTER_ID,
ZCL_HW_VERSION_ATTRIBUTE_ID,
returnData,
ZCL_INT8U_ATTRIBUTE_TYPE);
}
#if defined (EMBER_AF_PLUGIN_POWER_METER_CS5463)
halCommonGetToken(returnData, TOKEN_POWER_METER_CALIBRATION_CURRENT);
currentMultiplier = HIGH_LOW_TO_INT(returnData[1], returnData[0]);
emberAfCorePrintln("Configuration Server: Current setting from Token: 0x%2x",
currentMultiplier);
halSetCurrentGain(currentMultiplier);
#endif
}
bool emberAfOtaConfigurationClusterLockTokensCallback(void)
{
uint8_t lockTokenWrite = (uint8_t) TRUE_UINT8_T;
halCommonSetToken(TOKEN_OTA_CONFIG_LOCK, (uint8_t *) (&lockTokenWrite));
return true;
}
/** @brief Configuration Cluster Cluster Read Tokens
*
* This function will read the data specified by the 16-bit token value and
* generate the read response command.
*
* @param token Ver.: always
*/
bool emberAfOtaConfigurationClusterReadTokensCallback(uint16_t token)
{
uint8_t returnData[OTA_CONFIG_MAX_TOKEN_LENGTH + 1];
emAfPluginConfigurationServerReadTokenDataFromCreator(token, returnData);
// First, set up the outgoing command
emberAfFillCommandOtaConfigurationClusterReturnToken(token, returnData);
// now send to the current incoming device
emberAfSendResponse();
return true;
}
bool emberAfOtaConfigurationClusterSetTokenCallback(uint16_t token,
uint8_t* data)
{
#if defined (EMBER_AF_PLUGIN_POWER_METER_CS5463)
uint16_t currentGainRefernceMa;
#endif
if (emAfPluginConfigurationServerLocked()) {
emberAfCorePrintln("Locked");
return true;
} else {
emberAfCorePrintln("Unlocked");
}
switch (token) {
case CREATOR_OTA_CONFIG_TX_POWER:
halCommonSetToken(TOKEN_OTA_CONFIG_TX_POWER, (data + TOKEN_DATA_OFFSET));
break;
case CREATOR_OTA_CONFIG_TX_POWER25:
halCommonSetToken(TOKEN_OTA_CONFIG_TX_POWER25, (data + TOKEN_DATA_OFFSET));
break;
case CREATOR_OTA_CONFIG_TX_POWER26:
halCommonSetToken(TOKEN_OTA_CONFIG_TX_POWER26, (data + TOKEN_DATA_OFFSET));
break;
case CREATOR_OTA_CONFIG_MODEL_NAME:
if (data[TOKEN_DATA_LENGTH] > OTA_CONFIG_MAX_TOKEN_LENGTH) {
data[TOKEN_DATA_LENGTH] = OTA_CONFIG_MAX_TOKEN_LENGTH;
}
data[data[TOKEN_DATA_LENGTH] + 1] = STRING_TERMINATOR;
halCommonSetToken(TOKEN_OTA_CONFIG_MODEL_NAME, (data + TOKEN_DATA_OFFSET));
break;
case CREATOR_OTA_CONFIG_MANUFACTURER_NAME:
if (data[TOKEN_DATA_LENGTH] > OTA_CONFIG_MAX_TOKEN_LENGTH) {
data[TOKEN_DATA_LENGTH] = OTA_CONFIG_MAX_TOKEN_LENGTH;
}
data[data[TOKEN_DATA_LENGTH] + 1] = STRING_TERMINATOR;
halCommonSetToken(TOKEN_OTA_CONFIG_MANUFACTURER_NAME, (data + TOKEN_DATA_OFFSET));
break;
case CREATOR_OTA_CONFIG_HW_VERSION:
halCommonSetToken(TOKEN_OTA_CONFIG_HW_VERSION, (data + TOKEN_DATA_OFFSET));
break;
case CREATOR_OTA_CONFIG_DISTRIBUTED_KEY:
halCommonSetToken(TOKEN_OTA_CONFIG_DISTRIBUTED_KEY, (data + TOKEN_DATA_OFFSET));
break;
#if defined(EMBER_AF_PLUGIN_LED_RGB_PWM) || defined(EMBER_AF_PLUGIN_LED_TEMP_PWM) || defined(EMBER_AF_PLUGIN_LED_DIM_PWM)
case CREATOR_BULB_PWM_FREQUENCY_HZ:
halCommonSetToken(TOKEN_BULB_PWM_FREQUENCY_HZ, (data + TOKEN_DATA_OFFSET));
break;
case CREATOR_BULB_PWM_MIN_ON_US:
halCommonSetToken(TOKEN_BULB_PWM_MIN_ON_US, (data + TOKEN_DATA_OFFSET));
break;
case CREATOR_BULB_PWM_MAX_ON_US:
halCommonSetToken(TOKEN_BULB_PWM_MAX_ON_US, (data + TOKEN_DATA_OFFSET));
break;
#endif
#ifdef EMBER_AF_PLUGIN_BULB_UI
case CREATOR_BULB_UI_MIN_ON_TIME:
halCommonSetToken(TOKEN_BULB_UI_MIN_ON_TIME, (data + TOKEN_DATA_OFFSET));
break;
case CREATOR_BULB_UI_TIMEOUT:
halCommonSetToken(TOKEN_BULB_UI_TIMEOUT, (data + TOKEN_DATA_OFFSET));
break;
case CREATOR_BULB_UI_POWER_UP_BEHAVIOR:
halCommonSetToken(TOKEN_BULB_UI_POWER_UP_BEHAVIOR, (data + TOKEN_DATA_OFFSET));
break;
#endif
#if defined (EMBER_AF_PLUGIN_POWER_METER_CS5463)
case CREATOR_POWER_METER_CALIBRATION_CURRENT:
currentGainRefernceMa = HIGH_LOW_TO_INT(*((data + TOKEN_DATA_OFFSET) + 1),
*(data + TOKEN_DATA_OFFSET));
emberAfCorePrintln("Configuration Server: Reference Current: 0x%2x",
currentGainRefernceMa);
if (halPowerMeterCalibrateCurrentGain(currentGainRefernceMa)) {
emberAfCorePrintln("Configuration Server: Calibration started!");
} else {
emberAfCorePrintln("Configuration Server: Calibration failure!");
}
break;
#endif
default:
emberAfCorePrintln("Configuration Server: Unsupported Token %2x",
token);
break;
}
return true;
}
bool emberAfOtaConfigurationClusterUnlockTokensCallback(uint8_t* data)
{
uint8_t lockTokenWrite = (uint8_t) FALSE_UINT8_T;
uint8_t *eui64;
uint8_t hashData[EUI64_SIZE];
uint8_t i;
eui64 = emberGetEui64();
if (data[0] != EUI64_SIZE) {
return false;
}
// simple hash of the EUI64;
for (i = 0; i < EUI64_SIZE; i++) {
hashData[EUI64_SIZE - i - 1] = data[i + 1] + 0x80;
}
if (MEMCOMPARE(eui64, hashData, 8) == 0) {
halCommonSetToken(TOKEN_OTA_CONFIG_LOCK, (uint8_t *) (&lockTokenWrite));
}
return true;
}
void emAfPluginConfigurationServerReadTokenDataFromCreator(uint16_t creator,
uint8_t *data)
{
uint8_t returnData[OTA_CONFIG_MAX_TOKEN_LENGTH + 1];
switch (creator) {
case CREATOR_OTA_CONFIG_TX_POWER:
halCommonGetToken((uint8_t *) (data + TOKEN_DATA_OFFSET),
TOKEN_OTA_CONFIG_TX_POWER);
break;
case CREATOR_OTA_CONFIG_TX_POWER25:
halCommonGetToken((uint8_t *) (data + TOKEN_DATA_OFFSET),
TOKEN_OTA_CONFIG_TX_POWER25);
break;
case CREATOR_OTA_CONFIG_TX_POWER26:
halCommonGetToken((uint8_t *) (data + TOKEN_DATA_OFFSET),
TOKEN_OTA_CONFIG_TX_POWER26);
break;
case CREATOR_OTA_CONFIG_MODEL_NAME:
returnData[data[0] + 1] = 0;
halCommonGetToken((uint8_t *) (data + TOKEN_DATA_OFFSET),
TOKEN_OTA_CONFIG_MODEL_NAME);
break;
case CREATOR_OTA_CONFIG_MANUFACTURER_NAME:
returnData[data[0] + 1] = 0;
halCommonGetToken((uint8_t *) (data + TOKEN_DATA_OFFSET),
TOKEN_OTA_CONFIG_MANUFACTURER_NAME);
break;
case CREATOR_OTA_CONFIG_HW_VERSION:
halCommonGetToken((uint8_t *) (data + TOKEN_DATA_OFFSET),
TOKEN_OTA_CONFIG_HW_VERSION);
break;
case CREATOR_OTA_CONFIG_DISTRIBUTED_KEY:
halCommonGetToken((uint8_t *) (data + TOKEN_DATA_OFFSET),
TOKEN_OTA_CONFIG_DISTRIBUTED_KEY);
break;
#if defined(EMBER_AF_PLUGIN_LED_RGB_PWM) || defined(EMBER_AF_PLUGIN_LED_TEMP_PWM) || defined(EMBER_AF_PLUGIN_LED_DIM_PWM)
case CREATOR_BULB_PWM_FREQUENCY_HZ:
halCommonGetToken((uint8_t *) (data + TOKEN_DATA_OFFSET),
TOKEN_BULB_PWM_FREQUENCY_HZ);
break;
case CREATOR_BULB_PWM_MIN_ON_US:
halCommonGetToken((uint8_t *) (data + TOKEN_DATA_OFFSET),
TOKEN_BULB_PWM_MIN_ON_US);
break;
case CREATOR_BULB_PWM_MAX_ON_US:
halCommonGetToken((uint8_t *) (data + TOKEN_DATA_OFFSET),
TOKEN_BULB_PWM_MAX_ON_US);
break;
#endif
#ifdef EMBER_AF_PLUGIN_BULB_UI
case CREATOR_BULB_UI_MIN_ON_TIME:
halCommonGetToken((uint8_t *) (data + TOKEN_DATA_OFFSET),
TOKEN_BULB_UI_MIN_ON_TIME);
break;
case CREATOR_BULB_UI_TIMEOUT:
halCommonGetToken((uint8_t *) (data + TOKEN_DATA_OFFSET),
TOKEN_BULB_UI_TIMEOUT);
break;
case CREATOR_BULB_UI_POWER_UP_BEHAVIOR:
halCommonGetToken((uint8_t *) (data + TOKEN_DATA_OFFSET),
TOKEN_BULB_UI_POWER_UP_BEHAVIOR);
break;
#endif
#if defined (EMBER_AF_PLUGIN_POWER_METER_CS5463)
case CREATOR_POWER_METER_CALIBRATION_CURRENT:
halCommonGetToken((uint8_t *) (data + TOKEN_DATA_OFFSET),
TOKEN_POWER_METER_CALIBRATION_CURRENT);
break;
#endif
default:
break;
}
}
// callbacks for reading configuration values.
/** @brief Get Power For Radio Channel
*
* This callback is fired when the Network Steering plugin needs to set the
* power level. The application has the ability to change the max power level
* used for this particular channel.
*
* @param channel The channel that the plugin is inquiring about the power
* level. Ver.: always
*/
int8_t emberAfPluginNetworkSteeringGetPowerForRadioChannelCallback(uint8_t channel)
{
int8_t power, defaultPower;
switch (channel) {
case 26:
halCommonGetToken((uint8_t *) &power, TOKEN_OTA_CONFIG_TX_POWER26);
defaultPower = EMBER_AF_PLUGIN_CONFIGURATION_SERVER_TX_POWER26;
break;
case 25:
halCommonGetToken((uint8_t *) &power, TOKEN_OTA_CONFIG_TX_POWER25);
defaultPower = EMBER_AF_PLUGIN_CONFIGURATION_SERVER_TX_POWER25;
break;
default:
halCommonGetToken((uint8_t *) &power, TOKEN_OTA_CONFIG_TX_POWER);
defaultPower = EMBER_AF_PLUGIN_CONFIGURATION_SERVER_TX_POWER;
break;
}
emberAfCorePrintln("Config Tx Power: %d %d %d",
channel,
power,
defaultPower);
if (power == OTA_CONFIG_INVALID_TX_POWER) {
return defaultPower;
} else {
return power;
}
}
/** @brief Get Distributed Key
*
* This callback is fired when the Network Steering plugin needs to set the distributed
* key. The application set the distributed key from Zigbee Alliance thru this callback
* or the network steering will use the default test key.
*
* @param pointer to the distributed key struct
* @return true if the key is loaded successfully, otherwise false.
* level. Ver.: always
*/
bool emberAfPluginNetworkSteeringGetDistributedKeyCallback(EmberKeyData * key)
{
halCommonGetToken((key->contents), TOKEN_OTA_CONFIG_DISTRIBUTED_KEY);
return true;
}
#if defined(EMBER_AF_PLUGIN_LED_RGB_PWM) || defined(EMBER_AF_PLUGIN_LED_TEMP_PWM) || defined(EMBER_AF_PLUGIN_LED_DIM_PWM)
uint16_t emberAfPluginConfigurationServerReadMinOnTimeUs(void)
{
uint16_t time;
halCommonGetToken((uint8_t *) &time, TOKEN_BULB_PWM_MIN_ON_US);
return time;
}
uint16_t emberAfPluginConfigurationServerReadMaxOnTimeUs(void)
{
uint16_t time;
halCommonGetToken((uint8_t *) &time, TOKEN_BULB_PWM_MAX_ON_US);
return time;
}
uint16_t halBulbPwmDriverFrequencyCallback(void)
{
uint16_t frequency;
halCommonGetToken((uint8_t *) &frequency, TOKEN_BULB_PWM_FREQUENCY_HZ);
// Note: default value of token is the default value of the PWM frequency.
return frequency;
}
#endif //(EMBER_AF_PLUGIN_LED_RGB_PWM) || defined(EMBER_AF_PLUGIN_LED_TEMP_PWM) || defined(EMBER_AF_PLUGIN_LED_DIM_PWM)
#if defined (EMBER_AF_PLUGIN_POWER_METER_CS5463)
void halPowerMeterCalibrationFinishedCallback(uint16_t gainSetting)
{
halCommonSetToken(TOKEN_POWER_METER_CALIBRATION_CURRENT,
(uint8_t *)&gainSetting);
emberAfCorePrintln("Configuration Server: Calibration gain setting : 0x%2x",
gainSetting);
}
#endif
| 35.055288 | 121 | 0.687307 | [
"model"
] |
af862bc2d99c7c5a22fd524c7b902b8bb45fa1e4 | 3,679 | h | C | tools/mosesdecoder-master/moses/TranslationModel/UG/mm/ug_bitext_agenda_worker.h | shasha79/nectm | 600044a6fe2c3a73e0d9327bc85883831a26dcae | [
"Apache-2.0"
] | 3 | 2020-02-28T21:42:44.000Z | 2021-03-12T13:56:16.000Z | tools/mosesdecoder-master/moses/TranslationModel/UG/mm/ug_bitext_agenda_worker.h | Pangeamt/nectm | 6b84f048698f2530b9fdbb30695f2e2217c3fbfe | [
"Apache-2.0"
] | 2 | 2020-11-06T14:40:10.000Z | 2020-12-29T19:03:11.000Z | tools/mosesdecoder-master/moses/TranslationModel/UG/mm/ug_bitext_agenda_worker.h | Pangeamt/nectm | 6b84f048698f2530b9fdbb30695f2e2217c3fbfe | [
"Apache-2.0"
] | 2 | 2020-03-26T16:05:11.000Z | 2020-08-06T16:35:39.000Z | // -*- mode: c++; indent-tabs-mode: nil; tab-width:2 -*-
// to be included from ug_bitext_agenda.h
template<typename Token>
void
Bitext<Token>::agenda
::worker
::operator()()
{
// things to do:
//
// - have each worker maintain their own pstats object and merge
// results at the end (to minimize mutex locking);
//
// - use a non-locked, monotonically increasing counter to
// ensure the minimum size of samples considered --- it's OK if
// we look at more samples than required. This way, we can
// reduce the number of lock / unlock operations we need to do
// during sampling.
uint64_t sid=0, offset=0; // sid and offset of source phrase
size_t s1=0, s2=0, e1=0, e2=0; // soft and hard boundaries of target phrase
std::vector<unsigned char> aln; // stores phrase-pair-internal alignment
while(SPTR<job> j = ag.get_job())
{
j->stats->register_worker();
bitvector full_alignment(100*100); // Is full_alignment still needed???
while (j->nextSample(sid,offset))
{
aln.clear();
int po_fwd = LRModel::NONE;
int po_bwd = LRModel::NONE;
int docid = j->m_bias ? j->m_bias->GetClass(sid) : -1;
bitvector* full_aln = j->fwd ? &full_alignment : NULL;
// find soft and hard boundaries of target phrase
bool good = (ag.bt.find_trg_phr_bounds
(sid, offset, offset + j->len, // input parameters
s1, s2, e1, e2, po_fwd, po_bwd, // bounds & orientation
&aln, full_aln, !j->fwd)); // aln info / flip sides?
if (!good)
{ // no good, probably because phrase is not coherent
j->stats->count_sample(docid, 0, po_fwd, po_bwd);
continue;
}
// all good: register this sample as valid
size_t num_pairs = (s2-s1+1) * (e2-e1+1);
j->stats->count_sample(docid, num_pairs, po_fwd, po_bwd);
#if 0
Token const* t = ag.bt.T2->sntStart(sid);
Token const* eos = ag.bt.T2->sntEnd(sid);
cerr << "[" << j->stats->good + 1 << "] ";
while (t != eos) cerr << (*ag.bt.V2)[(t++)->id()] << " ";
cerr << "[" << docid << "]" << std::endl;
#endif
float sample_weight = 1./num_pairs;
Token const* o = (j->fwd ? ag.bt.T2 : ag.bt.T1)->sntStart(sid);
// adjust offsets in phrase-internal aligment
for (size_t k = 1; k < aln.size(); k += 2) aln[k] += s2 - s1;
std::vector<uint64_t> seen; seen.reserve(10);
// It is possible that the phrase extraction extracts the same
// phrase twice, e.g., when word a co-occurs with sequence b b b
// but is aligned only to the middle word. We can only count
// each phrase std::pair once per source phrase occurrence, or else
// run the risk of having more joint counts than marginal
// counts.
for (size_t s = s1; s <= s2; ++s)
{
TSA<Token> const& I = j->fwd ? *ag.bt.I2 : *ag.bt.I1;
SPTR<iter> b = I.find(o + s, e1 - s);
UTIL_THROW_IF2(!b || b->size() < e1-s, "target phrase not found");
for (size_t i = e1; i <= e2; ++i)
{
uint64_t tpid = b->getPid();
// poor man's protection against over-counting
size_t s = 0;
while (s < seen.size() && seen[s] != tpid) ++s;
if (s < seen.size()) continue;
seen.push_back(tpid);
size_t raw2 = b->approxOccurrenceCount();
float bwgt = j->m_bias ? (*j->m_bias)[sid] : 1;
j->stats->add(tpid, sample_weight, bwgt, aln, raw2,
po_fwd, po_bwd, docid);
bool ok = (i == e2) || b->extend(o[i].id());
UTIL_THROW_IF2(!ok, "Could not extend target phrase.");
}
if (s < s2) // shift phrase-internal alignments
for (size_t k = 1; k < aln.size(); k += 2)
--aln[k];
}
}
j->stats->release(); // indicate that you're done working on j->stats
}
}
| 35.038095 | 78 | 0.606687 | [
"object",
"vector"
] |
af943850b1f66581bbcd90a76d146af75bdc5cd8 | 3,548 | h | C | stig/indy/disk/test_file_service.h | ctidder/stigdb | d9ef3eb117d46542745ca98c55df13ec71447091 | [
"Apache-2.0"
] | 5 | 2018-04-24T12:36:50.000Z | 2020-03-25T00:37:17.000Z | stig/indy/disk/test_file_service.h | ctidder/stigdb | d9ef3eb117d46542745ca98c55df13ec71447091 | [
"Apache-2.0"
] | null | null | null | stig/indy/disk/test_file_service.h | ctidder/stigdb | d9ef3eb117d46542745ca98c55df13ec71447091 | [
"Apache-2.0"
] | 2 | 2018-04-24T12:39:24.000Z | 2020-03-25T00:45:08.000Z | /* <stig/indy/disk/test_file_service.h>
TODO
Copyright 2010-2014 Tagged
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 <stig/indy/disk/file_service_base.h>
namespace Stig {
namespace Indy {
namespace Disk {
/* TODO */
class TTestFileService
: public TFileServiceBase {
NO_COPY_SEMANTICS(TTestFileService);
public:
/* TODO */
virtual bool FindFile(const Base::TUuid &file_uid,
size_t gen_id,
size_t &out_block_id,
size_t &out_block_offset,
size_t &out_file_size,
size_t &out_num_keys) const override;
/* TODO */
virtual void InsertFile(const Base::TUuid &file_uid,
TFileObj::TKind file_kind,
size_t gen_id,
size_t starting_block_id,
size_t starting_block_offset,
size_t file_size,
size_t num_keys,
TSequenceNumber lowest_seq,
TSequenceNumber highest_seq,
TCompletionTrigger &completion_trigger) override;
/* TODO */
virtual void RemoveFile(const Base::TUuid &file_uid,
size_t gen_id,
TCompletionTrigger &completion_trigger) override;
/* TODO */
virtual void AppendFileGenSet(const Base::TUuid &file_uid,
std::vector<TFileObj> &out_vec) override;
/* TODO */
virtual bool ForEachFile(const std::function<bool (const Base::TUuid &file_uid, const TFileObj &)> &cb) override;
/* TODO */
TTestFileService() {}
/* TODO */
virtual ~TTestFileService() {}
private:
/* TODO */
typedef std::unordered_map<Base::TUuid, std::unordered_map<size_t, TFileObj>> TFileMap;
/* TODO */
static void AddToMap(TFileMap &file_map,
const Base::TUuid &file_uid,
TFileObj::TKind file_kind,
size_t file_gen,
size_t starting_block_id,
size_t starting_block_offset,
size_t file_size,
size_t num_keys,
TSequenceNumber lowest_seq,
TSequenceNumber highest_seq);
/* TODO */
static void RemoveFromMap(TFileMap &file_map,
const Base::TUuid &file_uid,
size_t file_gen);
/* TODO */
mutable std::mutex Mutex;
/* TODO */
TFileMap FileMap;
}; // TFileServiceBase
} // Disk
} // Indy
} // Stig
| 32.851852 | 121 | 0.515784 | [
"vector"
] |
af95b9409e0d86e9186ea051e5b83c997bb74585 | 5,477 | h | C | src/lib/UBIAnalysis.h | YizhuoZhai/UBITect | 525866d8ca24e03cb9ddd805c4dd0d789c33cff8 | [
"MIT"
] | 26 | 2020-06-20T15:13:14.000Z | 2022-03-30T12:49:51.000Z | src/lib/UBIAnalysis.h | YizhuoZhai/UBITect | 525866d8ca24e03cb9ddd805c4dd0d789c33cff8 | [
"MIT"
] | null | null | null | src/lib/UBIAnalysis.h | YizhuoZhai/UBITect | 525866d8ca24e03cb9ddd805c4dd0d789c33cff8 | [
"MIT"
] | 8 | 2020-07-09T23:39:23.000Z | 2021-04-21T20:21:20.000Z | //
// Created by ubuntu on 10/22/17.
//
#ifndef UBIANALYSIS_H
#define UBIANALYSIS_H
#include <llvm/IR/DebugInfo.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/Instructions.h>
#include <llvm/ADT/DenseMap.h>
#include <llvm/ADT/SmallPtrSet.h>
#include <llvm/ADT/StringExtras.h>
#include <llvm/Support/Path.h>
#include <llvm/Support/raw_ostream.h>
#include "llvm/Support/CommandLine.h"
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <list>
#include <queue>
#include "Common.h"
#include "StructAnalyzer.h"
#include "FunctionSummary.h"
//
// typedefs
//
typedef std::vector< std::pair<llvm::Module*, llvm::StringRef> > ModuleList;
// Mapping module to its file name.
typedef std::unordered_map<llvm::Module*, llvm::StringRef> ModuleNameMap;
// The set of all functions.
typedef llvm::SmallPtrSet<llvm::Function*, 8> FuncSet;
// Mapping from function name to function.
typedef std::unordered_map<std::string, llvm::Function*> NameFuncMap;
typedef llvm::SmallPtrSet<llvm::CallInst*, 8> CallInstSet;
typedef std::unordered_map<std::string, llvm::GlobalVariable*> GObjMap;
typedef llvm::DenseMap<llvm::Function*, CallInstSet> CallerMap;
typedef llvm::DenseMap<llvm::CallInst *, FuncSet> CalleeMap;
//mapping from the function to the functions it calls
typedef std::unordered_map<llvm::Function*, std::set<llvm::Function*>> CallMap;
typedef llvm::DenseMap<llvm::Function *, FuncSet> CalledMap;
typedef std::unordered_map<std::string, FuncSet> FuncPtrMap;
typedef std::unordered_map<llvm::Function *, Summary> FtSummary;
typedef std::unordered_map<llvm::Function*, std::set<llvm::Value*>> FuncHolder;
struct GlobalContext {
GlobalContext() {}
// Map global function name to function defination.
NameFuncMap Funcs;
std::map<std::string, std::set<llvm::Function*>> nameFuncs;
// Map global object name to object definition
GObjMap Gobjs;
// Map function pointers (IDs) to possible assignments
std::set<llvm::Function*> FPtrs;
FuncPtrMap FuncPtrs;
// Functions whose addresses are taken.
FuncSet AddressTakenFuncs;
// Map a callsite to all potential callee functions.
CalleeMap Callees;
// Conservative mapping for callees for a callsite
CalleeMap ConsCallees;
//map the function to the struct which holds the function
FuncHolder FuncHolders;
// Map a function to all potential caller instructions.
CallerMap Callers;
//Map a function to the functions it calls
CallMap CallMaps;
CallMap DirectCallMap;
//Map a function to the functions who call it
CalledMap CalledMaps;
//visit map used in qualifier analysis
std::map<llvm::Function *, bool> Visit;
//functions ready for analysis
std::set<llvm::Function* > ReadyList;
//calculate the # of called functions of the caller
std::map<llvm::Function*, int> RemainedFunction;
std::unordered_set<llvm::Function* > indFuncs;
std::vector<std::vector<llvm::Function*>> SCC;
std::set<llvm::Function*> rec;
std::unordered_map<std::string, std::set<int>> Warnings;
//FunctionSummary
FtSummary FSummaries;
//The number of the uninitialized variables when declared.
long long numDecl = 0;
long long numUninit = 0;
long long fieldDecl = 0;
long long fieldUninit = 0;
//The # of variables which treat as ubi with intra-procedural analysis
//uninitArg gives the total # of variables which are uninit while passing to the callee
long long uninitArg = 0;
//uninitOut Arg calculate the # of variables which are not uninit if it comes from argument
long long uninitOutArg = 0;
//ignoreOutArg calculate the # of variables which are
long long ignoreOutArg = 0;
//For the finalization, change means the summary changes
std::map<llvm::Function *, bool> ChangeMap;
// Indirect call instructions.
std::vector<llvm::CallInst *> IndirectCallInsts;
// Modules.
ModuleList Modules;
ModuleNameMap ModuleMaps;
std::set<std::string> InvolvedModules;
// Some manually-summarized functions that initialize
// values.
std::set<std::string> HeapAllocFuncs;
std::set<std::string> CopyFuncs;
std::set<std::string> InitFuncs;
std::set<std::string> TransferFuncs;
std::set<std::string> ZeroMallocFuncs;
std::set<std::string> ObjSizeFuncs;
std::set<std::string> StrFuncs;
std::set<std::string> OtherFuncs;
std::set<std::string> visitedFuncs;
// StructAnalyzer
StructAnalyzer structAnalyzer;
std::map<const llvm::StructType*, std::set<int>> usedField;
std::unordered_map<llvm::Function*, std::set<std::pair<std::string, std::string>>> fToWarns;
};
class IterativeModulePass {
protected:
GlobalContext *Ctx;
const char * ID;
public:
IterativeModulePass(GlobalContext *Ctx_, const char *ID_)
: Ctx(Ctx_), ID(ID_) { }
// Run on each module before iterative pass.
virtual bool doInitialization(llvm::Module *M)
{ return true; }
// Run on each module after iterative pass.
virtual bool doFinalization(llvm::Module *M)
{ return true; }
// Iterative pass.
virtual bool doModulePass(llvm::Module *M)
{ return false; }
virtual void run(ModuleList &modules);
// virtual void collectRemaining(){}
// virtual void calDepFuncs(){}
// virtual void finalize(){}
};
#endif //UBIANALYSIS_H
| 31.297143 | 96 | 0.707687 | [
"object",
"vector"
] |
af96784d3f70ea67c05e4f956fb06f92b60a544c | 5,220 | h | C | mango-library/include/misc/vector.h | lolsxds/mango-library | 0d0d22b7927a73763c62c93c09d320a2b0317ade | [
"MIT"
] | 1 | 2021-04-01T11:02:56.000Z | 2021-04-01T11:02:56.000Z | mango-library/include/misc/vector.h | lolsxds/mango-library | 0d0d22b7927a73763c62c93c09d320a2b0317ade | [
"MIT"
] | null | null | null | mango-library/include/misc/vector.h | lolsxds/mango-library | 0d0d22b7927a73763c62c93c09d320a2b0317ade | [
"MIT"
] | null | null | null | #pragma once
#include <array>
#include <ostream>
#include <iomanip>
#include <numeric>
#include "misc.h"
// fkn windows
#undef min
#undef max
namespace mango {
// vector class for math stuffz
template <typename T, size_t C>
class Vector : public std::array<T, C> {
public:
// only arithmetic values
static_assert(std::is_arithmetic_v<T>, "Only arithmetic types supported");
// dimension >= 1
static_assert(C >= 1, "Must have a size of one or more");
// std::array::fill() is not constexpr btw
constexpr explicit Vector(const T& scalar = T{ 0 }) noexcept {
for_constexpr<0, C, 1>([&](const size_t i) {
(*this)[i] = scalar;
});
}
// copy constructor
template <typename Type>
constexpr explicit Vector(const Vector<Type, C>& other) noexcept {
for_constexpr<0, C, 1>([&](const size_t i) {
(*this)[i] = T(other[i]);
});
}
// copy constructor from std::array
template <typename Type>
constexpr explicit Vector(const std::array<Type, C>& other) noexcept {
for_constexpr<0, C, 1>([&](const size_t i) {
(*this)[i] = T(other[i]);
});
}
// Vector(...) or Vector({...}) or Vector v = {...}
template <typename... Args>
constexpr Vector(const Args&... args) noexcept : std::array<T, C>{ T(args)... } {
static_assert(sizeof...(Args) == C, "Incorrect amount of arguments provided");
}
// addition
constexpr Vector<T, C>& operator+=(const Vector<T, C>& other) {
return *this = (*this + other);
}
constexpr Vector<T, C> operator+(const Vector<T, C>& other) const {
Vector<T, C> copy{ *this };
for_constexpr<0, C, 1>([&](const size_t i) {
copy[i] += other[i];
});
return copy;
}
// subtraction
constexpr Vector<T, C>& operator-=(const Vector<T, C>& other) {
return *this = (*this - other);
}
constexpr Vector<T, C> operator-(const Vector<T, C>& other) const {
Vector<T, C> copy{ *this };
for_constexpr<0, C, 1>([&](const size_t i) {
copy[i] -= other[i];
});
return copy;
}
// multiplication
constexpr Vector<T, C>& operator*=(const Vector<T, C>& other) {
return *this = (*this * other);
}
constexpr Vector<T, C> operator*(const Vector<T, C>& other) const {
Vector<T, C> copy{ *this };
for_constexpr<0, C, 1>([&](const size_t i) {
copy[i] *= other[i];
});
return copy;
}
// division
constexpr Vector<T, C>& operator/=(const Vector<T, C>& other) {
return *this = (*this / other);
}
constexpr Vector<T, C> operator/(const Vector<T, C>& other) const {
Vector<T, C> copy{ *this };
for_constexpr<0, C, 1>([&](const size_t i) {
copy[i] /= other[i];
});
return copy;
}
// get the length (or magnitude) of a vector
template <const size_t D = C>
double length() const noexcept {
// D must be in the range of (0, C]
static_assert(D <= C, "D cannot be higher than C");
static_assert(D >= 1, "D must be one or greater");
double total{ 0 };
for (const auto x : *this)
total += x * x;
return total <= 0.0 ? 0.0 : std::sqrt(total);
}
// normalize a vector (in place)
const Vector<T, C>& normalize() noexcept {
// only floats
static_assert(std::is_floating_point_v<T>, "Only floating-point vectors can be normalized");
const auto length{ this->length() };
// can't divide by 0
if (length <= 0.0)
return *this;
for (auto& x : *this)
x /= T(length);
return *this;
}
// return a normalized vector
static Vector<T, C> normalize(Vector<T, C> vec) noexcept {
vec.normalize();
return vec;
}
// the sum of all elements
constexpr T sum() const noexcept {
T total{ 0 };
for (const auto x : *this)
total += x;
return total;
}
// find the mean (obviously)
constexpr double mean() const noexcept {
return this->sum() / double(C);
}
// find the median (obviously)
constexpr double median() const noexcept {
const auto center{ C / 2 - 1 };
if (C % 2 == 0) { // even
return double((*this)[center] + (*this)[center + 1]) / 2.0;
} else { // odd
return double((*this)[center]);
}
}
};
// lets you do stuff like std::cout << vec;
template <typename T, const size_t C>
std::ostream& operator<<(std::ostream& stream, const Vector<T, C>& vec) {
stream << "[ " << +vec.front();
for (size_t i{ 1 }; i < vec.size(); ++i)
stream << ", " << +vec[i];
return stream << " ]";
}
// lets you do stuff like std::wcout << vec;
template <typename T, const size_t C>
std::wostream& operator<<(std::wostream& stream, const Vector<T, C>& vec) {
stream << L"[ " << +vec.front();
for (size_t i{ 1 }; i < vec.size(); ++i)
stream << L", " << +vec[i];
return stream << L" ]";
}
// floats
using Vec2f = Vector<float, 2>;
using Vec3f = Vector<float, 3>;
using Vec4f = Vector<float, 4>;
// doubles
using Vec2d = Vector<float, 2>;
using Vec3d = Vector<float, 3>;
using Vec4d = Vector<float, 4>;
// ints
using Vec2i = Vector<int, 2>;
using Vec3i = Vector<int, 3>;
using Vec4i = Vector<int, 4>;
} // namespace mango | 26.632653 | 96 | 0.575287 | [
"vector"
] |
afa02136ec734e6e99d50d56823747abf00d6c70 | 564 | h | C | src/xrServerEntities/object_factory_space.h | clayne/xray-16 | 32ebf81a252c7179e2824b2874f911a91e822ad1 | [
"OML",
"Linux-OpenIB"
] | 2 | 2015-02-23T10:43:02.000Z | 2015-06-11T14:45:08.000Z | src/xrServerEntities/object_factory_space.h | clayne/xray-16 | 32ebf81a252c7179e2824b2874f911a91e822ad1 | [
"OML",
"Linux-OpenIB"
] | 17 | 2022-01-25T08:58:23.000Z | 2022-03-28T17:18:28.000Z | src/xrServerEntities/object_factory_space.h | clayne/xray-16 | 32ebf81a252c7179e2824b2874f911a91e822ad1 | [
"OML",
"Linux-OpenIB"
] | 1 | 2015-06-05T20:04:00.000Z | 2015-06-05T20:04:00.000Z | ////////////////////////////////////////////////////////////////////////////
// Module : object_factory_space.h
// Created : 30.06.2004
// Modified : 30.06.2004
// Author : Dmitriy Iassenev
// Description : Object factory space
////////////////////////////////////////////////////////////////////////////
#pragma once
#ifndef XRGAME_EXPORTS
#define NO_XR_GAME
#endif
class IFactoryObject;
class CSE_Abstract;
namespace ObjectFactory
{
#ifndef NO_XR_GAME
using ClientObjectBaseClass = IFactoryObject;
#endif
using ServerObjectBaseClass = CSE_Abstract;
};
| 22.56 | 76 | 0.560284 | [
"object"
] |
afa406eba59f88f8dae51d0eab90c4dceeb4cd9e | 157,357 | c | C | SQLCipher/src/tsrc/parse.c | dwiller/grdb-swift | f207430b50af0f4cd735e5ae8361921f46814c2e | [
"MIT"
] | null | null | null | SQLCipher/src/tsrc/parse.c | dwiller/grdb-swift | f207430b50af0f4cd735e5ae8361921f46814c2e | [
"MIT"
] | null | null | null | SQLCipher/src/tsrc/parse.c | dwiller/grdb-swift | f207430b50af0f4cd735e5ae8361921f46814c2e | [
"MIT"
] | 1 | 2020-11-04T06:58:34.000Z | 2020-11-04T06:58:34.000Z | /* Driver template for the LEMON parser generator.
** The author disclaims copyright to this source code.
**
** This version of "lempar.c" is modified, slightly, for use by SQLite.
** The only modifications are the addition of a couple of NEVER()
** macros to disable tests that are needed in the case of a general
** LALR(1) grammar but which are always false in the
** specific grammar used by SQLite.
*/
/* First off, code is included that follows the "include" declaration
** in the input grammar file. */
#include <stdio.h>
#line 49 "parse.y"
#include "sqliteInt.h"
/*
** Disable all error recovery processing in the parser push-down
** automaton.
*/
#define YYNOERRORRECOVERY 1
/*
** Make yytestcase() the same as testcase()
*/
#define yytestcase(X) testcase(X)
/*
** An instance of this structure holds information about the
** LIMIT clause of a SELECT statement.
*/
struct LimitVal {
Expr *pLimit; /* The LIMIT expression. NULL if there is no limit */
Expr *pOffset; /* The OFFSET expression. NULL if there is none */
};
/*
** An instance of this structure is used to store the LIKE,
** GLOB, NOT LIKE, and NOT GLOB operators.
*/
struct LikeOp {
Token eOperator; /* "like" or "glob" or "regexp" */
int bNot; /* True if the NOT keyword is present */
};
/*
** An instance of the following structure describes the event of a
** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
** TK_DELETE, or TK_INSTEAD. If the event is of the form
**
** UPDATE ON (a,b,c)
**
** Then the "b" IdList records the list "a,b,c".
*/
struct TrigEvent { int a; IdList * b; };
/*
** An instance of this structure holds the ATTACH key and the key type.
*/
struct AttachKey { int type; Token key; };
#line 412 "parse.y"
/*
** For a compound SELECT statement, make sure p->pPrior->pNext==p for
** all elements in the list. And make sure list length does not exceed
** SQLITE_LIMIT_COMPOUND_SELECT.
*/
static void parserDoubleLinkSelect(Parse *pParse, Select *p){
if( p->pPrior ){
Select *pNext = 0, *pLoop;
int mxSelect, cnt = 0;
for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){
pLoop->pNext = pNext;
pLoop->selFlags |= SF_Compound;
}
if( (p->selFlags & SF_MultiValue)==0 &&
(mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0 &&
cnt>mxSelect
){
sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
}
}
}
#line 814 "parse.y"
/* This is a utility routine used to set the ExprSpan.zStart and
** ExprSpan.zEnd values of pOut so that the span covers the complete
** range of text beginning with pStart and going to the end of pEnd.
*/
static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
pOut->zStart = pStart->z;
pOut->zEnd = &pEnd->z[pEnd->n];
}
/* Construct a new Expr object from a single identifier. Use the
** new Expr to populate pOut. Set the span of pOut to be the identifier
** that created the expression.
*/
static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
pOut->zStart = pValue->z;
pOut->zEnd = &pValue->z[pValue->n];
}
#line 904 "parse.y"
/* This routine constructs a binary expression node out of two ExprSpan
** objects and uses the result to populate a new ExprSpan object.
*/
static void spanBinaryExpr(
ExprSpan *pOut, /* Write the result here */
Parse *pParse, /* The parsing context. Errors accumulate here */
int op, /* The binary operation */
ExprSpan *pLeft, /* The left operand */
ExprSpan *pRight /* The right operand */
){
pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
pOut->zStart = pLeft->zStart;
pOut->zEnd = pRight->zEnd;
}
#line 958 "parse.y"
/* Construct an expression node for a unary postfix operator
*/
static void spanUnaryPostfix(
ExprSpan *pOut, /* Write the new expression node here */
Parse *pParse, /* Parsing context to record errors */
int op, /* The operator */
ExprSpan *pOperand, /* The operand */
Token *pPostOp /* The operand token for setting the span */
){
pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
pOut->zStart = pOperand->zStart;
pOut->zEnd = &pPostOp->z[pPostOp->n];
}
#line 977 "parse.y"
/* A routine to convert a binary TK_IS or TK_ISNOT expression into a
** unary TK_ISNULL or TK_NOTNULL expression. */
static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
sqlite3 *db = pParse->db;
if( pY && pA && pY->op==TK_NULL ){
pA->op = (u8)op;
sqlite3ExprDelete(db, pA->pRight);
pA->pRight = 0;
}
}
#line 1005 "parse.y"
/* Construct an expression node for a unary prefix operator
*/
static void spanUnaryPrefix(
ExprSpan *pOut, /* Write the new expression node here */
Parse *pParse, /* Parsing context to record errors */
int op, /* The operator */
ExprSpan *pOperand, /* The operand */
Token *pPreOp /* The operand token for setting the span */
){
pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
pOut->zStart = pPreOp->z;
pOut->zEnd = pOperand->zEnd;
}
#line 164 "parse.c"
/* Next is all token values, in a form suitable for use by makeheaders.
** This section will be null unless lemon is run with the -m switch.
*/
/*
** These constants (all generated automatically by the parser generator)
** specify the various kinds of tokens (terminals) that the parser
** understands.
**
** Each symbol here is a terminal symbol in the grammar.
*/
/* Make sure the INTERFACE macro is defined.
*/
#ifndef INTERFACE
# define INTERFACE 1
#endif
/* The next thing included is series of defines which control
** various aspects of the generated parser.
** YYCODETYPE is the data type used for storing terminal
** and nonterminal numbers. "unsigned char" is
** used if there are fewer than 250 terminals
** and nonterminals. "int" is used otherwise.
** YYNOCODE is a number of type YYCODETYPE which corresponds
** to no legal terminal or nonterminal number. This
** number is used to fill in empty slots of the hash
** table.
** YYFALLBACK If defined, this indicates that one or more tokens
** have fall-back values which should be used if the
** original value of the token will not parse.
** YYACTIONTYPE is the data type used for storing terminal
** and nonterminal numbers. "unsigned char" is
** used if there are fewer than 250 rules and
** states combined. "int" is used otherwise.
** sqlite3ParserTOKENTYPE is the data type used for minor tokens given
** directly to the parser from the tokenizer.
** YYMINORTYPE is the data type used for all minor tokens.
** This is typically a union of many types, one of
** which is sqlite3ParserTOKENTYPE. The entry in the union
** for base tokens is called "yy0".
** YYSTACKDEPTH is the maximum depth of the parser's stack. If
** zero the stack is dynamically sized using realloc()
** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument
** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument
** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser
** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser
** YYNSTATE the combined number of states.
** YYNRULE the number of rules in the grammar
** YYERRORSYMBOL is the code number of the error symbol. If not
** defined, then do no error processing.
*/
#define YYCODETYPE unsigned char
#define YYNOCODE 254
#define YYACTIONTYPE unsigned short int
#define YYWILDCARD 70
#define sqlite3ParserTOKENTYPE Token
typedef union {
int yyinit;
sqlite3ParserTOKENTYPE yy0;
Select* yy3;
ExprList* yy14;
With* yy59;
SrcList* yy65;
struct LikeOp yy96;
Expr* yy132;
u8 yy186;
int yy328;
ExprSpan yy346;
struct TrigEvent yy378;
u16 yy381;
IdList* yy408;
struct {int value; int mask;} yy429;
TriggerStep* yy473;
struct LimitVal yy476;
} YYMINORTYPE;
#ifndef YYSTACKDEPTH
#define YYSTACKDEPTH 100
#endif
#define sqlite3ParserARG_SDECL Parse *pParse;
#define sqlite3ParserARG_PDECL ,Parse *pParse
#define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
#define sqlite3ParserARG_STORE yypParser->pParse = pParse
#define YYNSTATE 642
#define YYNRULE 327
#define YYFALLBACK 1
#define YY_NO_ACTION (YYNSTATE+YYNRULE+2)
#define YY_ACCEPT_ACTION (YYNSTATE+YYNRULE+1)
#define YY_ERROR_ACTION (YYNSTATE+YYNRULE)
/* The yyzerominor constant is used to initialize instances of
** YYMINORTYPE objects to zero. */
static const YYMINORTYPE yyzerominor = { 0 };
/* Define the yytestcase() macro to be a no-op if is not already defined
** otherwise.
**
** Applications can choose to define yytestcase() in the %include section
** to a macro that can assist in verifying code coverage. For production
** code the yytestcase() macro should be turned off. But it is useful
** for testing.
*/
#ifndef yytestcase
# define yytestcase(X)
#endif
/* Next are the tables used to determine what action to take based on the
** current state and lookahead token. These tables are used to implement
** functions that take a state number and lookahead value and return an
** action integer.
**
** Suppose the action integer is N. Then the action is determined as
** follows
**
** 0 <= N < YYNSTATE Shift N. That is, push the lookahead
** token onto the stack and goto state N.
**
** YYNSTATE <= N < YYNSTATE+YYNRULE Reduce by rule N-YYNSTATE.
**
** N == YYNSTATE+YYNRULE A syntax error has occurred.
**
** N == YYNSTATE+YYNRULE+1 The parser accepts its input.
**
** N == YYNSTATE+YYNRULE+2 No such action. Denotes unused
** slots in the yy_action[] table.
**
** The action table is constructed as a single large table named yy_action[].
** Given state S and lookahead X, the action is computed as
**
** yy_action[ yy_shift_ofst[S] + X ]
**
** If the index value yy_shift_ofst[S]+X is out of range or if the value
** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
** and that yy_default[S] should be used instead.
**
** The formula above is for computing the action when the lookahead is
** a terminal symbol. If the lookahead is a non-terminal (as occurs after
** a reduce action) then the yy_reduce_ofst[] array is used in place of
** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
** YY_SHIFT_USE_DFLT.
**
** The following are the tables generated in this section:
**
** yy_action[] A single table containing all actions.
** yy_lookahead[] A table containing the lookahead for each entry in
** yy_action. Used to detect hash collisions.
** yy_shift_ofst[] For each state, the offset into yy_action for
** shifting terminals.
** yy_reduce_ofst[] For each state, the offset into yy_action for
** shifting non-terminals after a reduce.
** yy_default[] Default action for each state.
*/
#define YY_ACTTAB_COUNT (1497)
static const YYACTIONTYPE yy_action[] = {
/* 0 */ 306, 212, 432, 955, 639, 191, 955, 295, 559, 88,
/* 10 */ 88, 88, 88, 81, 86, 86, 86, 86, 85, 85,
/* 20 */ 84, 84, 84, 83, 330, 185, 184, 183, 635, 635,
/* 30 */ 292, 606, 606, 88, 88, 88, 88, 683, 86, 86,
/* 40 */ 86, 86, 85, 85, 84, 84, 84, 83, 330, 16,
/* 50 */ 436, 597, 89, 90, 80, 600, 599, 601, 601, 87,
/* 60 */ 87, 88, 88, 88, 88, 684, 86, 86, 86, 86,
/* 70 */ 85, 85, 84, 84, 84, 83, 330, 306, 559, 84,
/* 80 */ 84, 84, 83, 330, 65, 86, 86, 86, 86, 85,
/* 90 */ 85, 84, 84, 84, 83, 330, 635, 635, 634, 633,
/* 100 */ 182, 682, 550, 379, 376, 375, 17, 322, 606, 606,
/* 110 */ 371, 198, 479, 91, 374, 82, 79, 165, 85, 85,
/* 120 */ 84, 84, 84, 83, 330, 598, 635, 635, 107, 89,
/* 130 */ 90, 80, 600, 599, 601, 601, 87, 87, 88, 88,
/* 140 */ 88, 88, 186, 86, 86, 86, 86, 85, 85, 84,
/* 150 */ 84, 84, 83, 330, 306, 594, 594, 142, 328, 327,
/* 160 */ 484, 249, 344, 238, 635, 635, 634, 633, 585, 448,
/* 170 */ 526, 525, 229, 388, 1, 394, 450, 584, 449, 635,
/* 180 */ 635, 635, 635, 319, 395, 606, 606, 199, 157, 273,
/* 190 */ 382, 268, 381, 187, 635, 635, 634, 633, 311, 555,
/* 200 */ 266, 593, 593, 266, 347, 588, 89, 90, 80, 600,
/* 210 */ 599, 601, 601, 87, 87, 88, 88, 88, 88, 478,
/* 220 */ 86, 86, 86, 86, 85, 85, 84, 84, 84, 83,
/* 230 */ 330, 306, 272, 536, 634, 633, 146, 610, 197, 310,
/* 240 */ 575, 182, 482, 271, 379, 376, 375, 506, 21, 634,
/* 250 */ 633, 634, 633, 635, 635, 374, 611, 574, 548, 440,
/* 260 */ 111, 563, 606, 606, 634, 633, 324, 479, 608, 608,
/* 270 */ 608, 300, 435, 573, 119, 407, 210, 162, 562, 883,
/* 280 */ 592, 592, 306, 89, 90, 80, 600, 599, 601, 601,
/* 290 */ 87, 87, 88, 88, 88, 88, 506, 86, 86, 86,
/* 300 */ 86, 85, 85, 84, 84, 84, 83, 330, 620, 111,
/* 310 */ 635, 635, 361, 606, 606, 358, 249, 349, 248, 433,
/* 320 */ 243, 479, 586, 634, 633, 195, 611, 93, 119, 221,
/* 330 */ 575, 497, 534, 534, 89, 90, 80, 600, 599, 601,
/* 340 */ 601, 87, 87, 88, 88, 88, 88, 574, 86, 86,
/* 350 */ 86, 86, 85, 85, 84, 84, 84, 83, 330, 306,
/* 360 */ 77, 429, 638, 573, 589, 530, 240, 230, 242, 105,
/* 370 */ 249, 349, 248, 515, 588, 208, 460, 529, 564, 173,
/* 380 */ 634, 633, 970, 144, 430, 2, 424, 228, 380, 557,
/* 390 */ 606, 606, 190, 153, 159, 158, 514, 51, 632, 631,
/* 400 */ 630, 71, 536, 432, 954, 196, 610, 954, 614, 45,
/* 410 */ 18, 89, 90, 80, 600, 599, 601, 601, 87, 87,
/* 420 */ 88, 88, 88, 88, 261, 86, 86, 86, 86, 85,
/* 430 */ 85, 84, 84, 84, 83, 330, 306, 608, 608, 608,
/* 440 */ 542, 424, 402, 385, 241, 506, 451, 320, 211, 543,
/* 450 */ 164, 436, 386, 293, 451, 587, 108, 496, 111, 334,
/* 460 */ 391, 591, 424, 614, 27, 452, 453, 606, 606, 72,
/* 470 */ 257, 70, 259, 452, 339, 342, 564, 582, 68, 415,
/* 480 */ 469, 328, 327, 62, 614, 45, 110, 393, 89, 90,
/* 490 */ 80, 600, 599, 601, 601, 87, 87, 88, 88, 88,
/* 500 */ 88, 152, 86, 86, 86, 86, 85, 85, 84, 84,
/* 510 */ 84, 83, 330, 306, 110, 499, 520, 538, 402, 389,
/* 520 */ 424, 110, 566, 500, 593, 593, 454, 82, 79, 165,
/* 530 */ 424, 591, 384, 564, 340, 615, 188, 162, 424, 350,
/* 540 */ 616, 424, 614, 44, 606, 606, 445, 582, 300, 434,
/* 550 */ 151, 19, 614, 9, 568, 580, 348, 615, 469, 567,
/* 560 */ 614, 26, 616, 614, 45, 89, 90, 80, 600, 599,
/* 570 */ 601, 601, 87, 87, 88, 88, 88, 88, 411, 86,
/* 580 */ 86, 86, 86, 85, 85, 84, 84, 84, 83, 330,
/* 590 */ 306, 579, 110, 578, 521, 282, 433, 398, 400, 255,
/* 600 */ 486, 82, 79, 165, 487, 164, 82, 79, 165, 488,
/* 610 */ 488, 364, 387, 424, 544, 544, 509, 350, 362, 155,
/* 620 */ 191, 606, 606, 559, 642, 640, 333, 82, 79, 165,
/* 630 */ 305, 564, 507, 312, 357, 614, 45, 329, 596, 595,
/* 640 */ 194, 337, 89, 90, 80, 600, 599, 601, 601, 87,
/* 650 */ 87, 88, 88, 88, 88, 424, 86, 86, 86, 86,
/* 660 */ 85, 85, 84, 84, 84, 83, 330, 306, 20, 323,
/* 670 */ 150, 263, 211, 543, 421, 596, 595, 614, 22, 424,
/* 680 */ 193, 424, 284, 424, 391, 424, 509, 424, 577, 424,
/* 690 */ 186, 335, 424, 559, 424, 313, 120, 546, 606, 606,
/* 700 */ 67, 614, 47, 614, 50, 614, 48, 614, 100, 614,
/* 710 */ 99, 614, 101, 576, 614, 102, 614, 109, 326, 89,
/* 720 */ 90, 80, 600, 599, 601, 601, 87, 87, 88, 88,
/* 730 */ 88, 88, 424, 86, 86, 86, 86, 85, 85, 84,
/* 740 */ 84, 84, 83, 330, 306, 424, 311, 424, 585, 54,
/* 750 */ 424, 516, 517, 590, 614, 112, 424, 584, 424, 572,
/* 760 */ 424, 195, 424, 571, 424, 67, 424, 614, 94, 614,
/* 770 */ 98, 424, 614, 97, 264, 606, 606, 195, 614, 46,
/* 780 */ 614, 96, 614, 30, 614, 49, 614, 115, 614, 114,
/* 790 */ 418, 229, 388, 614, 113, 306, 89, 90, 80, 600,
/* 800 */ 599, 601, 601, 87, 87, 88, 88, 88, 88, 424,
/* 810 */ 86, 86, 86, 86, 85, 85, 84, 84, 84, 83,
/* 820 */ 330, 119, 424, 590, 110, 372, 606, 606, 195, 53,
/* 830 */ 250, 614, 29, 195, 472, 438, 729, 190, 302, 498,
/* 840 */ 14, 523, 641, 2, 614, 43, 306, 89, 90, 80,
/* 850 */ 600, 599, 601, 601, 87, 87, 88, 88, 88, 88,
/* 860 */ 424, 86, 86, 86, 86, 85, 85, 84, 84, 84,
/* 870 */ 83, 330, 424, 613, 964, 964, 354, 606, 606, 420,
/* 880 */ 312, 64, 614, 42, 391, 355, 283, 437, 301, 255,
/* 890 */ 414, 410, 495, 492, 614, 28, 471, 306, 89, 90,
/* 900 */ 80, 600, 599, 601, 601, 87, 87, 88, 88, 88,
/* 910 */ 88, 424, 86, 86, 86, 86, 85, 85, 84, 84,
/* 920 */ 84, 83, 330, 424, 110, 110, 110, 110, 606, 606,
/* 930 */ 110, 254, 13, 614, 41, 532, 531, 283, 481, 531,
/* 940 */ 457, 284, 119, 561, 356, 614, 40, 284, 306, 89,
/* 950 */ 78, 80, 600, 599, 601, 601, 87, 87, 88, 88,
/* 960 */ 88, 88, 424, 86, 86, 86, 86, 85, 85, 84,
/* 970 */ 84, 84, 83, 330, 110, 424, 341, 220, 555, 606,
/* 980 */ 606, 351, 555, 318, 614, 95, 413, 255, 83, 330,
/* 990 */ 284, 284, 255, 640, 333, 356, 255, 614, 39, 306,
/* 1000 */ 356, 90, 80, 600, 599, 601, 601, 87, 87, 88,
/* 1010 */ 88, 88, 88, 424, 86, 86, 86, 86, 85, 85,
/* 1020 */ 84, 84, 84, 83, 330, 424, 317, 316, 141, 465,
/* 1030 */ 606, 606, 219, 619, 463, 614, 10, 417, 462, 255,
/* 1040 */ 189, 510, 553, 351, 207, 363, 161, 614, 38, 315,
/* 1050 */ 218, 255, 255, 80, 600, 599, 601, 601, 87, 87,
/* 1060 */ 88, 88, 88, 88, 424, 86, 86, 86, 86, 85,
/* 1070 */ 85, 84, 84, 84, 83, 330, 76, 419, 255, 3,
/* 1080 */ 878, 461, 424, 247, 331, 331, 614, 37, 217, 76,
/* 1090 */ 419, 390, 3, 216, 215, 422, 4, 331, 331, 424,
/* 1100 */ 547, 12, 424, 545, 614, 36, 424, 541, 422, 424,
/* 1110 */ 540, 424, 214, 424, 408, 424, 539, 403, 605, 605,
/* 1120 */ 237, 614, 25, 119, 614, 24, 588, 408, 614, 45,
/* 1130 */ 118, 614, 35, 614, 34, 614, 33, 614, 23, 588,
/* 1140 */ 60, 223, 603, 602, 513, 378, 73, 74, 140, 139,
/* 1150 */ 424, 110, 265, 75, 426, 425, 59, 424, 610, 73,
/* 1160 */ 74, 549, 402, 404, 424, 373, 75, 426, 425, 604,
/* 1170 */ 138, 610, 614, 11, 392, 76, 419, 181, 3, 614,
/* 1180 */ 32, 271, 369, 331, 331, 493, 614, 31, 149, 608,
/* 1190 */ 608, 608, 607, 15, 422, 365, 614, 8, 137, 489,
/* 1200 */ 136, 190, 608, 608, 608, 607, 15, 485, 176, 135,
/* 1210 */ 7, 252, 477, 408, 174, 133, 175, 474, 57, 56,
/* 1220 */ 132, 130, 119, 76, 419, 588, 3, 468, 245, 464,
/* 1230 */ 171, 331, 331, 125, 123, 456, 447, 122, 446, 104,
/* 1240 */ 336, 231, 422, 166, 154, 73, 74, 332, 116, 431,
/* 1250 */ 121, 309, 75, 426, 425, 222, 106, 610, 308, 637,
/* 1260 */ 204, 408, 629, 627, 628, 6, 200, 428, 427, 290,
/* 1270 */ 203, 622, 201, 588, 62, 63, 289, 66, 419, 399,
/* 1280 */ 3, 401, 288, 92, 143, 331, 331, 287, 608, 608,
/* 1290 */ 608, 607, 15, 73, 74, 227, 422, 325, 69, 416,
/* 1300 */ 75, 426, 425, 612, 412, 610, 192, 61, 569, 209,
/* 1310 */ 396, 226, 278, 225, 383, 408, 527, 558, 276, 533,
/* 1320 */ 552, 528, 321, 523, 370, 508, 180, 588, 494, 179,
/* 1330 */ 366, 117, 253, 269, 522, 503, 608, 608, 608, 607,
/* 1340 */ 15, 551, 502, 58, 274, 524, 178, 73, 74, 304,
/* 1350 */ 501, 368, 303, 206, 75, 426, 425, 491, 360, 610,
/* 1360 */ 213, 177, 483, 131, 345, 298, 297, 296, 202, 294,
/* 1370 */ 480, 490, 466, 134, 172, 129, 444, 346, 470, 128,
/* 1380 */ 314, 459, 103, 127, 126, 148, 124, 167, 443, 235,
/* 1390 */ 608, 608, 608, 607, 15, 442, 439, 623, 234, 299,
/* 1400 */ 145, 583, 291, 377, 581, 160, 119, 156, 270, 636,
/* 1410 */ 971, 169, 279, 626, 520, 625, 473, 624, 170, 621,
/* 1420 */ 618, 119, 168, 55, 409, 423, 537, 609, 286, 285,
/* 1430 */ 405, 570, 560, 556, 5, 52, 458, 554, 147, 267,
/* 1440 */ 519, 504, 518, 406, 262, 239, 260, 512, 343, 511,
/* 1450 */ 258, 353, 565, 256, 224, 251, 359, 277, 275, 476,
/* 1460 */ 475, 246, 352, 244, 467, 455, 236, 233, 232, 307,
/* 1470 */ 441, 281, 205, 163, 397, 280, 535, 505, 330, 617,
/* 1480 */ 971, 971, 971, 971, 367, 971, 971, 971, 971, 971,
/* 1490 */ 971, 971, 971, 971, 971, 971, 338,
};
static const YYCODETYPE yy_lookahead[] = {
/* 0 */ 19, 22, 22, 23, 1, 24, 26, 15, 27, 80,
/* 10 */ 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,
/* 20 */ 91, 92, 93, 94, 95, 108, 109, 110, 27, 28,
/* 30 */ 23, 50, 51, 80, 81, 82, 83, 122, 85, 86,
/* 40 */ 87, 88, 89, 90, 91, 92, 93, 94, 95, 22,
/* 50 */ 70, 23, 71, 72, 73, 74, 75, 76, 77, 78,
/* 60 */ 79, 80, 81, 82, 83, 122, 85, 86, 87, 88,
/* 70 */ 89, 90, 91, 92, 93, 94, 95, 19, 97, 91,
/* 80 */ 92, 93, 94, 95, 26, 85, 86, 87, 88, 89,
/* 90 */ 90, 91, 92, 93, 94, 95, 27, 28, 97, 98,
/* 100 */ 99, 122, 211, 102, 103, 104, 79, 19, 50, 51,
/* 110 */ 19, 122, 59, 55, 113, 224, 225, 226, 89, 90,
/* 120 */ 91, 92, 93, 94, 95, 23, 27, 28, 26, 71,
/* 130 */ 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
/* 140 */ 82, 83, 51, 85, 86, 87, 88, 89, 90, 91,
/* 150 */ 92, 93, 94, 95, 19, 132, 133, 58, 89, 90,
/* 160 */ 21, 108, 109, 110, 27, 28, 97, 98, 33, 100,
/* 170 */ 7, 8, 119, 120, 22, 19, 107, 42, 109, 27,
/* 180 */ 28, 27, 28, 95, 28, 50, 51, 99, 100, 101,
/* 190 */ 102, 103, 104, 105, 27, 28, 97, 98, 107, 152,
/* 200 */ 112, 132, 133, 112, 65, 69, 71, 72, 73, 74,
/* 210 */ 75, 76, 77, 78, 79, 80, 81, 82, 83, 11,
/* 220 */ 85, 86, 87, 88, 89, 90, 91, 92, 93, 94,
/* 230 */ 95, 19, 101, 97, 97, 98, 24, 101, 122, 157,
/* 240 */ 12, 99, 103, 112, 102, 103, 104, 152, 22, 97,
/* 250 */ 98, 97, 98, 27, 28, 113, 27, 29, 91, 164,
/* 260 */ 165, 124, 50, 51, 97, 98, 219, 59, 132, 133,
/* 270 */ 134, 22, 23, 45, 66, 47, 212, 213, 124, 140,
/* 280 */ 132, 133, 19, 71, 72, 73, 74, 75, 76, 77,
/* 290 */ 78, 79, 80, 81, 82, 83, 152, 85, 86, 87,
/* 300 */ 88, 89, 90, 91, 92, 93, 94, 95, 164, 165,
/* 310 */ 27, 28, 230, 50, 51, 233, 108, 109, 110, 70,
/* 320 */ 16, 59, 23, 97, 98, 26, 97, 22, 66, 185,
/* 330 */ 12, 187, 27, 28, 71, 72, 73, 74, 75, 76,
/* 340 */ 77, 78, 79, 80, 81, 82, 83, 29, 85, 86,
/* 350 */ 87, 88, 89, 90, 91, 92, 93, 94, 95, 19,
/* 360 */ 22, 148, 149, 45, 23, 47, 62, 154, 64, 156,
/* 370 */ 108, 109, 110, 37, 69, 23, 163, 59, 26, 26,
/* 380 */ 97, 98, 144, 145, 146, 147, 152, 200, 52, 23,
/* 390 */ 50, 51, 26, 22, 89, 90, 60, 210, 7, 8,
/* 400 */ 9, 138, 97, 22, 23, 26, 101, 26, 174, 175,
/* 410 */ 197, 71, 72, 73, 74, 75, 76, 77, 78, 79,
/* 420 */ 80, 81, 82, 83, 16, 85, 86, 87, 88, 89,
/* 430 */ 90, 91, 92, 93, 94, 95, 19, 132, 133, 134,
/* 440 */ 23, 152, 208, 209, 140, 152, 152, 111, 195, 196,
/* 450 */ 98, 70, 163, 160, 152, 23, 22, 164, 165, 246,
/* 460 */ 207, 27, 152, 174, 175, 171, 172, 50, 51, 137,
/* 470 */ 62, 139, 64, 171, 172, 222, 124, 27, 138, 24,
/* 480 */ 163, 89, 90, 130, 174, 175, 197, 163, 71, 72,
/* 490 */ 73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
/* 500 */ 83, 22, 85, 86, 87, 88, 89, 90, 91, 92,
/* 510 */ 93, 94, 95, 19, 197, 181, 182, 23, 208, 209,
/* 520 */ 152, 197, 26, 189, 132, 133, 232, 224, 225, 226,
/* 530 */ 152, 97, 91, 26, 232, 116, 212, 213, 152, 222,
/* 540 */ 121, 152, 174, 175, 50, 51, 243, 97, 22, 23,
/* 550 */ 22, 234, 174, 175, 177, 23, 239, 116, 163, 177,
/* 560 */ 174, 175, 121, 174, 175, 71, 72, 73, 74, 75,
/* 570 */ 76, 77, 78, 79, 80, 81, 82, 83, 24, 85,
/* 580 */ 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
/* 590 */ 19, 23, 197, 11, 23, 227, 70, 208, 220, 152,
/* 600 */ 31, 224, 225, 226, 35, 98, 224, 225, 226, 108,
/* 610 */ 109, 110, 115, 152, 117, 118, 27, 222, 49, 123,
/* 620 */ 24, 50, 51, 27, 0, 1, 2, 224, 225, 226,
/* 630 */ 166, 124, 168, 169, 239, 174, 175, 170, 171, 172,
/* 640 */ 22, 194, 71, 72, 73, 74, 75, 76, 77, 78,
/* 650 */ 79, 80, 81, 82, 83, 152, 85, 86, 87, 88,
/* 660 */ 89, 90, 91, 92, 93, 94, 95, 19, 22, 208,
/* 670 */ 24, 23, 195, 196, 170, 171, 172, 174, 175, 152,
/* 680 */ 26, 152, 152, 152, 207, 152, 97, 152, 23, 152,
/* 690 */ 51, 244, 152, 97, 152, 247, 248, 23, 50, 51,
/* 700 */ 26, 174, 175, 174, 175, 174, 175, 174, 175, 174,
/* 710 */ 175, 174, 175, 23, 174, 175, 174, 175, 188, 71,
/* 720 */ 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
/* 730 */ 82, 83, 152, 85, 86, 87, 88, 89, 90, 91,
/* 740 */ 92, 93, 94, 95, 19, 152, 107, 152, 33, 24,
/* 750 */ 152, 100, 101, 27, 174, 175, 152, 42, 152, 23,
/* 760 */ 152, 26, 152, 23, 152, 26, 152, 174, 175, 174,
/* 770 */ 175, 152, 174, 175, 23, 50, 51, 26, 174, 175,
/* 780 */ 174, 175, 174, 175, 174, 175, 174, 175, 174, 175,
/* 790 */ 163, 119, 120, 174, 175, 19, 71, 72, 73, 74,
/* 800 */ 75, 76, 77, 78, 79, 80, 81, 82, 83, 152,
/* 810 */ 85, 86, 87, 88, 89, 90, 91, 92, 93, 94,
/* 820 */ 95, 66, 152, 97, 197, 23, 50, 51, 26, 53,
/* 830 */ 23, 174, 175, 26, 23, 23, 23, 26, 26, 26,
/* 840 */ 36, 106, 146, 147, 174, 175, 19, 71, 72, 73,
/* 850 */ 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
/* 860 */ 152, 85, 86, 87, 88, 89, 90, 91, 92, 93,
/* 870 */ 94, 95, 152, 196, 119, 120, 19, 50, 51, 168,
/* 880 */ 169, 26, 174, 175, 207, 28, 152, 249, 250, 152,
/* 890 */ 163, 163, 163, 163, 174, 175, 163, 19, 71, 72,
/* 900 */ 73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
/* 910 */ 83, 152, 85, 86, 87, 88, 89, 90, 91, 92,
/* 920 */ 93, 94, 95, 152, 197, 197, 197, 197, 50, 51,
/* 930 */ 197, 194, 36, 174, 175, 191, 192, 152, 191, 192,
/* 940 */ 163, 152, 66, 124, 152, 174, 175, 152, 19, 71,
/* 950 */ 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
/* 960 */ 82, 83, 152, 85, 86, 87, 88, 89, 90, 91,
/* 970 */ 92, 93, 94, 95, 197, 152, 100, 188, 152, 50,
/* 980 */ 51, 152, 152, 188, 174, 175, 252, 152, 94, 95,
/* 990 */ 152, 152, 152, 1, 2, 152, 152, 174, 175, 19,
/* 1000 */ 152, 72, 73, 74, 75, 76, 77, 78, 79, 80,
/* 1010 */ 81, 82, 83, 152, 85, 86, 87, 88, 89, 90,
/* 1020 */ 91, 92, 93, 94, 95, 152, 188, 188, 22, 194,
/* 1030 */ 50, 51, 240, 173, 194, 174, 175, 252, 194, 152,
/* 1040 */ 36, 181, 28, 152, 23, 219, 122, 174, 175, 219,
/* 1050 */ 221, 152, 152, 73, 74, 75, 76, 77, 78, 79,
/* 1060 */ 80, 81, 82, 83, 152, 85, 86, 87, 88, 89,
/* 1070 */ 90, 91, 92, 93, 94, 95, 19, 20, 152, 22,
/* 1080 */ 23, 194, 152, 240, 27, 28, 174, 175, 240, 19,
/* 1090 */ 20, 26, 22, 194, 194, 38, 22, 27, 28, 152,
/* 1100 */ 23, 22, 152, 116, 174, 175, 152, 23, 38, 152,
/* 1110 */ 23, 152, 221, 152, 57, 152, 23, 163, 50, 51,
/* 1120 */ 194, 174, 175, 66, 174, 175, 69, 57, 174, 175,
/* 1130 */ 40, 174, 175, 174, 175, 174, 175, 174, 175, 69,
/* 1140 */ 22, 53, 74, 75, 30, 53, 89, 90, 22, 22,
/* 1150 */ 152, 197, 23, 96, 97, 98, 22, 152, 101, 89,
/* 1160 */ 90, 91, 208, 209, 152, 53, 96, 97, 98, 101,
/* 1170 */ 22, 101, 174, 175, 152, 19, 20, 105, 22, 174,
/* 1180 */ 175, 112, 19, 27, 28, 20, 174, 175, 24, 132,
/* 1190 */ 133, 134, 135, 136, 38, 44, 174, 175, 107, 61,
/* 1200 */ 54, 26, 132, 133, 134, 135, 136, 54, 107, 22,
/* 1210 */ 5, 140, 1, 57, 36, 111, 122, 28, 79, 79,
/* 1220 */ 131, 123, 66, 19, 20, 69, 22, 1, 16, 20,
/* 1230 */ 125, 27, 28, 123, 111, 120, 23, 131, 23, 16,
/* 1240 */ 68, 142, 38, 15, 22, 89, 90, 3, 167, 4,
/* 1250 */ 248, 251, 96, 97, 98, 180, 180, 101, 251, 151,
/* 1260 */ 6, 57, 151, 13, 151, 26, 25, 151, 161, 202,
/* 1270 */ 153, 162, 153, 69, 130, 128, 203, 19, 20, 127,
/* 1280 */ 22, 126, 204, 129, 22, 27, 28, 205, 132, 133,
/* 1290 */ 134, 135, 136, 89, 90, 231, 38, 95, 137, 179,
/* 1300 */ 96, 97, 98, 206, 179, 101, 122, 107, 159, 159,
/* 1310 */ 125, 231, 216, 228, 107, 57, 184, 217, 216, 176,
/* 1320 */ 217, 176, 48, 106, 18, 184, 158, 69, 159, 158,
/* 1330 */ 46, 71, 237, 176, 176, 176, 132, 133, 134, 135,
/* 1340 */ 136, 217, 176, 137, 216, 178, 158, 89, 90, 179,
/* 1350 */ 176, 159, 179, 159, 96, 97, 98, 159, 159, 101,
/* 1360 */ 5, 158, 202, 22, 18, 10, 11, 12, 13, 14,
/* 1370 */ 190, 238, 17, 190, 158, 193, 41, 159, 202, 193,
/* 1380 */ 159, 202, 245, 193, 193, 223, 190, 32, 159, 34,
/* 1390 */ 132, 133, 134, 135, 136, 159, 39, 155, 43, 150,
/* 1400 */ 223, 177, 201, 178, 177, 186, 66, 199, 177, 152,
/* 1410 */ 253, 56, 215, 152, 182, 152, 202, 152, 63, 152,
/* 1420 */ 152, 66, 67, 242, 229, 152, 174, 152, 152, 152,
/* 1430 */ 152, 152, 152, 152, 199, 242, 202, 152, 198, 152,
/* 1440 */ 152, 152, 183, 192, 152, 215, 152, 183, 215, 183,
/* 1450 */ 152, 241, 214, 152, 211, 152, 152, 211, 211, 152,
/* 1460 */ 152, 241, 152, 152, 152, 152, 152, 152, 152, 114,
/* 1470 */ 152, 152, 235, 152, 152, 152, 174, 187, 95, 174,
/* 1480 */ 253, 253, 253, 253, 236, 253, 253, 253, 253, 253,
/* 1490 */ 253, 253, 253, 253, 253, 253, 141,
};
#define YY_SHIFT_USE_DFLT (-86)
#define YY_SHIFT_COUNT (429)
#define YY_SHIFT_MIN (-85)
#define YY_SHIFT_MAX (1383)
static const short yy_shift_ofst[] = {
/* 0 */ 992, 1057, 1355, 1156, 1204, 1204, 1, 262, -19, 135,
/* 10 */ 135, 776, 1204, 1204, 1204, 1204, 69, 69, 53, 208,
/* 20 */ 283, 755, 58, 725, 648, 571, 494, 417, 340, 263,
/* 30 */ 212, 827, 827, 827, 827, 827, 827, 827, 827, 827,
/* 40 */ 827, 827, 827, 827, 827, 827, 878, 827, 929, 980,
/* 50 */ 980, 1070, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
/* 60 */ 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
/* 70 */ 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
/* 80 */ 1258, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
/* 90 */ 1204, 1204, 1204, 1204, -71, -47, -47, -47, -47, -47,
/* 100 */ 0, 29, -12, 283, 283, 139, 91, 392, 392, 894,
/* 110 */ 672, 726, 1383, -86, -86, -86, 88, 318, 318, 99,
/* 120 */ 381, -20, 283, 283, 283, 283, 283, 283, 283, 283,
/* 130 */ 283, 283, 283, 283, 283, 283, 283, 283, 283, 283,
/* 140 */ 283, 283, 283, 283, 624, 876, 726, 672, 1340, 1340,
/* 150 */ 1340, 1340, 1340, 1340, -86, -86, -86, 305, 136, 136,
/* 160 */ 142, 167, 226, 154, 137, 152, 283, 283, 283, 283,
/* 170 */ 283, 283, 283, 283, 283, 283, 283, 283, 283, 283,
/* 180 */ 283, 283, 283, 336, 336, 336, 283, 283, 352, 283,
/* 190 */ 283, 283, 283, 283, 228, 283, 283, 283, 283, 283,
/* 200 */ 283, 283, 283, 283, 283, 501, 569, 596, 596, 596,
/* 210 */ 507, 497, 441, 391, 353, 156, 156, 857, 353, 857,
/* 220 */ 735, 813, 639, 715, 156, 332, 715, 715, 496, 419,
/* 230 */ 646, 1357, 1184, 1184, 1335, 1335, 1184, 1341, 1260, 1144,
/* 240 */ 1346, 1346, 1346, 1346, 1184, 1306, 1144, 1341, 1260, 1260,
/* 250 */ 1144, 1184, 1306, 1206, 1284, 1184, 1184, 1306, 1184, 1306,
/* 260 */ 1184, 1306, 1262, 1207, 1207, 1207, 1274, 1262, 1207, 1217,
/* 270 */ 1207, 1274, 1207, 1207, 1185, 1200, 1185, 1200, 1185, 1200,
/* 280 */ 1184, 1184, 1161, 1262, 1202, 1202, 1262, 1154, 1155, 1147,
/* 290 */ 1152, 1144, 1241, 1239, 1250, 1250, 1254, 1254, 1254, 1254,
/* 300 */ -86, -86, -86, -86, -86, -86, 1068, 304, 526, 249,
/* 310 */ 408, -83, 434, 812, 27, 811, 807, 802, 751, 589,
/* 320 */ 651, 163, 131, 674, 366, 450, 299, 148, 23, 102,
/* 330 */ 229, -21, 1245, 1244, 1222, 1099, 1228, 1172, 1223, 1215,
/* 340 */ 1213, 1115, 1106, 1123, 1110, 1209, 1105, 1212, 1226, 1098,
/* 350 */ 1089, 1140, 1139, 1104, 1189, 1178, 1094, 1211, 1205, 1187,
/* 360 */ 1101, 1071, 1153, 1175, 1146, 1138, 1151, 1091, 1164, 1165,
/* 370 */ 1163, 1069, 1072, 1148, 1112, 1134, 1127, 1129, 1126, 1092,
/* 380 */ 1114, 1118, 1088, 1090, 1093, 1087, 1084, 987, 1079, 1077,
/* 390 */ 1074, 1065, 924, 1021, 1014, 1004, 1006, 819, 739, 896,
/* 400 */ 855, 804, 739, 740, 736, 690, 654, 665, 618, 582,
/* 410 */ 568, 528, 554, 379, 532, 479, 455, 379, 432, 371,
/* 420 */ 341, 28, 338, 116, -11, -57, -85, 7, -8, 3,
};
#define YY_REDUCE_USE_DFLT (-110)
#define YY_REDUCE_COUNT (305)
#define YY_REDUCE_MIN (-109)
#define YY_REDUCE_MAX (1323)
static const short yy_reduce_ofst[] = {
/* 0 */ 238, 954, 213, 289, 310, 234, 144, 317, -109, 382,
/* 10 */ 377, 303, 461, 389, 378, 368, 302, 294, 253, 395,
/* 20 */ 293, 324, 403, 403, 403, 403, 403, 403, 403, 403,
/* 30 */ 403, 403, 403, 403, 403, 403, 403, 403, 403, 403,
/* 40 */ 403, 403, 403, 403, 403, 403, 403, 403, 403, 403,
/* 50 */ 403, 1022, 1012, 1005, 998, 963, 961, 959, 957, 950,
/* 60 */ 947, 930, 912, 873, 861, 823, 810, 771, 759, 720,
/* 70 */ 708, 670, 657, 619, 614, 612, 610, 608, 606, 604,
/* 80 */ 598, 595, 593, 580, 542, 540, 537, 535, 533, 531,
/* 90 */ 529, 527, 503, 386, 403, 403, 403, 403, 403, 403,
/* 100 */ 403, 403, 403, 95, 447, 82, 334, 504, 467, 403,
/* 110 */ 477, 464, 403, 403, 403, 403, 860, 747, 744, 785,
/* 120 */ 638, 638, 926, 891, 900, 899, 887, 844, 840, 835,
/* 130 */ 848, 830, 843, 829, 792, 839, 826, 737, 838, 795,
/* 140 */ 789, 47, 734, 530, 696, 777, 711, 677, 733, 730,
/* 150 */ 729, 728, 727, 627, 448, 64, 187, 1305, 1302, 1252,
/* 160 */ 1290, 1273, 1323, 1322, 1321, 1319, 1318, 1316, 1315, 1314,
/* 170 */ 1313, 1312, 1311, 1310, 1308, 1307, 1304, 1303, 1301, 1298,
/* 180 */ 1294, 1292, 1289, 1266, 1264, 1259, 1288, 1287, 1238, 1285,
/* 190 */ 1281, 1280, 1279, 1278, 1251, 1277, 1276, 1275, 1273, 1268,
/* 200 */ 1267, 1265, 1263, 1261, 1257, 1248, 1237, 1247, 1246, 1243,
/* 210 */ 1238, 1240, 1235, 1249, 1234, 1233, 1230, 1220, 1214, 1210,
/* 220 */ 1225, 1219, 1232, 1231, 1197, 1195, 1227, 1224, 1201, 1208,
/* 230 */ 1242, 1137, 1236, 1229, 1193, 1181, 1221, 1177, 1196, 1179,
/* 240 */ 1191, 1190, 1186, 1182, 1218, 1216, 1176, 1162, 1183, 1180,
/* 250 */ 1160, 1199, 1203, 1133, 1095, 1198, 1194, 1188, 1192, 1171,
/* 260 */ 1169, 1168, 1173, 1174, 1166, 1159, 1141, 1170, 1158, 1167,
/* 270 */ 1157, 1132, 1145, 1143, 1124, 1128, 1103, 1102, 1100, 1096,
/* 280 */ 1150, 1149, 1085, 1125, 1080, 1064, 1120, 1097, 1082, 1078,
/* 290 */ 1073, 1067, 1109, 1107, 1119, 1117, 1116, 1113, 1111, 1108,
/* 300 */ 1007, 1000, 1002, 1076, 1075, 1081,
};
static const YYACTIONTYPE yy_default[] = {
/* 0 */ 647, 964, 964, 964, 878, 878, 969, 964, 774, 802,
/* 10 */ 802, 938, 969, 969, 969, 876, 969, 969, 969, 964,
/* 20 */ 969, 778, 808, 969, 969, 969, 969, 969, 969, 969,
/* 30 */ 969, 937, 939, 816, 815, 918, 789, 813, 806, 810,
/* 40 */ 879, 872, 873, 871, 875, 880, 969, 809, 841, 856,
/* 50 */ 840, 969, 969, 969, 969, 969, 969, 969, 969, 969,
/* 60 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
/* 70 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
/* 80 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
/* 90 */ 969, 969, 969, 969, 850, 855, 862, 854, 851, 843,
/* 100 */ 842, 844, 845, 969, 969, 673, 739, 969, 969, 846,
/* 110 */ 969, 685, 847, 859, 858, 857, 680, 969, 969, 969,
/* 120 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
/* 130 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
/* 140 */ 969, 969, 969, 969, 647, 964, 969, 969, 964, 964,
/* 150 */ 964, 964, 964, 964, 956, 778, 768, 969, 969, 969,
/* 160 */ 969, 969, 969, 969, 969, 969, 969, 944, 942, 969,
/* 170 */ 891, 969, 969, 969, 969, 969, 969, 969, 969, 969,
/* 180 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
/* 190 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
/* 200 */ 969, 969, 969, 969, 653, 969, 911, 774, 774, 774,
/* 210 */ 776, 754, 766, 655, 812, 791, 791, 923, 812, 923,
/* 220 */ 710, 733, 707, 802, 791, 874, 802, 802, 775, 766,
/* 230 */ 969, 949, 782, 782, 941, 941, 782, 821, 743, 812,
/* 240 */ 750, 750, 750, 750, 782, 670, 812, 821, 743, 743,
/* 250 */ 812, 782, 670, 917, 915, 782, 782, 670, 782, 670,
/* 260 */ 782, 670, 884, 741, 741, 741, 725, 884, 741, 710,
/* 270 */ 741, 725, 741, 741, 795, 790, 795, 790, 795, 790,
/* 280 */ 782, 782, 969, 884, 888, 888, 884, 807, 796, 805,
/* 290 */ 803, 812, 676, 728, 663, 663, 652, 652, 652, 652,
/* 300 */ 961, 961, 956, 712, 712, 695, 969, 969, 969, 969,
/* 310 */ 969, 969, 687, 969, 893, 969, 969, 969, 969, 969,
/* 320 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
/* 330 */ 969, 828, 969, 648, 951, 969, 969, 948, 969, 969,
/* 340 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
/* 350 */ 969, 969, 969, 969, 969, 969, 921, 969, 969, 969,
/* 360 */ 969, 969, 969, 914, 913, 969, 969, 969, 969, 969,
/* 370 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
/* 380 */ 969, 969, 969, 969, 969, 969, 969, 757, 969, 969,
/* 390 */ 969, 761, 969, 969, 969, 969, 969, 969, 804, 969,
/* 400 */ 797, 969, 877, 969, 969, 969, 969, 969, 969, 969,
/* 410 */ 969, 969, 969, 966, 969, 969, 969, 965, 969, 969,
/* 420 */ 969, 969, 969, 830, 969, 829, 833, 969, 661, 969,
/* 430 */ 644, 649, 960, 963, 962, 959, 958, 957, 952, 950,
/* 440 */ 947, 946, 945, 943, 940, 936, 897, 895, 902, 901,
/* 450 */ 900, 899, 898, 896, 894, 892, 818, 817, 814, 811,
/* 460 */ 753, 935, 890, 752, 749, 748, 669, 953, 920, 929,
/* 470 */ 928, 927, 822, 926, 925, 924, 922, 919, 906, 820,
/* 480 */ 819, 744, 882, 881, 672, 910, 909, 908, 912, 916,
/* 490 */ 907, 784, 751, 671, 668, 675, 679, 731, 732, 740,
/* 500 */ 738, 737, 736, 735, 734, 730, 681, 686, 724, 709,
/* 510 */ 708, 717, 716, 722, 721, 720, 719, 718, 715, 714,
/* 520 */ 713, 706, 705, 711, 704, 727, 726, 723, 703, 747,
/* 530 */ 746, 745, 742, 702, 701, 700, 833, 699, 698, 838,
/* 540 */ 837, 866, 826, 755, 759, 758, 762, 763, 771, 770,
/* 550 */ 769, 780, 781, 793, 792, 824, 823, 794, 779, 773,
/* 560 */ 772, 788, 787, 786, 785, 777, 767, 799, 798, 868,
/* 570 */ 783, 867, 865, 934, 933, 932, 931, 930, 870, 967,
/* 580 */ 968, 887, 889, 886, 801, 800, 885, 869, 839, 836,
/* 590 */ 690, 691, 905, 904, 903, 693, 692, 689, 688, 863,
/* 600 */ 860, 852, 864, 861, 853, 849, 848, 834, 832, 831,
/* 610 */ 827, 835, 760, 756, 825, 765, 764, 697, 696, 694,
/* 620 */ 678, 677, 674, 667, 665, 664, 666, 662, 660, 659,
/* 630 */ 658, 657, 656, 684, 683, 682, 654, 651, 650, 646,
/* 640 */ 645, 643,
};
/* The next table maps tokens into fallback tokens. If a construct
** like the following:
**
** %fallback ID X Y Z.
**
** appears in the grammar, then ID becomes a fallback token for X, Y,
** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
** but it does not parse, the type of the token is changed to ID and
** the parse is retried before an error is thrown.
*/
#ifdef YYFALLBACK
static const YYCODETYPE yyFallback[] = {
0, /* $ => nothing */
0, /* SEMI => nothing */
27, /* EXPLAIN => ID */
27, /* QUERY => ID */
27, /* PLAN => ID */
27, /* BEGIN => ID */
0, /* TRANSACTION => nothing */
27, /* DEFERRED => ID */
27, /* IMMEDIATE => ID */
27, /* EXCLUSIVE => ID */
0, /* COMMIT => nothing */
27, /* END => ID */
27, /* ROLLBACK => ID */
27, /* SAVEPOINT => ID */
27, /* RELEASE => ID */
0, /* TO => nothing */
0, /* TABLE => nothing */
0, /* CREATE => nothing */
27, /* IF => ID */
0, /* NOT => nothing */
0, /* EXISTS => nothing */
27, /* TEMP => ID */
0, /* LP => nothing */
0, /* RP => nothing */
0, /* AS => nothing */
27, /* WITHOUT => ID */
0, /* COMMA => nothing */
0, /* ID => nothing */
0, /* INDEXED => nothing */
27, /* ABORT => ID */
27, /* ACTION => ID */
27, /* AFTER => ID */
27, /* ANALYZE => ID */
27, /* ASC => ID */
27, /* ATTACH => ID */
27, /* BEFORE => ID */
27, /* BY => ID */
27, /* CASCADE => ID */
27, /* CAST => ID */
27, /* COLUMNKW => ID */
27, /* CONFLICT => ID */
27, /* DATABASE => ID */
27, /* DESC => ID */
27, /* DETACH => ID */
27, /* EACH => ID */
27, /* FAIL => ID */
27, /* FOR => ID */
27, /* IGNORE => ID */
27, /* INITIALLY => ID */
27, /* INSTEAD => ID */
27, /* LIKE_KW => ID */
27, /* MATCH => ID */
27, /* NO => ID */
27, /* KEY => ID */
27, /* OF => ID */
27, /* OFFSET => ID */
27, /* PRAGMA => ID */
27, /* RAISE => ID */
27, /* RECURSIVE => ID */
27, /* REPLACE => ID */
27, /* RESTRICT => ID */
27, /* ROW => ID */
27, /* TRIGGER => ID */
27, /* VACUUM => ID */
27, /* VIEW => ID */
27, /* VIRTUAL => ID */
27, /* WITH => ID */
27, /* REINDEX => ID */
27, /* RENAME => ID */
27, /* CTIME_KW => ID */
};
#endif /* YYFALLBACK */
/* The following structure represents a single element of the
** parser's stack. Information stored includes:
**
** + The state number for the parser at this level of the stack.
**
** + The value of the token stored at this level of the stack.
** (In other words, the "major" token.)
**
** + The semantic value stored at this level of the stack. This is
** the information used by the action routines in the grammar.
** It is sometimes called the "minor" token.
*/
struct yyStackEntry {
YYACTIONTYPE stateno; /* The state-number */
YYCODETYPE major; /* The major token value. This is the code
** number for the token at this stack level */
YYMINORTYPE minor; /* The user-supplied minor token value. This
** is the value of the token */
};
typedef struct yyStackEntry yyStackEntry;
/* The state of the parser is completely contained in an instance of
** the following structure */
struct yyParser {
int yyidx; /* Index of top element in stack */
#ifdef YYTRACKMAXSTACKDEPTH
int yyidxMax; /* Maximum value of yyidx */
#endif
int yyerrcnt; /* Shifts left before out of the error */
sqlite3ParserARG_SDECL /* A place to hold %extra_argument */
#if YYSTACKDEPTH<=0
int yystksz; /* Current side of the stack */
yyStackEntry *yystack; /* The parser's stack */
#else
yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */
#endif
};
typedef struct yyParser yyParser;
#ifndef NDEBUG
#include <stdio.h>
static FILE *yyTraceFILE = 0;
static char *yyTracePrompt = 0;
#endif /* NDEBUG */
#ifndef NDEBUG
/*
** Turn parser tracing on by giving a stream to which to write the trace
** and a prompt to preface each trace message. Tracing is turned off
** by making either argument NULL
**
** Inputs:
** <ul>
** <li> A FILE* to which trace output should be written.
** If NULL, then tracing is turned off.
** <li> A prefix string written at the beginning of every
** line of trace output. If NULL, then tracing is
** turned off.
** </ul>
**
** Outputs:
** None.
*/
void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
yyTraceFILE = TraceFILE;
yyTracePrompt = zTracePrompt;
if( yyTraceFILE==0 ) yyTracePrompt = 0;
else if( yyTracePrompt==0 ) yyTraceFILE = 0;
}
#endif /* NDEBUG */
#ifndef NDEBUG
/* For tracing shifts, the names of all terminals and nonterminals
** are required. The following table supplies these names */
static const char *const yyTokenName[] = {
"$", "SEMI", "EXPLAIN", "QUERY",
"PLAN", "BEGIN", "TRANSACTION", "DEFERRED",
"IMMEDIATE", "EXCLUSIVE", "COMMIT", "END",
"ROLLBACK", "SAVEPOINT", "RELEASE", "TO",
"TABLE", "CREATE", "IF", "NOT",
"EXISTS", "TEMP", "LP", "RP",
"AS", "WITHOUT", "COMMA", "ID",
"INDEXED", "ABORT", "ACTION", "AFTER",
"ANALYZE", "ASC", "ATTACH", "BEFORE",
"BY", "CASCADE", "CAST", "COLUMNKW",
"CONFLICT", "DATABASE", "DESC", "DETACH",
"EACH", "FAIL", "FOR", "IGNORE",
"INITIALLY", "INSTEAD", "LIKE_KW", "MATCH",
"NO", "KEY", "OF", "OFFSET",
"PRAGMA", "RAISE", "RECURSIVE", "REPLACE",
"RESTRICT", "ROW", "TRIGGER", "VACUUM",
"VIEW", "VIRTUAL", "WITH", "REINDEX",
"RENAME", "CTIME_KW", "ANY", "OR",
"AND", "IS", "BETWEEN", "IN",
"ISNULL", "NOTNULL", "NE", "EQ",
"GT", "LE", "LT", "GE",
"ESCAPE", "BITAND", "BITOR", "LSHIFT",
"RSHIFT", "PLUS", "MINUS", "STAR",
"SLASH", "REM", "CONCAT", "COLLATE",
"BITNOT", "STRING", "JOIN_KW", "CONSTRAINT",
"DEFAULT", "NULL", "PRIMARY", "UNIQUE",
"CHECK", "REFERENCES", "AUTOINCR", "ON",
"INSERT", "DELETE", "UPDATE", "SET",
"DEFERRABLE", "FOREIGN", "DROP", "UNION",
"ALL", "EXCEPT", "INTERSECT", "SELECT",
"VALUES", "DISTINCT", "DOT", "FROM",
"JOIN", "USING", "ORDER", "GROUP",
"HAVING", "LIMIT", "WHERE", "INTO",
"INTEGER", "FLOAT", "BLOB", "VARIABLE",
"CASE", "WHEN", "THEN", "ELSE",
"INDEX", "ALTER", "ADD", "error",
"input", "cmdlist", "ecmd", "explain",
"cmdx", "cmd", "transtype", "trans_opt",
"nm", "savepoint_opt", "create_table", "create_table_args",
"createkw", "temp", "ifnotexists", "dbnm",
"columnlist", "conslist_opt", "table_options", "select",
"column", "columnid", "type", "carglist",
"typetoken", "typename", "signed", "plus_num",
"minus_num", "ccons", "term", "expr",
"onconf", "sortorder", "autoinc", "idxlist_opt",
"refargs", "defer_subclause", "refarg", "refact",
"init_deferred_pred_opt", "conslist", "tconscomma", "tcons",
"idxlist", "defer_subclause_opt", "orconf", "resolvetype",
"raisetype", "ifexists", "fullname", "selectnowith",
"oneselect", "with", "multiselect_op", "distinct",
"selcollist", "from", "where_opt", "groupby_opt",
"having_opt", "orderby_opt", "limit_opt", "values",
"nexprlist", "exprlist", "sclp", "as",
"seltablist", "stl_prefix", "joinop", "indexed_opt",
"on_opt", "using_opt", "joinop2", "idlist",
"sortlist", "setlist", "insert_cmd", "inscollist_opt",
"likeop", "between_op", "in_op", "case_operand",
"case_exprlist", "case_else", "uniqueflag", "collate",
"nmnum", "trigger_decl", "trigger_cmd_list", "trigger_time",
"trigger_event", "foreach_clause", "when_clause", "trigger_cmd",
"trnm", "tridxby", "database_kw_opt", "key_opt",
"add_column_fullname", "kwcolumn_opt", "create_vtab", "vtabarglist",
"vtabarg", "vtabargtoken", "lp", "anylist",
"wqlist",
};
#endif /* NDEBUG */
#ifndef NDEBUG
/* For tracing reduce actions, the names of all rules are required.
*/
static const char *const yyRuleName[] = {
/* 0 */ "input ::= cmdlist",
/* 1 */ "cmdlist ::= cmdlist ecmd",
/* 2 */ "cmdlist ::= ecmd",
/* 3 */ "ecmd ::= SEMI",
/* 4 */ "ecmd ::= explain cmdx SEMI",
/* 5 */ "explain ::=",
/* 6 */ "explain ::= EXPLAIN",
/* 7 */ "explain ::= EXPLAIN QUERY PLAN",
/* 8 */ "cmdx ::= cmd",
/* 9 */ "cmd ::= BEGIN transtype trans_opt",
/* 10 */ "trans_opt ::=",
/* 11 */ "trans_opt ::= TRANSACTION",
/* 12 */ "trans_opt ::= TRANSACTION nm",
/* 13 */ "transtype ::=",
/* 14 */ "transtype ::= DEFERRED",
/* 15 */ "transtype ::= IMMEDIATE",
/* 16 */ "transtype ::= EXCLUSIVE",
/* 17 */ "cmd ::= COMMIT trans_opt",
/* 18 */ "cmd ::= END trans_opt",
/* 19 */ "cmd ::= ROLLBACK trans_opt",
/* 20 */ "savepoint_opt ::= SAVEPOINT",
/* 21 */ "savepoint_opt ::=",
/* 22 */ "cmd ::= SAVEPOINT nm",
/* 23 */ "cmd ::= RELEASE savepoint_opt nm",
/* 24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
/* 25 */ "cmd ::= create_table create_table_args",
/* 26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
/* 27 */ "createkw ::= CREATE",
/* 28 */ "ifnotexists ::=",
/* 29 */ "ifnotexists ::= IF NOT EXISTS",
/* 30 */ "temp ::= TEMP",
/* 31 */ "temp ::=",
/* 32 */ "create_table_args ::= LP columnlist conslist_opt RP table_options",
/* 33 */ "create_table_args ::= AS select",
/* 34 */ "table_options ::=",
/* 35 */ "table_options ::= WITHOUT nm",
/* 36 */ "columnlist ::= columnlist COMMA column",
/* 37 */ "columnlist ::= column",
/* 38 */ "column ::= columnid type carglist",
/* 39 */ "columnid ::= nm",
/* 40 */ "nm ::= ID|INDEXED",
/* 41 */ "nm ::= STRING",
/* 42 */ "nm ::= JOIN_KW",
/* 43 */ "type ::=",
/* 44 */ "type ::= typetoken",
/* 45 */ "typetoken ::= typename",
/* 46 */ "typetoken ::= typename LP signed RP",
/* 47 */ "typetoken ::= typename LP signed COMMA signed RP",
/* 48 */ "typename ::= ID|STRING",
/* 49 */ "typename ::= typename ID|STRING",
/* 50 */ "signed ::= plus_num",
/* 51 */ "signed ::= minus_num",
/* 52 */ "carglist ::= carglist ccons",
/* 53 */ "carglist ::=",
/* 54 */ "ccons ::= CONSTRAINT nm",
/* 55 */ "ccons ::= DEFAULT term",
/* 56 */ "ccons ::= DEFAULT LP expr RP",
/* 57 */ "ccons ::= DEFAULT PLUS term",
/* 58 */ "ccons ::= DEFAULT MINUS term",
/* 59 */ "ccons ::= DEFAULT ID|INDEXED",
/* 60 */ "ccons ::= NULL onconf",
/* 61 */ "ccons ::= NOT NULL onconf",
/* 62 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
/* 63 */ "ccons ::= UNIQUE onconf",
/* 64 */ "ccons ::= CHECK LP expr RP",
/* 65 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
/* 66 */ "ccons ::= defer_subclause",
/* 67 */ "ccons ::= COLLATE ID|STRING",
/* 68 */ "autoinc ::=",
/* 69 */ "autoinc ::= AUTOINCR",
/* 70 */ "refargs ::=",
/* 71 */ "refargs ::= refargs refarg",
/* 72 */ "refarg ::= MATCH nm",
/* 73 */ "refarg ::= ON INSERT refact",
/* 74 */ "refarg ::= ON DELETE refact",
/* 75 */ "refarg ::= ON UPDATE refact",
/* 76 */ "refact ::= SET NULL",
/* 77 */ "refact ::= SET DEFAULT",
/* 78 */ "refact ::= CASCADE",
/* 79 */ "refact ::= RESTRICT",
/* 80 */ "refact ::= NO ACTION",
/* 81 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
/* 82 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
/* 83 */ "init_deferred_pred_opt ::=",
/* 84 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
/* 85 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
/* 86 */ "conslist_opt ::=",
/* 87 */ "conslist_opt ::= COMMA conslist",
/* 88 */ "conslist ::= conslist tconscomma tcons",
/* 89 */ "conslist ::= tcons",
/* 90 */ "tconscomma ::= COMMA",
/* 91 */ "tconscomma ::=",
/* 92 */ "tcons ::= CONSTRAINT nm",
/* 93 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
/* 94 */ "tcons ::= UNIQUE LP idxlist RP onconf",
/* 95 */ "tcons ::= CHECK LP expr RP onconf",
/* 96 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
/* 97 */ "defer_subclause_opt ::=",
/* 98 */ "defer_subclause_opt ::= defer_subclause",
/* 99 */ "onconf ::=",
/* 100 */ "onconf ::= ON CONFLICT resolvetype",
/* 101 */ "orconf ::=",
/* 102 */ "orconf ::= OR resolvetype",
/* 103 */ "resolvetype ::= raisetype",
/* 104 */ "resolvetype ::= IGNORE",
/* 105 */ "resolvetype ::= REPLACE",
/* 106 */ "cmd ::= DROP TABLE ifexists fullname",
/* 107 */ "ifexists ::= IF EXISTS",
/* 108 */ "ifexists ::=",
/* 109 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
/* 110 */ "cmd ::= DROP VIEW ifexists fullname",
/* 111 */ "cmd ::= select",
/* 112 */ "select ::= with selectnowith",
/* 113 */ "selectnowith ::= oneselect",
/* 114 */ "selectnowith ::= selectnowith multiselect_op oneselect",
/* 115 */ "multiselect_op ::= UNION",
/* 116 */ "multiselect_op ::= UNION ALL",
/* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
/* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
/* 119 */ "oneselect ::= values",
/* 120 */ "values ::= VALUES LP nexprlist RP",
/* 121 */ "values ::= values COMMA LP exprlist RP",
/* 122 */ "distinct ::= DISTINCT",
/* 123 */ "distinct ::= ALL",
/* 124 */ "distinct ::=",
/* 125 */ "sclp ::= selcollist COMMA",
/* 126 */ "sclp ::=",
/* 127 */ "selcollist ::= sclp expr as",
/* 128 */ "selcollist ::= sclp STAR",
/* 129 */ "selcollist ::= sclp nm DOT STAR",
/* 130 */ "as ::= AS nm",
/* 131 */ "as ::= ID|STRING",
/* 132 */ "as ::=",
/* 133 */ "from ::=",
/* 134 */ "from ::= FROM seltablist",
/* 135 */ "stl_prefix ::= seltablist joinop",
/* 136 */ "stl_prefix ::=",
/* 137 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
/* 138 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
/* 139 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
/* 140 */ "dbnm ::=",
/* 141 */ "dbnm ::= DOT nm",
/* 142 */ "fullname ::= nm dbnm",
/* 143 */ "joinop ::= COMMA|JOIN",
/* 144 */ "joinop ::= JOIN_KW JOIN",
/* 145 */ "joinop ::= JOIN_KW nm JOIN",
/* 146 */ "joinop ::= JOIN_KW nm nm JOIN",
/* 147 */ "on_opt ::= ON expr",
/* 148 */ "on_opt ::=",
/* 149 */ "indexed_opt ::=",
/* 150 */ "indexed_opt ::= INDEXED BY nm",
/* 151 */ "indexed_opt ::= NOT INDEXED",
/* 152 */ "using_opt ::= USING LP idlist RP",
/* 153 */ "using_opt ::=",
/* 154 */ "orderby_opt ::=",
/* 155 */ "orderby_opt ::= ORDER BY sortlist",
/* 156 */ "sortlist ::= sortlist COMMA expr sortorder",
/* 157 */ "sortlist ::= expr sortorder",
/* 158 */ "sortorder ::= ASC",
/* 159 */ "sortorder ::= DESC",
/* 160 */ "sortorder ::=",
/* 161 */ "groupby_opt ::=",
/* 162 */ "groupby_opt ::= GROUP BY nexprlist",
/* 163 */ "having_opt ::=",
/* 164 */ "having_opt ::= HAVING expr",
/* 165 */ "limit_opt ::=",
/* 166 */ "limit_opt ::= LIMIT expr",
/* 167 */ "limit_opt ::= LIMIT expr OFFSET expr",
/* 168 */ "limit_opt ::= LIMIT expr COMMA expr",
/* 169 */ "cmd ::= with DELETE FROM fullname indexed_opt where_opt",
/* 170 */ "where_opt ::=",
/* 171 */ "where_opt ::= WHERE expr",
/* 172 */ "cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt",
/* 173 */ "setlist ::= setlist COMMA nm EQ expr",
/* 174 */ "setlist ::= nm EQ expr",
/* 175 */ "cmd ::= with insert_cmd INTO fullname inscollist_opt select",
/* 176 */ "cmd ::= with insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
/* 177 */ "insert_cmd ::= INSERT orconf",
/* 178 */ "insert_cmd ::= REPLACE",
/* 179 */ "inscollist_opt ::=",
/* 180 */ "inscollist_opt ::= LP idlist RP",
/* 181 */ "idlist ::= idlist COMMA nm",
/* 182 */ "idlist ::= nm",
/* 183 */ "expr ::= term",
/* 184 */ "expr ::= LP expr RP",
/* 185 */ "term ::= NULL",
/* 186 */ "expr ::= ID|INDEXED",
/* 187 */ "expr ::= JOIN_KW",
/* 188 */ "expr ::= nm DOT nm",
/* 189 */ "expr ::= nm DOT nm DOT nm",
/* 190 */ "term ::= INTEGER|FLOAT|BLOB",
/* 191 */ "term ::= STRING",
/* 192 */ "expr ::= VARIABLE",
/* 193 */ "expr ::= expr COLLATE ID|STRING",
/* 194 */ "expr ::= CAST LP expr AS typetoken RP",
/* 195 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
/* 196 */ "expr ::= ID|INDEXED LP STAR RP",
/* 197 */ "term ::= CTIME_KW",
/* 198 */ "expr ::= expr AND expr",
/* 199 */ "expr ::= expr OR expr",
/* 200 */ "expr ::= expr LT|GT|GE|LE expr",
/* 201 */ "expr ::= expr EQ|NE expr",
/* 202 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
/* 203 */ "expr ::= expr PLUS|MINUS expr",
/* 204 */ "expr ::= expr STAR|SLASH|REM expr",
/* 205 */ "expr ::= expr CONCAT expr",
/* 206 */ "likeop ::= LIKE_KW|MATCH",
/* 207 */ "likeop ::= NOT LIKE_KW|MATCH",
/* 208 */ "expr ::= expr likeop expr",
/* 209 */ "expr ::= expr likeop expr ESCAPE expr",
/* 210 */ "expr ::= expr ISNULL|NOTNULL",
/* 211 */ "expr ::= expr NOT NULL",
/* 212 */ "expr ::= expr IS expr",
/* 213 */ "expr ::= expr IS NOT expr",
/* 214 */ "expr ::= NOT expr",
/* 215 */ "expr ::= BITNOT expr",
/* 216 */ "expr ::= MINUS expr",
/* 217 */ "expr ::= PLUS expr",
/* 218 */ "between_op ::= BETWEEN",
/* 219 */ "between_op ::= NOT BETWEEN",
/* 220 */ "expr ::= expr between_op expr AND expr",
/* 221 */ "in_op ::= IN",
/* 222 */ "in_op ::= NOT IN",
/* 223 */ "expr ::= expr in_op LP exprlist RP",
/* 224 */ "expr ::= LP select RP",
/* 225 */ "expr ::= expr in_op LP select RP",
/* 226 */ "expr ::= expr in_op nm dbnm",
/* 227 */ "expr ::= EXISTS LP select RP",
/* 228 */ "expr ::= CASE case_operand case_exprlist case_else END",
/* 229 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
/* 230 */ "case_exprlist ::= WHEN expr THEN expr",
/* 231 */ "case_else ::= ELSE expr",
/* 232 */ "case_else ::=",
/* 233 */ "case_operand ::= expr",
/* 234 */ "case_operand ::=",
/* 235 */ "exprlist ::= nexprlist",
/* 236 */ "exprlist ::=",
/* 237 */ "nexprlist ::= nexprlist COMMA expr",
/* 238 */ "nexprlist ::= expr",
/* 239 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP where_opt",
/* 240 */ "uniqueflag ::= UNIQUE",
/* 241 */ "uniqueflag ::=",
/* 242 */ "idxlist_opt ::=",
/* 243 */ "idxlist_opt ::= LP idxlist RP",
/* 244 */ "idxlist ::= idxlist COMMA nm collate sortorder",
/* 245 */ "idxlist ::= nm collate sortorder",
/* 246 */ "collate ::=",
/* 247 */ "collate ::= COLLATE ID|STRING",
/* 248 */ "cmd ::= DROP INDEX ifexists fullname",
/* 249 */ "cmd ::= VACUUM",
/* 250 */ "cmd ::= VACUUM nm",
/* 251 */ "cmd ::= PRAGMA nm dbnm",
/* 252 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
/* 253 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
/* 254 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
/* 255 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
/* 256 */ "nmnum ::= plus_num",
/* 257 */ "nmnum ::= nm",
/* 258 */ "nmnum ::= ON",
/* 259 */ "nmnum ::= DELETE",
/* 260 */ "nmnum ::= DEFAULT",
/* 261 */ "plus_num ::= PLUS INTEGER|FLOAT",
/* 262 */ "plus_num ::= INTEGER|FLOAT",
/* 263 */ "minus_num ::= MINUS INTEGER|FLOAT",
/* 264 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
/* 265 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
/* 266 */ "trigger_time ::= BEFORE",
/* 267 */ "trigger_time ::= AFTER",
/* 268 */ "trigger_time ::= INSTEAD OF",
/* 269 */ "trigger_time ::=",
/* 270 */ "trigger_event ::= DELETE|INSERT",
/* 271 */ "trigger_event ::= UPDATE",
/* 272 */ "trigger_event ::= UPDATE OF idlist",
/* 273 */ "foreach_clause ::=",
/* 274 */ "foreach_clause ::= FOR EACH ROW",
/* 275 */ "when_clause ::=",
/* 276 */ "when_clause ::= WHEN expr",
/* 277 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
/* 278 */ "trigger_cmd_list ::= trigger_cmd SEMI",
/* 279 */ "trnm ::= nm",
/* 280 */ "trnm ::= nm DOT nm",
/* 281 */ "tridxby ::=",
/* 282 */ "tridxby ::= INDEXED BY nm",
/* 283 */ "tridxby ::= NOT INDEXED",
/* 284 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
/* 285 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
/* 286 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
/* 287 */ "trigger_cmd ::= select",
/* 288 */ "expr ::= RAISE LP IGNORE RP",
/* 289 */ "expr ::= RAISE LP raisetype COMMA nm RP",
/* 290 */ "raisetype ::= ROLLBACK",
/* 291 */ "raisetype ::= ABORT",
/* 292 */ "raisetype ::= FAIL",
/* 293 */ "cmd ::= DROP TRIGGER ifexists fullname",
/* 294 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
/* 295 */ "cmd ::= DETACH database_kw_opt expr",
/* 296 */ "key_opt ::=",
/* 297 */ "key_opt ::= KEY expr",
/* 298 */ "database_kw_opt ::= DATABASE",
/* 299 */ "database_kw_opt ::=",
/* 300 */ "cmd ::= REINDEX",
/* 301 */ "cmd ::= REINDEX nm dbnm",
/* 302 */ "cmd ::= ANALYZE",
/* 303 */ "cmd ::= ANALYZE nm dbnm",
/* 304 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
/* 305 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
/* 306 */ "add_column_fullname ::= fullname",
/* 307 */ "kwcolumn_opt ::=",
/* 308 */ "kwcolumn_opt ::= COLUMNKW",
/* 309 */ "cmd ::= create_vtab",
/* 310 */ "cmd ::= create_vtab LP vtabarglist RP",
/* 311 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
/* 312 */ "vtabarglist ::= vtabarg",
/* 313 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
/* 314 */ "vtabarg ::=",
/* 315 */ "vtabarg ::= vtabarg vtabargtoken",
/* 316 */ "vtabargtoken ::= ANY",
/* 317 */ "vtabargtoken ::= lp anylist RP",
/* 318 */ "lp ::= LP",
/* 319 */ "anylist ::=",
/* 320 */ "anylist ::= anylist LP anylist RP",
/* 321 */ "anylist ::= anylist ANY",
/* 322 */ "with ::=",
/* 323 */ "with ::= WITH wqlist",
/* 324 */ "with ::= WITH RECURSIVE wqlist",
/* 325 */ "wqlist ::= nm idxlist_opt AS LP select RP",
/* 326 */ "wqlist ::= wqlist COMMA nm idxlist_opt AS LP select RP",
};
#endif /* NDEBUG */
#if YYSTACKDEPTH<=0
/*
** Try to increase the size of the parser stack.
*/
static void yyGrowStack(yyParser *p){
int newSize;
yyStackEntry *pNew;
newSize = p->yystksz*2 + 100;
pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
if( pNew ){
p->yystack = pNew;
p->yystksz = newSize;
#ifndef NDEBUG
if( yyTraceFILE ){
fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
yyTracePrompt, p->yystksz);
}
#endif
}
}
#endif
/*
** This function allocates a new parser.
** The only argument is a pointer to a function which works like
** malloc.
**
** Inputs:
** A pointer to the function used to allocate memory.
**
** Outputs:
** A pointer to a parser. This pointer is used in subsequent calls
** to sqlite3Parser and sqlite3ParserFree.
*/
void *sqlite3ParserAlloc(void *(*mallocProc)(u64)){
yyParser *pParser;
pParser = (yyParser*)(*mallocProc)( (u64)sizeof(yyParser) );
if( pParser ){
pParser->yyidx = -1;
#ifdef YYTRACKMAXSTACKDEPTH
pParser->yyidxMax = 0;
#endif
#if YYSTACKDEPTH<=0
pParser->yystack = NULL;
pParser->yystksz = 0;
yyGrowStack(pParser);
#endif
}
return pParser;
}
/* The following function deletes the value associated with a
** symbol. The symbol can be either a terminal or nonterminal.
** "yymajor" is the symbol code, and "yypminor" is a pointer to
** the value.
*/
static void yy_destructor(
yyParser *yypParser, /* The parser */
YYCODETYPE yymajor, /* Type code for object to destroy */
YYMINORTYPE *yypminor /* The object to be destroyed */
){
sqlite3ParserARG_FETCH;
switch( yymajor ){
/* Here is inserted the actions which take place when a
** terminal or non-terminal is destroyed. This can happen
** when the symbol is popped from the stack during a
** reduce or during error processing or when a parser is
** being destroyed before it is finished parsing.
**
** Note: during a reduce, the only symbols destroyed are those
** which appear on the RHS of the rule, but which are not used
** inside the C code.
*/
case 163: /* select */
case 195: /* selectnowith */
case 196: /* oneselect */
case 207: /* values */
{
#line 406 "parse.y"
sqlite3SelectDelete(pParse->db, (yypminor->yy3));
#line 1418 "parse.c"
}
break;
case 174: /* term */
case 175: /* expr */
{
#line 812 "parse.y"
sqlite3ExprDelete(pParse->db, (yypminor->yy346).pExpr);
#line 1426 "parse.c"
}
break;
case 179: /* idxlist_opt */
case 188: /* idxlist */
case 200: /* selcollist */
case 203: /* groupby_opt */
case 205: /* orderby_opt */
case 208: /* nexprlist */
case 209: /* exprlist */
case 210: /* sclp */
case 220: /* sortlist */
case 221: /* setlist */
case 228: /* case_exprlist */
{
#line 1216 "parse.y"
sqlite3ExprListDelete(pParse->db, (yypminor->yy14));
#line 1443 "parse.c"
}
break;
case 194: /* fullname */
case 201: /* from */
case 212: /* seltablist */
case 213: /* stl_prefix */
{
#line 630 "parse.y"
sqlite3SrcListDelete(pParse->db, (yypminor->yy65));
#line 1453 "parse.c"
}
break;
case 197: /* with */
case 252: /* wqlist */
{
#line 1477 "parse.y"
sqlite3WithDelete(pParse->db, (yypminor->yy59));
#line 1461 "parse.c"
}
break;
case 202: /* where_opt */
case 204: /* having_opt */
case 216: /* on_opt */
case 227: /* case_operand */
case 229: /* case_else */
case 238: /* when_clause */
case 243: /* key_opt */
{
#line 739 "parse.y"
sqlite3ExprDelete(pParse->db, (yypminor->yy132));
#line 1474 "parse.c"
}
break;
case 217: /* using_opt */
case 219: /* idlist */
case 223: /* inscollist_opt */
{
#line 662 "parse.y"
sqlite3IdListDelete(pParse->db, (yypminor->yy408));
#line 1483 "parse.c"
}
break;
case 234: /* trigger_cmd_list */
case 239: /* trigger_cmd */
{
#line 1313 "parse.y"
sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy473));
#line 1491 "parse.c"
}
break;
case 236: /* trigger_event */
{
#line 1299 "parse.y"
sqlite3IdListDelete(pParse->db, (yypminor->yy378).b);
#line 1498 "parse.c"
}
break;
default: break; /* If no destructor action specified: do nothing */
}
}
/*
** Pop the parser's stack once.
**
** If there is a destructor routine associated with the token which
** is popped from the stack, then call it.
**
** Return the major token number for the symbol popped.
*/
static int yy_pop_parser_stack(yyParser *pParser){
YYCODETYPE yymajor;
yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
/* There is no mechanism by which the parser stack can be popped below
** empty in SQLite. */
if( NEVER(pParser->yyidx<0) ) return 0;
#ifndef NDEBUG
if( yyTraceFILE && pParser->yyidx>=0 ){
fprintf(yyTraceFILE,"%sPopping %s\n",
yyTracePrompt,
yyTokenName[yytos->major]);
}
#endif
yymajor = yytos->major;
yy_destructor(pParser, yymajor, &yytos->minor);
pParser->yyidx--;
return yymajor;
}
/*
** Deallocate and destroy a parser. Destructors are all called for
** all stack elements before shutting the parser down.
**
** Inputs:
** <ul>
** <li> A pointer to the parser. This should be a pointer
** obtained from sqlite3ParserAlloc.
** <li> A pointer to a function used to reclaim memory obtained
** from malloc.
** </ul>
*/
void sqlite3ParserFree(
void *p, /* The parser to be deleted */
void (*freeProc)(void*) /* Function used to reclaim memory */
){
yyParser *pParser = (yyParser*)p;
/* In SQLite, we never try to destroy a parser that was not successfully
** created in the first place. */
if( NEVER(pParser==0) ) return;
while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
#if YYSTACKDEPTH<=0
free(pParser->yystack);
#endif
(*freeProc)((void*)pParser);
}
/*
** Return the peak depth of the stack for a parser.
*/
#ifdef YYTRACKMAXSTACKDEPTH
int sqlite3ParserStackPeak(void *p){
yyParser *pParser = (yyParser*)p;
return pParser->yyidxMax;
}
#endif
/*
** Find the appropriate action for a parser given the terminal
** look-ahead token iLookAhead.
**
** If the look-ahead token is YYNOCODE, then check to see if the action is
** independent of the look-ahead. If it is, return the action, otherwise
** return YY_NO_ACTION.
*/
static int yy_find_shift_action(
yyParser *pParser, /* The parser */
YYCODETYPE iLookAhead /* The look-ahead token */
){
int i;
int stateno = pParser->yystack[pParser->yyidx].stateno;
if( stateno>YY_SHIFT_COUNT
|| (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
return yy_default[stateno];
}
assert( iLookAhead!=YYNOCODE );
i += iLookAhead;
if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
if( iLookAhead>0 ){
#ifdef YYFALLBACK
YYCODETYPE iFallback; /* Fallback token */
if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
&& (iFallback = yyFallback[iLookAhead])!=0 ){
#ifndef NDEBUG
if( yyTraceFILE ){
fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
}
#endif
return yy_find_shift_action(pParser, iFallback);
}
#endif
#ifdef YYWILDCARD
{
int j = i - iLookAhead + YYWILDCARD;
if(
#if YY_SHIFT_MIN+YYWILDCARD<0
j>=0 &&
#endif
#if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
j<YY_ACTTAB_COUNT &&
#endif
yy_lookahead[j]==YYWILDCARD
){
#ifndef NDEBUG
if( yyTraceFILE ){
fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
}
#endif /* NDEBUG */
return yy_action[j];
}
}
#endif /* YYWILDCARD */
}
return yy_default[stateno];
}else{
return yy_action[i];
}
}
/*
** Find the appropriate action for a parser given the non-terminal
** look-ahead token iLookAhead.
**
** If the look-ahead token is YYNOCODE, then check to see if the action is
** independent of the look-ahead. If it is, return the action, otherwise
** return YY_NO_ACTION.
*/
static int yy_find_reduce_action(
int stateno, /* Current state number */
YYCODETYPE iLookAhead /* The look-ahead token */
){
int i;
#ifdef YYERRORSYMBOL
if( stateno>YY_REDUCE_COUNT ){
return yy_default[stateno];
}
#else
assert( stateno<=YY_REDUCE_COUNT );
#endif
i = yy_reduce_ofst[stateno];
assert( i!=YY_REDUCE_USE_DFLT );
assert( iLookAhead!=YYNOCODE );
i += iLookAhead;
#ifdef YYERRORSYMBOL
if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
return yy_default[stateno];
}
#else
assert( i>=0 && i<YY_ACTTAB_COUNT );
assert( yy_lookahead[i]==iLookAhead );
#endif
return yy_action[i];
}
/*
** The following routine is called if the stack overflows.
*/
static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
sqlite3ParserARG_FETCH;
yypParser->yyidx--;
#ifndef NDEBUG
if( yyTraceFILE ){
fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
}
#endif
while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
/* Here code is inserted which will execute if the parser
** stack every overflows */
#line 37 "parse.y"
UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
sqlite3ErrorMsg(pParse, "parser stack overflow");
#line 1688 "parse.c"
sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
}
/*
** Perform a shift action.
*/
static void yy_shift(
yyParser *yypParser, /* The parser to be shifted */
int yyNewState, /* The new state to shift in */
int yyMajor, /* The major token to shift in */
YYMINORTYPE *yypMinor /* Pointer to the minor token to shift in */
){
yyStackEntry *yytos;
yypParser->yyidx++;
#ifdef YYTRACKMAXSTACKDEPTH
if( yypParser->yyidx>yypParser->yyidxMax ){
yypParser->yyidxMax = yypParser->yyidx;
}
#endif
#if YYSTACKDEPTH>0
if( yypParser->yyidx>=YYSTACKDEPTH ){
yyStackOverflow(yypParser, yypMinor);
return;
}
#else
if( yypParser->yyidx>=yypParser->yystksz ){
yyGrowStack(yypParser);
if( yypParser->yyidx>=yypParser->yystksz ){
yyStackOverflow(yypParser, yypMinor);
return;
}
}
#endif
yytos = &yypParser->yystack[yypParser->yyidx];
yytos->stateno = (YYACTIONTYPE)yyNewState;
yytos->major = (YYCODETYPE)yyMajor;
yytos->minor = *yypMinor;
#ifndef NDEBUG
if( yyTraceFILE && yypParser->yyidx>0 ){
int i;
fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
for(i=1; i<=yypParser->yyidx; i++)
fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
fprintf(yyTraceFILE,"\n");
}
#endif
}
/* The following table contains information about every rule that
** is used during the reduce.
*/
static const struct {
YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
unsigned char nrhs; /* Number of right-hand side symbols in the rule */
} yyRuleInfo[] = {
{ 144, 1 },
{ 145, 2 },
{ 145, 1 },
{ 146, 1 },
{ 146, 3 },
{ 147, 0 },
{ 147, 1 },
{ 147, 3 },
{ 148, 1 },
{ 149, 3 },
{ 151, 0 },
{ 151, 1 },
{ 151, 2 },
{ 150, 0 },
{ 150, 1 },
{ 150, 1 },
{ 150, 1 },
{ 149, 2 },
{ 149, 2 },
{ 149, 2 },
{ 153, 1 },
{ 153, 0 },
{ 149, 2 },
{ 149, 3 },
{ 149, 5 },
{ 149, 2 },
{ 154, 6 },
{ 156, 1 },
{ 158, 0 },
{ 158, 3 },
{ 157, 1 },
{ 157, 0 },
{ 155, 5 },
{ 155, 2 },
{ 162, 0 },
{ 162, 2 },
{ 160, 3 },
{ 160, 1 },
{ 164, 3 },
{ 165, 1 },
{ 152, 1 },
{ 152, 1 },
{ 152, 1 },
{ 166, 0 },
{ 166, 1 },
{ 168, 1 },
{ 168, 4 },
{ 168, 6 },
{ 169, 1 },
{ 169, 2 },
{ 170, 1 },
{ 170, 1 },
{ 167, 2 },
{ 167, 0 },
{ 173, 2 },
{ 173, 2 },
{ 173, 4 },
{ 173, 3 },
{ 173, 3 },
{ 173, 2 },
{ 173, 2 },
{ 173, 3 },
{ 173, 5 },
{ 173, 2 },
{ 173, 4 },
{ 173, 4 },
{ 173, 1 },
{ 173, 2 },
{ 178, 0 },
{ 178, 1 },
{ 180, 0 },
{ 180, 2 },
{ 182, 2 },
{ 182, 3 },
{ 182, 3 },
{ 182, 3 },
{ 183, 2 },
{ 183, 2 },
{ 183, 1 },
{ 183, 1 },
{ 183, 2 },
{ 181, 3 },
{ 181, 2 },
{ 184, 0 },
{ 184, 2 },
{ 184, 2 },
{ 161, 0 },
{ 161, 2 },
{ 185, 3 },
{ 185, 1 },
{ 186, 1 },
{ 186, 0 },
{ 187, 2 },
{ 187, 7 },
{ 187, 5 },
{ 187, 5 },
{ 187, 10 },
{ 189, 0 },
{ 189, 1 },
{ 176, 0 },
{ 176, 3 },
{ 190, 0 },
{ 190, 2 },
{ 191, 1 },
{ 191, 1 },
{ 191, 1 },
{ 149, 4 },
{ 193, 2 },
{ 193, 0 },
{ 149, 8 },
{ 149, 4 },
{ 149, 1 },
{ 163, 2 },
{ 195, 1 },
{ 195, 3 },
{ 198, 1 },
{ 198, 2 },
{ 198, 1 },
{ 196, 9 },
{ 196, 1 },
{ 207, 4 },
{ 207, 5 },
{ 199, 1 },
{ 199, 1 },
{ 199, 0 },
{ 210, 2 },
{ 210, 0 },
{ 200, 3 },
{ 200, 2 },
{ 200, 4 },
{ 211, 2 },
{ 211, 1 },
{ 211, 0 },
{ 201, 0 },
{ 201, 2 },
{ 213, 2 },
{ 213, 0 },
{ 212, 7 },
{ 212, 7 },
{ 212, 7 },
{ 159, 0 },
{ 159, 2 },
{ 194, 2 },
{ 214, 1 },
{ 214, 2 },
{ 214, 3 },
{ 214, 4 },
{ 216, 2 },
{ 216, 0 },
{ 215, 0 },
{ 215, 3 },
{ 215, 2 },
{ 217, 4 },
{ 217, 0 },
{ 205, 0 },
{ 205, 3 },
{ 220, 4 },
{ 220, 2 },
{ 177, 1 },
{ 177, 1 },
{ 177, 0 },
{ 203, 0 },
{ 203, 3 },
{ 204, 0 },
{ 204, 2 },
{ 206, 0 },
{ 206, 2 },
{ 206, 4 },
{ 206, 4 },
{ 149, 6 },
{ 202, 0 },
{ 202, 2 },
{ 149, 8 },
{ 221, 5 },
{ 221, 3 },
{ 149, 6 },
{ 149, 7 },
{ 222, 2 },
{ 222, 1 },
{ 223, 0 },
{ 223, 3 },
{ 219, 3 },
{ 219, 1 },
{ 175, 1 },
{ 175, 3 },
{ 174, 1 },
{ 175, 1 },
{ 175, 1 },
{ 175, 3 },
{ 175, 5 },
{ 174, 1 },
{ 174, 1 },
{ 175, 1 },
{ 175, 3 },
{ 175, 6 },
{ 175, 5 },
{ 175, 4 },
{ 174, 1 },
{ 175, 3 },
{ 175, 3 },
{ 175, 3 },
{ 175, 3 },
{ 175, 3 },
{ 175, 3 },
{ 175, 3 },
{ 175, 3 },
{ 224, 1 },
{ 224, 2 },
{ 175, 3 },
{ 175, 5 },
{ 175, 2 },
{ 175, 3 },
{ 175, 3 },
{ 175, 4 },
{ 175, 2 },
{ 175, 2 },
{ 175, 2 },
{ 175, 2 },
{ 225, 1 },
{ 225, 2 },
{ 175, 5 },
{ 226, 1 },
{ 226, 2 },
{ 175, 5 },
{ 175, 3 },
{ 175, 5 },
{ 175, 4 },
{ 175, 4 },
{ 175, 5 },
{ 228, 5 },
{ 228, 4 },
{ 229, 2 },
{ 229, 0 },
{ 227, 1 },
{ 227, 0 },
{ 209, 1 },
{ 209, 0 },
{ 208, 3 },
{ 208, 1 },
{ 149, 12 },
{ 230, 1 },
{ 230, 0 },
{ 179, 0 },
{ 179, 3 },
{ 188, 5 },
{ 188, 3 },
{ 231, 0 },
{ 231, 2 },
{ 149, 4 },
{ 149, 1 },
{ 149, 2 },
{ 149, 3 },
{ 149, 5 },
{ 149, 6 },
{ 149, 5 },
{ 149, 6 },
{ 232, 1 },
{ 232, 1 },
{ 232, 1 },
{ 232, 1 },
{ 232, 1 },
{ 171, 2 },
{ 171, 1 },
{ 172, 2 },
{ 149, 5 },
{ 233, 11 },
{ 235, 1 },
{ 235, 1 },
{ 235, 2 },
{ 235, 0 },
{ 236, 1 },
{ 236, 1 },
{ 236, 3 },
{ 237, 0 },
{ 237, 3 },
{ 238, 0 },
{ 238, 2 },
{ 234, 3 },
{ 234, 2 },
{ 240, 1 },
{ 240, 3 },
{ 241, 0 },
{ 241, 3 },
{ 241, 2 },
{ 239, 7 },
{ 239, 5 },
{ 239, 5 },
{ 239, 1 },
{ 175, 4 },
{ 175, 6 },
{ 192, 1 },
{ 192, 1 },
{ 192, 1 },
{ 149, 4 },
{ 149, 6 },
{ 149, 3 },
{ 243, 0 },
{ 243, 2 },
{ 242, 1 },
{ 242, 0 },
{ 149, 1 },
{ 149, 3 },
{ 149, 1 },
{ 149, 3 },
{ 149, 6 },
{ 149, 6 },
{ 244, 1 },
{ 245, 0 },
{ 245, 1 },
{ 149, 1 },
{ 149, 4 },
{ 246, 8 },
{ 247, 1 },
{ 247, 3 },
{ 248, 0 },
{ 248, 2 },
{ 249, 1 },
{ 249, 3 },
{ 250, 1 },
{ 251, 0 },
{ 251, 4 },
{ 251, 2 },
{ 197, 0 },
{ 197, 2 },
{ 197, 3 },
{ 252, 6 },
{ 252, 8 },
};
static void yy_accept(yyParser*); /* Forward Declaration */
/*
** Perform a reduce action and the shift that must immediately
** follow the reduce.
*/
static void yy_reduce(
yyParser *yypParser, /* The parser */
int yyruleno /* Number of the rule by which to reduce */
){
int yygoto; /* The next state */
int yyact; /* The next action */
YYMINORTYPE yygotominor; /* The LHS of the rule reduced */
yyStackEntry *yymsp; /* The top of the parser's stack */
int yysize; /* Amount to pop the stack */
sqlite3ParserARG_FETCH;
yymsp = &yypParser->yystack[yypParser->yyidx];
#ifndef NDEBUG
if( yyTraceFILE && yyruleno>=0
&& yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
yyRuleName[yyruleno]);
}
#endif /* NDEBUG */
/* Silence complaints from purify about yygotominor being uninitialized
** in some cases when it is copied into the stack after the following
** switch. yygotominor is uninitialized when a rule reduces that does
** not set the value of its left-hand side nonterminal. Leaving the
** value of the nonterminal uninitialized is utterly harmless as long
** as the value is never used. So really the only thing this code
** accomplishes is to quieten purify.
**
** 2007-01-16: The wireshark project (www.wireshark.org) reports that
** without this code, their parser segfaults. I'm not sure what there
** parser is doing to make this happen. This is the second bug report
** from wireshark this week. Clearly they are stressing Lemon in ways
** that it has not been previously stressed... (SQLite ticket #2172)
*/
/*memset(&yygotominor, 0, sizeof(yygotominor));*/
yygotominor = yyzerominor;
switch( yyruleno ){
/* Beginning here are the reduction cases. A typical example
** follows:
** case 0:
** #line <lineno> <grammarfile>
** { ... } // User supplied code
** #line <lineno> <thisfile>
** break;
*/
case 5: /* explain ::= */
#line 105 "parse.y"
{ sqlite3BeginParse(pParse, 0); }
#line 2129 "parse.c"
break;
case 6: /* explain ::= EXPLAIN */
#line 107 "parse.y"
{ sqlite3BeginParse(pParse, 1); }
#line 2134 "parse.c"
break;
case 7: /* explain ::= EXPLAIN QUERY PLAN */
#line 108 "parse.y"
{ sqlite3BeginParse(pParse, 2); }
#line 2139 "parse.c"
break;
case 8: /* cmdx ::= cmd */
#line 110 "parse.y"
{ sqlite3FinishCoding(pParse); }
#line 2144 "parse.c"
break;
case 9: /* cmd ::= BEGIN transtype trans_opt */
#line 115 "parse.y"
{sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy328);}
#line 2149 "parse.c"
break;
case 13: /* transtype ::= */
#line 120 "parse.y"
{yygotominor.yy328 = TK_DEFERRED;}
#line 2154 "parse.c"
break;
case 14: /* transtype ::= DEFERRED */
case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
#line 121 "parse.y"
{yygotominor.yy328 = yymsp[0].major;}
#line 2163 "parse.c"
break;
case 17: /* cmd ::= COMMIT trans_opt */
case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
#line 124 "parse.y"
{sqlite3CommitTransaction(pParse);}
#line 2169 "parse.c"
break;
case 19: /* cmd ::= ROLLBACK trans_opt */
#line 126 "parse.y"
{sqlite3RollbackTransaction(pParse);}
#line 2174 "parse.c"
break;
case 22: /* cmd ::= SAVEPOINT nm */
#line 130 "parse.y"
{
sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
}
#line 2181 "parse.c"
break;
case 23: /* cmd ::= RELEASE savepoint_opt nm */
#line 133 "parse.y"
{
sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
}
#line 2188 "parse.c"
break;
case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
#line 136 "parse.y"
{
sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
}
#line 2195 "parse.c"
break;
case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
#line 143 "parse.y"
{
sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy328,0,0,yymsp[-2].minor.yy328);
}
#line 2202 "parse.c"
break;
case 27: /* createkw ::= CREATE */
#line 146 "parse.y"
{
pParse->db->lookaside.bEnabled = 0;
yygotominor.yy0 = yymsp[0].minor.yy0;
}
#line 2210 "parse.c"
break;
case 28: /* ifnotexists ::= */
case 31: /* temp ::= */ yytestcase(yyruleno==31);
case 68: /* autoinc ::= */ yytestcase(yyruleno==68);
case 81: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==81);
case 83: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==83);
case 85: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==85);
case 97: /* defer_subclause_opt ::= */ yytestcase(yyruleno==97);
case 108: /* ifexists ::= */ yytestcase(yyruleno==108);
case 218: /* between_op ::= BETWEEN */ yytestcase(yyruleno==218);
case 221: /* in_op ::= IN */ yytestcase(yyruleno==221);
#line 151 "parse.y"
{yygotominor.yy328 = 0;}
#line 2224 "parse.c"
break;
case 29: /* ifnotexists ::= IF NOT EXISTS */
case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
case 69: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==69);
case 84: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==84);
case 107: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==107);
case 219: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==219);
case 222: /* in_op ::= NOT IN */ yytestcase(yyruleno==222);
#line 152 "parse.y"
{yygotominor.yy328 = 1;}
#line 2235 "parse.c"
break;
case 32: /* create_table_args ::= LP columnlist conslist_opt RP table_options */
#line 158 "parse.y"
{
sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy186,0);
}
#line 2242 "parse.c"
break;
case 33: /* create_table_args ::= AS select */
#line 161 "parse.y"
{
sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy3);
sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
}
#line 2250 "parse.c"
break;
case 34: /* table_options ::= */
#line 166 "parse.y"
{yygotominor.yy186 = 0;}
#line 2255 "parse.c"
break;
case 35: /* table_options ::= WITHOUT nm */
#line 167 "parse.y"
{
if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
yygotominor.yy186 = TF_WithoutRowid;
}else{
yygotominor.yy186 = 0;
sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
}
}
#line 2267 "parse.c"
break;
case 38: /* column ::= columnid type carglist */
#line 183 "parse.y"
{
yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
}
#line 2275 "parse.c"
break;
case 39: /* columnid ::= nm */
#line 187 "parse.y"
{
sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
yygotominor.yy0 = yymsp[0].minor.yy0;
pParse->constraintName.n = 0;
}
#line 2284 "parse.c"
break;
case 40: /* nm ::= ID|INDEXED */
case 41: /* nm ::= STRING */ yytestcase(yyruleno==41);
case 42: /* nm ::= JOIN_KW */ yytestcase(yyruleno==42);
case 45: /* typetoken ::= typename */ yytestcase(yyruleno==45);
case 48: /* typename ::= ID|STRING */ yytestcase(yyruleno==48);
case 130: /* as ::= AS nm */ yytestcase(yyruleno==130);
case 131: /* as ::= ID|STRING */ yytestcase(yyruleno==131);
case 141: /* dbnm ::= DOT nm */ yytestcase(yyruleno==141);
case 150: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==150);
case 247: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==247);
case 256: /* nmnum ::= plus_num */ yytestcase(yyruleno==256);
case 257: /* nmnum ::= nm */ yytestcase(yyruleno==257);
case 258: /* nmnum ::= ON */ yytestcase(yyruleno==258);
case 259: /* nmnum ::= DELETE */ yytestcase(yyruleno==259);
case 260: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==260);
case 261: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==261);
case 262: /* plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==262);
case 263: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==263);
case 279: /* trnm ::= nm */ yytestcase(yyruleno==279);
#line 247 "parse.y"
{yygotominor.yy0 = yymsp[0].minor.yy0;}
#line 2307 "parse.c"
break;
case 44: /* type ::= typetoken */
#line 257 "parse.y"
{sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
#line 2312 "parse.c"
break;
case 46: /* typetoken ::= typename LP signed RP */
#line 259 "parse.y"
{
yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
}
#line 2320 "parse.c"
break;
case 47: /* typetoken ::= typename LP signed COMMA signed RP */
#line 263 "parse.y"
{
yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
}
#line 2328 "parse.c"
break;
case 49: /* typename ::= typename ID|STRING */
#line 269 "parse.y"
{yygotominor.yy0.z=yymsp[-1].minor.yy0.z; yygotominor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);}
#line 2333 "parse.c"
break;
case 54: /* ccons ::= CONSTRAINT nm */
case 92: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==92);
#line 278 "parse.y"
{pParse->constraintName = yymsp[0].minor.yy0;}
#line 2339 "parse.c"
break;
case 55: /* ccons ::= DEFAULT term */
case 57: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==57);
#line 279 "parse.y"
{sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy346);}
#line 2345 "parse.c"
break;
case 56: /* ccons ::= DEFAULT LP expr RP */
#line 280 "parse.y"
{sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy346);}
#line 2350 "parse.c"
break;
case 58: /* ccons ::= DEFAULT MINUS term */
#line 282 "parse.y"
{
ExprSpan v;
v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy346.pExpr, 0, 0);
v.zStart = yymsp[-1].minor.yy0.z;
v.zEnd = yymsp[0].minor.yy346.zEnd;
sqlite3AddDefaultValue(pParse,&v);
}
#line 2361 "parse.c"
break;
case 59: /* ccons ::= DEFAULT ID|INDEXED */
#line 289 "parse.y"
{
ExprSpan v;
spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
sqlite3AddDefaultValue(pParse,&v);
}
#line 2370 "parse.c"
break;
case 61: /* ccons ::= NOT NULL onconf */
#line 299 "parse.y"
{sqlite3AddNotNull(pParse, yymsp[0].minor.yy328);}
#line 2375 "parse.c"
break;
case 62: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
#line 301 "parse.y"
{sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy328,yymsp[0].minor.yy328,yymsp[-2].minor.yy328);}
#line 2380 "parse.c"
break;
case 63: /* ccons ::= UNIQUE onconf */
#line 302 "parse.y"
{sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy328,0,0,0,0);}
#line 2385 "parse.c"
break;
case 64: /* ccons ::= CHECK LP expr RP */
#line 303 "parse.y"
{sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy346.pExpr);}
#line 2390 "parse.c"
break;
case 65: /* ccons ::= REFERENCES nm idxlist_opt refargs */
#line 305 "parse.y"
{sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy14,yymsp[0].minor.yy328);}
#line 2395 "parse.c"
break;
case 66: /* ccons ::= defer_subclause */
#line 306 "parse.y"
{sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy328);}
#line 2400 "parse.c"
break;
case 67: /* ccons ::= COLLATE ID|STRING */
#line 307 "parse.y"
{sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
#line 2405 "parse.c"
break;
case 70: /* refargs ::= */
#line 320 "parse.y"
{ yygotominor.yy328 = OE_None*0x0101; /* EV: R-19803-45884 */}
#line 2410 "parse.c"
break;
case 71: /* refargs ::= refargs refarg */
#line 321 "parse.y"
{ yygotominor.yy328 = (yymsp[-1].minor.yy328 & ~yymsp[0].minor.yy429.mask) | yymsp[0].minor.yy429.value; }
#line 2415 "parse.c"
break;
case 72: /* refarg ::= MATCH nm */
case 73: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==73);
#line 323 "parse.y"
{ yygotominor.yy429.value = 0; yygotominor.yy429.mask = 0x000000; }
#line 2421 "parse.c"
break;
case 74: /* refarg ::= ON DELETE refact */
#line 325 "parse.y"
{ yygotominor.yy429.value = yymsp[0].minor.yy328; yygotominor.yy429.mask = 0x0000ff; }
#line 2426 "parse.c"
break;
case 75: /* refarg ::= ON UPDATE refact */
#line 326 "parse.y"
{ yygotominor.yy429.value = yymsp[0].minor.yy328<<8; yygotominor.yy429.mask = 0x00ff00; }
#line 2431 "parse.c"
break;
case 76: /* refact ::= SET NULL */
#line 328 "parse.y"
{ yygotominor.yy328 = OE_SetNull; /* EV: R-33326-45252 */}
#line 2436 "parse.c"
break;
case 77: /* refact ::= SET DEFAULT */
#line 329 "parse.y"
{ yygotominor.yy328 = OE_SetDflt; /* EV: R-33326-45252 */}
#line 2441 "parse.c"
break;
case 78: /* refact ::= CASCADE */
#line 330 "parse.y"
{ yygotominor.yy328 = OE_Cascade; /* EV: R-33326-45252 */}
#line 2446 "parse.c"
break;
case 79: /* refact ::= RESTRICT */
#line 331 "parse.y"
{ yygotominor.yy328 = OE_Restrict; /* EV: R-33326-45252 */}
#line 2451 "parse.c"
break;
case 80: /* refact ::= NO ACTION */
#line 332 "parse.y"
{ yygotominor.yy328 = OE_None; /* EV: R-33326-45252 */}
#line 2456 "parse.c"
break;
case 82: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
case 98: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==98);
case 100: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==100);
case 103: /* resolvetype ::= raisetype */ yytestcase(yyruleno==103);
#line 335 "parse.y"
{yygotominor.yy328 = yymsp[0].minor.yy328;}
#line 2464 "parse.c"
break;
case 86: /* conslist_opt ::= */
#line 341 "parse.y"
{yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
#line 2469 "parse.c"
break;
case 87: /* conslist_opt ::= COMMA conslist */
#line 342 "parse.y"
{yygotominor.yy0 = yymsp[-1].minor.yy0;}
#line 2474 "parse.c"
break;
case 90: /* tconscomma ::= COMMA */
#line 345 "parse.y"
{pParse->constraintName.n = 0;}
#line 2479 "parse.c"
break;
case 93: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
#line 349 "parse.y"
{sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy14,yymsp[0].minor.yy328,yymsp[-2].minor.yy328,0);}
#line 2484 "parse.c"
break;
case 94: /* tcons ::= UNIQUE LP idxlist RP onconf */
#line 351 "parse.y"
{sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy14,yymsp[0].minor.yy328,0,0,0,0);}
#line 2489 "parse.c"
break;
case 95: /* tcons ::= CHECK LP expr RP onconf */
#line 353 "parse.y"
{sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy346.pExpr);}
#line 2494 "parse.c"
break;
case 96: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
#line 355 "parse.y"
{
sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy14, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy14, yymsp[-1].minor.yy328);
sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy328);
}
#line 2502 "parse.c"
break;
case 99: /* onconf ::= */
#line 369 "parse.y"
{yygotominor.yy328 = OE_Default;}
#line 2507 "parse.c"
break;
case 101: /* orconf ::= */
#line 371 "parse.y"
{yygotominor.yy186 = OE_Default;}
#line 2512 "parse.c"
break;
case 102: /* orconf ::= OR resolvetype */
#line 372 "parse.y"
{yygotominor.yy186 = (u8)yymsp[0].minor.yy328;}
#line 2517 "parse.c"
break;
case 104: /* resolvetype ::= IGNORE */
#line 374 "parse.y"
{yygotominor.yy328 = OE_Ignore;}
#line 2522 "parse.c"
break;
case 105: /* resolvetype ::= REPLACE */
#line 375 "parse.y"
{yygotominor.yy328 = OE_Replace;}
#line 2527 "parse.c"
break;
case 106: /* cmd ::= DROP TABLE ifexists fullname */
#line 379 "parse.y"
{
sqlite3DropTable(pParse, yymsp[0].minor.yy65, 0, yymsp[-1].minor.yy328);
}
#line 2534 "parse.c"
break;
case 109: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
#line 389 "parse.y"
{
sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, yymsp[0].minor.yy3, yymsp[-6].minor.yy328, yymsp[-4].minor.yy328);
}
#line 2541 "parse.c"
break;
case 110: /* cmd ::= DROP VIEW ifexists fullname */
#line 392 "parse.y"
{
sqlite3DropTable(pParse, yymsp[0].minor.yy65, 1, yymsp[-1].minor.yy328);
}
#line 2548 "parse.c"
break;
case 111: /* cmd ::= select */
#line 399 "parse.y"
{
SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};
sqlite3Select(pParse, yymsp[0].minor.yy3, &dest);
sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
}
#line 2557 "parse.c"
break;
case 112: /* select ::= with selectnowith */
#line 436 "parse.y"
{
Select *p = yymsp[0].minor.yy3;
if( p ){
p->pWith = yymsp[-1].minor.yy59;
parserDoubleLinkSelect(pParse, p);
}else{
sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy59);
}
yygotominor.yy3 = p;
}
#line 2571 "parse.c"
break;
case 113: /* selectnowith ::= oneselect */
case 119: /* oneselect ::= values */ yytestcase(yyruleno==119);
#line 447 "parse.y"
{yygotominor.yy3 = yymsp[0].minor.yy3;}
#line 2577 "parse.c"
break;
case 114: /* selectnowith ::= selectnowith multiselect_op oneselect */
#line 449 "parse.y"
{
Select *pRhs = yymsp[0].minor.yy3;
if( pRhs && pRhs->pPrior ){
SrcList *pFrom;
Token x;
x.n = 0;
parserDoubleLinkSelect(pParse, pRhs);
pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0,0);
}
if( pRhs ){
pRhs->op = (u8)yymsp[-1].minor.yy328;
pRhs->pPrior = yymsp[-2].minor.yy3;
pRhs->selFlags &= ~SF_MultiValue;
if( yymsp[-1].minor.yy328!=TK_ALL ) pParse->hasCompound = 1;
}else{
sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy3);
}
yygotominor.yy3 = pRhs;
}
#line 2601 "parse.c"
break;
case 116: /* multiselect_op ::= UNION ALL */
#line 471 "parse.y"
{yygotominor.yy328 = TK_ALL;}
#line 2606 "parse.c"
break;
case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
#line 475 "parse.y"
{
yygotominor.yy3 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy14,yymsp[-5].minor.yy65,yymsp[-4].minor.yy132,yymsp[-3].minor.yy14,yymsp[-2].minor.yy132,yymsp[-1].minor.yy14,yymsp[-7].minor.yy381,yymsp[0].minor.yy476.pLimit,yymsp[0].minor.yy476.pOffset);
#if SELECTTRACE_ENABLED
/* Populate the Select.zSelName[] string that is used to help with
** query planner debugging, to differentiate between multiple Select
** objects in a complex query.
**
** If the SELECT keyword is immediately followed by a C-style comment
** then extract the first few alphanumeric characters from within that
** comment to be the zSelName value. Otherwise, the label is #N where
** is an integer that is incremented with each SELECT statement seen.
*/
if( yygotominor.yy3!=0 ){
const char *z = yymsp[-8].minor.yy0.z+6;
int i;
sqlite3_snprintf(sizeof(yygotominor.yy3->zSelName), yygotominor.yy3->zSelName, "#%d",
++pParse->nSelect);
while( z[0]==' ' ) z++;
if( z[0]=='/' && z[1]=='*' ){
z += 2;
while( z[0]==' ' ) z++;
for(i=0; sqlite3Isalnum(z[i]); i++){}
sqlite3_snprintf(sizeof(yygotominor.yy3->zSelName), yygotominor.yy3->zSelName, "%.*s", i, z);
}
}
#endif /* SELECTRACE_ENABLED */
}
#line 2637 "parse.c"
break;
case 120: /* values ::= VALUES LP nexprlist RP */
#line 506 "parse.y"
{
yygotominor.yy3 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy14,0,0,0,0,0,SF_Values,0,0);
}
#line 2644 "parse.c"
break;
case 121: /* values ::= values COMMA LP exprlist RP */
#line 509 "parse.y"
{
Select *pRight, *pLeft = yymsp[-4].minor.yy3;
pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy14,0,0,0,0,0,SF_Values|SF_MultiValue,0,0);
if( ALWAYS(pLeft) ) pLeft->selFlags &= ~SF_MultiValue;
if( pRight ){
pRight->op = TK_ALL;
pLeft = yymsp[-4].minor.yy3;
pRight->pPrior = pLeft;
yygotominor.yy3 = pRight;
}else{
yygotominor.yy3 = pLeft;
}
}
#line 2661 "parse.c"
break;
case 122: /* distinct ::= DISTINCT */
#line 527 "parse.y"
{yygotominor.yy381 = SF_Distinct;}
#line 2666 "parse.c"
break;
case 123: /* distinct ::= ALL */
case 124: /* distinct ::= */ yytestcase(yyruleno==124);
#line 528 "parse.y"
{yygotominor.yy381 = 0;}
#line 2672 "parse.c"
break;
case 125: /* sclp ::= selcollist COMMA */
case 243: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==243);
#line 540 "parse.y"
{yygotominor.yy14 = yymsp[-1].minor.yy14;}
#line 2678 "parse.c"
break;
case 126: /* sclp ::= */
case 154: /* orderby_opt ::= */ yytestcase(yyruleno==154);
case 161: /* groupby_opt ::= */ yytestcase(yyruleno==161);
case 236: /* exprlist ::= */ yytestcase(yyruleno==236);
case 242: /* idxlist_opt ::= */ yytestcase(yyruleno==242);
#line 541 "parse.y"
{yygotominor.yy14 = 0;}
#line 2687 "parse.c"
break;
case 127: /* selcollist ::= sclp expr as */
#line 542 "parse.y"
{
yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy14, yymsp[-1].minor.yy346.pExpr);
if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[0].minor.yy0, 1);
sqlite3ExprListSetSpan(pParse,yygotominor.yy14,&yymsp[-1].minor.yy346);
}
#line 2696 "parse.c"
break;
case 128: /* selcollist ::= sclp STAR */
#line 547 "parse.y"
{
Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy14, p);
}
#line 2704 "parse.c"
break;
case 129: /* selcollist ::= sclp nm DOT STAR */
#line 551 "parse.y"
{
Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14, pDot);
}
#line 2714 "parse.c"
break;
case 132: /* as ::= */
#line 564 "parse.y"
{yygotominor.yy0.n = 0;}
#line 2719 "parse.c"
break;
case 133: /* from ::= */
#line 576 "parse.y"
{yygotominor.yy65 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy65));}
#line 2724 "parse.c"
break;
case 134: /* from ::= FROM seltablist */
#line 577 "parse.y"
{
yygotominor.yy65 = yymsp[0].minor.yy65;
sqlite3SrcListShiftJoinType(yygotominor.yy65);
}
#line 2732 "parse.c"
break;
case 135: /* stl_prefix ::= seltablist joinop */
#line 585 "parse.y"
{
yygotominor.yy65 = yymsp[-1].minor.yy65;
if( ALWAYS(yygotominor.yy65 && yygotominor.yy65->nSrc>0) ) yygotominor.yy65->a[yygotominor.yy65->nSrc-1].jointype = (u8)yymsp[0].minor.yy328;
}
#line 2740 "parse.c"
break;
case 136: /* stl_prefix ::= */
#line 589 "parse.y"
{yygotominor.yy65 = 0;}
#line 2745 "parse.c"
break;
case 137: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
#line 591 "parse.y"
{
yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
sqlite3SrcListIndexedBy(pParse, yygotominor.yy65, &yymsp[-2].minor.yy0);
}
#line 2753 "parse.c"
break;
case 138: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
#line 597 "parse.y"
{
yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy3,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
}
#line 2760 "parse.c"
break;
case 139: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
#line 601 "parse.y"
{
if( yymsp[-6].minor.yy65==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy132==0 && yymsp[0].minor.yy408==0 ){
yygotominor.yy65 = yymsp[-4].minor.yy65;
}else if( yymsp[-4].minor.yy65->nSrc==1 ){
yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
if( yygotominor.yy65 ){
struct SrcList_item *pNew = &yygotominor.yy65->a[yygotominor.yy65->nSrc-1];
struct SrcList_item *pOld = yymsp[-4].minor.yy65->a;
pNew->zName = pOld->zName;
pNew->zDatabase = pOld->zDatabase;
pNew->pSelect = pOld->pSelect;
pOld->zName = pOld->zDatabase = 0;
pOld->pSelect = 0;
}
sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy65);
}else{
Select *pSubquery;
sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy65);
pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy65,0,0,0,0,SF_NestedFrom,0,0);
yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
}
}
#line 2786 "parse.c"
break;
case 140: /* dbnm ::= */
case 149: /* indexed_opt ::= */ yytestcase(yyruleno==149);
#line 626 "parse.y"
{yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
#line 2792 "parse.c"
break;
case 142: /* fullname ::= nm dbnm */
#line 631 "parse.y"
{yygotominor.yy65 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
#line 2797 "parse.c"
break;
case 143: /* joinop ::= COMMA|JOIN */
#line 635 "parse.y"
{ yygotominor.yy328 = JT_INNER; }
#line 2802 "parse.c"
break;
case 144: /* joinop ::= JOIN_KW JOIN */
#line 636 "parse.y"
{ yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
#line 2807 "parse.c"
break;
case 145: /* joinop ::= JOIN_KW nm JOIN */
#line 637 "parse.y"
{ yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
#line 2812 "parse.c"
break;
case 146: /* joinop ::= JOIN_KW nm nm JOIN */
#line 639 "parse.y"
{ yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
#line 2817 "parse.c"
break;
case 147: /* on_opt ::= ON expr */
case 164: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==164);
case 171: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==171);
case 231: /* case_else ::= ELSE expr */ yytestcase(yyruleno==231);
case 233: /* case_operand ::= expr */ yytestcase(yyruleno==233);
#line 643 "parse.y"
{yygotominor.yy132 = yymsp[0].minor.yy346.pExpr;}
#line 2826 "parse.c"
break;
case 148: /* on_opt ::= */
case 163: /* having_opt ::= */ yytestcase(yyruleno==163);
case 170: /* where_opt ::= */ yytestcase(yyruleno==170);
case 232: /* case_else ::= */ yytestcase(yyruleno==232);
case 234: /* case_operand ::= */ yytestcase(yyruleno==234);
#line 644 "parse.y"
{yygotominor.yy132 = 0;}
#line 2835 "parse.c"
break;
case 151: /* indexed_opt ::= NOT INDEXED */
#line 659 "parse.y"
{yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
#line 2840 "parse.c"
break;
case 152: /* using_opt ::= USING LP idlist RP */
case 180: /* inscollist_opt ::= LP idlist RP */ yytestcase(yyruleno==180);
#line 663 "parse.y"
{yygotominor.yy408 = yymsp[-1].minor.yy408;}
#line 2846 "parse.c"
break;
case 153: /* using_opt ::= */
case 179: /* inscollist_opt ::= */ yytestcase(yyruleno==179);
#line 664 "parse.y"
{yygotominor.yy408 = 0;}
#line 2852 "parse.c"
break;
case 155: /* orderby_opt ::= ORDER BY sortlist */
case 162: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==162);
case 235: /* exprlist ::= nexprlist */ yytestcase(yyruleno==235);
#line 673 "parse.y"
{yygotominor.yy14 = yymsp[0].minor.yy14;}
#line 2859 "parse.c"
break;
case 156: /* sortlist ::= sortlist COMMA expr sortorder */
#line 674 "parse.y"
{
yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14,yymsp[-1].minor.yy346.pExpr);
if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
}
#line 2867 "parse.c"
break;
case 157: /* sortlist ::= expr sortorder */
#line 678 "parse.y"
{
yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy346.pExpr);
if( yygotominor.yy14 && ALWAYS(yygotominor.yy14->a) ) yygotominor.yy14->a[0].sortOrder = (u8)yymsp[0].minor.yy328;
}
#line 2875 "parse.c"
break;
case 158: /* sortorder ::= ASC */
case 160: /* sortorder ::= */ yytestcase(yyruleno==160);
#line 685 "parse.y"
{yygotominor.yy328 = SQLITE_SO_ASC;}
#line 2881 "parse.c"
break;
case 159: /* sortorder ::= DESC */
#line 686 "parse.y"
{yygotominor.yy328 = SQLITE_SO_DESC;}
#line 2886 "parse.c"
break;
case 165: /* limit_opt ::= */
#line 712 "parse.y"
{yygotominor.yy476.pLimit = 0; yygotominor.yy476.pOffset = 0;}
#line 2891 "parse.c"
break;
case 166: /* limit_opt ::= LIMIT expr */
#line 713 "parse.y"
{yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr; yygotominor.yy476.pOffset = 0;}
#line 2896 "parse.c"
break;
case 167: /* limit_opt ::= LIMIT expr OFFSET expr */
#line 715 "parse.y"
{yygotominor.yy476.pLimit = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pOffset = yymsp[0].minor.yy346.pExpr;}
#line 2901 "parse.c"
break;
case 168: /* limit_opt ::= LIMIT expr COMMA expr */
#line 717 "parse.y"
{yygotominor.yy476.pOffset = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr;}
#line 2906 "parse.c"
break;
case 169: /* cmd ::= with DELETE FROM fullname indexed_opt where_opt */
#line 731 "parse.y"
{
sqlite3WithPush(pParse, yymsp[-5].minor.yy59, 1);
sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy65, &yymsp[-1].minor.yy0);
sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy65,yymsp[0].minor.yy132);
}
#line 2915 "parse.c"
break;
case 172: /* cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt */
#line 758 "parse.y"
{
sqlite3WithPush(pParse, yymsp[-7].minor.yy59, 1);
sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy65, &yymsp[-3].minor.yy0);
sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy14,"set list");
sqlite3Update(pParse,yymsp[-4].minor.yy65,yymsp[-1].minor.yy14,yymsp[0].minor.yy132,yymsp[-5].minor.yy186);
}
#line 2925 "parse.c"
break;
case 173: /* setlist ::= setlist COMMA nm EQ expr */
#line 769 "parse.y"
{
yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy14, yymsp[0].minor.yy346.pExpr);
sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
}
#line 2933 "parse.c"
break;
case 174: /* setlist ::= nm EQ expr */
#line 773 "parse.y"
{
yygotominor.yy14 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy346.pExpr);
sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
}
#line 2941 "parse.c"
break;
case 175: /* cmd ::= with insert_cmd INTO fullname inscollist_opt select */
#line 780 "parse.y"
{
sqlite3WithPush(pParse, yymsp[-5].minor.yy59, 1);
sqlite3Insert(pParse, yymsp[-2].minor.yy65, yymsp[0].minor.yy3, yymsp[-1].minor.yy408, yymsp[-4].minor.yy186);
}
#line 2949 "parse.c"
break;
case 176: /* cmd ::= with insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
#line 785 "parse.y"
{
sqlite3WithPush(pParse, yymsp[-6].minor.yy59, 1);
sqlite3Insert(pParse, yymsp[-3].minor.yy65, 0, yymsp[-2].minor.yy408, yymsp[-5].minor.yy186);
}
#line 2957 "parse.c"
break;
case 177: /* insert_cmd ::= INSERT orconf */
#line 791 "parse.y"
{yygotominor.yy186 = yymsp[0].minor.yy186;}
#line 2962 "parse.c"
break;
case 178: /* insert_cmd ::= REPLACE */
#line 792 "parse.y"
{yygotominor.yy186 = OE_Replace;}
#line 2967 "parse.c"
break;
case 181: /* idlist ::= idlist COMMA nm */
#line 802 "parse.y"
{yygotominor.yy408 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy408,&yymsp[0].minor.yy0);}
#line 2972 "parse.c"
break;
case 182: /* idlist ::= nm */
#line 804 "parse.y"
{yygotominor.yy408 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
#line 2977 "parse.c"
break;
case 183: /* expr ::= term */
#line 835 "parse.y"
{yygotominor.yy346 = yymsp[0].minor.yy346;}
#line 2982 "parse.c"
break;
case 184: /* expr ::= LP expr RP */
#line 836 "parse.y"
{yygotominor.yy346.pExpr = yymsp[-1].minor.yy346.pExpr; spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
#line 2987 "parse.c"
break;
case 185: /* term ::= NULL */
case 190: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==190);
case 191: /* term ::= STRING */ yytestcase(yyruleno==191);
#line 837 "parse.y"
{spanExpr(&yygotominor.yy346, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
#line 2994 "parse.c"
break;
case 186: /* expr ::= ID|INDEXED */
case 187: /* expr ::= JOIN_KW */ yytestcase(yyruleno==187);
#line 838 "parse.y"
{spanExpr(&yygotominor.yy346, pParse, TK_ID, &yymsp[0].minor.yy0);}
#line 3000 "parse.c"
break;
case 188: /* expr ::= nm DOT nm */
#line 840 "parse.y"
{
Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
}
#line 3010 "parse.c"
break;
case 189: /* expr ::= nm DOT nm DOT nm */
#line 846 "parse.y"
{
Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
}
#line 3022 "parse.c"
break;
case 192: /* expr ::= VARIABLE */
#line 856 "parse.y"
{
if( yymsp[0].minor.yy0.n>=2 && yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1]) ){
/* When doing a nested parse, one can include terms in an expression
** that look like this: #1 #2 ... These terms refer to registers
** in the virtual machine. #N is the N-th register. */
if( pParse->nested==0 ){
sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
yygotominor.yy346.pExpr = 0;
}else{
yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
if( yygotominor.yy346.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy346.pExpr->iTable);
}
}else{
spanExpr(&yygotominor.yy346, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
sqlite3ExprAssignVarNumber(pParse, yygotominor.yy346.pExpr);
}
spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
}
#line 3044 "parse.c"
break;
case 193: /* expr ::= expr COLLATE ID|STRING */
#line 874 "parse.y"
{
yygotominor.yy346.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy346.pExpr, &yymsp[0].minor.yy0, 1);
yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart;
yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
}
#line 3053 "parse.c"
break;
case 194: /* expr ::= CAST LP expr AS typetoken RP */
#line 880 "parse.y"
{
yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy346.pExpr, 0, &yymsp[-1].minor.yy0);
spanSet(&yygotominor.yy346,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
}
#line 3061 "parse.c"
break;
case 195: /* expr ::= ID|INDEXED LP distinct exprlist RP */
#line 885 "parse.y"
{
if( yymsp[-1].minor.yy14 && yymsp[-1].minor.yy14->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
}
yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy14, &yymsp[-4].minor.yy0);
spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
if( yymsp[-2].minor.yy381 && yygotominor.yy346.pExpr ){
yygotominor.yy346.pExpr->flags |= EP_Distinct;
}
}
#line 3075 "parse.c"
break;
case 196: /* expr ::= ID|INDEXED LP STAR RP */
#line 895 "parse.y"
{
yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
spanSet(&yygotominor.yy346,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
}
#line 3083 "parse.c"
break;
case 197: /* term ::= CTIME_KW */
#line 899 "parse.y"
{
yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0);
spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
}
#line 3091 "parse.c"
break;
case 198: /* expr ::= expr AND expr */
case 199: /* expr ::= expr OR expr */ yytestcase(yyruleno==199);
case 200: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==200);
case 201: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==201);
case 202: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==202);
case 203: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==203);
case 204: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==204);
case 205: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==205);
#line 921 "parse.y"
{spanBinaryExpr(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);}
#line 3103 "parse.c"
break;
case 206: /* likeop ::= LIKE_KW|MATCH */
#line 934 "parse.y"
{yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.bNot = 0;}
#line 3108 "parse.c"
break;
case 207: /* likeop ::= NOT LIKE_KW|MATCH */
#line 935 "parse.y"
{yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.bNot = 1;}
#line 3113 "parse.c"
break;
case 208: /* expr ::= expr likeop expr */
#line 936 "parse.y"
{
ExprList *pList;
pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy346.pExpr);
pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy346.pExpr);
yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy96.eOperator);
if( yymsp[-1].minor.yy96.bNot ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart;
yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
if( yygotominor.yy346.pExpr ) yygotominor.yy346.pExpr->flags |= EP_InfixFunc;
}
#line 3127 "parse.c"
break;
case 209: /* expr ::= expr likeop expr ESCAPE expr */
#line 946 "parse.y"
{
ExprList *pList;
pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy346.pExpr);
pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy96.eOperator);
if( yymsp[-3].minor.yy96.bNot ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
if( yygotominor.yy346.pExpr ) yygotominor.yy346.pExpr->flags |= EP_InfixFunc;
}
#line 3142 "parse.c"
break;
case 210: /* expr ::= expr ISNULL|NOTNULL */
#line 974 "parse.y"
{spanUnaryPostfix(&yygotominor.yy346,pParse,yymsp[0].major,&yymsp[-1].minor.yy346,&yymsp[0].minor.yy0);}
#line 3147 "parse.c"
break;
case 211: /* expr ::= expr NOT NULL */
#line 975 "parse.y"
{spanUnaryPostfix(&yygotominor.yy346,pParse,TK_NOTNULL,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy0);}
#line 3152 "parse.c"
break;
case 212: /* expr ::= expr IS expr */
#line 996 "parse.y"
{
spanBinaryExpr(&yygotominor.yy346,pParse,TK_IS,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);
binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_ISNULL);
}
#line 3160 "parse.c"
break;
case 213: /* expr ::= expr IS NOT expr */
#line 1000 "parse.y"
{
spanBinaryExpr(&yygotominor.yy346,pParse,TK_ISNOT,&yymsp[-3].minor.yy346,&yymsp[0].minor.yy346);
binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_NOTNULL);
}
#line 3168 "parse.c"
break;
case 214: /* expr ::= NOT expr */
case 215: /* expr ::= BITNOT expr */ yytestcase(yyruleno==215);
#line 1023 "parse.y"
{spanUnaryPrefix(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
#line 3174 "parse.c"
break;
case 216: /* expr ::= MINUS expr */
#line 1026 "parse.y"
{spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UMINUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
#line 3179 "parse.c"
break;
case 217: /* expr ::= PLUS expr */
#line 1028 "parse.y"
{spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UPLUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
#line 3184 "parse.c"
break;
case 220: /* expr ::= expr between_op expr AND expr */
#line 1033 "parse.y"
{
ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy346.pExpr, 0, 0);
if( yygotominor.yy346.pExpr ){
yygotominor.yy346.pExpr->x.pList = pList;
}else{
sqlite3ExprListDelete(pParse->db, pList);
}
if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
}
#line 3201 "parse.c"
break;
case 223: /* expr ::= expr in_op LP exprlist RP */
#line 1050 "parse.y"
{
if( yymsp[-1].minor.yy14==0 ){
/* Expressions of the form
**
** expr1 IN ()
** expr1 NOT IN ()
**
** simplify to constants 0 (false) and 1 (true), respectively,
** regardless of the value of expr1.
*/
yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy328]);
sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy346.pExpr);
}else if( yymsp[-1].minor.yy14->nExpr==1 ){
/* Expressions of the form:
**
** expr1 IN (?1)
** expr1 NOT IN (?2)
**
** with exactly one value on the RHS can be simplified to something
** like this:
**
** expr1 == ?1
** expr1 <> ?2
**
** But, the RHS of the == or <> is marked with the EP_Generic flag
** so that it may not contribute to the computation of comparison
** affinity or the collating sequence to use for comparison. Otherwise,
** the semantics would be subtly different from IN or NOT IN.
*/
Expr *pRHS = yymsp[-1].minor.yy14->a[0].pExpr;
yymsp[-1].minor.yy14->a[0].pExpr = 0;
sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
/* pRHS cannot be NULL because a malloc error would have been detected
** before now and control would have never reached this point */
if( ALWAYS(pRHS) ){
pRHS->flags &= ~EP_Collate;
pRHS->flags |= EP_Generic;
}
yygotominor.yy346.pExpr = sqlite3PExpr(pParse, yymsp[-3].minor.yy328 ? TK_NE : TK_EQ, yymsp[-4].minor.yy346.pExpr, pRHS, 0);
}else{
yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
if( yygotominor.yy346.pExpr ){
yygotominor.yy346.pExpr->x.pList = yymsp[-1].minor.yy14;
sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy346.pExpr);
}else{
sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
}
if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
}
yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
}
#line 3257 "parse.c"
break;
case 224: /* expr ::= LP select RP */
#line 1102 "parse.y"
{
yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
if( yygotominor.yy346.pExpr ){
yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect|EP_Subquery);
sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy346.pExpr);
}else{
sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
}
yygotominor.yy346.zStart = yymsp[-2].minor.yy0.z;
yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
}
#line 3273 "parse.c"
break;
case 225: /* expr ::= expr in_op LP select RP */
#line 1114 "parse.y"
{
yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
if( yygotominor.yy346.pExpr ){
yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect|EP_Subquery);
sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy346.pExpr);
}else{
sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
}
if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
}
#line 3290 "parse.c"
break;
case 226: /* expr ::= expr in_op nm dbnm */
#line 1127 "parse.y"
{
SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy346.pExpr, 0, 0);
if( yygotominor.yy346.pExpr ){
yygotominor.yy346.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect|EP_Subquery);
sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy346.pExpr);
}else{
sqlite3SrcListDelete(pParse->db, pSrc);
}
if( yymsp[-2].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
yygotominor.yy346.zStart = yymsp[-3].minor.yy346.zStart;
yygotominor.yy346.zEnd = yymsp[0].minor.yy0.z ? &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] : &yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n];
}
#line 3308 "parse.c"
break;
case 227: /* expr ::= EXISTS LP select RP */
#line 1141 "parse.y"
{
Expr *p = yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
if( p ){
p->x.pSelect = yymsp[-1].minor.yy3;
ExprSetProperty(p, EP_xIsSelect|EP_Subquery);
sqlite3ExprSetHeightAndFlags(pParse, p);
}else{
sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
}
yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
}
#line 3324 "parse.c"
break;
case 228: /* expr ::= CASE case_operand case_exprlist case_else END */
#line 1156 "parse.y"
{
yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy132, 0, 0);
if( yygotominor.yy346.pExpr ){
yygotominor.yy346.pExpr->x.pList = yymsp[-1].minor.yy132 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[-1].minor.yy132) : yymsp[-2].minor.yy14;
sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy346.pExpr);
}else{
sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy14);
sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy132);
}
yygotominor.yy346.zStart = yymsp[-4].minor.yy0.z;
yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
}
#line 3340 "parse.c"
break;
case 229: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
#line 1170 "parse.y"
{
yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, yymsp[-2].minor.yy346.pExpr);
yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
}
#line 3348 "parse.c"
break;
case 230: /* case_exprlist ::= WHEN expr THEN expr */
#line 1174 "parse.y"
{
yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
}
#line 3356 "parse.c"
break;
case 237: /* nexprlist ::= nexprlist COMMA expr */
#line 1195 "parse.y"
{yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[0].minor.yy346.pExpr);}
#line 3361 "parse.c"
break;
case 238: /* nexprlist ::= expr */
#line 1197 "parse.y"
{yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy346.pExpr);}
#line 3366 "parse.c"
break;
case 239: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP where_opt */
#line 1203 "parse.y"
{
sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy14, yymsp[-10].minor.yy328,
&yymsp[-11].minor.yy0, yymsp[0].minor.yy132, SQLITE_SO_ASC, yymsp[-8].minor.yy328);
}
#line 3375 "parse.c"
break;
case 240: /* uniqueflag ::= UNIQUE */
case 291: /* raisetype ::= ABORT */ yytestcase(yyruleno==291);
#line 1210 "parse.y"
{yygotominor.yy328 = OE_Abort;}
#line 3381 "parse.c"
break;
case 241: /* uniqueflag ::= */
#line 1211 "parse.y"
{yygotominor.yy328 = OE_None;}
#line 3386 "parse.c"
break;
case 244: /* idxlist ::= idxlist COMMA nm collate sortorder */
#line 1220 "parse.y"
{
Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0, 1);
yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, p);
sqlite3ExprListSetName(pParse,yygotominor.yy14,&yymsp[-2].minor.yy0,1);
sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
}
#line 3397 "parse.c"
break;
case 245: /* idxlist ::= nm collate sortorder */
#line 1227 "parse.y"
{
Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0, 1);
yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, p);
sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
}
#line 3408 "parse.c"
break;
case 246: /* collate ::= */
#line 1236 "parse.y"
{yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
#line 3413 "parse.c"
break;
case 248: /* cmd ::= DROP INDEX ifexists fullname */
#line 1242 "parse.y"
{sqlite3DropIndex(pParse, yymsp[0].minor.yy65, yymsp[-1].minor.yy328);}
#line 3418 "parse.c"
break;
case 249: /* cmd ::= VACUUM */
case 250: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==250);
#line 1248 "parse.y"
{sqlite3Vacuum(pParse);}
#line 3424 "parse.c"
break;
case 251: /* cmd ::= PRAGMA nm dbnm */
#line 1256 "parse.y"
{sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
#line 3429 "parse.c"
break;
case 252: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
#line 1257 "parse.y"
{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
#line 3434 "parse.c"
break;
case 253: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
#line 1258 "parse.y"
{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
#line 3439 "parse.c"
break;
case 254: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
#line 1260 "parse.y"
{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
#line 3444 "parse.c"
break;
case 255: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
#line 1262 "parse.y"
{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
#line 3449 "parse.c"
break;
case 264: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
#line 1278 "parse.y"
{
Token all;
all.z = yymsp[-3].minor.yy0.z;
all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy473, &all);
}
#line 3459 "parse.c"
break;
case 265: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
#line 1287 "parse.y"
{
sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy328, yymsp[-4].minor.yy378.a, yymsp[-4].minor.yy378.b, yymsp[-2].minor.yy65, yymsp[0].minor.yy132, yymsp[-10].minor.yy328, yymsp[-8].minor.yy328);
yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
}
#line 3467 "parse.c"
break;
case 266: /* trigger_time ::= BEFORE */
case 269: /* trigger_time ::= */ yytestcase(yyruleno==269);
#line 1293 "parse.y"
{ yygotominor.yy328 = TK_BEFORE; }
#line 3473 "parse.c"
break;
case 267: /* trigger_time ::= AFTER */
#line 1294 "parse.y"
{ yygotominor.yy328 = TK_AFTER; }
#line 3478 "parse.c"
break;
case 268: /* trigger_time ::= INSTEAD OF */
#line 1295 "parse.y"
{ yygotominor.yy328 = TK_INSTEAD;}
#line 3483 "parse.c"
break;
case 270: /* trigger_event ::= DELETE|INSERT */
case 271: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==271);
#line 1300 "parse.y"
{yygotominor.yy378.a = yymsp[0].major; yygotominor.yy378.b = 0;}
#line 3489 "parse.c"
break;
case 272: /* trigger_event ::= UPDATE OF idlist */
#line 1302 "parse.y"
{yygotominor.yy378.a = TK_UPDATE; yygotominor.yy378.b = yymsp[0].minor.yy408;}
#line 3494 "parse.c"
break;
case 275: /* when_clause ::= */
case 296: /* key_opt ::= */ yytestcase(yyruleno==296);
#line 1309 "parse.y"
{ yygotominor.yy132 = 0; }
#line 3500 "parse.c"
break;
case 276: /* when_clause ::= WHEN expr */
case 297: /* key_opt ::= KEY expr */ yytestcase(yyruleno==297);
#line 1310 "parse.y"
{ yygotominor.yy132 = yymsp[0].minor.yy346.pExpr; }
#line 3506 "parse.c"
break;
case 277: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
#line 1314 "parse.y"
{
assert( yymsp[-2].minor.yy473!=0 );
yymsp[-2].minor.yy473->pLast->pNext = yymsp[-1].minor.yy473;
yymsp[-2].minor.yy473->pLast = yymsp[-1].minor.yy473;
yygotominor.yy473 = yymsp[-2].minor.yy473;
}
#line 3516 "parse.c"
break;
case 278: /* trigger_cmd_list ::= trigger_cmd SEMI */
#line 1320 "parse.y"
{
assert( yymsp[-1].minor.yy473!=0 );
yymsp[-1].minor.yy473->pLast = yymsp[-1].minor.yy473;
yygotominor.yy473 = yymsp[-1].minor.yy473;
}
#line 3525 "parse.c"
break;
case 280: /* trnm ::= nm DOT nm */
#line 1332 "parse.y"
{
yygotominor.yy0 = yymsp[0].minor.yy0;
sqlite3ErrorMsg(pParse,
"qualified table names are not allowed on INSERT, UPDATE, and DELETE "
"statements within triggers");
}
#line 3535 "parse.c"
break;
case 282: /* tridxby ::= INDEXED BY nm */
#line 1344 "parse.y"
{
sqlite3ErrorMsg(pParse,
"the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
"within triggers");
}
#line 3544 "parse.c"
break;
case 283: /* tridxby ::= NOT INDEXED */
#line 1349 "parse.y"
{
sqlite3ErrorMsg(pParse,
"the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
"within triggers");
}
#line 3553 "parse.c"
break;
case 284: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
#line 1362 "parse.y"
{ yygotominor.yy473 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy14, yymsp[0].minor.yy132, yymsp[-5].minor.yy186); }
#line 3558 "parse.c"
break;
case 285: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
#line 1366 "parse.y"
{yygotominor.yy473 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy408, yymsp[0].minor.yy3, yymsp[-4].minor.yy186);}
#line 3563 "parse.c"
break;
case 286: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
#line 1370 "parse.y"
{yygotominor.yy473 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy132);}
#line 3568 "parse.c"
break;
case 287: /* trigger_cmd ::= select */
#line 1373 "parse.y"
{yygotominor.yy473 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy3); }
#line 3573 "parse.c"
break;
case 288: /* expr ::= RAISE LP IGNORE RP */
#line 1376 "parse.y"
{
yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
if( yygotominor.yy346.pExpr ){
yygotominor.yy346.pExpr->affinity = OE_Ignore;
}
yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
}
#line 3585 "parse.c"
break;
case 289: /* expr ::= RAISE LP raisetype COMMA nm RP */
#line 1384 "parse.y"
{
yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
if( yygotominor.yy346.pExpr ) {
yygotominor.yy346.pExpr->affinity = (char)yymsp[-3].minor.yy328;
}
yygotominor.yy346.zStart = yymsp[-5].minor.yy0.z;
yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
}
#line 3597 "parse.c"
break;
case 290: /* raisetype ::= ROLLBACK */
#line 1395 "parse.y"
{yygotominor.yy328 = OE_Rollback;}
#line 3602 "parse.c"
break;
case 292: /* raisetype ::= FAIL */
#line 1397 "parse.y"
{yygotominor.yy328 = OE_Fail;}
#line 3607 "parse.c"
break;
case 293: /* cmd ::= DROP TRIGGER ifexists fullname */
#line 1402 "parse.y"
{
sqlite3DropTrigger(pParse,yymsp[0].minor.yy65,yymsp[-1].minor.yy328);
}
#line 3614 "parse.c"
break;
case 294: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
#line 1409 "parse.y"
{
sqlite3Attach(pParse, yymsp[-3].minor.yy346.pExpr, yymsp[-1].minor.yy346.pExpr, yymsp[0].minor.yy132);
}
#line 3621 "parse.c"
break;
case 295: /* cmd ::= DETACH database_kw_opt expr */
#line 1412 "parse.y"
{
sqlite3Detach(pParse, yymsp[0].minor.yy346.pExpr);
}
#line 3628 "parse.c"
break;
case 300: /* cmd ::= REINDEX */
#line 1427 "parse.y"
{sqlite3Reindex(pParse, 0, 0);}
#line 3633 "parse.c"
break;
case 301: /* cmd ::= REINDEX nm dbnm */
#line 1428 "parse.y"
{sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
#line 3638 "parse.c"
break;
case 302: /* cmd ::= ANALYZE */
#line 1433 "parse.y"
{sqlite3Analyze(pParse, 0, 0);}
#line 3643 "parse.c"
break;
case 303: /* cmd ::= ANALYZE nm dbnm */
#line 1434 "parse.y"
{sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
#line 3648 "parse.c"
break;
case 304: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
#line 1439 "parse.y"
{
sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy65,&yymsp[0].minor.yy0);
}
#line 3655 "parse.c"
break;
case 305: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
#line 1442 "parse.y"
{
sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
}
#line 3662 "parse.c"
break;
case 306: /* add_column_fullname ::= fullname */
#line 1445 "parse.y"
{
pParse->db->lookaside.bEnabled = 0;
sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy65);
}
#line 3670 "parse.c"
break;
case 309: /* cmd ::= create_vtab */
#line 1455 "parse.y"
{sqlite3VtabFinishParse(pParse,0);}
#line 3675 "parse.c"
break;
case 310: /* cmd ::= create_vtab LP vtabarglist RP */
#line 1456 "parse.y"
{sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
#line 3680 "parse.c"
break;
case 311: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
#line 1458 "parse.y"
{
sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy328);
}
#line 3687 "parse.c"
break;
case 314: /* vtabarg ::= */
#line 1463 "parse.y"
{sqlite3VtabArgInit(pParse);}
#line 3692 "parse.c"
break;
case 316: /* vtabargtoken ::= ANY */
case 317: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==317);
case 318: /* lp ::= LP */ yytestcase(yyruleno==318);
#line 1465 "parse.y"
{sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
#line 3699 "parse.c"
break;
case 322: /* with ::= */
#line 1480 "parse.y"
{yygotominor.yy59 = 0;}
#line 3704 "parse.c"
break;
case 323: /* with ::= WITH wqlist */
case 324: /* with ::= WITH RECURSIVE wqlist */ yytestcase(yyruleno==324);
#line 1482 "parse.y"
{ yygotominor.yy59 = yymsp[0].minor.yy59; }
#line 3710 "parse.c"
break;
case 325: /* wqlist ::= nm idxlist_opt AS LP select RP */
#line 1485 "parse.y"
{
yygotominor.yy59 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy14, yymsp[-1].minor.yy3);
}
#line 3717 "parse.c"
break;
case 326: /* wqlist ::= wqlist COMMA nm idxlist_opt AS LP select RP */
#line 1488 "parse.y"
{
yygotominor.yy59 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy59, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy14, yymsp[-1].minor.yy3);
}
#line 3724 "parse.c"
break;
default:
/* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
/* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
/* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
/* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
/* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
/* (10) trans_opt ::= */ yytestcase(yyruleno==10);
/* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
/* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
/* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
/* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
/* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
/* (36) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==36);
/* (37) columnlist ::= column */ yytestcase(yyruleno==37);
/* (43) type ::= */ yytestcase(yyruleno==43);
/* (50) signed ::= plus_num */ yytestcase(yyruleno==50);
/* (51) signed ::= minus_num */ yytestcase(yyruleno==51);
/* (52) carglist ::= carglist ccons */ yytestcase(yyruleno==52);
/* (53) carglist ::= */ yytestcase(yyruleno==53);
/* (60) ccons ::= NULL onconf */ yytestcase(yyruleno==60);
/* (88) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==88);
/* (89) conslist ::= tcons */ yytestcase(yyruleno==89);
/* (91) tconscomma ::= */ yytestcase(yyruleno==91);
/* (273) foreach_clause ::= */ yytestcase(yyruleno==273);
/* (274) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==274);
/* (281) tridxby ::= */ yytestcase(yyruleno==281);
/* (298) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==298);
/* (299) database_kw_opt ::= */ yytestcase(yyruleno==299);
/* (307) kwcolumn_opt ::= */ yytestcase(yyruleno==307);
/* (308) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==308);
/* (312) vtabarglist ::= vtabarg */ yytestcase(yyruleno==312);
/* (313) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==313);
/* (315) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==315);
/* (319) anylist ::= */ yytestcase(yyruleno==319);
/* (320) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==320);
/* (321) anylist ::= anylist ANY */ yytestcase(yyruleno==321);
break;
};
assert( yyruleno>=0 && yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
yygoto = yyRuleInfo[yyruleno].lhs;
yysize = yyRuleInfo[yyruleno].nrhs;
yypParser->yyidx -= yysize;
yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
if( yyact < YYNSTATE ){
#ifdef NDEBUG
/* If we are not debugging and the reduce action popped at least
** one element off the stack, then we can push the new element back
** onto the stack here, and skip the stack overflow test in yy_shift().
** That gives a significant speed improvement. */
if( yysize ){
yypParser->yyidx++;
yymsp -= yysize-1;
yymsp->stateno = (YYACTIONTYPE)yyact;
yymsp->major = (YYCODETYPE)yygoto;
yymsp->minor = yygotominor;
}else
#endif
{
yy_shift(yypParser,yyact,yygoto,&yygotominor);
}
}else{
assert( yyact == YYNSTATE + YYNRULE + 1 );
yy_accept(yypParser);
}
}
/*
** The following code executes when the parse fails
*/
#ifndef YYNOERRORRECOVERY
static void yy_parse_failed(
yyParser *yypParser /* The parser */
){
sqlite3ParserARG_FETCH;
#ifndef NDEBUG
if( yyTraceFILE ){
fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
}
#endif
while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
/* Here code is inserted which will be executed whenever the
** parser fails */
sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
}
#endif /* YYNOERRORRECOVERY */
/*
** The following code executes when a syntax error first occurs.
*/
static void yy_syntax_error(
yyParser *yypParser, /* The parser */
int yymajor, /* The major type of the error token */
YYMINORTYPE yyminor /* The minor type of the error token */
){
sqlite3ParserARG_FETCH;
#define TOKEN (yyminor.yy0)
#line 32 "parse.y"
UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */
assert( TOKEN.z[0] ); /* The tokenizer always gives us a token */
sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
#line 3827 "parse.c"
sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
}
/*
** The following is executed when the parser accepts
*/
static void yy_accept(
yyParser *yypParser /* The parser */
){
sqlite3ParserARG_FETCH;
#ifndef NDEBUG
if( yyTraceFILE ){
fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
}
#endif
while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
/* Here code is inserted which will be executed whenever the
** parser accepts */
sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
}
/* The main parser program.
** The first argument is a pointer to a structure obtained from
** "sqlite3ParserAlloc" which describes the current state of the parser.
** The second argument is the major token number. The third is
** the minor token. The fourth optional argument is whatever the
** user wants (and specified in the grammar) and is available for
** use by the action routines.
**
** Inputs:
** <ul>
** <li> A pointer to the parser (an opaque structure.)
** <li> The major token number.
** <li> The minor token number.
** <li> An option argument of a grammar-specified type.
** </ul>
**
** Outputs:
** None.
*/
void sqlite3Parser(
void *yyp, /* The parser */
int yymajor, /* The major token code number */
sqlite3ParserTOKENTYPE yyminor /* The value for the token */
sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */
){
YYMINORTYPE yyminorunion;
int yyact; /* The parser action. */
#if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
int yyendofinput; /* True if we are at the end of input */
#endif
#ifdef YYERRORSYMBOL
int yyerrorhit = 0; /* True if yymajor has invoked an error */
#endif
yyParser *yypParser; /* The parser */
/* (re)initialize the parser, if necessary */
yypParser = (yyParser*)yyp;
if( yypParser->yyidx<0 ){
#if YYSTACKDEPTH<=0
if( yypParser->yystksz <=0 ){
/*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
yyminorunion = yyzerominor;
yyStackOverflow(yypParser, &yyminorunion);
return;
}
#endif
yypParser->yyidx = 0;
yypParser->yyerrcnt = -1;
yypParser->yystack[0].stateno = 0;
yypParser->yystack[0].major = 0;
}
yyminorunion.yy0 = yyminor;
#if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
yyendofinput = (yymajor==0);
#endif
sqlite3ParserARG_STORE;
#ifndef NDEBUG
if( yyTraceFILE ){
fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
}
#endif
do{
yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
if( yyact<YYNSTATE ){
yy_shift(yypParser,yyact,yymajor,&yyminorunion);
yypParser->yyerrcnt--;
yymajor = YYNOCODE;
}else if( yyact < YYNSTATE + YYNRULE ){
yy_reduce(yypParser,yyact-YYNSTATE);
}else{
assert( yyact == YY_ERROR_ACTION );
#ifdef YYERRORSYMBOL
int yymx;
#endif
#ifndef NDEBUG
if( yyTraceFILE ){
fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
}
#endif
#ifdef YYERRORSYMBOL
/* A syntax error has occurred.
** The response to an error depends upon whether or not the
** grammar defines an error token "ERROR".
**
** This is what we do if the grammar does define ERROR:
**
** * Call the %syntax_error function.
**
** * Begin popping the stack until we enter a state where
** it is legal to shift the error symbol, then shift
** the error symbol.
**
** * Set the error count to three.
**
** * Begin accepting and shifting new tokens. No new error
** processing will occur until three tokens have been
** shifted successfully.
**
*/
if( yypParser->yyerrcnt<0 ){
yy_syntax_error(yypParser,yymajor,yyminorunion);
}
yymx = yypParser->yystack[yypParser->yyidx].major;
if( yymx==YYERRORSYMBOL || yyerrorhit ){
#ifndef NDEBUG
if( yyTraceFILE ){
fprintf(yyTraceFILE,"%sDiscard input token %s\n",
yyTracePrompt,yyTokenName[yymajor]);
}
#endif
yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
yymajor = YYNOCODE;
}else{
while(
yypParser->yyidx >= 0 &&
yymx != YYERRORSYMBOL &&
(yyact = yy_find_reduce_action(
yypParser->yystack[yypParser->yyidx].stateno,
YYERRORSYMBOL)) >= YYNSTATE
){
yy_pop_parser_stack(yypParser);
}
if( yypParser->yyidx < 0 || yymajor==0 ){
yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
yy_parse_failed(yypParser);
yymajor = YYNOCODE;
}else if( yymx!=YYERRORSYMBOL ){
YYMINORTYPE u2;
u2.YYERRSYMDT = 0;
yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
}
}
yypParser->yyerrcnt = 3;
yyerrorhit = 1;
#elif defined(YYNOERRORRECOVERY)
/* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
** do any kind of error recovery. Instead, simply invoke the syntax
** error routine and continue going as if nothing had happened.
**
** Applications can set this macro (for example inside %include) if
** they intend to abandon the parse upon the first syntax error seen.
*/
yy_syntax_error(yypParser,yymajor,yyminorunion);
yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
yymajor = YYNOCODE;
#else /* YYERRORSYMBOL is not defined */
/* This is what we do if the grammar does not define ERROR:
**
** * Report an error message, and throw away the input token.
**
** * If the input token is $, then fail the parse.
**
** As before, subsequent error messages are suppressed until
** three input tokens have been successfully shifted.
*/
if( yypParser->yyerrcnt<=0 ){
yy_syntax_error(yypParser,yymajor,yyminorunion);
}
yypParser->yyerrcnt = 3;
yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
if( yyendofinput ){
yy_parse_failed(yypParser);
}
yymajor = YYNOCODE;
#endif
}
}while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
return;
}
| 39.143532 | 252 | 0.566597 | [
"object"
] |
afa4970386579e2c95d48bea1e3bf846049b962c | 17,400 | c | C | kernel/msm-4.14/drivers/gpu/drm/msm/dsi-staging/dsi_phy_hw_v4_0.c | clovadevice/clockplus2 | c347c3e1bf20dbb93ab533c58c2ce11367aa80cd | [
"Apache-2.0"
] | null | null | null | kernel/msm-4.14/drivers/gpu/drm/msm/dsi-staging/dsi_phy_hw_v4_0.c | clovadevice/clockplus2 | c347c3e1bf20dbb93ab533c58c2ce11367aa80cd | [
"Apache-2.0"
] | null | null | null | kernel/msm-4.14/drivers/gpu/drm/msm/dsi-staging/dsi_phy_hw_v4_0.c | clovadevice/clockplus2 | c347c3e1bf20dbb93ab533c58c2ce11367aa80cd | [
"Apache-2.0"
] | 1 | 2021-06-29T01:29:23.000Z | 2021-06-29T01:29:23.000Z | /*
* Copyright (c) 2016-2019, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* 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.
*/
#define pr_fmt(fmt) "dsi-phy-hw-v4: %s:" fmt, __func__
#include <linux/math64.h>
#include <linux/delay.h>
#include <linux/iopoll.h>
#include "dsi_hw.h"
#include "dsi_phy_hw.h"
#include "dsi_catalog.h"
#define DSIPHY_CMN_REVISION_ID0 0x000
#define DSIPHY_CMN_REVISION_ID1 0x004
#define DSIPHY_CMN_REVISION_ID2 0x008
#define DSIPHY_CMN_REVISION_ID3 0x00C
#define DSIPHY_CMN_CLK_CFG0 0x010
#define DSIPHY_CMN_CLK_CFG1 0x014
#define DSIPHY_CMN_GLBL_CTRL 0x018
#define DSIPHY_CMN_RBUF_CTRL 0x01C
#define DSIPHY_CMN_VREG_CTRL_0 0x020
#define DSIPHY_CMN_CTRL_0 0x024
#define DSIPHY_CMN_CTRL_1 0x028
#define DSIPHY_CMN_CTRL_2 0x02C
#define DSIPHY_CMN_CTRL_3 0x030
#define DSIPHY_CMN_LANE_CFG0 0x034
#define DSIPHY_CMN_LANE_CFG1 0x038
#define DSIPHY_CMN_PLL_CNTRL 0x03C
#define DSIPHY_CMN_DPHY_SOT 0x040
#define DSIPHY_CMN_LANE_CTRL0 0x0A0
#define DSIPHY_CMN_LANE_CTRL1 0x0A4
#define DSIPHY_CMN_LANE_CTRL2 0x0A8
#define DSIPHY_CMN_LANE_CTRL3 0x0AC
#define DSIPHY_CMN_LANE_CTRL4 0x0B0
#define DSIPHY_CMN_TIMING_CTRL_0 0x0B4
#define DSIPHY_CMN_TIMING_CTRL_1 0x0B8
#define DSIPHY_CMN_TIMING_CTRL_2 0x0Bc
#define DSIPHY_CMN_TIMING_CTRL_3 0x0C0
#define DSIPHY_CMN_TIMING_CTRL_4 0x0C4
#define DSIPHY_CMN_TIMING_CTRL_5 0x0C8
#define DSIPHY_CMN_TIMING_CTRL_6 0x0CC
#define DSIPHY_CMN_TIMING_CTRL_7 0x0D0
#define DSIPHY_CMN_TIMING_CTRL_8 0x0D4
#define DSIPHY_CMN_TIMING_CTRL_9 0x0D8
#define DSIPHY_CMN_TIMING_CTRL_10 0x0DC
#define DSIPHY_CMN_TIMING_CTRL_11 0x0E0
#define DSIPHY_CMN_TIMING_CTRL_12 0x0E4
#define DSIPHY_CMN_TIMING_CTRL_13 0x0E8
#define DSIPHY_CMN_GLBL_HSTX_STR_CTRL_0 0x0EC
#define DSIPHY_CMN_GLBL_HSTX_STR_CTRL_1 0x0F0
#define DSIPHY_CMN_GLBL_RESCODE_OFFSET_TOP_CTRL 0x0F4
#define DSIPHY_CMN_GLBL_RESCODE_OFFSET_BOT_CTRL 0x0F8
#define DSIPHY_CMN_GLBL_RESCODE_OFFSET_MID_CTRL 0x0FC
#define DSIPHY_CMN_GLBL_LPTX_STR_CTRL 0x100
#define DSIPHY_CMN_GLBL_PEMPH_CTRL_0 0x104
#define DSIPHY_CMN_GLBL_PEMPH_CTRL_1 0x108
#define DSIPHY_CMN_GLBL_STR_SWI_CAL_SEL_CTRL 0x10C
#define DSIPHY_CMN_VREG_CTRL_1 0x110
#define DSIPHY_CMN_CTRL_4 0x114
#define DSIPHY_CMN_PHY_STATUS 0x140
#define DSIPHY_CMN_LANE_STATUS0 0x148
#define DSIPHY_CMN_LANE_STATUS1 0x14C
/* n = 0..3 for data lanes and n = 4 for clock lane */
#define DSIPHY_LNX_CFG0(n) (0x200 + (0x80 * (n)))
#define DSIPHY_LNX_CFG1(n) (0x204 + (0x80 * (n)))
#define DSIPHY_LNX_CFG2(n) (0x208 + (0x80 * (n)))
#define DSIPHY_LNX_TEST_DATAPATH(n) (0x20C + (0x80 * (n)))
#define DSIPHY_LNX_PIN_SWAP(n) (0x210 + (0x80 * (n)))
#define DSIPHY_LNX_LPRX_CTRL(n) (0x214 + (0x80 * (n)))
#define DSIPHY_LNX_TX_DCTRL(n) (0x218 + (0x80 * (n)))
static int dsi_phy_hw_v4_0_is_pll_on(struct dsi_phy_hw *phy)
{
u32 data = 0;
data = DSI_R32(phy, DSIPHY_CMN_PLL_CNTRL);
mb(); /*make sure read happened */
return (data & BIT(0));
}
static void dsi_phy_hw_v4_0_config_lpcdrx(struct dsi_phy_hw *phy,
struct dsi_phy_cfg *cfg, bool enable)
{
int phy_lane_0 = dsi_phy_conv_logical_to_phy_lane(&cfg->lane_map,
DSI_LOGICAL_LANE_0);
/*
* LPRX and CDRX need to enabled only for physical data lane
* corresponding to the logical data lane 0
*/
if (enable)
DSI_W32(phy, DSIPHY_LNX_LPRX_CTRL(phy_lane_0),
cfg->strength.lane[phy_lane_0][1]);
else
DSI_W32(phy, DSIPHY_LNX_LPRX_CTRL(phy_lane_0), 0);
}
static void dsi_phy_hw_v4_0_lane_swap_config(struct dsi_phy_hw *phy,
struct dsi_lane_map *lane_map)
{
DSI_W32(phy, DSIPHY_CMN_LANE_CFG0,
(lane_map->lane_map_v2[DSI_LOGICAL_LANE_0] |
(lane_map->lane_map_v2[DSI_LOGICAL_LANE_1] << 4)));
DSI_W32(phy, DSIPHY_CMN_LANE_CFG1,
(lane_map->lane_map_v2[DSI_LOGICAL_LANE_2] |
(lane_map->lane_map_v2[DSI_LOGICAL_LANE_3] << 4)));
}
static void dsi_phy_hw_v4_0_lane_settings(struct dsi_phy_hw *phy,
struct dsi_phy_cfg *cfg)
{
int i;
u8 tx_dctrl[] = {0x00, 0x00, 0x00, 0x04, 0x01};
/* Strength ctrl settings */
for (i = DSI_LOGICAL_LANE_0; i < DSI_LANE_MAX; i++) {
/*
* Disable LPRX and CDRX for all lanes. And later on, it will
* be only enabled for the physical data lane corresponding
* to the logical data lane 0
*/
DSI_W32(phy, DSIPHY_LNX_LPRX_CTRL(i), 0);
}
dsi_phy_hw_v4_0_config_lpcdrx(phy, cfg, true);
/* other settings */
for (i = DSI_LOGICAL_LANE_0; i < DSI_LANE_MAX; i++) {
DSI_W32(phy, DSIPHY_LNX_CFG0(i), cfg->lanecfg.lane[i][0]);
DSI_W32(phy, DSIPHY_LNX_CFG1(i), cfg->lanecfg.lane[i][1]);
DSI_W32(phy, DSIPHY_LNX_CFG2(i), cfg->lanecfg.lane[i][2]);
DSI_W32(phy, DSIPHY_LNX_TX_DCTRL(i), tx_dctrl[i]);
DSI_W32(phy, DSIPHY_LNX_PIN_SWAP(i),
(cfg->lane_pnswap >> i) & 0x1);
}
if (cfg->phy_type == DSI_PHY_TYPE_CPHY)
DSI_W32(phy, DSIPHY_LNX_TX_DCTRL(3), 0x02);
}
/**
* cphy_enable() - Enable CPHY hardware
* @phy: Pointer to DSI PHY hardware object.
* @cfg: Per lane configurations for timing, strength and lane
* configurations.
*/
static void dsi_phy_hw_cphy_enable(struct dsi_phy_hw *phy,
struct dsi_phy_cfg *cfg)
{
struct dsi_phy_per_lane_cfgs *timing = &cfg->timing;
u32 data;
/* For C-PHY, no low power settings for lower clk rate */
u32 vreg_ctrl_0 = 0x5A;
u32 glbl_str_swi_cal_sel_ctrl = 0x03;
u32 glbl_hstx_str_ctrl_0 = 0x66;
/* de-assert digital and pll power down */
data = BIT(6) | BIT(5);
DSI_W32(phy, DSIPHY_CMN_CTRL_0, data);
/* Assert PLL core reset */
DSI_W32(phy, DSIPHY_CMN_PLL_CNTRL, 0x00);
/* turn off resync FIFO */
DSI_W32(phy, DSIPHY_CMN_RBUF_CTRL, 0x00);
/* Configure PHY lane swap */
dsi_phy_hw_v4_0_lane_swap_config(phy, &cfg->lane_map);
DSI_W32(phy, DSIPHY_CMN_GLBL_CTRL, BIT(6));
/* Enable LDO */
DSI_W32(phy, DSIPHY_CMN_VREG_CTRL_0, vreg_ctrl_0);
DSI_W32(phy, DSIPHY_CMN_VREG_CTRL_1, 0x5c);
DSI_W32(phy, DSIPHY_CMN_GLBL_STR_SWI_CAL_SEL_CTRL,
glbl_str_swi_cal_sel_ctrl);
DSI_W32(phy, DSIPHY_CMN_GLBL_HSTX_STR_CTRL_0, glbl_hstx_str_ctrl_0);
DSI_W32(phy, DSIPHY_CMN_GLBL_PEMPH_CTRL_0, 0x00);
DSI_W32(phy, DSIPHY_CMN_GLBL_RESCODE_OFFSET_TOP_CTRL, 0x03);
DSI_W32(phy, DSIPHY_CMN_GLBL_RESCODE_OFFSET_BOT_CTRL, 0x3c);
DSI_W32(phy, DSIPHY_CMN_GLBL_LPTX_STR_CTRL, 0x55);
/* Remove power down from all blocks */
DSI_W32(phy, DSIPHY_CMN_CTRL_0, 0x7f);
DSI_W32(phy, DSIPHY_CMN_LANE_CTRL0, 0x17);
switch (cfg->pll_source) {
case DSI_PLL_SOURCE_STANDALONE:
case DSI_PLL_SOURCE_NATIVE:
data = 0x0; /* internal PLL */
break;
case DSI_PLL_SOURCE_NON_NATIVE:
data = 0x1; /* external PLL */
break;
default:
break;
}
DSI_W32(phy, DSIPHY_CMN_CLK_CFG1, (data << 2)); /* set PLL src */
/* DSI PHY timings */
DSI_W32(phy, DSIPHY_CMN_TIMING_CTRL_0, timing->lane_v4[0]);
DSI_W32(phy, DSIPHY_CMN_TIMING_CTRL_4, timing->lane_v4[4]);
DSI_W32(phy, DSIPHY_CMN_TIMING_CTRL_5, timing->lane_v4[5]);
DSI_W32(phy, DSIPHY_CMN_TIMING_CTRL_6, timing->lane_v4[6]);
DSI_W32(phy, DSIPHY_CMN_TIMING_CTRL_7, timing->lane_v4[7]);
DSI_W32(phy, DSIPHY_CMN_TIMING_CTRL_8, timing->lane_v4[8]);
DSI_W32(phy, DSIPHY_CMN_TIMING_CTRL_9, timing->lane_v4[9]);
DSI_W32(phy, DSIPHY_CMN_TIMING_CTRL_10, timing->lane_v4[10]);
DSI_W32(phy, DSIPHY_CMN_TIMING_CTRL_11, timing->lane_v4[11]);
/* DSI lane settings */
dsi_phy_hw_v4_0_lane_settings(phy, cfg);
pr_debug("[DSI_%d] C-Phy enabled ", phy->index);
}
/**
* dphy_enable() - Enable DPHY hardware
* @phy: Pointer to DSI PHY hardware object.
* @cfg: Per lane configurations for timing, strength and lane
* configurations.
*/
static void dsi_phy_hw_dphy_enable(struct dsi_phy_hw *phy,
struct dsi_phy_cfg *cfg)
{
struct dsi_phy_per_lane_cfgs *timing = &cfg->timing;
u32 data;
bool less_than_1500_mhz = false;
u32 vreg_ctrl_0 = 0;
u32 glbl_str_swi_cal_sel_ctrl = 0;
u32 glbl_hstx_str_ctrl_0 = 0;
/* Alter PHY configurations if data rate less than 1.5GHZ*/
if (cfg->bit_clk_rate_hz < 1500000000)
less_than_1500_mhz = true;
vreg_ctrl_0 = less_than_1500_mhz ? 0x5B : 0x59;
glbl_str_swi_cal_sel_ctrl = less_than_1500_mhz ? 0x03 : 0x00;
glbl_hstx_str_ctrl_0 = less_than_1500_mhz ? 0x66 : 0x88;
/* de-assert digital and pll power down */
data = BIT(6) | BIT(5);
DSI_W32(phy, DSIPHY_CMN_CTRL_0, data);
/* Assert PLL core reset */
DSI_W32(phy, DSIPHY_CMN_PLL_CNTRL, 0x00);
/* turn off resync FIFO */
DSI_W32(phy, DSIPHY_CMN_RBUF_CTRL, 0x00);
/* Configure PHY lane swap */
dsi_phy_hw_v4_0_lane_swap_config(phy, &cfg->lane_map);
/* Enable LDO */
DSI_W32(phy, DSIPHY_CMN_VREG_CTRL_0, vreg_ctrl_0);
DSI_W32(phy, DSIPHY_CMN_VREG_CTRL_1, 0x5c);
DSI_W32(phy, DSIPHY_CMN_CTRL_3, 0x00);
DSI_W32(phy, DSIPHY_CMN_GLBL_STR_SWI_CAL_SEL_CTRL,
glbl_str_swi_cal_sel_ctrl);
DSI_W32(phy, DSIPHY_CMN_GLBL_HSTX_STR_CTRL_0, glbl_hstx_str_ctrl_0);
DSI_W32(phy, DSIPHY_CMN_GLBL_PEMPH_CTRL_0, 0x00);
DSI_W32(phy, DSIPHY_CMN_GLBL_RESCODE_OFFSET_TOP_CTRL, 0x03);
DSI_W32(phy, DSIPHY_CMN_GLBL_RESCODE_OFFSET_BOT_CTRL, 0x3c);
DSI_W32(phy, DSIPHY_CMN_GLBL_LPTX_STR_CTRL, 0x55);
/* Remove power down from all blocks */
DSI_W32(phy, DSIPHY_CMN_CTRL_0, 0x7f);
DSI_W32(phy, DSIPHY_CMN_LANE_CTRL0, 0x1F);
/* Select full-rate mode */
DSI_W32(phy, DSIPHY_CMN_CTRL_2, 0x40);
switch (cfg->pll_source) {
case DSI_PLL_SOURCE_STANDALONE:
case DSI_PLL_SOURCE_NATIVE:
data = 0x0; /* internal PLL */
break;
case DSI_PLL_SOURCE_NON_NATIVE:
data = 0x1; /* external PLL */
break;
default:
break;
}
DSI_W32(phy, DSIPHY_CMN_CLK_CFG1, (data << 2)); /* set PLL src */
/* DSI PHY timings */
DSI_W32(phy, DSIPHY_CMN_TIMING_CTRL_0, timing->lane_v4[0]);
DSI_W32(phy, DSIPHY_CMN_TIMING_CTRL_1, timing->lane_v4[1]);
DSI_W32(phy, DSIPHY_CMN_TIMING_CTRL_2, timing->lane_v4[2]);
DSI_W32(phy, DSIPHY_CMN_TIMING_CTRL_3, timing->lane_v4[3]);
DSI_W32(phy, DSIPHY_CMN_TIMING_CTRL_4, timing->lane_v4[4]);
DSI_W32(phy, DSIPHY_CMN_TIMING_CTRL_5, timing->lane_v4[5]);
DSI_W32(phy, DSIPHY_CMN_TIMING_CTRL_6, timing->lane_v4[6]);
DSI_W32(phy, DSIPHY_CMN_TIMING_CTRL_7, timing->lane_v4[7]);
DSI_W32(phy, DSIPHY_CMN_TIMING_CTRL_8, timing->lane_v4[8]);
DSI_W32(phy, DSIPHY_CMN_TIMING_CTRL_9, timing->lane_v4[9]);
DSI_W32(phy, DSIPHY_CMN_TIMING_CTRL_10, timing->lane_v4[10]);
DSI_W32(phy, DSIPHY_CMN_TIMING_CTRL_11, timing->lane_v4[11]);
DSI_W32(phy, DSIPHY_CMN_TIMING_CTRL_12, timing->lane_v4[12]);
DSI_W32(phy, DSIPHY_CMN_TIMING_CTRL_13, timing->lane_v4[13]);
/* DSI lane settings */
dsi_phy_hw_v4_0_lane_settings(phy, cfg);
pr_debug("[DSI_%d] D-Phy enabled ", phy->index);
}
/**
* enable() - Enable PHY hardware
* @phy: Pointer to DSI PHY hardware object.
* @cfg: Per lane configurations for timing, strength and lane
* configurations.
*/
void dsi_phy_hw_v4_0_enable(struct dsi_phy_hw *phy,
struct dsi_phy_cfg *cfg)
{
int rc = 0;
u32 status;
u32 const delay_us = 5;
u32 const timeout_us = 1000;
if (dsi_phy_hw_v4_0_is_pll_on(phy))
pr_warn("PLL turned on before configuring PHY\n");
/* wait for REFGEN READY */
rc = readl_poll_timeout_atomic(phy->base + DSIPHY_CMN_PHY_STATUS,
status, (status & BIT(0)), delay_us, timeout_us);
if (rc) {
pr_err("Ref gen not ready. Aborting\n");
return;
}
if (cfg->phy_type == DSI_PHY_TYPE_CPHY)
dsi_phy_hw_cphy_enable(phy, cfg);
else /* Default PHY type is DPHY */
dsi_phy_hw_dphy_enable(phy, cfg);
}
/**
* disable() - Disable PHY hardware
* @phy: Pointer to DSI PHY hardware object.
*/
void dsi_phy_hw_v4_0_disable(struct dsi_phy_hw *phy,
struct dsi_phy_cfg *cfg)
{
u32 data = 0;
if (dsi_phy_hw_v4_0_is_pll_on(phy))
pr_warn("Turning OFF PHY while PLL is on\n");
dsi_phy_hw_v4_0_config_lpcdrx(phy, cfg, false);
data = DSI_R32(phy, DSIPHY_CMN_CTRL_0);
/* disable all lanes */
data &= ~0x1F;
DSI_W32(phy, DSIPHY_CMN_CTRL_0, data);
DSI_W32(phy, DSIPHY_CMN_LANE_CTRL0, 0);
/* Turn off all PHY blocks */
DSI_W32(phy, DSIPHY_CMN_CTRL_0, 0x00);
/* make sure phy is turned off */
wmb();
pr_debug("[DSI_%d]Phy disabled ", phy->index);
}
void dsi_phy_hw_v4_0_toggle_resync_fifo(struct dsi_phy_hw *phy)
{
DSI_W32(phy, DSIPHY_CMN_RBUF_CTRL, 0x00);
/* ensure that the FIFO is off */
wmb();
DSI_W32(phy, DSIPHY_CMN_RBUF_CTRL, 0x1);
/* ensure that the FIFO is toggled back on */
wmb();
}
void dsi_phy_hw_v4_0_reset_clk_en_sel(struct dsi_phy_hw *phy)
{
u32 data = 0;
/*Turning off CLK_EN_SEL after retime buffer sync */
data = DSI_R32(phy, DSIPHY_CMN_CLK_CFG1);
data &= ~BIT(4);
DSI_W32(phy, DSIPHY_CMN_CLK_CFG1, data);
/* ensure that clk_en_sel bit is turned off */
wmb();
}
int dsi_phy_hw_v4_0_wait_for_lane_idle(
struct dsi_phy_hw *phy, u32 lanes)
{
int rc = 0, val = 0;
u32 stop_state_mask = 0;
u32 const sleep_us = 10;
u32 const timeout_us = 100;
stop_state_mask = BIT(4); /* clock lane */
if (lanes & DSI_DATA_LANE_0)
stop_state_mask |= BIT(0);
if (lanes & DSI_DATA_LANE_1)
stop_state_mask |= BIT(1);
if (lanes & DSI_DATA_LANE_2)
stop_state_mask |= BIT(2);
if (lanes & DSI_DATA_LANE_3)
stop_state_mask |= BIT(3);
pr_debug("%s: polling for lanes to be in stop state, mask=0x%08x\n",
__func__, stop_state_mask);
rc = readl_poll_timeout(phy->base + DSIPHY_CMN_LANE_STATUS1, val,
((val & stop_state_mask) == stop_state_mask),
sleep_us, timeout_us);
if (rc) {
pr_err("%s: lanes not in stop state, LANE_STATUS=0x%08x\n",
__func__, val);
return rc;
}
return 0;
}
void dsi_phy_hw_v4_0_ulps_request(struct dsi_phy_hw *phy,
struct dsi_phy_cfg *cfg, u32 lanes)
{
u32 reg = 0;
if (lanes & DSI_CLOCK_LANE)
reg = BIT(4);
if (lanes & DSI_DATA_LANE_0)
reg |= BIT(0);
if (lanes & DSI_DATA_LANE_1)
reg |= BIT(1);
if (lanes & DSI_DATA_LANE_2)
reg |= BIT(2);
if (lanes & DSI_DATA_LANE_3)
reg |= BIT(3);
if (cfg->force_clk_lane_hs)
reg |= BIT(5) | BIT(6);
/*
* ULPS entry request. Wait for short time to make sure
* that the lanes enter ULPS. Recommended as per HPG.
*/
DSI_W32(phy, DSIPHY_CMN_LANE_CTRL1, reg);
usleep_range(100, 110);
/* disable LPRX and CDRX */
dsi_phy_hw_v4_0_config_lpcdrx(phy, cfg, false);
pr_debug("[DSI_PHY%d] ULPS requested for lanes 0x%x\n", phy->index,
lanes);
}
int dsi_phy_hw_v4_0_lane_reset(struct dsi_phy_hw *phy)
{
int ret = 0, loop = 10, u_dly = 200;
u32 ln_status = 0;
while ((ln_status != 0x1f) && loop) {
DSI_W32(phy, DSIPHY_CMN_LANE_CTRL3, 0x1f);
wmb(); /* ensure register is committed */
loop--;
udelay(u_dly);
ln_status = DSI_R32(phy, DSIPHY_CMN_LANE_STATUS1);
pr_debug("trial no: %d\n", loop);
}
if (!loop)
pr_debug("could not reset phy lanes\n");
DSI_W32(phy, DSIPHY_CMN_LANE_CTRL3, 0x0);
wmb(); /* ensure register is committed */
return ret;
}
void dsi_phy_hw_v4_0_ulps_exit(struct dsi_phy_hw *phy,
struct dsi_phy_cfg *cfg, u32 lanes)
{
u32 reg = 0;
if (lanes & DSI_CLOCK_LANE)
reg = BIT(4);
if (lanes & DSI_DATA_LANE_0)
reg |= BIT(0);
if (lanes & DSI_DATA_LANE_1)
reg |= BIT(1);
if (lanes & DSI_DATA_LANE_2)
reg |= BIT(2);
if (lanes & DSI_DATA_LANE_3)
reg |= BIT(3);
/* enable LPRX and CDRX */
dsi_phy_hw_v4_0_config_lpcdrx(phy, cfg, true);
/* ULPS exit request */
DSI_W32(phy, DSIPHY_CMN_LANE_CTRL2, reg);
usleep_range(1000, 1010);
/* Clear ULPS request flags on all lanes */
DSI_W32(phy, DSIPHY_CMN_LANE_CTRL1, 0);
/* Clear ULPS exit flags on all lanes */
DSI_W32(phy, DSIPHY_CMN_LANE_CTRL2, 0);
/*
* Sometimes when exiting ULPS, it is possible that some DSI
* lanes are not in the stop state which could lead to DSI
* commands not going through. To avoid this, force the lanes
* to be in stop state.
*/
DSI_W32(phy, DSIPHY_CMN_LANE_CTRL3, reg);
DSI_W32(phy, DSIPHY_CMN_LANE_CTRL3, 0);
usleep_range(100, 110);
if (cfg->force_clk_lane_hs) {
reg = BIT(5) | BIT(6);
DSI_W32(phy, DSIPHY_CMN_LANE_CTRL1, reg);
}
}
u32 dsi_phy_hw_v4_0_get_lanes_in_ulps(struct dsi_phy_hw *phy)
{
u32 lanes = 0;
lanes = DSI_R32(phy, DSIPHY_CMN_LANE_STATUS0);
pr_debug("[DSI_PHY%d] lanes in ulps = 0x%x\n", phy->index, lanes);
return lanes;
}
bool dsi_phy_hw_v4_0_is_lanes_in_ulps(u32 lanes, u32 ulps_lanes)
{
if (lanes & ulps_lanes)
return false;
return true;
}
int dsi_phy_hw_timing_val_v4_0(struct dsi_phy_per_lane_cfgs *timing_cfg,
u32 *timing_val, u32 size)
{
int i = 0;
if (size != DSI_PHY_TIMING_V4_SIZE) {
pr_err("Unexpected timing array size %d\n", size);
return -EINVAL;
}
for (i = 0; i < size; i++)
timing_cfg->lane_v4[i] = timing_val[i];
return 0;
}
void dsi_phy_hw_v4_0_set_continuous_clk(struct dsi_phy_hw *phy, bool enable)
{
u32 reg = 0;
reg = DSI_R32(phy, DSIPHY_CMN_LANE_CTRL1);
if (enable)
reg |= BIT(5) | BIT(6);
else
reg &= ~(BIT(5) | BIT(6));
DSI_W32(phy, DSIPHY_CMN_LANE_CTRL1, reg);
wmb(); /* make sure request is set */
}
| 29.948365 | 76 | 0.723046 | [
"object"
] |
afa657a95931be1bc7e8ecb56e79e87b6a041bc7 | 764 | h | C | Plugins/LevelGenPlugin/Source/LevelGenPluginRuntime/LevelGenSplineMeshActor.h | Deema35/LevelGen | 507171103bed2824bc71cb33dbac11aad7bae3b5 | [
"MIT"
] | 38 | 2018-04-17T17:10:59.000Z | 2022-01-11T22:00:13.000Z | Plugins/LevelGenPlugin/Source/LevelGenPluginRuntime/LevelGenSplineMeshActor.h | Deema35/LevelGen | 507171103bed2824bc71cb33dbac11aad7bae3b5 | [
"MIT"
] | 1 | 2020-06-06T08:01:18.000Z | 2020-06-07T05:40:15.000Z | Plugins/LevelGenPlugin/Source/LevelGenPluginRuntime/LevelGenSplineMeshActor.h | Deema35/LevelGen | 507171103bed2824bc71cb33dbac11aad7bae3b5 | [
"MIT"
] | 12 | 2018-07-27T19:32:35.000Z | 2022-01-11T22:00:14.000Z | // Copyright 2018 Pavlov Dmitriy
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include <vector>
#include "LevelGenSplineMeshActor.generated.h"
class USplineMeshComponent;
class UStaticMesh;
UCLASS()
class LEVELGENPLUGINRUNTIME_API ALevelGenSplineMeshActor : public AActor
{
GENERATED_BODY()
public:
ALevelGenSplineMeshActor();
UPROPERTY(VisibleAnywhere)
TArray<USplineMeshComponent*> SplineMeshComponents;
UPROPERTY(VisibleAnywhere)
UStaticMesh* Mesh;
USceneComponent* Root;
void AddPoints(const std::vector<FVector>& Coordinate);
void SetStaticMesh(UStaticMesh* _Mesh) { Mesh = _Mesh; }
void SetScale(FVector2D _Scale) { Scale = _Scale; }
private:
int CurrentLenghtSpline = 0;
FVector2D Scale = FVector2D(1,1);
}; | 20.105263 | 72 | 0.782723 | [
"mesh",
"vector"
] |
afacfe4a71d47cff24ab0e1612351d4d686ef7d8 | 576 | h | C | src/Units/MyWorker.h | bmnielsen/Stardust | 343e0c123f85e080e5d3a744d1cc47b3adfe9efd | [
"MIT"
] | 15 | 2020-10-01T07:04:33.000Z | 2022-03-20T12:41:25.000Z | src/Units/MyWorker.h | bmnielsen/Stardust | 343e0c123f85e080e5d3a744d1cc47b3adfe9efd | [
"MIT"
] | null | null | null | src/Units/MyWorker.h | bmnielsen/Stardust | 343e0c123f85e080e5d3a744d1cc47b3adfe9efd | [
"MIT"
] | null | null | null | #pragma once
#include "MyUnit.h"
class MyWorker : public MyUnitImpl
{
public:
explicit MyWorker(BWAPI::Unit unit);
protected:
void resetMoveData() override;
bool mineralWalk(const Choke *choke) override;
private:
BWAPI::Unit mineralWalkingPatch;
const BWEM::Area *mineralWalkingTargetArea;
BWAPI::Position mineralWalkingStartPosition;
void attackUnit(const Unit &target,
std::vector<std::pair<MyUnit, Unit>> &unitsAndTargets,
bool clusterAttacking,
int enemyAoeRadius) override;
};
| 23.04 | 74 | 0.671875 | [
"vector"
] |
afb12bbfca50ea446aa3cbc0005524a378933d26 | 1,582 | h | C | include/Location.h | jipolanco/HDF5mm | 684a7ebec4fefe60d813cdac71859e21e9092c39 | [
"MIT"
] | null | null | null | include/Location.h | jipolanco/HDF5mm | 684a7ebec4fefe60d813cdac71859e21e9092c39 | [
"MIT"
] | null | null | null | include/Location.h | jipolanco/HDF5mm | 684a7ebec4fefe60d813cdac71859e21e9092c39 | [
"MIT"
] | null | null | null | #pragma once
#include "IdComponent.h"
#if H5_VERS_MAJOR == 1 && H5_VERS_MINOR < 10
#include <cstring> // strlen
#endif
namespace HDF5 {
/// HDF5 location.
class Location : public IdComponent {
public:
/// Check if a link (can be a group) exists under the current location.
bool exists(const char *path) const {
#if H5_VERS_MAJOR == 1 && H5_VERS_MINOR < 10
// Return true if path == "/".
// This is consistent with the behaviour of H5Lexists starting from HDF5
// 1.10.0. H5Lexists would return 0 in previous releases.
// See <https://portal.hdfgroup.org/display/HDF5/H5L_EXISTS> for details.
if (std::strlen(path) == 1 && path[0] == '/') return true;
#endif
return H5Lexists(get_id(), path, H5P_DEFAULT) > 0;
}
bool exists(const std::string &path) const { return exists(path.c_str()); }
/// Check if a given path corresponds to a group.
/// If the path doesn't exist, return false.
bool is_group(const char *path) const {
if (!exists(path)) return false;
// Try to open it as a generic object and check its type.
hid_t obj_id = H5Oopen(get_id(), path, H5P_DEFAULT);
if (obj_id < 0) throw Exception("Location::is_group");
bool g = get_type(obj_id) == H5I_GROUP;
H5Oclose(obj_id);
return g;
}
bool is_group(const std::string &path) const {
return is_group(path.c_str());
}
protected:
/// Default constructor.
/// Generates an object with invalid id.
Location() = default;
/// Construct from existing location id.
Location(hid_t loc_id) : IdComponent(loc_id) {}
};
} // namespace HDF5
| 29.296296 | 77 | 0.668142 | [
"object"
] |
afb991bf00924116ec650b37fef98b2d069546c7 | 4,133 | h | C | Examples/include/Aspose.Pdf.Cpp/Tagged/LogicalStructure/ElementList.h | kashifiqb/Aspose.PDF-for-C | 13d49bba591c5704685820185741e64a462a5bdc | [
"MIT"
] | null | null | null | Examples/include/Aspose.Pdf.Cpp/Tagged/LogicalStructure/ElementList.h | kashifiqb/Aspose.PDF-for-C | 13d49bba591c5704685820185741e64a462a5bdc | [
"MIT"
] | null | null | null | Examples/include/Aspose.Pdf.Cpp/Tagged/LogicalStructure/ElementList.h | kashifiqb/Aspose.PDF-for-C | 13d49bba591c5704685820185741e64a462a5bdc | [
"MIT"
] | null | null | null | #pragma once
// Copyright (c) 2001-2019 Aspose Pty Ltd. All Rights Reserved.
#include <system/shared_ptr.h>
#include <system/object.h>
#include <system/collections/list.h>
#include <system/collections/ienumerator.h>
#include <system/collections/ienumerable.h>
#include <cstdint>
#include "aspose_pdf_api_defs.h"
namespace Aspose { namespace Pdf { namespace LogicalStructure { class StructureElement; } } }
namespace Aspose { namespace Pdf { namespace LogicalStructure { class Element; } } }
namespace Aspose { namespace Pdf { namespace Tagged { class TaggedContext; } } }
namespace Aspose {
namespace Pdf {
namespace LogicalStructure {
/// <summary>
/// Represents an ordered collection of elements.
/// </summary>
class ASPOSE_PDF_SHARED_API ElementList : public System::Collections::Generic::IEnumerable<System::SharedPtr<Aspose::Pdf::LogicalStructure::Element>>
{
typedef ElementList ThisType;
typedef System::Collections::Generic::IEnumerable<System::SharedPtr<Aspose::Pdf::LogicalStructure::Element>> BaseType;
typedef ::System::BaseTypesInfo<BaseType> ThisTypeBaseTypesInfo;
RTTI_INFO_DECL();
FRIEND_FUNCTION_System_MakeObject;
friend class Aspose::Pdf::LogicalStructure::StructureElement;
friend class Aspose::Pdf::LogicalStructure::Element;
friend class Aspose::Pdf::Tagged::TaggedContext;
public:
/// <summary>
/// Gets the number of elements in the ElementList.
/// </summary>
virtual int32_t get_Count() = 0;
/// <summary>
/// Retrieves a element at the given index.
/// </summary>
/// <param name="index">The index into the list of elements.</param>
/// <returns>The <see cref="T:/Aspose::Pdf::LogicalStructure::Element" /> with the specified index in the collection. If <paramref name="index" /> is greater than or equal to the number of elements in the list, this returns null.</returns>
virtual System::SharedPtr<Element> Item(int32_t index) = 0;
/// <summary>
/// Gets an element at the given index.
/// </summary>
/// <param name="index">The index into the list of elements.</param>
/// <returns>The <see cref="T:/Aspose::Pdf::LogicalStructure::Element" /> with the specified index in the collection. If index is greater than or equal to the number of elements in the list, this returns null.</returns>
virtual System::SharedPtr<Element> idx_get(int32_t index);
/// <summary>
/// Gets an enumerator that iterates through the collection of elements.
/// </summary>
/// <returns>An enumerator used to iterate through the collection of elements.</returns>
virtual System::SharedPtr<System::Collections::Generic::IEnumerator<System::SharedPtr<Element>>> GetEnumerator() = 0;
protected:
virtual void AddElement(System::SharedPtr<Element> element, bool updatePdfDictionary = true) = 0;
virtual void RemoveElement(System::SharedPtr<Element> element, bool updatePdfDictionary = true) = 0;
ElementList();
};
class ElementListImplementation : public Aspose::Pdf::LogicalStructure::ElementList
{
typedef ElementListImplementation ThisType;
typedef Aspose::Pdf::LogicalStructure::ElementList BaseType;
typedef ::System::BaseTypesInfo<BaseType> ThisTypeBaseTypesInfo;
RTTI_INFO_DECL();
public:
virtual int32_t get_Count();
ElementListImplementation(System::SharedPtr<Element> owner);
virtual System::SharedPtr<Element> Item(int32_t index);
virtual System::SharedPtr<System::Collections::Generic::IEnumerator<System::SharedPtr<Element>>> GetEnumerator();
virtual void AddElement(System::SharedPtr<Element> element, bool updatePdfDictionary = true);
virtual void RemoveElement(System::SharedPtr<Element> element, bool updatePdfDictionary = true);
protected:
System::Object::shared_members_type GetSharedMembers() override;
private:
System::WeakPtr<Element> _owner;
System::SharedPtr<System::Collections::Generic::List<System::SharedPtr<Element>>> _elements;
};
} // namespace LogicalStructure
} // namespace Pdf
} // namespace Aspose
| 37.572727 | 243 | 0.719816 | [
"object"
] |
afc057dd08c59d3321a5237c4e3243e6b84d0395 | 11,736 | h | C | src/include/hi_drm_common.h | y33988979/testhelper | 8d109cd70a4996a0db912c265a710d4a0c457a84 | [
"MIT"
] | null | null | null | src/include/hi_drm_common.h | y33988979/testhelper | 8d109cd70a4996a0db912c265a710d4a0c457a84 | [
"MIT"
] | null | null | null | src/include/hi_drm_common.h | y33988979/testhelper | 8d109cd70a4996a0db912c265a710d4a0c457a84 | [
"MIT"
] | 1 | 2021-12-03T18:41:23.000Z | 2021-12-03T18:41:23.000Z | /*
* hi_drm_common.h
*
* Created on: Jul 31, 2012
* Author: zhangyi
*/
#ifndef HI_DRM_COMMON_H_
#define HI_DRM_COMMON_H_
#include <sys/types.h>
#include <hi_type.h>
#ifdef __cplusplus
#if __cplusplus
extern "C" {
#endif
#endif /* __cplusplus */
//------------------------------------------------------------------------------
/**
* \breif Macros defined by Playready
*/
/**
* \breif Define the mimetype of playraedy
* {HI_KEY_PDY_MimeType, "application/vnd.ms-playready"}
*/
extern const HI_CHAR* HI_KEY_PDY_MimeType;
extern const HI_CHAR* HI_KEY_WMDRM_MimeType;
/**
* \breif key strings used by playready open
*/
extern const HI_CHAR* HI_KEY_PDY_DrmPath;
extern const HI_CHAR* HI_KEY_PDY_LocalStoreFile;
extern const HI_CHAR* HI_KEY_PDY_OriginalFile;
extern const HI_CHAR* HI_KEY_PDY_SercureClockServerIP;
extern const HI_CHAR* HI_KEY_PDY_SecureServerPort;
extern const HI_CHAR* HI_KEY_PDY_ServerIP;
extern const HI_CHAR* HI_KEY_PDY_ServerPort;
extern const HI_CHAR* HI_KEY_PDY_ResponseFile;
extern const HI_CHAR* HI_KEY_PDY_SecretData;
extern const HI_CHAR* HI_KEY_PDY_ProtectionType;
extern const HI_CHAR* HI_KEY_PDY_KeyID;
extern const HI_CHAR* HI_KEY_PDY_LicenseURL;
extern const HI_CHAR* HI_KEY_PDY_EncryVer2Data;
extern const HI_CHAR* HI_KEY_PDY_EncryVersion;
extern const HI_CHAR* HI_KEY_PDY_EncryType;
extern const HI_CHAR* HI_KEY_PDY_InitiatorFile;
extern const HI_CHAR* HI_KEY_PDY_DataSize;
extern const HI_CHAR* HI_KEY_PDY_KeyFilePath;
extern const HI_CHAR* HI_KEY_PDY_EnvelopFile;
extern const HI_CHAR* HI_KEY_PDY_EnvelopOutputFile;
extern const HI_CHAR* HI_VAL_PDY_EncryVersion1;
extern const HI_CHAR* HI_VAL_PDY_EncryVersion2;
extern const HI_CHAR* HI_VAL_PDY_EncryTypeWMDRM;
extern const HI_CHAR* HI_VAL_PDY_EncryTypePlayReady;
/*PlayReady Certification Buffer define*/
typedef struct tagHI_PLAYREADY_DEVCERT_BUF_S HI_PLAYREADY_DEVCERT_BUF_S;
struct tagHI_PLAYREADY_DEVCERT_BUF_S
{
HI_U8* pu8Pri;
HI_S32 s32PriLen;
HI_U8* pu8Zgpriv;
HI_S32 s32ZgprivLen;
HI_U8* pu8Bgroupcert;
HI_S32 s32BgroupcertLen;
HI_U8* pu8Devcerttemplate;
HI_S32 s32DevcerttemplateLen;
HI_VOID (*pfnDestructor)(HI_PLAYREADY_DEVCERT_BUF_S* thiz);
};
/*End of playready defines*/
//------------------------------------------------------------------------------
enum {
HI_DRM_STATUS_OK = 1,
HI_DRM_STATUS_ERROR = 2,
};
/**
* \breif Error code for DRM Frameowrk
*/
typedef enum hiDRM_ERROR_E{
// The following constant values should be in sync with
// media/stagefright/MediaErrors.h
HI_DRM_ERROR_BASE = -2000,
HI_DRM_ERROR_UNKNOWN = HI_DRM_ERROR_BASE,
HI_DRM_ERROR_NO_LICENSE = HI_DRM_ERROR_BASE - 1,
HI_DRM_ERROR_LICENSE_EXPIRED = HI_DRM_ERROR_BASE - 2,
HI_DRM_ERROR_SESSION_NOT_OPENED = HI_DRM_ERROR_BASE - 3,
HI_DRM_ERROR_DECRYPT_UNIT_NOT_INITIALIZED = HI_DRM_ERROR_BASE - 4,
HI_DRM_ERROR_DECRYPT = HI_DRM_ERROR_BASE - 5,
HI_DRM_ERROR_CANNOT_HANDLE = HI_DRM_ERROR_BASE - 6,
HI_DRM_ERROR_TAMPER_DETECTED = HI_DRM_ERROR_BASE - 7,
HI_DRM_ERROR_NO_PERMISSION = HI_DRM_ERROR_BASE - 8,
HI_DRM_NO_ERROR = HI_SUCCESS
} HI_DRM_ERROR_E;
/**
* \breif copy control settings used in DecryptHandle::copyControlVector
*/
typedef enum hiDRM_COPY_CONTROL_E {
HI_DRM_COPY_CONTROL_BASE = 1000,
// the key used to set the value for HDCP
// if the associated value is 1, then HDCP is required
// otherwise, HDCP is not required
HI_DRM_COPY_CONTROL_HDCP = HI_DRM_COPY_CONTROL_BASE
} HI_DRM_COPY_CONTROL_E;
/**
* \breif Defines DRM Buffer
*/
typedef struct hiDRM_BUFFER_S {
HI_CHAR* data;
HI_U32 length;
HI_VOID (*destructor)(HI_VOID*);
} HI_DRM_BUFFER_S;
#define DECLARE_DRM_BUFFER(name, _data, _len) \
HI_DRM_BUFFER_S name = {\
.data = (HI_CHAR*)_data,\
.length = (HI_U32)_len,\
.destructor = 0,\
}
#define DECLARE_DRM_BUFFER_D(name, _data, _len, _destructor) \
HI_DRM_BUFFER_S name = {\
.data = (HI_CHAR*)_data,\
.length = (HI_U32)_len,\
.destructor = _destructor,\
}
/**
* \breif Defines detailed description of the action
*/
typedef struct hiACTION_DESCRIPTION_S {
HI_S32 outputType; /* BLUETOOTH , HDMI*/
HI_S32 configuration; /* RESOLUTION_720_480 , RECORDABLE etc.*/
} HI_ACTION_DESCRIPTION_S;
/**
* \breif Defines constants related to DRM types
*/
typedef enum hiDRM_OBJECT_TYPE_E {
/**
* Field specifies the unknown type
*/
HI_DRM_OBJECT_TYPE_UNKNOWN = 0x00,
/**
* Field specifies the protected content type
*/
HI_DRM_OBJECT_TYPE_CONTENT = 0x01,
/**
* Field specifies the rights information
*/
HI_DRM_OBJECT_TYPE_RIGHTS = 0x02,
/**
* Field specifies the trigger information
*/
HI_DRM_OBJECT_TYPE_TRIGGER = 0x03,
} HI_DRM_OBJECT_TYPE_E;
/**
* \breif Defines constants related to play back
*/
typedef enum hiPLAY_BACK_E {
/**
* Constant field signifies playback start
*/
HI_PLAY_BACK_START = 0x00,
/**
* Constant field signifies playback stop
*/
HI_PLAY_BACK_STOP = 0x01,
/**
* Constant field signifies playback paused
*/
HI_PLAY_BACK_PAUSE = 0x02,
/**
* Constant field signifies playback resumed
*/
HI_PLAY_BACK_RESUME = 0x03,
} HI_PLAY_BACK_E;
/**
* \breif Defines actions that can be performed on protected content
*/
typedef enum hiACTION_E {
/**
* Constant field signifies that the default action
*/
HI_ACTION_DEFAULT = 0x00,
/**
* Constant field signifies that the content can be played
*/
HI_ACTION_PLAY = 0x01,
/**
* Constant field signifies that the content can be set as ring tone
*/
HI_ACTION_RINGTONE = 0x02,
/**
* Constant field signifies that the content can be transfered
*/
HI_ACTION_TRANSFER = 0x03,
/**
* Constant field signifies that the content can be set as output
*/
HI_ACTION_OUTPUT = 0x04,
/**
* Constant field signifies that preview is allowed
*/
HI_ACTION_PREVIEW = 0x05,
/**
* Constant field signifies that the content can be executed
*/
HI_ACTION_EXECUTE = 0x06,
/**
* Constant field signifies that the content can displayed
*/
HI_ACTION_DISPLAY = 0x07,
} HI_ACTION_E;
/**
* \breif Defines constants related to status of the rights
*/
typedef enum hiRIGHTS_STATUS_E {
/**
* Constant field signifies that the rights are valid
*/
HI_DRM_RIGHTS_VALID = 0x00,
/**
* Constant field signifies that the rights are invalid
*/
HI_DRM_RIGHTS_INVALID = 0x01,
/**
* Constant field signifies that the rights are expired for the content
*/
HI_DRM_RIGHTS_EXPIRED = 0x02,
/**
* Constant field signifies that the rights are not acquired for the content
*/
HI_DRM_RIGHTS_NOT_ACQUIRED = 0x03,
} HI_DRM_RIGHTS_STATUS_E;
/**
* \breif Defines API set for decryption
*/
typedef enum hiDECRYPT_API_TYPE_E {
/**
* Decrypt API set for non encrypted content
*/
HI_DECRYPT_API_NON_ENCRYPTED = 0x00,
/**
* Decrypt API set for ES based DRM
*/
HI_DECRYPT_API_ELEMENTARY_STREAM_BASED = 0x01,
/**
* POSIX based Decrypt API set for container based DRM
*/
HI_DECRYPT_API_CONTAINER_BASED = 0x02,
/**
* Decrypt API for Widevine streams
*/
HI_DECRYPT_API_WV_BASED = 0x3,
} HI_DECRYPT_API_TYPE_E;
/**
* \breif Defines decryption information
*/
typedef struct hiDECRYPT_INFO_S {
/**
* size of memory to be allocated to get the decrypted content.
*/
HI_S32 decryptBufferLength;
/**
* reserved for future purpose
*/
} HI_DECRYPT_INFO_S;
/**
* \breif Defines Iterator type
*/
typedef struct hiITERATOR_S HI_ITERATOR_S;
struct hiITERATOR_S {
HI_BOOL (*pfnHasNext)(HI_ITERATOR_S* self);
const HI_CHAR* (*pfnNext)(HI_ITERATOR_S* self);
HI_S32 index;
HI_VOID* opaque;
};
static inline HI_BOOL HI_ITERATOR_HasNext(HI_ITERATOR_S* self)
{
return self->pfnHasNext(self);
}
static inline const HI_CHAR* HI_ITERATOR_Next(HI_ITERATOR_S* self)
{
return self->pfnNext(self);
}
/**
* \breif Defines decryption handle
*/
typedef struct hiDECRYPT_HANDLE_S * HI_DECRYPT_HANDLE_PTR;
typedef struct hiDECRYPT_HANDLE_S {
/**
* Decryption session Handle
*/
HI_S32 decryptId;
/**
* Mimetype of the content to be used to select the media extractor
* For e.g., "video/mpeg" or "audio/mp3"
*/
HI_CHAR* mimeType;
/**
* Defines which decryption pattern should be used to decrypt the given content
* DrmFramework provides two different set of decryption APIs.
* 1. Decrypt APIs for elementary stream based DRM
* (file format is not encrypted but ES is encrypted)
* e.g., Marlin DRM (MP4 file format), WM-DRM (asf file format)
*
* DecryptApiType::ELEMENTARY_STREAM_BASED
* Decryption API set for ES based DRM
* initializeDecryptUnit(), decrypt(), and finalizeDecryptUnit()
* 2. Decrypt APIs for container based DRM (file format itself is encrypted)
* e.g., OMA DRM (dcf file format)
*
* DecryptApiType::CONTAINER_BASED
* POSIX based Decryption API set for container based DRM
* pread()
*/
HI_S32 decryptApiType;
/**
* Defines the status of the rights like
* RIGHTS_VALID, RIGHTS_INVALID, RIGHTS_EXPIRED or RIGHTS_NOT_ACQUIRED
*/
HI_S32 status;
/**
* Information required to decrypt content
* e.g. size of memory to be allocated to get the decrypted content.
*/
HI_DECRYPT_INFO_S* decryptInfo;
/**
* Defines a vector for the copy control settings sent from the DRM plugin
* to the player
*/
HI_ITERATOR_S copyControlVector;
/**
* Defines a vector for any extra data the DRM plugin wants to send
* to the native code
*/
HI_ITERATOR_S extendedData;
} HI_DECRYPT_HANDLE_S;
//------------------------------------------------------------------------------
/**
* \breif This is an utility class which wraps the status of the conversion, the converted
* data/checksum data and the offset. Offset is going to be used in the case of close
* session where the agent will inform where the header and body signature should be added
*
* As a result of DrmManagerClient::convertData(HI_S32, const DrmBuffer*) and
* DrmManagerClient::closeConvertSession(HI_S32) an instance of DrmConvertedStatus
* would be returned.
*
*/
// Should be in sync with DrmConvertedStatus.java
enum {
HI_DRM_CONVERTED_STATUS_OK = 1,
HI_DRM_CONVERTED_STATUS_INPUTDATA_ERROR = 2,
HI_DRM_CONVERTED_TATUS_ERROR = 3,
};
typedef struct hiDRM_CONVERTED_STATUS_S {
HI_S32 statusCode;
const HI_DRM_BUFFER_S convertedData;
HI_S32 offset;
} HI_DRM_CONVERTED_STATUS_S;
typedef HI_DRM_CONVERTED_STATUS_S* HI_DRM_CONVERTED_STATUS_PTR;
#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif /* __cplusplus */
#endif /* HI_DRM_COMMON_H_ */
| 30.325581 | 91 | 0.652863 | [
"vector"
] |
afc481ac2525889f3cfb726952a0a0eecb4f5bce | 625 | h | C | docs/src/GameData.h | lucas-zimerman/SuperShibe3K | 02eaf7f0237987310c8a27ff7c838024043839c0 | [
"MIT"
] | 2 | 2020-03-21T02:55:28.000Z | 2020-04-15T20:29:13.000Z | docs/src/GameData.h | ibm5155/SuperShibe3K | 02eaf7f0237987310c8a27ff7c838024043839c0 | [
"MIT"
] | null | null | null | docs/src/GameData.h | ibm5155/SuperShibe3K | 02eaf7f0237987310c8a27ff7c838024043839c0 | [
"MIT"
] | null | null | null | #pragma once
#include <MT2D/ObjectCore/Object.h>
#include "Enums/Level.h"
#define constTick 67
struct GameData {
int tick = 0;
int j = 0;
int seconds = 0;
int bossAppear = 119;
int k;
int bossActive = 0;
int nextTickSecond = constTick;
int nextCactusSecond = 2;
int nextRailSecond = 5;
int nextRocketSecond = 5;
int nextFireSecond = 5;
int nextBossSecond = 0;
int nextLevelSecond = 60;
unsigned int RailCount = 0;
unsigned int RocketCount = 0;
Level level = easy;
ObjectScene* objectsFloor;
ObjectScene* backgroundFloor;
ObjectScene* sceneEffects;
Sprite* GameOverSprite;
Sprite** NumbersSprites;
}; | 19.53125 | 35 | 0.728 | [
"object"
] |
afc4c44d88258adb45a446884f4dab01cd4e1692 | 10,080 | h | C | trynester.h | 980f/arduino | 56ceb9cc349d7c4290562b6c5b67f609640410a9 | [
"MIT"
] | null | null | null | trynester.h | 980f/arduino | 56ceb9cc349d7c4290562b6c5b67f609640410a9 | [
"MIT"
] | null | null | null | trynester.h | 980f/arduino | 56ceb9cc349d7c4290562b6c5b67f609640410a9 | [
"MIT"
] | null | null | null | // Copyright 2021 by Andy Heilveil (github/980f)
// Created by andyh on 12/28/21.
/**
* These classes wrap setjmp/longjmp usage for microcontrollers for which c++'s exception handling is too expensive.
* It is not sane to use these with interrupts or multiple threads, although a threadlocal instance might work as expected.
*
* Unlike true exception handling you do NOT get destruction of items on the stack. That means that if you have any dynamic allocation going on you should not use this.
* One could complexify the class by registering destructors with it, but then you should probably not be disabling exceptions, this module is intended for resource limited microcontrollers.
*
* The LocationStack is an attempt at getting better info on the cause of an exception.
* */
#ifndef TRYNESTER_H
#define TRYNESTER_H
#if __has_include(<csetjmp>)
#include <csetjmp>
#else
#include "setjmp.h"
#endif
#pragma ide diagnostic ignored "cert-err52-cpp" //this file exists to manage lomgjmp when exceptions are too expensive to use.
/** simple stack via linked list, intended to preserve block nesting information when a psuedo exception is thrown.
* All objects to push must be allocated locally, not statically.
* The tos is a statically allocated pointer and should be used for all operations. For coding simplicity */
template<typename Element> class Stacked {
protected:
Stacked *stacked = nullptr;
//todo
// /** cache depth value for printing convenience */
// unsigned depth;
//
// static unsigned Depth;
public:
/** all throws should be called on this object:
* if using threads this must be a thread_local
* */
static Stacked *tos;
static Element *top() {
return tos ? tos->guts() : nullptr;
}
/**
* tos is a pointer, you can call tos->notEmpty even if tos is a nullptr */
bool notEmpty() const {
return this != nullptr;
}
/**
/** this will only work for certain classes and certain compilers:
* the thing stacked, must be declared class MyStackedThing:public Stacked<MyStackedThing>[, other bases] {..} any other base class MUST follow the Stacked<> one for this to work.
* This is necessary due to insisting that we operate with RTTI disabled, which is common if you are disabling exeptions which disablement is the reason this module exists.
* */
Element *guts() {
return reinterpret_cast<Element *>(this);
}
/** the visitor is given a pointer to what is a base class of the class being stacked.
* Visitor returns true if walk is to continue, false to stop it (useful for pealing off part of the top such as only the stack from the try to the throw) */
template<typename Visitor>
static void walk(Visitor &&visitor) {
for (Stacked *item = Stacked<Element>::tos; item && visitor(item->guts()); item = item->stacked) {
}
}
/** @returns what to feed to unwind to restore stack to present state */
static Stacked *mark() {
return tos;
}
/** remove stack elements without notifying anyone. Stops the unwind when it finds @param mark, leaving mark as top of stack.
* if mark is not in stack then tos is unchanged. */
static void unwind(Stacked<Element> *mark) {
if (mark == nullptr) {
tos = nullptr;
return;
}
walk([mark](Stacked *stackentry) {
if (stackentry == mark) {//equal addresses
tos = mark;
return false;
}
return true;
});
}
protected:
/** pop is used when the stack frame is ended via normal execution.
* it is idempotent= no matter how many times it is called on an object the stack just pops once. */
void pop() const {
if (stacked != nullptr) {
tos = stacked;
}
//else it is the root and we shouldn't actually get here.
}
Stacked() {
this->stacked = tos;
tos = this;
}
~Stacked() {
pop();
}
};
/**
* Each Throw source should have a location stack, to provide a full backtrace on exception.
* Until we find a use for more than one we make our life easy by having a static instance.
* */
class LocationStack : public Stacked<LocationStack> {
/** a STATIC one of these Elements may be created for each function, so that a backtrace can be printed after an exception has been caught without using stale objects.
* static construction also allows you to have a per-instance flag to control reporting on function exit and perhaps entrance that you can get to with a debugger.
* */
public:
static bool onEntry;
class Element {
friend class LocationStack;
public:
const char *const function;
const char *const file;
const unsigned line;
//mutable for debugger based fiddling:
mutable bool reportOnExit;
//constructor for static use case:
Element(const char *function, const char *file, unsigned line,bool reportOnExit = false) : function(function), file(file), line(line) ,reportOnExit(reportOnExit){
}
};
using Ticks = unsigned long; //todo: take in the class for Ticks via a #define
struct Logger {
virtual Ticks stamper() = 0;
/** this gets called as each routine exits */
virtual void reportElapsed(const Element &, Ticks elapsed) = 0;
/** this gets called just before reportElapsed gets called on all stack members */
virtual void exception(int throwncode) = 0;
virtual void moreInfo(const char *info, ...){};
};
static Logger *logger;
/** designed to only be called on TOS, but can make sense using a local one since that is usually the top of the stack:
* @return @param throwcode !=0 as a convenience for a migration from another system's error logging call */
static bool logTrace(int throwcode, const char *function, const char *file, unsigned line) {
if (logger) {
//todo:m a list of "errors worth tracing" could be checked here, IE filter out trivial/convenience throws.
LocationStack::Element tracer(function, file, line);
tracer.reportOnExit = true;//always trace this guy
LocationStack convenientrick(tracer);//puts this blocks tracer on top of stack
logException(throwcode);
}
return throwcode != 0;
}
private:
const Element &element;
Ticks timestamp = 0;//timestamp is on object that manages the push and pop so that Element with location information can be const static.
private:
void pop() {
if (element.reportOnExit) {
if (logger) {
logger->reportElapsed(element, logger->stamper() - timestamp);
}
}
Stacked::pop();
}
public:
explicit LocationStack(Element &element);
~LocationStack() {
pop();
}
static void logException(int thrown);
};
//you can put a TRACE_ENTRY inside any block statement.
#define TRACE_ENTRY static LocationStack::Element tracer(__FUNCTION__, __FILE__, __LINE__);LocationStack namedoesntmatter(tracer);
/** wrap a class around jmp_buf for exception handling via longjmp.
* */
class Thrower : public Stacked<Thrower> { //class Stacked provides a static member so only one Thrower stack is allowed
jmp_buf opaque; //an array of bytes that magically gets us back to where setjmp was called.
/** for passing the longjmp provided value out of the constructor which contains the setjmp */
int thrown = 0;
/** thing used by locationstack to synch with try block */
Stacked<LocationStack> *mark;
public:
/** this is the global accessor for throwing a psuedo exception.*/
static int Throw(int error) {
(*top())(error);//this longjmp's (if stack has been initialized properly and there are no other bugs in this module)
return error;//appeases compiler, and perhaps we might not actually throw when there is no try block active
}
/** construction pushes this object onto the exception context stack and runs the setjmp.
Thrown exceptions appear at the object construction point in the code, but after the execution of allocation of the object.
*/
Thrower() { // NOLINT(cppcoreguidelines-pro-type-member-init)
mark = LocationStack::mark();
//# base constructor places this on the top of the throw stack before the setjmp is called
thrown = setjmp(opaque);
if (thrown) {//then we got here due to a throw on the tos instance, or rarely a "throw to self"
LocationStack::logException(thrown);
//we have a design decision to make here, where should exceptions in the exception handlers get handled?
//if we do what C++ does (a reasonable choice by the principle of least surprise) then:
LocationStack::unwind(mark);//not part of pop as its own destructor takes care of popping it under normal circumstances.
pop();//can't wait until context exits to point exceptions outside of this instance
//if we have a peculiar need to join some other catch clause of the present handler we can throw via its local thrower.
}
}
/** invoked on a named constructor instance can be used to make the if() {} block the try block and the else{} the catches */
operator bool() const {
return thrown == 0;
}
/** read only to public */
operator int() const {
return thrown;
}
/** throw! This is only called on the tos entity, although one could throw to one's self locally in a try block.
* if there is no receiver (or particular error code is deemed not worthy of throwing) then we return the passed argument so that you can:
* return Thrower(exception, returnIfExceptionsDisbled);
* or value=Thrower(exception, inrangevalue) //throw or coerce runtime choice
* */
template<typename Altreturn> Altreturn
operator()(int errorcode, Altreturn alt) {
operator()(errorcode);//which might longjmp instead of returning
return alt;
}
/** throw! (or ignore) */
void operator()(int errorcode);
/** leaving try/catch */
~Thrower() {
pop();
}
};
//see example in matching cpp file for limitations on using the following macros
#define TRY switch (Thrower Throw; int(Throw)) { case 0:
#define CATCH(code) } break; case code: {
#define UNCAUGHT } break; default:
// in case we change our mind (again ;) :
#define THROW(error) Thrower::Throw(error)
#endif //VL53_TRYNESTER_H
| 38.326996 | 190 | 0.707242 | [
"object"
] |
afc917c0536924425ca7ad5146673d9bed14bdff | 1,476 | h | C | thirdparty/toolcursor/vtkOpacityTool.h | greydongilmore/tactics | e57008ded07eb798368ccb161d9bf06d9a16f52c | [
"BSD-3-Clause"
] | 5 | 2015-06-02T22:10:36.000Z | 2022-01-02T09:26:47.000Z | thirdparty/toolcursor/vtkOpacityTool.h | greydongilmore/tactics | e57008ded07eb798368ccb161d9bf06d9a16f52c | [
"BSD-3-Clause"
] | 2 | 2015-06-04T14:52:09.000Z | 2015-06-04T18:58:50.000Z | thirdparty/toolcursor/vtkOpacityTool.h | greydongilmore/tactics | e57008ded07eb798368ccb161d9bf06d9a16f52c | [
"BSD-3-Clause"
] | 3 | 2015-06-04T15:02:25.000Z | 2021-02-02T01:47:56.000Z | /*=========================================================================
Program: ToolCursor
Module: vtkOpacityTool.h
Copyright (c) 2010 David Gobbi
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// .NAME vtkOpacityTool - Adjusts the opacity of an image.
// .SECTION Description
// This class adjusts the Opacity of an image property.
#ifndef __vtkOpacityTool_h
#define __vtkOpacityTool_h
#include "vtkTool.h"
class vtkImageProperty;
class VTK_EXPORT vtkOpacityTool : public vtkTool
{
public:
// Description:
// Instantiate the object.
static vtkOpacityTool *New();
// Description:
// Standard vtkObject methods
vtkTypeMacro(vtkOpacityTool, vtkTool);
void PrintSelf(ostream& os, vtkIndent indent);
// Description:
// These are the methods that are called when the action takes place.
virtual void StartAction();
virtual void StopAction();
virtual void DoAction();
protected:
vtkOpacityTool();
~vtkOpacityTool();
double StartOpacity;
vtkImageProperty *CurrentImageProperty;
void SetCurrentImageToNthImage(int i);
private:
vtkOpacityTool(const vtkOpacityTool&); //Not implemented
void operator=(const vtkOpacityTool&); //Not implemented
};
#endif
| 25.448276 | 75 | 0.672764 | [
"object"
] |
afc97d8ace34d3b15a4b16b54945d1a5a6d61a23 | 6,542 | h | C | src/AbstractTab.h | shtroizel/completable | f98372fc655aa8a8fcffaf9ef5e0fa8fab73a048 | [
"BSD-3-Clause"
] | null | null | null | src/AbstractTab.h | shtroizel/completable | f98372fc655aa8a8fcffaf9ef5e0fa8fab73a048 | [
"BSD-3-Clause"
] | null | null | null | src/AbstractTab.h | shtroizel/completable | f98372fc655aa8a8fcffaf9ef5e0fa8fab73a048 | [
"BSD-3-Clause"
] | null | null | null | #pragma once
/*
Copyright (c) 2020, Eric Hyer
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <array>
#include <memory>
#include <vector>
#include <matchable/matchable.h>
#include <matchable/matchable_fwd.h>
MATCHABLE_FWD(Layer)
class AbstractTab;
class AbstractWindow;
// handle for AbstractTab types
// derivers need to use SPREAD_MATCHABLE() to add their types
// the "AbstractTab" property allows retrieval of the "real" tab
PROPERTYx1_MATCHABLE(AbstractTab *, AbstractTab, Tab)
/**
* AbstractTab serves as the base for all Tabs, which provide a space for windows that should be
* seen together.
*
* Windows are known by Tabs but not owned by them (*TabAgent classes take care of ownership).
*
* Tabs manage windows within layers
* Each window specifies which layer it belongs to with AbstractWindow::layer()
* - A window's defined layer determines its stacking order, with Layer::Help above all others
* - Key events are caught here first to handle Layer enabledness before being forwarded to the active
* window
* - Each layer has its own active window, with the top most receiving any unhandled key events
*/
class AbstractTab
{
public:
AbstractTab(AbstractTab const &) = delete;
AbstractTab & operator=(AbstractTab const &) = delete;
AbstractTab();
virtual ~AbstractTab();
/**
* @returns A handle to the tab with access back to the tab via matchable property
*/
Tab::Type as_handle() const { return as_matchable(); }
/**
* Adds a window to the tab. Ownership is preserved.
* Also, the tab will add its handle to the window for back-referencing
*
* @param[in] win Window to be added
*/
void add_window(AbstractWindow * win);
/**
* recalculate size and position for all windows managed by the tab
*/
void resize();
/**
* redraw all windows managed by the tab
* @see AbstractWindow::draw()
*/
void draw(bool clear_first);
/**
* Set the tab's left neighbor.
* When switching tabs with shift + left arrow, this tab is to be the next tab shown
* @param[in] neighbor handle to the tab's left neighbor
*/
void set_left_neighbor(Tab::Type neighbor) { left_neighbor = neighbor; }
/**
* Set the tab's right neighbor.
* When switching tabs with shift + right arrow, this tab is to be the next tab shown
* @param[in] neighbor handle to the tab's right neighbor
*/
void set_right_neighbor(Tab::Type neighbor) { right_neighbor = neighbor; }
/**
* Set which tab should be visible (activated). One tab is visible at a time.
* @param[in] handle to a tab to be activated
*/
static void set_active_tab(Tab::Type tab);
/**
* @returns A handle to the currently active tab
*/
static Tab::Type get_active_tab();
/**
* @returns true if the tab is currently active or false otherwise
*/
bool is_active() { return get_active_tab() == as_handle(); }
/**
* Sets the active window for the layer that the given window belongs to. Note that if the window's
* layer is disabled or lies underneath another enabled layer then the window returned by
* get_active_window() may remain unchanged
*
* @param[in] win new active window for the layer specified by win->get_layer()
*/
void set_active_window(AbstractWindow * win);
/**
* @returns the active window for the top-most enabled layer
*/
AbstractWindow * get_active_window();
/**
* @param[in] layer The layer for which to retrieve an active window
* @returns the active window for the given layer
*/
AbstractWindow * get_active_window(Layer::Type layer);
/**
* Event handler for keyboard
* Keys used for tab switching or layer enabledness are caught while unhandled keys are forwarded
* to the active window of the top-most enabled layer
*
* @param[in] key keyboard key to be handled
*/
void on_KEY(int key);
/**
* Indicator positions start at 0 and go from right to left
*
* @returns The tab's indicator position (example: third indicator from the right has position 2)
*/
int get_indicator_position() const { return indicator_position(); }
private:
// dependencies
virtual int indicator_position() const = 0;
virtual Tab::Type as_matchable() const = 0;
void on_ANY_F();
void on_COMMA();
void toggle_layer(Layer::Type, bool &);
void on_SHIFT_LEFT();
void on_SHIFT_RIGHT();
private:
Tab::Type left_neighbor;
Tab::Type right_neighbor;
std::shared_ptr<
matchable::MatchBox<
Layer::Type,
// first for all windows in layer, second for layer's active window
std::pair<std::vector<AbstractWindow *>, AbstractWindow *>
>
> layers;
bool layer_F_enabled{false};
bool layer_Help_enabled{false};
// static variable for the active tab (look like a function but its a variable)
static AbstractTab * & active_tab() { static AbstractTab * tab; return tab; }
};
| 33.377551 | 104 | 0.700703 | [
"vector"
] |
afcd2a639b1c9a5831e55ea3d85c60109a02a4f7 | 899 | h | C | 014_StencilTesting/StencilTesting/Engine/Light/SpotLight.h | David-Luis/graphics | 2397e79353e4721ed6199a4e05572bc992ba24d4 | [
"MIT"
] | null | null | null | 014_StencilTesting/StencilTesting/Engine/Light/SpotLight.h | David-Luis/graphics | 2397e79353e4721ed6199a4e05572bc992ba24d4 | [
"MIT"
] | null | null | null | 014_StencilTesting/StencilTesting/Engine/Light/SpotLight.h | David-Luis/graphics | 2397e79353e4721ed6199a4e05572bc992ba24d4 | [
"MIT"
] | null | null | null | #pragma once
#include <Engine/Light/Light.h>
#include <glm/glm.hpp>
class Mesh;
class Shader;
class Camera;
class SpotLight : public Light
{
public:
SpotLight();
virtual ~SpotLight() {}
SpotLight(const SpotLight&) = delete;
SpotLight& operator=(SpotLight const&) = delete;
void SetAttenuation(float constant, float linear, float quadratic);
void SetCutoff(float cutOff, float outerCutOff);
void SetDirection(const glm::vec3& direction);
glm::vec3 GetDirection() const;
void DebugDraw(Camera& camera) override;
private:
void Use(const Shader& shader, int count) const override;
void BindUniformsDebug(const Shader& shader, const Camera& camera);
void CreateDebugDrawData();
Mesh* m_debugMesh;
Shader* m_debugShader;
glm::vec3 m_direction;
float m_constantAttenuation;
float m_linearAttenuation;
float m_quadraticAttenuation;
float m_cutOff;
float m_outerCutOff;
};
| 19.12766 | 68 | 0.759733 | [
"mesh"
] |
afcd69251a6e4ddd65b0e8c4c21fa5d9176c6b58 | 35,529 | c | C | 03-D3D12-Triangle/main.c | Sand3r-/SDL-Samples | 4043f6bc637455125996ad62bc9e8d52287a6e45 | [
"MIT"
] | null | null | null | 03-D3D12-Triangle/main.c | Sand3r-/SDL-Samples | 4043f6bc637455125996ad62bc9e8d52287a6e45 | [
"MIT"
] | null | null | null | 03-D3D12-Triangle/main.c | Sand3r-/SDL-Samples | 4043f6bc637455125996ad62bc9e8d52287a6e45 | [
"MIT"
] | null | null | null | #define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <Windows.h>
#include <assert.h>
#include <time.h>
#include <signal.h>
#include <SDL.h>
#include <SDL_syswm.h>
#define COBJMACROS
#pragma warning(push)
#pragma warning(disable:4115) // named type definition in parentheses
#include <d3d12.h>
#include <d3dcompiler.h>
#include <dxgi1_6.h>
#include <dxgidebug.h>
#include <d3d12sdklayers.h>
#pragma warning(pop)
#undef COBJMACROS
#define HD_EXIT_FAILURE -1
#define HD_EXIT_SUCCESS 0
// Number of render targets
#define FRAMES_NUM 3
#define ID3DBlob_GetBufferPointer(self) ID3D10Blob_GetBufferPointer(self)
#define ID3DBlob_Release(self) ID3D10Blob_Release(self)
#define ID3DBlob_GetBufferSize(self) ID3D10Blob_GetBufferSize(self)
#define MAX(x, y) (((x) > (y)) ? (x) : (y))
#define MIN(x, y) (((x) < (y)) ? (x) : (y))
#define ExitOnFailure(expression) if (FAILED(expression)) raise(SIGINT);
#define S(x) #x
#define S_(x) S(x)
#define S__LINE__ S_(__LINE__)
#define GEN_REPORT_STRING() "Reporting Live objects at " __FUNCTION__ ", L:" S__LINE__ "\n"
#define REPORT_LIVE_OBJ() ReportLiveObjects(GEN_REPORT_STRING())
typedef struct ResizeData
{
D3D12_VIEWPORT* viewport;
ID3D12Device2* device;
ID3D12Resource** depthBuffer;
float fov;
} ResizeData;
ID3D12Device2* g_Device;
IDXGISwapChain4* g_SwapChain;
ID3D12CommandQueue* g_CommandQueue;
ID3D12GraphicsCommandList* g_CommandList;
ID3D12PipelineState* g_PipelineState;
ID3D12RootSignature* g_RootSignature;
D3D12_VIEWPORT g_Viewport;
D3D12_RECT g_ScissorRect;
IDXGIDebug1* g_Debug;
ID3D12Resource* g_BackBuffers[FRAMES_NUM];
ID3D12Resource* g_DepthBuffer;
ID3D12CommandAllocator* g_CommandAllocators[FRAMES_NUM];
uint64_t g_FrameFenceValues[FRAMES_NUM];
uint64_t g_FenceValue = 0;
UINT g_CurrentBackBufferIndex;
UINT g_RTVDescriptorSize;
UINT g_DSVDescriptorSize;
ID3D12DescriptorHeap* g_RTVDescriptorHeap;
ID3D12DescriptorHeap* g_DSVDescriptorHeap;
ID3D12Fence* g_Fence;
HANDLE g_FenceEvent;
ResizeData g_ResizeData;
void EnableDebuggingLayer()
{
ID3D12Debug* debugInterface;
ExitOnFailure(D3D12GetDebugInterface(&IID_ID3D12Debug, &debugInterface));
ID3D12Debug_EnableDebugLayer(debugInterface);
ID3D12Debug_Release(debugInterface);
ExitOnFailure(DXGIGetDebugInterface1(0, &IID_IDXGIDebug1, &g_Debug));
}
void ReportLiveObjects(const char* report)
{
OutputDebugString("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
OutputDebugString(report);
OutputDebugString("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
IDXGIDebug1_ReportLiveObjects(g_Debug, DXGI_DEBUG_ALL, DXGI_DEBUG_RLO_ALL);
}
IDXGIAdapter4* GetAdapter()
{
IDXGIFactory4* dxgiFactory;
UINT createFactoryFlags = 0;
#if defined(_DEBUG)
createFactoryFlags = DXGI_CREATE_FACTORY_DEBUG;
#endif
ExitOnFailure(CreateDXGIFactory2(createFactoryFlags, &IID_IDXGIFactory4, &dxgiFactory));
IDXGIAdapter1* dxgiAdapter1;
IDXGIAdapter4* dxgiAdapter4;
SIZE_T maxDedicatedVideoMemory = 0;
for (UINT i = 0; IDXGIFactory1_EnumAdapters1(dxgiFactory, i, &dxgiAdapter1) != DXGI_ERROR_NOT_FOUND; ++i)
{
DXGI_ADAPTER_DESC1 dxgiAdapterDesc1;
IDXGIAdapter1_GetDesc1(dxgiAdapter1, &dxgiAdapterDesc1);
if ((dxgiAdapterDesc1.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) == 0 &&
SUCCEEDED(D3D12CreateDevice((IUnknown*)dxgiAdapter1,
D3D_FEATURE_LEVEL_11_0, &IID_ID3D12Device, NULL)) &&
dxgiAdapterDesc1.DedicatedVideoMemory > maxDedicatedVideoMemory )
{
maxDedicatedVideoMemory = dxgiAdapterDesc1.DedicatedVideoMemory;
ExitOnFailure(IDXGIAdapter1_QueryInterface(dxgiAdapter1, &IID_IDXGIAdapter4, &dxgiAdapter4));
}
IDXGIAdapter1_Release(dxgiAdapter1);
}
IDXGIFactory4_Release(dxgiFactory);
return dxgiAdapter4;
}
ID3D12Device2* CreateDevice(IDXGIAdapter4* adapter)
{
ID3D12Device2* d3d12Device2;
ExitOnFailure(D3D12CreateDevice((IUnknown*)adapter, D3D_FEATURE_LEVEL_11_0, &IID_ID3D12Device2, &d3d12Device2));
// Enable debug messages in debug mode.
#if defined(_DEBUG)
ID3D12InfoQueue* pInfoQueue;
if (SUCCEEDED(ID3D12Device2_QueryInterface(d3d12Device2, &IID_ID3D12InfoQueue, &pInfoQueue)))
{
ID3D12InfoQueue_SetBreakOnSeverity(pInfoQueue, D3D12_MESSAGE_SEVERITY_CORRUPTION, TRUE);
ID3D12InfoQueue_SetBreakOnSeverity(pInfoQueue, D3D12_MESSAGE_SEVERITY_ERROR, TRUE);
ID3D12InfoQueue_SetBreakOnSeverity(pInfoQueue, D3D12_MESSAGE_SEVERITY_WARNING, FALSE);
// Suppress messages based on their severity level
D3D12_MESSAGE_SEVERITY Severities[] =
{
D3D12_MESSAGE_SEVERITY_INFO
};
// Suppress individual messages by their ID
D3D12_MESSAGE_ID DenyIds[] = {
D3D12_MESSAGE_ID_CLEARRENDERTARGETVIEW_MISMATCHINGCLEARVALUE,
D3D12_MESSAGE_ID_MAP_INVALID_NULLRANGE,
D3D12_MESSAGE_ID_UNMAP_INVALID_NULLRANGE,
};
D3D12_INFO_QUEUE_FILTER NewFilter = {0};
NewFilter.DenyList.NumSeverities = _countof(Severities);
NewFilter.DenyList.pSeverityList = Severities;
NewFilter.DenyList.NumIDs = _countof(DenyIds);
NewFilter.DenyList.pIDList = DenyIds;
ExitOnFailure(ID3D12InfoQueue_PushStorageFilter(pInfoQueue, &NewFilter));
}
#endif
ID3D12Object_SetName(d3d12Device2, L"Device2");
return d3d12Device2;
}
ID3D12CommandQueue* CreateCommandQueue(ID3D12Device2* device, D3D12_COMMAND_LIST_TYPE type)
{
ID3D12CommandQueue* d3d12CommandQueue;
D3D12_COMMAND_QUEUE_DESC desc = {0};
desc.Type = type;
desc.Priority = D3D12_COMMAND_QUEUE_PRIORITY_NORMAL;
desc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
desc.NodeMask = 0;
ExitOnFailure(ID3D12Device2_CreateCommandQueue(device, &desc, &IID_ID3D12CommandQueue, &d3d12CommandQueue));
ID3D12Object_SetName(d3d12CommandQueue, L"CommandQueue");
return d3d12CommandQueue;
}
IDXGISwapChain4* CreateSwapChain(HWND hWnd,
ID3D12CommandQueue* commandQueue,
uint32_t width, uint32_t height, uint32_t bufferCount )
{
IDXGISwapChain4* dxgiSwapChain4;
IDXGIFactory4* dxgiFactory4;
UINT createFactoryFlags = 0;
#if defined(_DEBUG)
createFactoryFlags = DXGI_CREATE_FACTORY_DEBUG;
#endif
ExitOnFailure(CreateDXGIFactory2(createFactoryFlags, &IID_IDXGIFactory4, &dxgiFactory4));
DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {
.Width = width,
.Height = height,
.Format = DXGI_FORMAT_R8G8B8A8_UNORM,
.Stereo = FALSE,
.SampleDesc = {
.Count = 1,
.Quality = 0,
},
.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT,
.BufferCount = bufferCount,
.Scaling = DXGI_SCALING_STRETCH,
.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD,
.AlphaMode = DXGI_ALPHA_MODE_UNSPECIFIED,
.Flags = 0
};
IDXGISwapChain1* swapChain1;
ExitOnFailure(IDXGIFactory4_CreateSwapChainForHwnd(dxgiFactory4,
(IUnknown*)commandQueue,
hWnd,
&swapChainDesc,
NULL,
NULL,
&swapChain1));
ExitOnFailure(IDXGIFactory4_MakeWindowAssociation(dxgiFactory4, hWnd, DXGI_MWA_NO_ALT_ENTER));
ExitOnFailure(IDXGISwapChain1_QueryInterface(swapChain1, &IID_IDXGISwapChain4, &dxgiSwapChain4));
IDXGIFactory4_Release(dxgiFactory4);
return dxgiSwapChain4;
}
ID3D12DescriptorHeap* CreateDescriptorHeap(ID3D12Device2* device,
D3D12_DESCRIPTOR_HEAP_TYPE type,
uint32_t numDescriptors)
{
ID3D12DescriptorHeap* descriptorHeap;
D3D12_DESCRIPTOR_HEAP_DESC desc = {0};
desc.NumDescriptors = numDescriptors;
desc.Type = type;
ExitOnFailure(ID3D12Device2_CreateDescriptorHeap(device, &desc, &IID_ID3D12DescriptorHeap, &descriptorHeap));
ID3D12Object_SetName(descriptorHeap, L"DescriptorHeap");
return descriptorHeap;
}
void UpdateRenderTargetViews(ID3D12Device2* device,
IDXGISwapChain4* swapChain, ID3D12DescriptorHeap* descriptorHeap)
{
D3D12_CPU_DESCRIPTOR_HANDLE rtvHandle;
ID3D12DescriptorHeap_GetCPUDescriptorHandleForHeapStart(descriptorHeap, &rtvHandle);
for (int i = 0; i < FRAMES_NUM; ++i)
{
ID3D12Resource* backBuffer;
ExitOnFailure(IDXGISwapChain4_GetBuffer(swapChain, i, &IID_ID3D12Resource, &backBuffer));
ID3D12Device2_CreateRenderTargetView(device, backBuffer, NULL, rtvHandle);
g_BackBuffers[i] = backBuffer;
rtvHandle.ptr += g_RTVDescriptorSize;
}
}
ID3D12CommandAllocator* CreateCommandAllocator(ID3D12Device2* device,
D3D12_COMMAND_LIST_TYPE type)
{
ID3D12CommandAllocator* commandAllocator;
ExitOnFailure(ID3D12Device2_CreateCommandAllocator(device, type,
&IID_ID3D12CommandAllocator,
&commandAllocator));
ID3D12Object_SetName(commandAllocator, L"Command Allocator");
return commandAllocator;
}
ID3D12GraphicsCommandList* CreateCommandList(ID3D12Device2* device,
ID3D12CommandAllocator* commandAllocator,
D3D12_COMMAND_LIST_TYPE type)
{
ID3D12GraphicsCommandList* commandList;
ExitOnFailure(ID3D12Device2_CreateCommandList(device, 0, type, commandAllocator, NULL, &IID_ID3D12CommandList, &commandList));
ExitOnFailure(ID3D12GraphicsCommandList_Close(commandList));
ID3D12Object_SetName(commandList, L"CommandList");
return commandList;
}
ID3D12Fence* CreateFence(ID3D12Device2* device)
{
// Reset fence values
memset(g_FrameFenceValues, 0, FRAMES_NUM * sizeof(uint64_t));
ID3D12Fence* fence;
ExitOnFailure(ID3D12Device2_CreateFence(device, 0, D3D12_FENCE_FLAG_NONE, &IID_ID3D12Fence, &fence));
ID3D12Object_SetName(fence, L"Fence");
return fence;
}
D3D12_RESOURCE_BARRIER D3D12_RESOURCE_BARRIER_Transition(
ID3D12Resource* pResource,
D3D12_RESOURCE_STATES stateBefore,
D3D12_RESOURCE_STATES stateAfter,
UINT subresource, // = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
D3D12_RESOURCE_BARRIER_FLAGS flags) // = D3D12_RESOURCE_BARRIER_FLAG_NONE
{
D3D12_RESOURCE_BARRIER barrier;
barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
barrier.Flags = flags;
barrier.Transition.pResource = pResource;
barrier.Transition.StateBefore = stateBefore;
barrier.Transition.StateAfter = stateAfter;
barrier.Transition.Subresource = subresource;
return barrier;
}
D3D12_CPU_DESCRIPTOR_HANDLE D3D12_CPU_DESCRIPTOR_HANDLE_Offset(
D3D12_CPU_DESCRIPTOR_HANDLE handle,
INT offsetInDescriptors,
UINT descriptorIncrementSize)
{
handle.ptr += offsetInDescriptors * descriptorIncrementSize;
return handle;
}
uint64_t Signal(ID3D12CommandQueue* commandQueue, ID3D12Fence* fence,
uint64_t* fenceValue)
{
(*fenceValue)++;
ExitOnFailure(ID3D12CommandQueue_Signal(commandQueue, fence, *fenceValue));
return *fenceValue;
}
HANDLE CreateEventHandle()
{
HANDLE fenceEvent;
fenceEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
assert(fenceEvent && "Failed to create fence event.");
return fenceEvent;
}
void WaitForFenceValue(ID3D12Fence* fence, uint64_t fenceValue, HANDLE fenceEvent, DWORD duration)
{
if (ID3D12Fence_GetCompletedValue(fence) < fenceValue)
{
ExitOnFailure(ID3D12Fence_SetEventOnCompletion(fence, fenceValue, fenceEvent));
WaitForSingleObject(fenceEvent, duration ? duration : INFINITE);
}
}
ID3DBlob* LoadShader(LPCWSTR path, LPCSTR target)
{
ID3DBlob* shaderBlob = NULL;
ID3DBlob* errorBlob = NULL;
UINT flags = D3DCOMPILE_DEBUG | D3DCOMPILE_DEBUG_NAME_FOR_SOURCE | D3DCOMPILE_PARTIAL_PRECISION | D3DCOMPILE_OPTIMIZATION_LEVEL3;
HRESULT hr = D3DCompileFromFile(path, NULL,
D3D_COMPILE_STANDARD_FILE_INCLUDE, "main", target, flags, 0, &shaderBlob, &errorBlob);
if (FAILED(hr))
{
if (errorBlob != NULL)
{
char* data = ID3DBlob_GetBufferPointer(errorBlob);
OutputDebugString(data);
ID3DBlob_Release(errorBlob);
exit(HD_EXIT_FAILURE);
}
else
{
OutputDebugString("Invalid shader path");
}
}
return shaderBlob;
}
// From d3dx12.h, converted to C
//------------------------------------------------------------------------------------------------
// D3D12 exports a new method for serializing root signatures in the Windows 10 Anniversary Update.
// To help enable root signature 1.1 features when they are available and not require maintaining
// two code paths for building root signatures, this helper method reconstructs a 1.0 signature when
// 1.1 is not supported.
inline HRESULT D3DX12SerializeVersionedRootSignature(
const D3D12_VERSIONED_ROOT_SIGNATURE_DESC* pRootSignatureDesc,
D3D_ROOT_SIGNATURE_VERSION MaxVersion,
ID3DBlob** ppBlob,
ID3DBlob** ppErrorBlob)
{
if (ppErrorBlob != NULL)
{
*ppErrorBlob = NULL;
}
switch (MaxVersion)
{
case D3D_ROOT_SIGNATURE_VERSION_1_0:
switch (pRootSignatureDesc->Version)
{
case D3D_ROOT_SIGNATURE_VERSION_1_0:
return D3D12SerializeRootSignature(&pRootSignatureDesc->Desc_1_0, D3D_ROOT_SIGNATURE_VERSION_1, ppBlob, ppErrorBlob);
case D3D_ROOT_SIGNATURE_VERSION_1_1:
{
HRESULT hr = S_OK;
const D3D12_ROOT_SIGNATURE_DESC1* desc_1_1 = &pRootSignatureDesc->Desc_1_1;
const SIZE_T ParametersSize = sizeof(D3D12_ROOT_PARAMETER) * desc_1_1->NumParameters;
void* pParameters = (ParametersSize > 0) ? HeapAlloc(GetProcessHeap(), 0, ParametersSize) : NULL;
if (ParametersSize > 0 && pParameters == NULL)
{
hr = E_OUTOFMEMORY;
}
D3D12_ROOT_PARAMETER* pParameters_1_0 = (D3D12_ROOT_PARAMETER*)pParameters;
if (SUCCEEDED(hr))
{
for (UINT n = 0; n < desc_1_1->NumParameters; n++)
{
pParameters_1_0[n].ParameterType = desc_1_1->pParameters[n].ParameterType;
pParameters_1_0[n].ShaderVisibility = desc_1_1->pParameters[n].ShaderVisibility;
switch (desc_1_1->pParameters[n].ParameterType)
{
case D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS:
pParameters_1_0[n].Constants.Num32BitValues = desc_1_1->pParameters[n].Constants.Num32BitValues;
pParameters_1_0[n].Constants.RegisterSpace = desc_1_1->pParameters[n].Constants.RegisterSpace;
pParameters_1_0[n].Constants.ShaderRegister = desc_1_1->pParameters[n].Constants.ShaderRegister;
break;
case D3D12_ROOT_PARAMETER_TYPE_CBV:
case D3D12_ROOT_PARAMETER_TYPE_SRV:
case D3D12_ROOT_PARAMETER_TYPE_UAV:
pParameters_1_0[n].Descriptor.RegisterSpace = desc_1_1->pParameters[n].Descriptor.RegisterSpace;
pParameters_1_0[n].Descriptor.ShaderRegister = desc_1_1->pParameters[n].Descriptor.ShaderRegister;
break;
case D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE:
const D3D12_ROOT_DESCRIPTOR_TABLE1* table_1_1 = &desc_1_1->pParameters[n].DescriptorTable;
const SIZE_T DescriptorRangesSize = sizeof(D3D12_DESCRIPTOR_RANGE) * table_1_1->NumDescriptorRanges;
void* pDescriptorRanges = (DescriptorRangesSize > 0 && SUCCEEDED(hr)) ? HeapAlloc(GetProcessHeap(), 0, DescriptorRangesSize) : NULL;
if (DescriptorRangesSize > 0 && pDescriptorRanges == NULL)
{
hr = E_OUTOFMEMORY;
}
D3D12_DESCRIPTOR_RANGE* pDescriptorRanges_1_0 = (D3D12_DESCRIPTOR_RANGE*)pDescriptorRanges;
if (SUCCEEDED(hr))
{
for (UINT x = 0; x < table_1_1->NumDescriptorRanges; x++)
{
pDescriptorRanges_1_0[x].BaseShaderRegister = table_1_1->pDescriptorRanges[x].BaseShaderRegister;
pDescriptorRanges_1_0[x].NumDescriptors = table_1_1->pDescriptorRanges[x].NumDescriptors;
pDescriptorRanges_1_0[x].OffsetInDescriptorsFromTableStart = table_1_1->pDescriptorRanges[x].OffsetInDescriptorsFromTableStart;
pDescriptorRanges_1_0[x].RangeType = table_1_1->pDescriptorRanges[x].RangeType;
pDescriptorRanges_1_0[x].RegisterSpace = table_1_1->pDescriptorRanges[x].RegisterSpace;
}
}
D3D12_ROOT_DESCRIPTOR_TABLE* table_1_0 = &pParameters_1_0[n].DescriptorTable;
table_1_0->NumDescriptorRanges = table_1_1->NumDescriptorRanges;
table_1_0->pDescriptorRanges = pDescriptorRanges_1_0;
}
}
}
if (SUCCEEDED(hr))
{
D3D12_ROOT_SIGNATURE_DESC desc_1_0;
desc_1_0.NumParameters = desc_1_1->NumParameters;
desc_1_0.pParameters = pParameters_1_0;
desc_1_0.NumStaticSamplers = desc_1_1->NumStaticSamplers;
desc_1_0.pStaticSamplers = desc_1_1->pStaticSamplers;
desc_1_0.Flags = desc_1_1->Flags;
hr = D3D12SerializeRootSignature(&desc_1_0, D3D_ROOT_SIGNATURE_VERSION_1, ppBlob, ppErrorBlob);
}
if (pParameters)
{
for (UINT n = 0; n < desc_1_1->NumParameters; n++)
{
if (desc_1_1->pParameters[n].ParameterType == D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE)
{
HeapFree(GetProcessHeap(), 0, (void*)((D3D12_DESCRIPTOR_RANGE*)(pParameters_1_0[n].DescriptorTable.pDescriptorRanges)));
}
}
HeapFree(GetProcessHeap(), 0, pParameters);
}
return hr;
}
}
break;
case D3D_ROOT_SIGNATURE_VERSION_1_1:
return D3D12SerializeVersionedRootSignature(pRootSignatureDesc, ppBlob, ppErrorBlob);
}
return E_INVALIDARG;
}
ID3D12RootSignature* CreateRootSignature(ID3D12Device2* device)
{
// Create a root signature.
D3D12_FEATURE_DATA_ROOT_SIGNATURE featureData = {0};
featureData.HighestVersion = D3D_ROOT_SIGNATURE_VERSION_1_1;
if (FAILED(ID3D12Device2_CheckFeatureSupport(device,
D3D12_FEATURE_ROOT_SIGNATURE, &featureData, sizeof(featureData))))
{
featureData.HighestVersion = D3D_ROOT_SIGNATURE_VERSION_1_0;
}
// Allow input layout and deny unnecessary access to certain pipeline stages.
D3D12_ROOT_SIGNATURE_FLAGS rootSignatureFlags =
D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT |
D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS |
D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS |
D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS |
D3D12_ROOT_SIGNATURE_FLAG_DENY_PIXEL_SHADER_ROOT_ACCESS;
D3D12_VERSIONED_ROOT_SIGNATURE_DESC rootSignatureDescription;
rootSignatureDescription.Version = D3D_ROOT_SIGNATURE_VERSION_1_1;
rootSignatureDescription.Desc_1_1.NumParameters = 0;
rootSignatureDescription.Desc_1_1.pParameters = NULL;
rootSignatureDescription.Desc_1_1.NumStaticSamplers = 0;
rootSignatureDescription.Desc_1_1.pStaticSamplers = NULL;
rootSignatureDescription.Desc_1_1.Flags = rootSignatureFlags;
// Serialize the root signature.
ID3DBlob* rootSignatureBlob;
ID3DBlob* errorBlob;
ExitOnFailure(D3DX12SerializeVersionedRootSignature(&rootSignatureDescription,
featureData.HighestVersion, &rootSignatureBlob, &errorBlob));
// Create the root signature.
ID3D12RootSignature* rootSignature;
ExitOnFailure(ID3D12Device2_CreateRootSignature(device, 0, ID3DBlob_GetBufferPointer(rootSignatureBlob),
ID3DBlob_GetBufferSize(rootSignatureBlob), &IID_ID3D12RootSignature, &rootSignature));
return rootSignature;
}
D3D12_SHADER_BYTECODE D3D12_SHADER_BYTECODE_Init(ID3DBlob* blob)
{
D3D12_SHADER_BYTECODE bytecode = {
.BytecodeLength = ID3DBlob_GetBufferSize(blob),
.pShaderBytecode = ID3DBlob_GetBufferPointer(blob)
};
return bytecode;
}
ID3D12PipelineState* CreatePipelineState(ID3D12Device2* device,
ID3D12RootSignature* rootSignature, ID3DBlob* vertexShaderBlob, ID3DBlob* pixelShaderBlob)
{
D3D12_SHADER_BYTECODE vertexShaderBytecode = D3D12_SHADER_BYTECODE_Init(vertexShaderBlob);
D3D12_SHADER_BYTECODE pixelShaderBytecode = D3D12_SHADER_BYTECODE_Init(pixelShaderBlob);
D3D12_GRAPHICS_PIPELINE_STATE_DESC pipelineStateDesc = {
.pRootSignature = rootSignature,
.InputLayout = { NULL, 0 },
.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
.RasterizerState = {
.DepthClipEnable = TRUE,
.FillMode = D3D12_FILL_MODE_SOLID,
.CullMode = D3D12_CULL_MODE_BACK
},
.VS = vertexShaderBytecode,
.PS = pixelShaderBytecode,
.DSVFormat = DXGI_FORMAT_D32_FLOAT,
.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM,
.NumRenderTargets = 1,
.SampleDesc = {
.Count = 1,
.Quality = 0
},
.DepthStencilState = {
.DepthEnable = TRUE,
.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL,
.DepthFunc = D3D12_COMPARISON_FUNC_LESS,
.StencilEnable = FALSE
},
.SampleMask = UINT_MAX,
.BlendState = {
.RenderTarget[0] = {
.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL
}
}
};
ID3D12PipelineState* pipelineState;
ID3D12Device2_CreateGraphicsPipelineState(device, &pipelineStateDesc, &IID_ID3D12PipelineState, &pipelineState);
return pipelineState;
}
void ResizeDepthBuffer(ID3D12Device2* device, int width, int height, ID3D12Resource** depthBuffer)
{
WaitForFenceValue(g_Fence, g_FenceValue, g_FenceEvent, 0);
width = MAX(1, width);
height = MAX(1, height);
// Resize screen dependent resources.
// Create a depth buffer.
D3D12_CLEAR_VALUE optimizedClearValue = {
.Color = { 0.0f, 0.0f, 0.0f, 0.0f },
.Format = DXGI_FORMAT_D32_FLOAT,
.DepthStencil = {
.Depth = 1.0f,
.Stencil = 0.0f
}
};
D3D12_HEAP_PROPERTIES heapProperties = {
.Type = D3D12_HEAP_TYPE_DEFAULT,
.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN,
.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN,
.CreationNodeMask = 1,
.VisibleNodeMask = 1
};
D3D12_RESOURCE_DESC resourceDesc = {
.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D,
.Alignment = 0,
.Width = width,
.Height = height,
.DepthOrArraySize = 1,
.MipLevels = 0,
.Format = DXGI_FORMAT_D32_FLOAT,
.SampleDesc = {
.Count = 1,
.Quality = 0
},
.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN,
.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL
};
if (*depthBuffer != NULL) ID3D12Resource_Release(*depthBuffer);
ExitOnFailure(ID3D12Device2_CreateCommittedResource(
device,
&heapProperties,
D3D12_HEAP_FLAG_NONE,
&resourceDesc,
D3D12_RESOURCE_STATE_DEPTH_WRITE,
&optimizedClearValue,
&IID_ID3D12Resource,
depthBuffer
));
// Update the depth-stencil view.
D3D12_DEPTH_STENCIL_VIEW_DESC dsv = {
.Format = DXGI_FORMAT_D32_FLOAT,
.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D,
.Texture2D.MipSlice = 0,
.Flags = D3D12_DSV_FLAG_NONE
};
D3D12_CPU_DESCRIPTOR_HANDLE descHandle = {0};
ID3D12DescriptorHeap_GetCPUDescriptorHandleForHeapStart(g_DSVDescriptorHeap, &descHandle);
ID3D12Device2_CreateDepthStencilView(device, *depthBuffer, &dsv, descHandle);
}
void Render(IDXGISwapChain4* swapChain, ID3D12CommandQueue* g_CommandQueue,
ID3D12GraphicsCommandList* commandList, ID3D12PipelineState* pipelineState,
ID3D12RootSignature* rootSignature, D3D12_VIEWPORT* viewport,
D3D12_RECT* scisssorRect)
{
ID3D12CommandAllocator* commandAllocator = g_CommandAllocators[g_CurrentBackBufferIndex];
ID3D12Resource* backBuffer = g_BackBuffers[g_CurrentBackBufferIndex];
ID3D12CommandAllocator_Reset(commandAllocator);
ID3D12GraphicsCommandList_Reset(commandList, commandAllocator, NULL);
D3D12_CPU_DESCRIPTOR_HANDLE rtv;
D3D12_CPU_DESCRIPTOR_HANDLE dsv;
ID3D12DescriptorHeap_GetCPUDescriptorHandleForHeapStart(g_DSVDescriptorHeap, &dsv);
// Clear the render target.
{
D3D12_RESOURCE_BARRIER barrier = D3D12_RESOURCE_BARRIER_Transition(backBuffer,
D3D12_RESOURCE_STATE_PRESENT,
D3D12_RESOURCE_STATE_RENDER_TARGET,
D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
D3D12_RESOURCE_BARRIER_FLAG_NONE);
ID3D12GraphicsCommandList_ResourceBarrier(commandList, 1, &barrier);
FLOAT clearColor[] = { 0.0f, 0.0f, 0.0f, 1.0f };
ID3D12DescriptorHeap_GetCPUDescriptorHandleForHeapStart(g_RTVDescriptorHeap, &rtv);
rtv = D3D12_CPU_DESCRIPTOR_HANDLE_Offset(rtv, g_CurrentBackBufferIndex, g_RTVDescriptorSize);
ID3D12GraphicsCommandList_ClearRenderTargetView(commandList, rtv, clearColor, 0, NULL);
ID3D12GraphicsCommandList_ClearDepthStencilView(commandList, dsv, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, NULL);
}
ID3D12GraphicsCommandList_SetPipelineState(commandList, pipelineState);
ID3D12GraphicsCommandList_SetGraphicsRootSignature(commandList, rootSignature);
ID3D12GraphicsCommandList_IASetPrimitiveTopology(commandList, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
ID3D12GraphicsCommandList_RSSetViewports(commandList, 1, viewport);
ID3D12GraphicsCommandList_RSSetScissorRects(commandList, 1, scisssorRect);
ID3D12GraphicsCommandList_OMSetRenderTargets(commandList, 1, &rtv, FALSE, &dsv);
ID3D12GraphicsCommandList_DrawInstanced(commandList, 3, 1, 0, 0);
// Present
{
D3D12_RESOURCE_BARRIER barrier = D3D12_RESOURCE_BARRIER_Transition(backBuffer,
D3D12_RESOURCE_STATE_RENDER_TARGET,
D3D12_RESOURCE_STATE_PRESENT,
D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
D3D12_RESOURCE_BARRIER_FLAG_NONE);
ID3D12GraphicsCommandList_ResourceBarrier(commandList, 1, &barrier);
ExitOnFailure(ID3D12GraphicsCommandList_Close(commandList));
ID3D12CommandList* const commandLists[] = { (ID3D12CommandList* const)commandList };
ID3D12CommandQueue_ExecuteCommandLists(g_CommandQueue, _countof(commandLists), commandLists);
g_FrameFenceValues[g_CurrentBackBufferIndex] = Signal(g_CommandQueue, g_Fence, &g_FenceValue);
UINT syncInterval = 1;
UINT presentFlags = 0;
ExitOnFailure(IDXGISwapChain4_Present(swapChain, syncInterval, presentFlags));
g_CurrentBackBufferIndex = IDXGISwapChain4_GetCurrentBackBufferIndex(swapChain);
WaitForFenceValue(g_Fence, g_FrameFenceValues[g_CurrentBackBufferIndex], g_FenceEvent, 0);
}
}
void Flush(ID3D12CommandQueue* commandQueue, ID3D12Fence* fence,
uint64_t* fenceValue, HANDLE fenceEvent)
{
uint64_t fenceValueForSignal = Signal(commandQueue, fence, fenceValue);
WaitForFenceValue(fence, fenceValueForSignal, fenceEvent, 0);
}
void ResizeSwapchain(int width, int height)
{
width = MAX(1, width);
height = MAX(1, height);
Flush(g_CommandQueue, g_Fence, &g_FenceValue, g_FenceEvent);
for (int i = 0; i < FRAMES_NUM; ++i)
{
ID3D12Resource_Release(g_BackBuffers[i]);
}
DXGI_SWAP_CHAIN_DESC swapChainDesc = {0};
ExitOnFailure(IDXGISwapChain4_GetDesc(g_SwapChain, &swapChainDesc));
ExitOnFailure(IDXGISwapChain4_ResizeBuffers(g_SwapChain, FRAMES_NUM, width, height, swapChainDesc.BufferDesc.Format, swapChainDesc.Flags));
g_CurrentBackBufferIndex = IDXGISwapChain4_GetCurrentBackBufferIndex(g_SwapChain);
UpdateRenderTargetViews(g_Device, g_SwapChain, g_RTVDescriptorHeap);
}
static int Resize(void* data, SDL_Event* event)
{
if (event->type != SDL_WINDOWEVENT ||
event->window.event != SDL_WINDOWEVENT_RESIZED)
return 1;
SDL_Window* window = SDL_GetWindowFromID(event->window.windowID);
if (window != (SDL_Window*)data)
return 2;
int width, height;
SDL_GetWindowSize(window, &width, &height);
ResizeData* resizeData = SDL_GetWindowData(window, "resize");
resizeData->viewport->Width = (float)width;
resizeData->viewport->Height = (float)height;
ResizeSwapchain(width, height);
ResizeDepthBuffer(resizeData->device, width, height, resizeData->depthBuffer);
return 0;
}
int InitRenderer(SDL_Window* window)
{
#ifdef _DEBUG
EnableDebuggingLayer();
#endif
g_ResizeData;
int width, height;
SDL_GetWindowSize(window, &width, &height);
SDL_SetWindowData(window, "resize", (void*)&g_ResizeData);
SDL_AddEventWatch(Resize, window);
SDL_SysWMinfo wmInfo;
SDL_VERSION(&wmInfo.version);
SDL_GetWindowWMInfo(window, &wmInfo);
HWND hwnd = wmInfo.info.win.window;
IDXGIAdapter4* dxgiAdapter4 = GetAdapter();
g_Device = CreateDevice(dxgiAdapter4);
g_CommandQueue = CreateCommandQueue(g_Device, D3D12_COMMAND_LIST_TYPE_DIRECT);
g_SwapChain = CreateSwapChain(hwnd,
g_CommandQueue, width, height,
FRAMES_NUM);
g_CurrentBackBufferIndex = IDXGISwapChain4_GetCurrentBackBufferIndex(g_SwapChain);
g_RTVDescriptorHeap = CreateDescriptorHeap(g_Device, D3D12_DESCRIPTOR_HEAP_TYPE_RTV, FRAMES_NUM);
g_DSVDescriptorHeap = CreateDescriptorHeap(g_Device, D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1);
g_RTVDescriptorSize = ID3D12Device2_GetDescriptorHandleIncrementSize(g_Device, D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
UpdateRenderTargetViews(g_Device, g_SwapChain, g_RTVDescriptorHeap);
for (int i = 0; i < FRAMES_NUM; ++i)
{
g_CommandAllocators[i] = CreateCommandAllocator(g_Device, D3D12_COMMAND_LIST_TYPE_DIRECT);
}
g_CommandList = CreateCommandList(g_Device,
g_CommandAllocators[g_CurrentBackBufferIndex], D3D12_COMMAND_LIST_TYPE_DIRECT);
g_Fence = CreateFence(g_Device);
g_FenceEvent = CreateEventHandle();
// Load the vertex shader.
ID3DBlob* vertexShaderBlob = LoadShader(L"shaders/vertex.hlsl", "vs_5_1");
// Load the pixel shader.
ID3DBlob* pixelShaderBlob = LoadShader(L"shaders/pixel.hlsl", "ps_5_1");
// Create depth buffer
g_DepthBuffer = NULL;
ResizeDepthBuffer(g_Device, width, height, &g_DepthBuffer);
// Root signature
g_RootSignature = CreateRootSignature(g_Device);
// Pipeline state object.
g_PipelineState = CreatePipelineState(g_Device, g_RootSignature, vertexShaderBlob, pixelShaderBlob);
D3D12_VIEWPORT viewport = { 0.0f, 0.0f, (float)width, (float)height, D3D12_MIN_DEPTH, D3D12_MAX_DEPTH };
g_Viewport = viewport;
D3D12_RECT scissors = { 0, 0, LONG_MAX, LONG_MAX };
g_ScissorRect = scissors;
g_ResizeData.device = g_Device;
g_ResizeData.depthBuffer = &g_DepthBuffer;
g_ResizeData.viewport = &g_Viewport;
g_ResizeData.fov = 45.0f;
IDXGIAdapter4_Release(dxgiAdapter4);
ID3DBlob_Release(vertexShaderBlob);
ID3DBlob_Release(pixelShaderBlob);
}
static void RendererUpdate()
{
Render(g_SwapChain, g_CommandQueue, g_CommandList, g_PipelineState,
g_RootSignature, &g_Viewport, &g_ScissorRect);
}
static void RendererClose()
{
// Make sure the command queue has finished all commands before closing.
Flush(g_CommandQueue, g_Fence, &g_FenceValue, g_FenceEvent);
CloseHandle(g_FenceEvent);
ID3D12Resource_Release(g_DepthBuffer);
ID3D12PipelineState_Release(g_PipelineState);
ID3D12RootSignature_Release(g_RootSignature);
ID3D12Fence_Release(g_Fence);
ID3D12GraphicsCommandList_Release(g_CommandList);
for (int i = 0; i < FRAMES_NUM; ++i)
{
ID3D12CommandAllocator_Release(g_CommandAllocators[i]);
}
ID3D12DescriptorHeap_Release(g_DSVDescriptorHeap);
ID3D12DescriptorHeap_Release(g_RTVDescriptorHeap);
IDXGISwapChain4_Release(g_SwapChain);
IDXGISwapChain4_Release(g_SwapChain);
IDXGISwapChain4_Release(g_SwapChain);
ID3D12CommandQueue_Release(g_CommandQueue);
ID3D12Device2_Release(g_Device);
ID3D12Device2_Release(g_Device);
#ifdef _DEBUG
REPORT_LIVE_OBJ();
#endif
}
int main()
{
SDL_Init(SDL_INIT_VIDEO);
SDL_Window* window = SDL_CreateWindow("D3D12 - Hello Triangle", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, SDL_WINDOW_RESIZABLE);
// Check that the window was successfully created
if (window == NULL) {
// In the case that the window could not be made...
SDL_LogCritical(SDL_LOG_CATEGORY_ERROR, "Could not create window: %s\n", SDL_GetError());
return 1;
}
InitRenderer(window);
while (1)
{
SDL_Event e;
while (SDL_PollEvent(&e) > 0)
{
if (e.type == SDL_QUIT)
goto quit;
}
RendererUpdate();
}
quit:
RendererClose();
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
} | 38.203226 | 167 | 0.668721 | [
"render",
"object"
] |
afd25d157e3f34caf21d1cce84fe7fbe50de1c01 | 2,066 | h | C | copasi/plotUI/C2DCurveData.h | tobiaselsaesser/COPASI | 7e61c1b1667b0f4acf8f3865fe557603f221c472 | [
"Artistic-2.0"
] | null | null | null | copasi/plotUI/C2DCurveData.h | tobiaselsaesser/COPASI | 7e61c1b1667b0f4acf8f3865fe557603f221c472 | [
"Artistic-2.0"
] | null | null | null | copasi/plotUI/C2DCurveData.h | tobiaselsaesser/COPASI | 7e61c1b1667b0f4acf8f3865fe557603f221c472 | [
"Artistic-2.0"
] | null | null | null | // Copyright (C) 2017 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and University of
// of Connecticut School of Medicine.
// All rights reserved.
// Copyright (C) 2015 - 2016 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.
#ifndef C2DCURVEDATA_H
#define C2DCURVEDATA_H
#include <string>
#include <vector>
#include <fstream>
#include <iostream>
#include <QPainter>
#include <QtCore/QMutex>
#include <QtCore/QWaitCondition>
#include <QRectF>
#include <qwt_plot.h>
#include <qwt_painter.h>
#if QWT_VERSION > 0x060000
#include <qwt_compat.h>
#else
#include <qwt_data.h>
#include <qwt_raster_data.h>
#endif
#include <qwt_plot_curve.h>
#include <qwt_plot_spectrogram.h>
#include "plot/CPlotItem.h"
#include "copasi/core/CDataObject.h"
#include "output/COutputHandler.h"
#include "utilities/CopasiTime.h"
#include "copasi/core/CVector.h"
#include "copasi/core/CMatrix.h"
// NaN are ignored bounding rectangle
class C2DCurveData :
#if QWT_VERSION > 0x060000
public QwtSeriesData<QPointF>
#else
public QwtData
#endif
{
public:
C2DCurveData();
C2DCurveData(const CVector< double > & x, const CVector< double > & y, size_t size);
virtual ~C2DCurveData();
#if QWT_VERSION > 0x060000
virtual QwtSeriesData<QPointF> *copy() const;
virtual QPointF sample(size_t i) const;
#else
virtual QwtData *copy() const;
#endif
virtual QwtDoubleRect boundingRect() const;
virtual size_t size() const;
virtual double x(size_t i) const;
virtual double y(size_t i) const;
void setSize(const size_t & size);
void reallocated(const CVector< double > * pX, const CVector< double > * pY);
protected:
C2DCurveData &operator = (const C2DCurveData & rhs);
private:
const double * mpX;
const double * mpY;
size_t mSize;
size_t mMaxSize;
mutable size_t mLastRectangle;
mutable double mMinX;
mutable double mMaxX;
mutable double mMinY;
mutable double mMaxY;
};
#endif // C2DCURVEDATA_H
| 21.978723 | 86 | 0.741045 | [
"vector"
] |
afd51d91852394e3a6a9dc82f449e846e412376d | 5,034 | h | C | 058/route.h | Ponz-Tofu-N/ModernCppChallengePractice | c2003fc180fc28448a3ff5b3e0f0c2788154af8c | [
"MIT"
] | null | null | null | 058/route.h | Ponz-Tofu-N/ModernCppChallengePractice | c2003fc180fc28448a3ff5b3e0f0c2788154af8c | [
"MIT"
] | null | null | null | 058/route.h | Ponz-Tofu-N/ModernCppChallengePractice | c2003fc180fc28448a3ff5b3e0f0c2788154af8c | [
"MIT"
] | null | null | null | #include <iostream>
#include <map>
#include <vector>
#include <algorithm>
#include <limits>
#include <queue>
#include <functional>
class Node
{
using Node_ptr = Node *;
private:
std::string m_name;
std::vector<std::pair<Node_ptr, size_t>> m_dest;
public:
Node(/* args */){};
Node(std::string const &_name)
: m_name(_name){};
Node(std::string const &_name, std::vector<std::pair<Node_ptr, size_t>> _dest)
: m_name(_name), m_dest(_dest){};
~Node(){};
std::string name() { return m_name; }
std::vector<Node_ptr> dest()
{
std::vector<Node_ptr> res;
for (auto &&dest : m_dest)
res.push_back(dest.first);
return res;
}
std::size_t weight;
};
class Route
{
using Node_ptr = Node *;
std::map<Node_ptr, std::vector<std::pair<Node_ptr, size_t>>> adjacent_nodes;
std::vector<Node_ptr> nodes;
void clear_nodes()
{
for (auto &&node : nodes)
{
node->weight = std::numeric_limits<std::size_t>::max();
}
}
public:
~Route()
{
for (auto &&node : nodes)
{
delete node;
}
}
void add_node(std::string const &src, std::string const &dest, size_t const weight) // "A", "B", 7
{
if (std::find_if(nodes.begin(), nodes.end(), [&](Node_ptr node)
{ return node->name() == src; }) == nodes.end())
nodes.push_back(new Node(src));
if (std::find_if(nodes.begin(), nodes.end(), [&](Node_ptr node)
{ return node->name() == dest; }) == nodes.end())
nodes.push_back(new Node(dest));
auto src_itr = std::find_if(nodes.begin(), nodes.end(), [&](Node_ptr node)
{ return node->name() == src; });
auto dest_itr = std::find_if(nodes.begin(), nodes.end(), [&](Node_ptr node)
{ return node->name() == dest; });
adjacent_nodes[*src_itr].push_back(std::make_pair(*dest_itr, weight));
adjacent_nodes[*dest_itr].push_back(std::make_pair(*src_itr, weight));
}
void dijkstra(std::string const &start)
{
//0. 初期化
clear_nodes();
// 1. 起点集合を定義
std::vector<Node_ptr> start_set;
// 1.5. 起点のweightは0
auto start_itr = std::find_if(nodes.begin(), nodes.end(), [&](Node_ptr node)
{
if(node->name() == start)
{
node->weight = 0;
return true;
}
return false; });
start_set.push_back(*start_itr);
// 4. 起点集合 == 全ノード集合でなければ、2から繰り返す
while (start_set.size() != nodes.size())
{
std::priority_queue<Node_ptr,
std::vector<Node_ptr>,
std::function<bool(const Node_ptr, const Node_ptr)>>
que([&](const Node_ptr node1, const Node_ptr node2) -> bool
{ return node1->weight > node2->weight; });
// 2. 起点集合から伸びるノードのうち、起点集合に無い全てのノードの重みを計算
// 双方向に対応するためには何が必要?
// source -> targetのMapと、target -> sourceのMapがいる?
for (auto &&start_node : start_set)
{
for (auto &&target : adjacent_nodes[start_node])
{
// 起点集合に対象ノードが見つかったら、スキップする。
if (std::find(start_set.begin(), start_set.end(), target.first) != start_set.end())
continue;
// 既にある重みより計算結果が小さければ更新。
if (target.first->weight > (target.second + start_node->weight))
target.first->weight = target.second + start_node->weight;
que.push(target.first);
}
}
// 3. 3で選択したノードを起点集合へ移動
start_set.push_back(que.top());
}
}
std::vector<Node_ptr> shortest_path(std::string const &start, std::string const &goal)
{
this->dijkstra(start);
// 5. ゴールから逆にたどっていって最終結果をreturn
std::vector<Node_ptr> res;
Node_ptr on_path = *std::find_if(nodes.begin(), nodes.end(), [&](Node_ptr node)
{ return node->name() == goal; });
res.insert(res.begin(), on_path);
while (on_path->name() != start)
{
on_path = (*std::find_if(adjacent_nodes[on_path].begin(), adjacent_nodes[on_path].end(), [&](auto target_pair)
{
auto target = target_pair.first;
auto cost = target_pair.second;
return (target->weight + cost) == on_path->weight; }))
.first;
res.insert(res.begin(), on_path);
}
return res;
}
};
| 31.267081 | 122 | 0.485499 | [
"vector"
] |
4b4f13bae13c64aebb5ca365503ac024d97a425a | 5,345 | h | C | src/db/timing/spef/spef_reader.h | lbz007/rectanglequery | 59d6eb007bf65480fa3e9245542d0b6071f81831 | [
"BSD-3-Clause"
] | null | null | null | src/db/timing/spef/spef_reader.h | lbz007/rectanglequery | 59d6eb007bf65480fa3e9245542d0b6071f81831 | [
"BSD-3-Clause"
] | null | null | null | src/db/timing/spef/spef_reader.h | lbz007/rectanglequery | 59d6eb007bf65480fa3e9245542d0b6071f81831 | [
"BSD-3-Clause"
] | null | null | null | /**
* @file spef_reader.h
* @date 2020-11-02
* @brief
*
* Copyright (C) 2020 NIIC EDA
*
* All rights reserved.
*
* This software may be modified and distributed under the terms
*
* of the BSD license. See the LICENSE file for details.
*/
#ifndef EDI_DB_TIMING_SPEF_SPEF_READER_H_
#define EDI_DB_TIMING_SPEF_SPEF_READER_H_
#include <algorithm>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <map>
#include <utility>
#include <vector>
#include <ctype.h>
#include <iostream>
#include "stdlib.h"
#include "db/core/object.h"
#include "db/util/array.h"
#include "util/data_traits.h"
#include "db/timing/spef/design_parasitics.h"
#include "db/timing/spef/nets_parasitics.h"
namespace open_edi {
namespace db {
class DesignParasitics;
class NetsParasitics;
}
}
using namespace open_edi::db;
namespace SpefReader {
enum class ReaderStage : uint8_t {
ReadingNameMap = 0x1,
ReadingNet
};
typedef std::vector<const char*> StringVec;
class SpefReader {
public:
SpefReader(std::string fileName, DesignParasitics *designParasitics);
~SpefReader();
void stringDelete(const char *str) const;
void recordChar(const char ch) { record_str_ += ch; }
const char* getRecordStr() { return stringCopy(record_str_.c_str()); }
void clearRecordStr() { record_str_.clear(); }
const char* stringCopy(const char *str);
bool isDigits(const char *str) const;
Cell* getCell() const { return cell_; }
void setCell(const char *designName);
void addDesignNetsParasitics();
void setDivider(const char divider) { if (nets_parasitics_) nets_parasitics_->setDivider(divider); }
void setDelimiter(const char delimiter) { delimiter_ = delimiter; if (nets_parasitics_) nets_parasitics_->setDelimiter(delimiter); }
void setPreBusDel(const char prebusdel) { if (nets_parasitics_) nets_parasitics_->setPreBusDel(prebusdel); }
void setSufBusDel(const char sufbusdel) { if (nets_parasitics_) nets_parasitics_->setSufBusDel(sufbusdel); }
void setTimeScale(float digits, const char *unit);
void setCapScale(float digits, const char *unit);
void setResScale(float digits, const char *unit);
void setInductScale(float digits, const char *unit);
void setDesignFlow(StringVec *dsgFlow);
void addNameMap(const char *index, const char *name);
SymbolIndex getNameMap(uint32_t idx) const;
void addPort(const char *name);
float addParValue(float value1) { par_value_ = value1; return par_value_; }
float addParValue(float value1, float value2, float value3);
Net* findNet(const char *name) const;
Net* findNet(const std::string &name) const;
Pin* findPin(const char *name) const;
void addDNetBegin(Net *net);
void addDNetEnd();
NodeID getOrCreateParasiticNode(const std::string &node_name, float cap = DUMMY_CAP,
float coordinate_x = DUMMY_COORDINATE,
float coordinate_y = DUMMY_COORDINATE);
std::tuple<Net*, NodeID> getParasiticExtNode(const std::string &node_name);
void addGroundCap(const char *nodeName);
void addCouplingCap(const char *nodeName1, const char *nodeName2);
void addResistor(const char *nodeName1, const char *nodeName2);
void addRNetBegin(Net *net);
void addRNetDrvr(const char *pinName);
void addPiModel(float c2, float r1, float c1);
void addRNetEnd() { net_ = nullptr; rnet_parasitics_ = nullptr; }
void setSpefField(uint8_t spefFiled) { spef_field_ = spefFiled; }
uint8_t getSpefField() const { return spef_field_; }
void incrLineNo() { line_no_++; }
uint32_t getLineNo() const { return line_no_; }
std::string getSpefFile() const { return spef_file_name_; }
bool parseSpefFile();
bool isExtendedSpef() const { return is_extended_spef_; }
void setExtendedSpef(bool is_extended) { is_extended_spef_ = is_extended;}
void setCoordinate(float x, float y);
void addParasiticNodeCoordinate(const char *pin_name);
private:
void __spef_parse_begin(FILE *fp);
void __spef_parse_end(FILE *fp);
int __spef_parse();
NodeStrIdMap node_id_map_; //use to check if node created for current net
// std::unordered_map<std::string, NodeID> node_index_map_; //use to check if node created for net
ExtNodeStrIdMap ext_node_id_map_;
PinIdMap pin_id_map_;
NetParaMap net_para_map_;
bool is_name_index_continuous_;
uint32_t name_index_shift_;
// !Because NAME_MAP is not guaranteed to be continuous, we have to use unordered_map to handle
std::unordered_map<uint32_t, SymbolIndex> name_hash_map_;
// !Assume name id is continuous first. If not, convert to unordered_map
std::vector<SymbolIndex> name_map_;
DesignParasitics *design_parasitics_;
NetsParasitics *nets_parasitics_;
DNetParasitics *dnet_parasitics_;
RNetParasitics *rnet_parasitics_;
Cell *cell_;
Net *net_;
void *scanner_;
std::string spef_file_name_;
std::string record_str_;
float par_value_;
uint32_t line_no_;
uint8_t spef_field_;
char delimiter_;
Monitor monitor_;
std::unordered_set<Net*> net_set_;
ReaderStage stage_;
bool is_extended_spef_;
float coordinate_x_;
float coordinate_y_;
};
} // namespace SpefReader
#endif // EDI_DB_TIMING_SPEF_SPEF_READER_H_
| 35.872483 | 136 | 0.721796 | [
"object",
"vector"
] |
4b51dc6af33976b66e2fdf584147368f6e834302 | 642 | h | C | EditorLib/Controls/VectorEdit.h | elix22/UrhoEditor | 8b2578610b21e60f4126e351a1c7e01d639be695 | [
"MIT"
] | 23 | 2017-06-14T02:22:10.000Z | 2021-11-25T05:09:21.000Z | EditorLib/Controls/VectorEdit.h | elix22/UrhoEditor | 8b2578610b21e60f4126e351a1c7e01d639be695 | [
"MIT"
] | null | null | null | EditorLib/Controls/VectorEdit.h | elix22/UrhoEditor | 8b2578610b21e60f4126e351a1c7e01d639be695 | [
"MIT"
] | 22 | 2017-06-15T12:09:23.000Z | 2021-01-02T13:05:15.000Z | #pragma once
#include <QWidget>
#include <QSpinBox>
namespace SprueEditor
{
class VectorEdit : public QWidget
{
Q_OBJECT;
public:
VectorEdit(bool integral, const char* xName, const char* yName = 0x0, const char* zName = 0x0, const char* wName = 0x0);
virtual ~VectorEdit();
void SetValue(float* data, int ct);
void SetValue(int* data, int ct);
signals:
void FloatValueChange(int index, float value);
void IntValueChange(int index, int value);
private:
std::vector<QSpinBox*> intSpinners_;
std::vector<QDoubleSpinBox*> doubleSpinners_;
};
} | 22.928571 | 128 | 0.635514 | [
"vector"
] |
4b57df4b1e42baf87c7b406df71c73640591c4c7 | 6,863 | h | C | include/gat/gat_types.h | bal-chettri/gat | 1fd6a6c55d466c61204ff5ed64dde14c47ff2361 | [
"MIT"
] | null | null | null | include/gat/gat_types.h | bal-chettri/gat | 1fd6a6c55d466c61204ff5ed64dde14c47ff2361 | [
"MIT"
] | null | null | null | include/gat/gat_types.h | bal-chettri/gat | 1fd6a6c55d466c61204ff5ed64dde14c47ff2361 | [
"MIT"
] | null | null | null | /*
* Copyright 2017, Bal Chettri
*
* 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 __gat_types_h__
#define __gat_types_h__
#include <stdio.h>
/* define fixed size types for cross platform compatibility */
#ifdef WIN32
/* basic int types */
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
typedef unsigned long uint32_t;
#else
# include <stdint.h>
#endif
typedef char * gat_char;
/* define gat version */
#define GAT_VERSION "0.0.1"
/* define token types */
#define GAT_EQU 0
#define GAT_ORG 1
#define GAT_END 2
#define GAT_LABEL 3
/* define constants */
#define GAT_WHITE "\r\n\f\t\v "
#define GAT_SYMBOLS "~~!@#$%^&*()+-={}[]:\";'<>?,./|\\"
#define GAT_COMMENT_CHAR ';'
#define GAT_MAX_IO 5
#define GAT_MAX_IDS 1000
#define GAT_MAX_LABELS GAT_MAX_IDS
#define GAT_MAX_TOKENS 4
#define GAT_MAX_TOKEN_LEN 16
#define GAT_MAX_MNEMONIC_LEN 4
#define GAT_MAX_ID_LEN 16
#define GAT_MAX_PATH 255
#define GAT_MAX_LINEBUFF_SIZE 255
#define GAT_MAX_ERRORS 100
#define GAT_MAX_BYTE 0xFF
#define GAT_MAX_DBL 0xFFFF
#define \
GAT_MAX_NUMERIC_TOKEN_LENGTH 6
#define GAT_OPRND_REG8 1
#define GAT_OPRND_REG16 2
#define GAT_OPRND_BYTE 3
#define GAT_OPRND_DBL 4
#define GAT_OPRND_SYMBOL 5
#define GAT_OPRND_INVALID 0xFF
#define GAT_IDTYPE_BYTE 3
#define GAT_IDTYPE_DBL 4
/* constants for Intel HEX file format */
#define INTEL_HEX_RECTYPE_DATA 0
#define INTEL_HEX_RECTYPE_EOF 1
#define INTEL_MAX_HEX_RECSIZE 16
/* define bit mask for command line switches */
#define GAT_NUM_SWITCHES 5
#define GAT_CMDLN_SWITCH '-'
/* gat assembler */
struct _gat;
/* enum _gat_token_type */
typedef enum _gat_token_type {
GAT_TOK_INVALID,
GAT_TOK_WORD,
GAT_TOK_SYMBOL,
GAT_TOK_WHITE,
GAT_TOK_STRING
}gat_token_type; /* enum gat_token_type */
typedef enum _gat_callback_type {
GAT_CALLBACK_TEXT,
GAT_CALLBACK_ERROR
}gat_callback_type;
/* gat_callback type */
typedef void (*gat_callback) \
(struct _gat *ga, gat_callback_type type, void *data, void *ctx);
struct _gat_io;
typedef enum _gat_emitter_state {
GAT_EMIT_BEGIN_ASSEMBLY,
GAT_EMIT_END_ASSEMBLY,
GAT_EMIT_SET_ORG,
GAT_EMIT_CODE
}gat_emitter_state;
/* gat_emitter type */
typedef void (*gat_emitter) \
(struct _gat *, struct _gat_io *, gat_emitter_state);
/* define structure types */
/* io structure */
typedef struct _gat_io {
char mode[4];
char path[GAT_MAX_PATH];
FILE *fp;
gat_emitter emitter;
}gat_io;
/* error info structure */
typedef struct _gat_error_info {
int errno; /* error no */
uint8_t warning; /* is warning? */
uint8_t fatal; /* fatal error? */
char *desc; /* error description */
char *file; /* source/object file path */
int line; /* line no */
int col; /* col no */
}gat_error_info;
/* cmd line structure */
typedef struct _gat_cmdline {
unsigned count;
char **args;
}gat_cmdline;
/* LABEL */
typedef struct _gat_label {
char name [GAT_MAX_ID_LEN + 1];
uint16_t address;
}gat_label;
/* ID */
typedef struct _gat_id {
char name [GAT_MAX_ID_LEN + 1];
uint16_t data;
uint8_t idtype;
/* uint8_t assumed; */
}gat_id;
/* directive */
typedef struct _gat_dir {
uint8_t token;
char *command;
uint8_t token_index;
uint8_t num_tokens;
}gat_dirt;
/* INSTR */
typedef struct _gat_instr {
char mnemonic [GAT_MAX_MNEMONIC_LEN + 1]; /* mnemonic */
uint8_t opcode; /* preliminary opcode */
uint8_t num_tokens; /* number of tokens including mnemonic */
uint8_t type_operands[3];
uint8_t type_options[3];
}gat_instr;
/* Intel HEX record */
typedef struct _INTEL_HEX_RECORD {
char header;
uint8_t length;
uint16_t offset;
uint8_t type;
}INTEL_HEX_RECORD;
/* struct gat_token */
typedef struct _gat_token {
char *string; /* pointer to actual string */
size_t length; /* length of string */
gat_token_type type; /* type of token */
}gat_token;
/* gat arch interface */
typedef struct _gat_arch {
int (* is_reg8) (const char *);
int (* is_reg16) (const char *);
int (* is_reg32) (const char *);
uint8_t (* creg8) (const char *);
uint8_t (* creg16) (const char *);
uint8_t (* creg32) (const char *);
int (* filter) (struct _gat *);
void (* get_code_size) (struct _gat *, const gat_instr *);
void (* gen_code) (struct _gat *, const gat_instr *);
}gat_arch;
/* gat */
typedef struct _gat {
gat_callback callback;
void *context;
gat_arch *arch;
int fatal_error;
unsigned num_ids;
gat_id arr_ids[GAT_MAX_IDS];
unsigned num_labels ;
gat_label arr_labels[GAT_MAX_LABELS];
gat_io ios [GAT_MAX_IO];
unsigned num_ios;
unsigned pass;
unsigned err_count;
unsigned warn_count;
uint32_t line_num;
uint32_t org;
uint32_t offset;
uint32_t size;
char str_line [GAT_MAX_LINEBUFF_SIZE + 1];
unsigned num_tokens;
char *arr_tokens [GAT_MAX_TOKENS];
gat_token arr_raw_tokens [GAT_MAX_TOKENS];
uint16_t arr_cooked_tokens [GAT_MAX_TOKENS];
uint8_t bin[3];
unsigned bin_size;
unsigned long cmdline_flags;
uint16_t rec_length;
uint32_t offset_hexrec;
uint8_t checksum;
gat_dirt *dirt_table;
unsigned len_dirt_table;
gat_instr *instr_table;
unsigned len_instr_table;
}gat;
#endif /* !__gat_types_h__ */
| 28.359504 | 107 | 0.660207 | [
"object"
] |
4b5b0d241acdc02b41bab4b7349d304afd469480 | 7,611 | h | C | chrome/browser/ui/android/autofill/autofill_dialog_view_android.h | hujiajie/pa-chromium | 1816ff80336a6efd1616f9e936880af460b1e105 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2020-05-03T06:33:56.000Z | 2021-11-14T18:39:42.000Z | chrome/browser/ui/android/autofill/autofill_dialog_view_android.h | hujiajie/pa-chromium | 1816ff80336a6efd1616f9e936880af460b1e105 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/ui/android/autofill/autofill_dialog_view_android.h | hujiajie/pa-chromium | 1816ff80336a6efd1616f9e936880af460b1e105 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2013 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 CHROME_BROWSER_UI_ANDROID_AUTOFILL_AUTOFILL_DIALOG_VIEW_ANDROID_H_
#define CHROME_BROWSER_UI_ANDROID_AUTOFILL_AUTOFILL_DIALOG_VIEW_ANDROID_H_
#include <jni.h>
#include "base/android/jni_string.h"
#include "base/android/scoped_java_ref.h"
#include "chrome/browser/ui/autofill/autofill_dialog_controller.h"
#include "chrome/browser/ui/autofill/autofill_dialog_view.h"
namespace autofill {
// Android implementation of the Autofill dialog that handles the imperative
// autocomplete API call.
class AutofillDialogViewAndroid : public AutofillDialogView {
public:
explicit AutofillDialogViewAndroid(AutofillDialogController* controller);
virtual ~AutofillDialogViewAndroid();
// AutofillDialogView implementation:
virtual void Show() OVERRIDE;
virtual void Hide() OVERRIDE;
virtual void UpdateNotificationArea() OVERRIDE;
virtual void UpdateAccountChooser() OVERRIDE;
virtual void UpdateButtonStrip() OVERRIDE;
virtual void UpdateDetailArea() OVERRIDE;
virtual void UpdateForErrors() OVERRIDE;
virtual void UpdateSection(DialogSection section) OVERRIDE;
virtual void FillSection(DialogSection section,
const DetailInput& originating_input) OVERRIDE;
virtual void GetUserInput(DialogSection section,
DetailOutputMap* output) OVERRIDE;
virtual string16 GetCvc() OVERRIDE;
virtual bool SaveDetailsLocally() OVERRIDE;
virtual const content::NavigationController* ShowSignIn() OVERRIDE;
virtual void HideSignIn() OVERRIDE;
virtual void UpdateProgressBar(double value) OVERRIDE;
virtual void ModelChanged() OVERRIDE;
virtual void OnSignInResize(const gfx::Size& pref_size) OVERRIDE;
// Java to C++ calls
void ItemSelected(JNIEnv* env, jobject obj, jint section, jint index);
void AccountSelected(JNIEnv* env, jobject obj, jint index);
void NotificationCheckboxStateChanged(JNIEnv* env,
jobject obj,
jint type,
jboolean checked);
void EditingStart(JNIEnv* env, jobject obj, jint section);
jboolean EditingComplete(JNIEnv* env, jobject obj, jint section);
void EditingCancel(JNIEnv* env, jobject obj, jint section);
void EditedOrActivatedField(JNIEnv* env,
jobject obj,
jint section,
jint detail_input,
jint view_android,
jstring value,
jboolean was_edit);
base::android::ScopedJavaLocalRef<jstring> ValidateField(
JNIEnv* env, jobject obj, jint section, jint type, jstring value);
void ValidateSection(JNIEnv* env, jobject obj, jint section);
void DialogSubmit(JNIEnv* env, jobject obj);
void DialogCancel(JNIEnv* env, jobject obj);
void DialogDismissed(JNIEnv* env, jobject obj);
base::android::ScopedJavaLocalRef<jstring> GetLabelForSection(
JNIEnv* env,
jobject obj,
jint section);
base::android::ScopedJavaLocalRef<jobjectArray> GetListForField(JNIEnv* env,
jobject obj,
jint field);
void ContinueAutomaticSignin(JNIEnv* env, jobject obj,
jstring account_name, jstring sid, jstring lsid);
base::android::ScopedJavaLocalRef<jobject> GetIconForField(
JNIEnv* env,
jobject obj,
jint field_id,
jstring jinput);
base::android::ScopedJavaLocalRef<jstring> GetPlaceholderForField(
JNIEnv* env,
jobject obj,
jint section,
jint field_id);
base::android::ScopedJavaLocalRef<jstring> GetDialogButtonText(
JNIEnv* env,
jobject obj,
jint dialog_button_id);
jboolean IsDialogButtonEnabled(
JNIEnv* env,
jobject obj,
jint dialog_button_id);
base::android::ScopedJavaLocalRef<jstring> GetSaveLocallyText(JNIEnv* env,
jobject obj);
base::android::ScopedJavaLocalRef<jstring> GetLegalDocumentsText(JNIEnv* env,
jobject obj);
base::android::ScopedJavaLocalRef<jstring> GetProgressBarText(JNIEnv* env,
jobject obj);
jboolean IsTheAddItem(JNIEnv* env, jobject obj, jint section, jint index);
static bool RegisterAutofillDialogViewAndroid(JNIEnv* env);
private:
// A button type for a menu item.
enum MenuItemButtonType {
MENU_ITEM_BUTTON_TYPE_NONE = 0,
MENU_ITEM_BUTTON_TYPE_ADD = 1,
MENU_ITEM_BUTTON_TYPE_EDIT = 2,
};
// To fit the return type and GetMenuItemButtonType() name into 80 chars.
typedef MenuItemButtonType MBT;
// Returns the list of available user accounts.
std::vector<std::string> GetAvailableUserAccounts();
bool ValidateSection(DialogSection section, ValidationType type);
// Starts an automatic sign-in attempt for a given account.
bool StartAutomaticSignIn(const std::string& username);
// Updates the visibility of the checkbox to save the edited information
// locally.
void UpdateSaveLocallyCheckBox();
// Updates a given |section| to match the state provided by |controller_|. If
// |clobber_inputs| is true, the user input will be ignored, otherwise it will
// be preserved for all inputs except for the |field_type_to_always_clobber|.
void UpdateOrFillSectionToJava(DialogSection section,
bool clobber_inputs,
int field_type_to_always_clobber);
// Fills |output| with data the user manually input.
void GetUserInputImpl(DialogSection section, DetailOutputMap* output) const;
// Returns the model for suggestions for fields that fall under |section|.
ui::MenuModel* GetMenuModelForSection(DialogSection section) const;
// Returns the index of the currently selected item in |section|, or -1.
int GetSelectedItemIndexForSection(DialogSection section) const;
// Returns true if the item at |index| in |section| is the "Add...".
bool IsTheAddMenuItem(DialogSection section, int index) const;
// Returns true if the item at |index| in |section| is the "Manage...".
bool IsTheManageMenuItem(DialogSection section, int index) const;
// Returns an |image| converted to a Java image, or null if |image| is empty.
base::android::ScopedJavaLocalRef<jobject> GetJavaBitmap(
const gfx::Image& image) const;
// Returns the button type for a menu item at |index| in |section|.
MenuItemButtonType GetMenuItemButtonType(
DialogSection section, int index) const;
// Collapse the user input into a menu item.
// TODO(aruslan): http://crbug.com/230685
bool CollapseUserDataIntoMenuItem(DialogSection section,
string16* label,
string16* sublabel,
gfx::Image* icon) const;
// The controller that drives this view. Weak pointer, always non-NULL.
AutofillDialogController* const controller_;
// The corresponding java object.
base::android::ScopedJavaGlobalRef<jobject> java_object_;
DISALLOW_COPY_AND_ASSIGN(AutofillDialogViewAndroid);
};
} // namespace autofill
#endif // CHROME_BROWSER_UI_ANDROID_AUTOFILL_AUTOFILL_DIALOG_VIEW_ANDROID_H_
| 43.244318 | 80 | 0.681119 | [
"object",
"vector",
"model"
] |
4b65d6c33767a955b2ca0a60e62c019c37e0d961 | 7,432 | h | C | ecmascript/mem/ecma_heap_manager-inl.h | openharmony-sig-ci/ark_js_runtime | 72fcff4c114fd8323c9a5d1a835efeac043e9a72 | [
"Apache-2.0"
] | null | null | null | ecmascript/mem/ecma_heap_manager-inl.h | openharmony-sig-ci/ark_js_runtime | 72fcff4c114fd8323c9a5d1a835efeac043e9a72 | [
"Apache-2.0"
] | null | null | null | ecmascript/mem/ecma_heap_manager-inl.h | openharmony-sig-ci/ark_js_runtime | 72fcff4c114fd8323c9a5d1a835efeac043e9a72 | [
"Apache-2.0"
] | 1 | 2021-09-13T12:12:04.000Z | 2021-09-13T12:12:04.000Z | /*
* Copyright (c) 2021 Huawei Device 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 ECMASCRIPT_MEM_HEAP_MANAGER_INL_H
#define ECMASCRIPT_MEM_HEAP_MANAGER_INL_H
#include "ecmascript/mem/ecma_heap_manager.h"
#include <ctime>
#include "ecmascript/mem/allocator-inl.h"
#include "ecmascript/mem/heap-inl.h"
#include "ecmascript/mem/heap_roots.h"
#include "ecmascript/js_hclass.h"
#include "ecmascript/js_hclass.h"
namespace panda::ecmascript {
TaggedObject *EcmaHeapManager::AllocateYoungGenerationOrHugeObject(JSHClass *hclass)
{
size_t size = hclass->GetObjectSize();
return AllocateYoungGenerationOrHugeObject(hclass, size);
}
TaggedObject *EcmaHeapManager::AllocateYoungGenerationOrHugeObject(JSHClass *hclass, size_t size)
{
if (size > MAX_REGULAR_HEAP_OBJECT_SIZE) {
return AllocateHugeObject(hclass, size);
}
// regular objects
auto object = reinterpret_cast<TaggedObject *>(newSpaceAllocator_.Allocate(size));
if (LIKELY(object != nullptr)) {
SetClass(object, hclass);
heap_->OnAllocateEvent(reinterpret_cast<uintptr_t>(object));
return object;
}
// hclass must nonmovable
if (!heap_->FillNewSpaceAndTryGC(&newSpaceAllocator_)) {
LOG_ECMA_MEM(FATAL) << "OOM : extend failed";
UNREACHABLE();
}
object = reinterpret_cast<TaggedObject *>(newSpaceAllocator_.Allocate(size));
if (UNLIKELY(object == nullptr)) {
heap_->CollectGarbage(TriggerGCType::SEMI_GC);
object = reinterpret_cast<TaggedObject *>(newSpaceAllocator_.Allocate(size));
if (UNLIKELY(object == nullptr)) {
heap_->CollectGarbage(TriggerGCType::OLD_GC);
object = reinterpret_cast<TaggedObject *>(newSpaceAllocator_.Allocate(size));
if (UNLIKELY(object == nullptr)) {
heap_->ThrowOutOfMemoryError(size);
UNREACHABLE();
}
}
}
SetClass(object, hclass);
heap_->OnAllocateEvent(reinterpret_cast<uintptr_t>(object));
return object;
}
TaggedObject *EcmaHeapManager::TryAllocateYoungGeneration(size_t size)
{
if (size > MAX_REGULAR_HEAP_OBJECT_SIZE) {
return nullptr;
}
return reinterpret_cast<TaggedObject *>(newSpaceAllocator_.Allocate(size));
}
TaggedObject *EcmaHeapManager::AllocateNonMovableOrHugeObject(JSHClass *hclass, size_t size)
{
if (size > MAX_REGULAR_HEAP_OBJECT_SIZE) {
return AllocateHugeObject(hclass, size);
}
auto object = reinterpret_cast<TaggedObject *>(nonMovableAllocator_.Allocate(size));
if (UNLIKELY(object == nullptr)) {
if (heap_->CheckAndTriggerNonMovableGC()) {
object = reinterpret_cast<TaggedObject *>(nonMovableAllocator_.Allocate(size));
}
if (UNLIKELY(object == nullptr)) {
// hclass must be nonmovable
if (!heap_->FillNonMovableSpaceAndTryGC(&nonMovableAllocator_)) {
LOG_ECMA_MEM(FATAL) << "OOM : extend failed";
UNREACHABLE();
}
object = reinterpret_cast<TaggedObject *>(nonMovableAllocator_.Allocate(size));
if (UNLIKELY(object == nullptr)) {
heap_->ThrowOutOfMemoryError(size);
UNREACHABLE();
}
}
}
SetClass(object, hclass);
heap_->OnAllocateEvent(reinterpret_cast<uintptr_t>(object));
return object;
}
uintptr_t EcmaHeapManager::AllocateSnapShotSpace(size_t size)
{
uintptr_t object = snapshotSpaceAllocator_.Allocate(size);
if (UNLIKELY(object == 0)) {
if (!heap_->FillSnapShotSpace(&snapshotSpaceAllocator_)) {
LOG_ECMA_MEM(FATAL) << "alloc failed";
UNREACHABLE();
}
object = snapshotSpaceAllocator_.Allocate(size);
if (UNLIKELY(object == 0)) {
LOG_ECMA_MEM(FATAL) << "alloc failed";
UNREACHABLE();
}
}
return object;
}
void EcmaHeapManager::SetClass(TaggedObject *header, JSHClass *hclass)
{
header->SetClass(hclass);
}
TaggedObject *EcmaHeapManager::AllocateNonMovableOrHugeObject(JSHClass *hclass)
{
size_t size = hclass->GetObjectSize();
return AllocateNonMovableOrHugeObject(hclass, size);
}
TaggedObject *EcmaHeapManager::AllocateOldGenerationOrHugeObject(JSHClass *hclass, size_t size)
{
ASSERT(size > 0);
if (size > MAX_REGULAR_HEAP_OBJECT_SIZE) {
return AllocateHugeObject(hclass, size);
}
auto object = reinterpret_cast<TaggedObject *>(oldSpaceAllocator_.Allocate(size));
if (UNLIKELY(object == nullptr)) {
if (heap_->CheckAndTriggerOldGC()) {
object = reinterpret_cast<TaggedObject *>(oldSpaceAllocator_.Allocate(size));
}
if (UNLIKELY(object == nullptr)) {
// hclass must nonmovable
if (!heap_->FillOldSpaceAndTryGC(&oldSpaceAllocator_)) {
LOG_ECMA_MEM(FATAL) << "OOM : extend failed";
UNREACHABLE();
}
object = reinterpret_cast<TaggedObject *>(oldSpaceAllocator_.Allocate(size));
if (UNLIKELY(object == nullptr)) {
heap_->ThrowOutOfMemoryError(size);
UNREACHABLE();
}
}
}
SetClass(object, hclass);
heap_->OnAllocateEvent(reinterpret_cast<uintptr_t>(object));
return object;
}
TaggedObject *EcmaHeapManager::AllocateHugeObject(JSHClass *hclass, size_t size)
{
ASSERT(size > MAX_REGULAR_HEAP_OBJECT_SIZE);
// large objects
heap_->CheckAndTriggerOldGC();
auto *object =
reinterpret_cast<TaggedObject *>(const_cast<HugeObjectSpace *>(heap_->GetHugeObjectSpace())->Allocate(size));
if (UNLIKELY(object == nullptr)) {
heap_->CollectGarbage(TriggerGCType::HUGE_GC);
object = reinterpret_cast<TaggedObject *>(
const_cast<HugeObjectSpace *>(heap_->GetHugeObjectSpace())->Allocate(size));
if (UNLIKELY(object == nullptr)) {
heap_->ThrowOutOfMemoryError(size);
UNREACHABLE();
}
}
SetClass(object, hclass);
heap_->OnAllocateEvent(reinterpret_cast<uintptr_t>(object));
return object;
}
TaggedObject *EcmaHeapManager::AllocateMachineCodeSpaceObject(JSHClass *hclass, size_t size)
{
auto object = reinterpret_cast<TaggedObject *>(machineCodeSpaceAllocator_.Allocate(size));
if (UNLIKELY(object == nullptr)) {
if (!heap_->FillMachineCodeSpaceAndTryGC(&machineCodeSpaceAllocator_)) {
return nullptr;
}
object = reinterpret_cast<TaggedObject *>(machineCodeSpaceAllocator_.Allocate(size));
if (UNLIKELY(object == nullptr)) {
heap_->ThrowOutOfMemoryError(size);
return nullptr;
}
}
SetClass(object, hclass);
heap_->OnAllocateEvent(reinterpret_cast<uintptr_t>(object));
return object;
}
} // namespace panda::ecmascript
#endif // ECMASCRIPT_MEM_HEAP_MANAGER_INL_H
| 35.903382 | 117 | 0.671825 | [
"object"
] |
4b67bf50b34c84a8ca5fa7fd8336d34f2cd69cab | 10,829 | h | C | src/sensors/YosemitechY514.h | AndresLu97/ModularSensors | 03e9058317f794e6958bf96a2d59cc63a35d0222 | [
"BSD-3-Clause"
] | 58 | 2017-06-22T18:28:16.000Z | 2022-03-20T17:48:27.000Z | src/sensors/YosemitechY514.h | AndresLu97/ModularSensors | 03e9058317f794e6958bf96a2d59cc63a35d0222 | [
"BSD-3-Clause"
] | 293 | 2017-02-24T16:49:35.000Z | 2022-03-31T17:09:32.000Z | src/sensors/YosemitechY514.h | AndresLu97/ModularSensors | 03e9058317f794e6958bf96a2d59cc63a35d0222 | [
"BSD-3-Clause"
] | 36 | 2017-06-22T18:28:17.000Z | 2021-12-09T22:47:04.000Z | /**
* @file YosemitechY514.h
* @copyright 2020 Stroud Water Research Center
* Part of the EnviroDIY ModularSensors library for Arduino
* @author Sara Geleskie Damiano <sdamiano@stroudcenter.org>
*
* @brief Contains the YosemitechY514 sensor subclass and the variable
* subclasses YosemitechY514_Chlorophyll and YosemitechY514_Temp.
*
* These are for the Yosemitech Y514 chlorophyll sensor with wiper.
*
* This depends on the YosemitechParent super class.
*
* Documentation for the Modbus Protocol commands and responses can be found
* within the documentation in the YosemitechModbus library at:
* https://github.com/EnviroDIY/YosemitechModbus
*/
/* clang-format off */
/**
* @defgroup sensor_y514 Yosemitech Y514 Wipered Chlorophyll Sensor
* Classes for the Yosemitech Y514 chlorophyll sensor with wiper.
*
* @ingroup yosemitech_group
*
* @tableofcontents
* @m_footernavigation
*
* @section sensor_y514_datasheet Sensor Datasheet
* - [Y514 Manual](https://github.com/EnviroDIY/YosemitechModbus/tree/master/doc/Y514-Chlorophyl+Wiper_UserManual-v1.0.pdf)
* - [Y515 Manual](https://github.com/EnviroDIY/YosemitechModbus/tree/master/doc/Y515-Chlorophyll_UserManual-v1.0_en.pdf)
* - [Modbus Instructions](https://github.com/EnviroDIY/YosemitechModbus/tree/master/doc/Y514-Chlorophyl+Wiper-v1.6_ModbusInstructions.pdf)
*
* @note The reported resolution (32 bit) gives far more precision than is significant
* based on the specified accuracy of the sensor, so the resolutions kept in the
* string representation of the variable values is based on the accuracy not the
* maximum reported resolution of the sensor.
*
* @section sensor_y514_ctor Sensor Constructor
* {{ @ref YosemitechY514::YosemitechY514 }}
*
* ___
* @section sensor_y514_examples Example Code
* The Yosemitech Y514 chlorophyll sensor is used in the @menulink{y514}
* example.
*
* @menusnip{y514}
*/
/* clang-format on */
// Header Guards
#ifndef SRC_SENSORS_YOSEMITECHY514_H_
#define SRC_SENSORS_YOSEMITECHY514_H_
// Included Dependencies
#include "sensors/YosemitechParent.h"
// Sensor Specific Defines
/** @ingroup sensor_y514 */
/**@{*/
/// @brief Sensor::_numReturnedValues; the Y514 can report 2 values.
#define Y514_NUM_VARIABLES 2
/// @brief Sensor::_incCalcValues; we don't calculate any additional values.
#define Y514_INC_CALC_VARIABLES 0
/**
* @anchor sensor_y514_timing
* @name Sensor Timing
* The sensor timing for a Yosemitch Y514
*/
/**@{*/
/// @brief Sensor::_warmUpTime_ms; time before sensor responds after power - 1.3
/// seconds (1300ms).
#define Y514_WARM_UP_TIME_MS 1300
/// @brief Sensor::_stabilizationTime_ms; time between "StartMeasurement"
/// command and stable reading - 8sec (8000ms).
#define Y514_STABILIZATION_TIME_MS 8000
/// @brief Sensor::_measurementTime_ms; the Y514 takes ~2000ms to complete a
/// measurement.
#define Y514_MEASUREMENT_TIME_MS 2000
/**@}*/
/**
* @anchor sensor_y514_chloro
* @name Chlorophyll Concentration
* The chlorophyll concentration variable from a Yosemitch Y514
* - Range is 0 to 400 µg/L or 0 to 100 RFU
* - Accuracy is ± 1 %
*
* {{ @ref YosemitechY514_Chlorophyll::YosemitechY514_Chlorophyll }}
*/
/**@{*/
/// @brief Decimals places in string representation; chlorophyll concentration
/// should have 1 - resolution is 0.1 µg/L / 0.1 RFU.
#define Y514_CHLORO_RESOLUTION 1
/// @brief Sensor variable number; chlorophyll concentration is stored in
/// sensorValues[0].
#define Y514_CHLORO_VAR_NUM 0
/// @brief Variable name in
/// [ODM2 controlled vocabulary](http://vocabulary.odm2.org/variablename/);
/// "chlorophyllFluorescence"
#define Y514_CHLORO_VAR_NAME "chlorophyllFluorescence"
/// @brief Variable unit name in
/// [ODM2 controlled vocabulary](http://vocabulary.odm2.org/units/);
/// "microgramPerLiter" (µg/L)
#define Y514_CHLORO_UNIT_NAME "microgramPerLiter"
/// @brief Default variable short code; "Y514Chloro"
#define Y514_CHLORO_DEFAULT_CODE "Y514Chloro"
/**@}*/
/**
* @anchor sensor_y514_temp
* @name Temperature
* The temperature variable from a Yosemitch Y514
* - Range is 0°C to + 50°C
* - Accuracy is ± 0.2°C
*
* {{ @ref YosemitechY514_Temp::YosemitechY514_Temp }}
*/
/**@{*/
/// @brief Decimals places in string representation; temperature should have 1 -
/// resolution is 0.1°C.
#define Y514_TEMP_RESOLUTION 1
/// @brief Sensor variable number; temperature is stored in sensorValues[1].
#define Y514_TEMP_VAR_NUM 1
/// @brief Variable name in
/// [ODM2 controlled vocabulary](http://vocabulary.odm2.org/variablename/);
/// "temperature"
#define Y514_TEMP_VAR_NAME "temperature"
/// @brief Variable unit name in
/// [ODM2 controlled vocabulary](http://vocabulary.odm2.org/units/);
/// "degreeCelsius" (°C)
#define Y514_TEMP_UNIT_NAME "degreeCelsius"
/// @brief Default variable short code; "Y514Temp"
#define Y514_TEMP_DEFAULT_CODE "Y514Temp"
/**@}*/
/* clang-format off */
/**
* @brief The Sensor sub-class for the
* [Yosemitech Y514 sensor](@ref sensor_y514).
*
* @ingroup sensor_y514
*/
/* clang-format on */
class YosemitechY514 : public YosemitechParent {
public:
// Constructors with overloads
/**
* @brief Construct a new Yosemitech Y514 object.
*
* @param modbusAddress The modbus address of the sensor.
* @param stream An Arduino data stream for modbus communication. See
* [notes](@ref page_arduino_streams) for more information on what streams
* can be used.
* @param powerPin The pin on the mcu controlling power to the Y514.
* Use -1 if it is continuously powered.
* @param powerPin2 The pin on the mcu controlling power to the RS485
* adapter, if it is different from that used to power the sensor. Use -1
* or omit if not applicable.
* @param enablePin The pin on the mcu controlling the direction enable on
* the RS485 adapter, if necessary; use -1 or omit if not applicable.
* @note An RS485 adapter with integrated flow control is strongly
* recommended.
* @param measurementsToAverage The number of measurements to take and
* average before giving a "final" result from the sensor; optional with a
* default value of 1.
*/
YosemitechY514(byte modbusAddress, Stream* stream, int8_t powerPin,
int8_t powerPin2 = -1, int8_t enablePin = -1,
uint8_t measurementsToAverage = 1)
: YosemitechParent(modbusAddress, stream, powerPin, powerPin2,
enablePin, measurementsToAverage, Y514,
"YosemitechY514", Y514_NUM_VARIABLES,
Y514_WARM_UP_TIME_MS, Y514_STABILIZATION_TIME_MS,
Y514_MEASUREMENT_TIME_MS, Y514_INC_CALC_VARIABLES) {}
/**
* @copydoc YosemitechY514::YosemitechY514
*/
YosemitechY514(byte modbusAddress, Stream& stream, int8_t powerPin,
int8_t powerPin2 = -1, int8_t enablePin = -1,
uint8_t measurementsToAverage = 1)
: YosemitechParent(modbusAddress, stream, powerPin, powerPin2,
enablePin, measurementsToAverage, Y514,
"YosemitechY514", Y514_NUM_VARIABLES,
Y514_WARM_UP_TIME_MS, Y514_STABILIZATION_TIME_MS,
Y514_MEASUREMENT_TIME_MS, Y514_INC_CALC_VARIABLES) {}
/**
* @brief Destroy the Yosemitech Y514 object
*/
~YosemitechY514() {}
};
/* clang-format off */
/**
* @brief The Variable sub-class used for the
* [chlorophyll concentration output](@ref sensor_y514_chloro) from a
* [Yosemitech Y514-A chlorophyll sensor with wiper](@ref sensor_y514).
*
* @ingroup sensor_y514
*/
/* clang-format on */
class YosemitechY514_Chlorophyll : public Variable {
public:
/**
* @brief Construct a new YosemitechY514_Chlorophyll object.
*
* @param parentSense The parent YosemitechY514 providing the result
* values.
* @param uuid A universally unique identifier (UUID or GUID) for the
* variable; optional with the default value of an empty string.
* @param varCode A short code to help identify the variable in files;
* optional with a default value of "Y514Chloro".
*/
explicit YosemitechY514_Chlorophyll(
YosemitechY514* parentSense, const char* uuid = "",
const char* varCode = Y514_CHLORO_DEFAULT_CODE)
: Variable(parentSense, (const uint8_t)Y514_CHLORO_VAR_NUM,
(uint8_t)Y514_CHLORO_RESOLUTION, Y514_CHLORO_VAR_NAME,
Y514_CHLORO_UNIT_NAME, varCode, uuid) {}
/**
* @brief Construct a new YosemitechY514_Chlorophyll object.
*
* @note This must be tied with a parent YosemitechY514 before it can be
* used.
*/
YosemitechY514_Chlorophyll()
: Variable((const uint8_t)Y514_CHLORO_VAR_NUM,
(uint8_t)Y514_CHLORO_RESOLUTION, Y514_CHLORO_VAR_NAME,
Y514_CHLORO_UNIT_NAME, Y514_CHLORO_DEFAULT_CODE) {}
/**
* @brief Destroy the YosemitechY514_Chlorophyll() object - no action
* needed.
*/
~YosemitechY514_Chlorophyll() {}
};
/* clang-format off */
/**
* @brief The Variable sub-class used for the
* [temperature output](@ref sensor_y514_temp) from a
* [Yosemitech Y514-A chlorophyll sensor with wiper](@ref sensor_y514).
*
* @ingroup sensor_y514
*/
/* clang-format on */
class YosemitechY514_Temp : public Variable {
public:
/**
* @brief Construct a new YosemitechY514_Temp object.
*
* @param parentSense The parent YosemitechY514 providing the result
* values.
* @param uuid A universally unique identifier (UUID or GUID) for the
* variable; optional with the default value of an empty string.
* @param varCode A short code to help identify the variable in files;
* optional with a default value of "Y514Temp".
*/
explicit YosemitechY514_Temp(YosemitechY514* parentSense,
const char* uuid = "",
const char* varCode = Y514_TEMP_DEFAULT_CODE)
: Variable(parentSense, (const uint8_t)Y514_TEMP_VAR_NUM,
(uint8_t)Y514_TEMP_RESOLUTION, Y514_TEMP_VAR_NAME,
Y514_TEMP_UNIT_NAME, varCode, uuid) {}
/**
* @brief Construct a new YosemitechY514_Temp object.
*
* @note This must be tied with a parent YosemitechY514 before it can be
* used.
*/
YosemitechY514_Temp()
: Variable((const uint8_t)Y514_TEMP_VAR_NUM,
(uint8_t)Y514_TEMP_RESOLUTION, Y514_TEMP_VAR_NAME,
Y514_TEMP_UNIT_NAME, Y514_TEMP_DEFAULT_CODE) {}
/**
* @brief Destroy the YosemitechY514_Temp object - no action needed.
*/
~YosemitechY514_Temp() {}
};
/**@}*/
#endif // SRC_SENSORS__YOSEMITECHY514_H_
| 37.996491 | 139 | 0.697664 | [
"object"
] |
4b72063e6eaf174269d38d0d80ac36db3a70e0ba | 3,076 | h | C | CoreDataFullStack-iOS/Services/Deletion/CDFDeletionService.h | GabrielMassana/CoreDataFullStack-iOS | 3bf2d09b0c73c1abfc838f8da953ba34bbf22c1a | [
"MIT"
] | 14 | 2016-01-24T12:10:37.000Z | 2021-02-24T02:00:27.000Z | CoreDataFullStack-iOS/Services/Deletion/CDFDeletionService.h | GabrielMassana/CoreDataManager-iOS | 3bf2d09b0c73c1abfc838f8da953ba34bbf22c1a | [
"MIT"
] | 1 | 2017-04-08T17:36:08.000Z | 2017-04-08T18:10:32.000Z | CoreDataFullStack-iOS/Services/Deletion/CDFDeletionService.h | GabrielMassana/CoreDataManager-iOS | 3bf2d09b0c73c1abfc838f8da953ba34bbf22c1a | [
"MIT"
] | 3 | 2016-07-19T07:53:16.000Z | 2021-02-24T02:00:29.000Z | //
// CDFDeletionService.h
// CoreDataFullStack
//
// Created by Gabriel Massana on 24/1/16.
// Copyright © 2016 Gabriel Massana. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
/**
Help service to simplify deletion.
*/
@interface CDFDeletionService : NSObject
#pragma mark - Single
/**
Deletes an nsmanagedobject from specfic context
@param managedObject - to be deleted
@param managedObjectContext - the context used to access the entries
*/
+ (void) deleteManagedObject:(NSManagedObject *)managedObject
managedObjectContext:(NSManagedObjectContext *)managedObjectContext;
/**
Deletes an nsmanagedobject from specfic context
@param managedObject - to be deleted
@param saveAfterDeletion - used to determine if after deletion the managed object context should be saved
@param managedObjectContext - the context used to access the entries
*/
+ (void) deleteManagedObject:(NSManagedObject *)managedObject
saveAfterDeletion:(BOOL)saveAfterDeletion
managedObjectContext:(NSManagedObjectContext *)managedObjectContext;
#pragma mark - Multiple
/**
Deletes entites from specfic context
@param entityClass - a class value for the entity in core data
@param managedObjectContext - the context used to access the entries
*/
+ (void) deleteEntriesForEntityClass:(Class)entityClass
managedObjectContext:(NSManagedObjectContext *)managedObjectContext;
/**
Deletes entites from specfic context
@param entityClass - a class value for the entity in core data
@param saveAfterDeletion - used to determine if after deletion the managed object context should be saved
@param managedObjectContext - the context used to access the entries
*/
+ (void) deleteEntriesForEntityClass:(Class)entityClass
saveAfterDeletion:(BOOL)saveAfterDeletion
managedObjectContext:(NSManagedObjectContext *)managedObjectContext;
/**
Deletes entites that match the predicate from specfic context
@param entityClass - a class value for the entity in core data
@param predicate - a predicate used to limit the entries deleted
@param managedObjectContext - the context used to access the entries
*/
+ (void) deleteEntriesForEntityClass:(Class)entityClass
predicate:(NSPredicate *)predicate
managedObjectContext:(NSManagedObjectContext *)managedObjectContext;
/**
Deletes entites that match the predicate from specfic context
@param entityClass - a class value for the entity in core data
@param predicate - a predicate used to limit the entries deleted
@param saveAfterDeletion - used to determine if after deletion the managed object context should be saved
@param managedObjectContext - the context used to access the entries
*/
+ (void) deleteEntriesForEntityClass:(Class)entityClass
predicate:(NSPredicate *)predicate
saveAfterDeletion:(BOOL)saveAfterDeletion
managedObjectContext:(NSManagedObjectContext *)managedObjectContext;
@end
| 35.356322 | 106 | 0.751951 | [
"object"
] |
4b73b61cc696ae6e4428b4dc83d34a06ec83dcb7 | 6,856 | h | C | usr/src/uts/common/rpc/rpcsec_gss.h | AsahiOS/gate | 283d47da4e17a5871d9d575e7ffb81e8f6c52e51 | [
"MIT"
] | null | null | null | usr/src/uts/common/rpc/rpcsec_gss.h | AsahiOS/gate | 283d47da4e17a5871d9d575e7ffb81e8f6c52e51 | [
"MIT"
] | null | null | null | usr/src/uts/common/rpc/rpcsec_gss.h | AsahiOS/gate | 283d47da4e17a5871d9d575e7ffb81e8f6c52e51 | [
"MIT"
] | 1 | 2020-12-30T00:04:16.000Z | 2020-12-30T00:04:16.000Z | /*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2008 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
/*
* Copyright 1993 OpenVision Technologies, Inc., All Rights Reserved.
*/
/*
* rpcsec_gss.h, RPCSEC_GSS security service interface.
*/
#ifndef _RPCSEC_GSS_H
#define _RPCSEC_GSS_H
#ifdef __cplusplus
extern "C" {
#endif
#include <rpc/auth.h>
#include <rpc/clnt.h>
#include <gssapi/gssapi.h>
/*
* Interface definitions.
*/
#define MAX_NAME_LEN 64
#define MAX_GSS_MECH 128
#define MAX_GSS_NAME 128
typedef enum {
rpc_gss_svc_default = 0,
rpc_gss_svc_none = 1,
rpc_gss_svc_integrity = 2,
rpc_gss_svc_privacy = 3
} rpc_gss_service_t;
/*
* GSS-API based security mechanism type specified as
* object identifiers (OIDs).
* This type is derived from gss_OID_desc/gss_OID.
*/
#define rpc_gss_OID_s gss_OID_desc_struct
typedef struct rpc_gss_OID_s rpc_gss_OID_desc, *rpc_gss_OID;
/*
* Interface data.
* This is already suitable for both LP64 and ILP32.
*/
typedef struct rpc_gss_principal {
int len;
char name[1];
} *rpc_gss_principal_t;
typedef struct {
int req_flags;
int time_req;
gss_cred_id_t my_cred;
gss_channel_bindings_t input_channel_bindings;
} rpc_gss_options_req_t;
typedef struct {
int major_status;
int minor_status;
uint_t rpcsec_version;
int ret_flags;
int time_ret;
gss_ctx_id_t gss_context;
#ifdef _KERNEL
rpc_gss_OID actual_mechanism;
#else
char actual_mechanism[MAX_GSS_MECH];
#endif
} rpc_gss_options_ret_t;
/*
* raw credentials
*/
typedef struct {
uint_t version;
#ifdef _KERNEL
rpc_gss_OID mechanism;
uint_t qop;
#else
char *mechanism;
char *qop;
#endif
rpc_gss_principal_t client_principal;
char *svc_principal; /* service@server, e.g. nfs@caribe */
rpc_gss_service_t service;
} rpc_gss_rawcred_t;
/*
* unix credentials
*/
typedef struct {
uid_t uid;
gid_t gid;
short gidlen;
gid_t *gidlist;
} rpc_gss_ucred_t;
/*
* for callback routine
*/
typedef struct {
uint_t program;
uint_t version;
bool_t (*callback)();
} rpc_gss_callback_t;
/*
* lock used for the callback routine
*/
typedef struct {
bool_t locked;
rpc_gss_rawcred_t *raw_cred;
} rpc_gss_lock_t;
/*
* This is for user RPC applications.
* Structure used to fetch the error code when one of
* the rpc_gss_* routines fails.
*/
typedef struct {
int rpc_gss_error;
int system_error;
} rpc_gss_error_t;
#define RPC_GSS_ER_SUCCESS 0 /* no error */
#define RPC_GSS_ER_SYSTEMERROR 1 /* system error */
#ifdef _SYSCALL32
struct gss_clnt_data32 {
gss_OID_desc32 mechanism;
rpc_gss_service_t service;
char uname[MAX_NAME_LEN]; /* server's service name */
char inst[MAX_NAME_LEN]; /* server's instance name */
char realm[MAX_NAME_LEN]; /* server's realm */
uint_t qop;
};
#endif
/*
* This is for Kernel RPC applications.
* RPCSEC_GSS flavor specific data in sec_data opaque field.
*/
typedef struct gss_clnt_data {
rpc_gss_OID_desc mechanism;
rpc_gss_service_t service;
char uname[MAX_NAME_LEN]; /* server's service name */
char inst[MAX_NAME_LEN]; /* server's instance name */
char realm[MAX_NAME_LEN]; /* server's realm */
uint_t qop;
} gss_clntdata_t;
struct svc_req;
/*
* KERNEL rpc_gss_* interfaces.
*/
#ifdef _KERNEL
int rpc_gss_secget(CLIENT *, char *, rpc_gss_OID,
rpc_gss_service_t, uint_t, rpc_gss_options_req_t *,
rpc_gss_options_ret_t *, void *, cred_t *, AUTH **);
void rpc_gss_secfree(AUTH *);
int rpc_gss_seccreate(CLIENT *, char *, rpc_gss_OID,
rpc_gss_service_t, uint_t, rpc_gss_options_req_t *,
rpc_gss_options_ret_t *, cred_t *, AUTH **);
int rpc_gss_revauth(uid_t, rpc_gss_OID);
void rpc_gss_secpurge(void *);
enum auth_stat __svcrpcsec_gss(struct svc_req *,
struct rpc_msg *, bool_t *);
bool_t rpc_gss_set_defaults(AUTH *, rpc_gss_service_t, uint_t);
rpc_gss_service_t rpc_gss_get_service_type(AUTH *);
#else
/*
* USER rpc_gss_* public interfaces
*/
AUTH *
rpc_gss_seccreate(
CLIENT *clnt, /* associated client handle */
char *principal, /* server service principal */
char *mechanism, /* security mechanism */
rpc_gss_service_t service_type, /* security service */
char *qop, /* requested QOP */
rpc_gss_options_req_t *options_req, /* requested options */
rpc_gss_options_ret_t *options_ret /* returned options */
);
bool_t
rpc_gss_get_principal_name(
rpc_gss_principal_t *principal,
char *mechanism,
char *user_name,
char *node,
char *secdomain
);
char **rpc_gss_get_mechanisms();
char **rpc_gss_get_mech_info(
char *mechanism,
rpc_gss_service_t *service
);
bool_t
rpc_gss_is_installed(
char *mechanism
);
bool_t
rpc_gss_mech_to_oid(
char *mech,
rpc_gss_OID *oid
);
bool_t
rpc_gss_qop_to_num(
char *qop,
char *mech,
uint_t *num
);
bool_t
rpc_gss_set_svc_name(
char *principal,
char *mechanism,
uint_t req_time,
uint_t program,
uint_t version
);
bool_t
rpc_gss_set_defaults(
AUTH *auth,
rpc_gss_service_t service,
char *qop
);
void
rpc_gss_get_error(
rpc_gss_error_t *error
);
/*
* User level private interfaces
*/
enum auth_stat __svcrpcsec_gss();
bool_t __rpc_gss_wrap();
bool_t __rpc_gss_unwrap();
#endif
/*
* USER and KERNEL rpc_gss_* interfaces.
*/
bool_t
rpc_gss_set_callback(
rpc_gss_callback_t *cb
);
bool_t
rpc_gss_getcred(
struct svc_req *req,
rpc_gss_rawcred_t **rcred,
rpc_gss_ucred_t **ucred,
void **cookie
);
int
rpc_gss_max_data_length(
AUTH *rpcgss_handle,
int max_tp_unit_len
);
int
rpc_gss_svc_max_data_length(
struct svc_req *req,
int max_tp_unit_len
);
bool_t
rpc_gss_get_versions(
uint_t *vers_hi,
uint_t *vers_lo
);
#define RPCSEC_GSS_REFRESH_ATTEMPTS 20
/*
* Protocol data.
*
* The reason to put these definition in this header file
* is for 2.6 snoop to handle the RPCSEC_GSS protocol
* interpretation.
*/
#define RPCSEC_GSS_DATA 0
#define RPCSEC_GSS_INIT 1
#define RPCSEC_GSS_CONTINUE_INIT 2
#define RPCSEC_GSS_DESTROY 3
#define RPCSEC_GSS_VERSION 1
#ifdef __cplusplus
}
#endif
#endif /* !_RPCSEC_GSS_H */
| 20.284024 | 70 | 0.737894 | [
"object"
] |
4b761d76a3d12b579c86bb9cd0ae586b98f26e69 | 760 | h | C | core/PrecompiledHeader.h | mczhu/interpret | c31b939dfe3ad1878ab81ec85230e9b41f98722e | [
"MIT"
] | 1 | 2021-12-27T13:42:01.000Z | 2021-12-27T13:42:01.000Z | core/PrecompiledHeader.h | mczhu/interpret | c31b939dfe3ad1878ab81ec85230e9b41f98722e | [
"MIT"
] | null | null | null | core/PrecompiledHeader.h | mczhu/interpret | c31b939dfe3ad1878ab81ec85230e9b41f98722e | [
"MIT"
] | 2 | 2021-08-10T19:40:47.000Z | 2021-11-16T16:01:22.000Z | // Copyright (c) 2018 Microsoft Corporation
// Licensed under the MIT license.
// Author: Paul Koch <code@koch.ninja>
#include <stddef.h> // size_t, ptrdiff_t
#include <inttypes.h> // any of the fixed size types like int64_t
#include <limits> // numeric_limits
#include <type_traits> // std::is_standard_layout, std::is_integral
#include <stdlib.h> // malloc, realloc, free
#include <string.h> // memset
#include <new> // std::nothrow
#include <vector>
#include <queue>
#include <random>
#include <cmath> // log, exp, sqrt, etc. Use cmath instead of math.h so that we get type overloading for these functions for seemless float/double useage
#include <stdio.h> // snprintf/vsnprintf for logging
#include <stdarg.h> // va_start, va_end
#include <assert.h>
| 34.545455 | 154 | 0.728947 | [
"vector"
] |
4b8546a4c22e105ad3803cd830f21985c89f6a85 | 2,880 | h | C | src/include/kernel/x86/vga.h | kiznit/kiznix | f061391ab29b7cbec48a5f73a318d5dc59046201 | [
"BSD-2-Clause"
] | 5 | 2015-10-15T06:55:36.000Z | 2016-01-28T03:32:00.000Z | src/include/kernel/x86/vga.h | kiznit/kiznix | f061391ab29b7cbec48a5f73a318d5dc59046201 | [
"BSD-2-Clause"
] | 1 | 2015-08-11T19:38:04.000Z | 2015-08-11T20:09:42.000Z | src/include/kernel/x86/vga.h | kiznit/kiznix | f061391ab29b7cbec48a5f73a318d5dc59046201 | [
"BSD-2-Clause"
] | null | null | null | /*
Copyright (c) 2015, Thierry Tremblay
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 KIZNIX_INCLUDED_KERNEL_X86_VGA_H
#define KIZNIX_INCLUDED_KERNEL_X86_VGA_H
//todo: vga shouldn't be under 'x86'
#include <kernel/vmm.h>
#include <kernel/x86/io.h>
static const int VGA_WIDTH = 80;
static const int VGA_HEIGHT = 25;
static uint16_t* const VGA_MEMORY = (uint16_t*)(ISA_IO_BASE + 0x000B8000);
enum vga_color
{
VGA_COLOR_BLACK = 0,
VGA_COLOR_BLUE = 1,
VGA_COLOR_GREEN = 2,
VGA_COLOR_CYAN = 3,
VGA_COLOR_RED = 4,
VGA_COLOR_MAGENTA = 5,
VGA_COLOR_BROWN = 6,
VGA_COLOR_LIGHT_GREY = 7,
VGA_COLOR_DARK_GREY = 8,
VGA_COLOR_LIGHT_BLUE = 9,
VGA_COLOR_LIGHT_GREEN = 10,
VGA_COLOR_LIGHT_CYAN = 11,
VGA_COLOR_LIGHT_RED = 12,
VGA_COLOR_LIGHT_MAGENTA = 13,
VGA_COLOR_LIGHT_BROWN = 14,
VGA_COLOR_WHITE = 15,
};
static inline uint8_t vga_make_color(enum vga_color fg, enum vga_color bg)
{
return fg | bg << 4;
}
static inline uint16_t vga_make_entry(char c, uint8_t color)
{
uint16_t c16 = c;
uint16_t color16 = color;
return c16 | color16 << 8;
}
static inline vga_move_cursor(int x, int y)
{
uint16_t cursorLocation = y * VGA_WIDTH + x;
io_out_8(0x3D4, 14);
io_out_8(0x3D5, cursorLocation >> 8);
io_out_8(0x3D4, 15);
io_out_8(0x3D5, cursorLocation);
}
/* Make the cursor a solid block */
static inline vga_solid_cursor()
{
io_out_8(0x3d4, 0x0a);
io_out_8(0x3d5, 0x00);
}
static inline vga_hide_cursor()
{
io_out_8(0x3d4, 0x200a);
io_out_8(0x3d4, 0x000b);
}
#endif
| 28.235294 | 82 | 0.729514 | [
"solid"
] |
4b884ba8c2a175352b9475350661f9146dd22241 | 11,985 | c | C | src/sky_qip_module.c | dasfaha/sky | 4f2696e9abe54f4818f94337ed3bceae798e5a6d | [
"MIT"
] | 2 | 2018-01-16T07:26:53.000Z | 2021-12-08T03:12:40.000Z | src/sky_qip_module.c | dasfaha/sky | 4f2696e9abe54f4818f94337ed3bceae798e5a6d | [
"MIT"
] | null | null | null | src/sky_qip_module.c | dasfaha/sky | 4f2696e9abe54f4818f94337ed3bceae798e5a6d | [
"MIT"
] | null | null | null | #include <stdlib.h>
#include "sky_qip_module.h"
#include "property.h"
#include "constants.h"
#include "minipack.h"
#include "mem.h"
#include "dbg.h"
#include "qip/qip.h"
#include "qip_path.h"
//==============================================================================
//
// Definitions
//
//==============================================================================
typedef void (*sky_qip_path_map_func)(sky_qip_path *path, qip_map *map);
typedef void (*sky_qip_result_serialize_func)(void *result, qip_serializer *serializer);
typedef void (*sky_qip_update_dynamic_offsets_func)(void *event, qip_fixed_array *offsets);
//==============================================================================
//
// Forward Declarations
//
//==============================================================================
int sky_qip_module_process_dynamic_class_callback(qip_module *module,
qip_ast_node *class);
int sky_qip_module_process_event_class(sky_qip_module *module,
qip_ast_node *class);
//==============================================================================
//
// Functions
//
//==============================================================================
//--------------------------------------
// Lifecycle
//--------------------------------------
// Creates a wrapped module.
//
// Returns a new module.
sky_qip_module *sky_qip_module_create()
{
struct tagbstring core_class_path = bsStatic(SKY_LIB_CORE_PATH);
struct tagbstring sky_class_path = bsStatic(SKY_LIB_SKY_PATH);
sky_qip_module *module = NULL;
module = calloc(1, sizeof(sky_qip_module)); check_mem(module);
// Setup compiler.
module->compiler = qip_compiler_create(); check_mem(module->compiler);
module->compiler->process_dynamic_class = sky_qip_module_process_dynamic_class_callback;
module->compiler->dependency_count = 1;
module->compiler->dependencies = calloc(module->compiler->dependency_count, sizeof(*module->compiler->dependencies));
module->compiler->dependencies[0] = bfromcstr("String");
qip_compiler_add_class_path(module->compiler, &core_class_path);
qip_compiler_add_class_path(module->compiler, &sky_class_path);
return module;
error:
sky_qip_module_free(module);
return NULL;
}
// Frees a wrapped module object from memory.
//
// module - The module.
//
// Returns nothing.
void sky_qip_module_free(sky_qip_module *module)
{
if(module) {
sky_qip_module_free_event_info(module);
qip_compiler_free(module->compiler);
qip_module_free(module->_qip_module);
free(module);
}
}
// Frees dynamic event data from the module.
//
// module - The module.
//
// Returns nothing.
void sky_qip_module_free_event_info(sky_qip_module *module)
{
if(module) {
free(module->event_property_ids);
module->event_property_ids = NULL;
free(module->event_property_offsets);
module->event_property_offsets = NULL;
free(module->event_property_types);
module->event_property_types = NULL;
module->event_property_count = 0;
}
}
//--------------------------------------
// Dynamic Event Property Processing
//--------------------------------------
// Preprocesses dynamic classes to add database properties.
//
// module - The Qip module.
// class - The class AST node.
//
// Returns 0 if successful, otherwise returns -1.
int sky_qip_module_process_dynamic_class_callback(qip_module *module,
qip_ast_node *class)
{
int rc;
check(module != NULL, "Module required");
check(class != NULL, "Class required");
// Extract wrapped module via context.
sky_qip_module *wrapped_module = module->context;
check(wrapped_module != NULL, "Module context required");
// Process Event class only.
if(biseqcstr(class->class.name, "Event")) {
rc = sky_qip_module_process_event_class(wrapped_module, class);
}
return 0;
error:
return -1;
}
// Preprocesses dynamic classes to add database properties.
//
// module - The wrapped module.
// class - The class AST node.
//
// Returns 0 if successful, otherwise returns -1.
int sky_qip_module_process_event_class(sky_qip_module *module,
qip_ast_node *class)
{
int rc;
uint32_t i;
check(module != NULL, "Module required");
check(class != NULL, "Class required");
struct tagbstring this_str = bsStatic("this");
struct tagbstring event_str = bsStatic("Event");
struct tagbstring udo_str = bsStatic("updateDynamicOffsets");
struct tagbstring offsets_str = bsStatic("offsets");
struct tagbstring set_item_at_str = bsStatic("setItemAt");
// Retrieve updateDynamicOffsets() method.
qip_ast_node *udo_method = NULL;
rc = qip_ast_class_get_method(class, &udo_str, &udo_method);
check(rc == 0 && udo_method != NULL, "Unable to find Event.updateDynamicOffsets() method");
qip_ast_node *udo_block = udo_method->method.function->function.body;
qip_ast_block_free_exprs(udo_block);
// Loop over each module to find Event variable references.
qip_array *var_refs = qip_array_create(); check_mem(var_refs);
for(i=0; i<module->_qip_module->ast_module_count; i++) {
qip_ast_node *ast_module = module->_qip_module->ast_modules[i];
rc = qip_ast_node_get_var_refs_by_type(ast_module, module->_qip_module, &event_str, var_refs);
check(rc == 0, "Unable to search for Event variable references");
}
// Loop over references and add properties as needed.
module->event_property_count = 0;
for(i=0; i<var_refs->length; i++) {
qip_ast_node *var_ref = (qip_ast_node*)var_refs->elements[i];
// Add property if member is a property reference.
if(var_ref->var_ref.member && var_ref->var_ref.member->var_ref.type == QIP_AST_VAR_REF_TYPE_VALUE) {
bstring property_name = var_ref->var_ref.member->var_ref.name;
// Check if it exists on the Event class.
qip_ast_node *property = NULL;
rc = qip_ast_class_get_property(class, property_name, &property);
check(rc == 0, "Unable to retrieve property from Event class");
// Only add one if it doesn't exist.
if(property == NULL) {
// Lookup property in the database.
sky_property *db_property = NULL;
rc = sky_property_file_find_by_name(module->table->property_file, property_name, &db_property);
check(rc == 0 && db_property != NULL, "Unable to find property '%s' in table: %s", bdata(property_name), bdata(module->table->path));
// Generate and add property to class.
property = qip_ast_property_create(QIP_ACCESS_PUBLIC,
qip_ast_var_decl_create(qip_ast_type_ref_create(db_property->data_type), property_name, NULL)
);
rc = qip_ast_class_add_property(class, property);
check(rc == 0, "Unable to add property to class");
// Add to db property id to updateDynamicOffsets() method:
//
// offsets.setItemAt(offsetof(this.<db-prop-name>), <index>);
qip_ast_node *args[2];
args[0] = qip_ast_offsetof_create(
qip_ast_var_ref_create_property_access(&this_str, property_name)
);
args[1] = qip_ast_int_literal_create(module->event_property_count);
rc = qip_ast_block_add_expr(udo_block, qip_ast_var_ref_create_method_invoke(&offsets_str, &set_item_at_str, args, 2));
check(rc == 0, "Unable to add property id to updateDynamicOffsets()");
// Increment counter.
module->event_property_count++;
// Append to property id array.
module->event_property_ids = realloc(module->event_property_ids, sizeof(*module->event_property_ids) * module->event_property_count);
module->event_property_ids[module->event_property_count-1] = db_property->id;
// Append to property type array.
bstring type_name = property->property.var_decl->var_decl.type->type_ref.name;
module->event_property_types = realloc(module->event_property_types, sizeof(*module->event_property_types) * module->event_property_count);
rc = sky_property_get_standard_data_type_name(type_name, &module->event_property_types[module->event_property_count-1]);
check(rc == 0, "Unable to retrieve standard type name: '%s'", bdata(type_name));
}
}
}
// Append void return for dynamic array method.
rc = qip_ast_block_add_expr(udo_block, qip_ast_freturn_create(NULL));
check(rc == 0, "Unable to add return to updateDynamicOffsets() block");
qip_array_free(var_refs);
return 0;
error:
qip_array_free(var_refs);
return -1;
}
// Compiles a Qip query against the module. This can only be performed once
// on a module. Modules cannot be reused.
//
// module - The wrapped module.
// query_text - The text content of the query to compile.
//
// Returns 0 if successful, otherwise returns -1.
int sky_qip_module_compile(sky_qip_module *module, bstring query_text)
{
int rc;
check(module != NULL, "Module required");
check(module->_qip_module == NULL, "Module cannot be reused");
check(query_text != NULL, "Query text required");
struct tagbstring event_str = bsStatic("Event");
struct tagbstring udo_str = bsStatic("updateDynamicOffsets");
// Compile query and execute.
qip_ast_node *type_ref, *var_decl;
qip_ast_node *args[2];
// Path argument.
struct tagbstring path_str = bsStatic("path");
type_ref = qip_ast_type_ref_create_cstr("Path");
var_decl = qip_ast_var_decl_create(type_ref, &path_str, NULL);
args[0] = qip_ast_farg_create(var_decl);
// Data argument.
struct tagbstring data_str = bsStatic("data");
type_ref = qip_ast_type_ref_create_cstr("Map");
qip_ast_type_ref_add_subtype(type_ref, qip_ast_type_ref_create_cstr("Int"));
qip_ast_type_ref_add_subtype(type_ref, qip_ast_type_ref_create_cstr("Result"));
var_decl = qip_ast_var_decl_create(type_ref, &data_str, NULL);
args[1] = qip_ast_farg_create(var_decl);
// Compile.
struct tagbstring module_name = bsStatic("sky");
module->_qip_module = qip_module_create(&module_name, module->compiler);
module->_qip_module->context = module;
rc = qip_compiler_compile(module->compiler, module->_qip_module, query_text, args, 2);
check(rc == 0, "Unable to compile");
if(module->_qip_module->error_count > 0) {
debug("Parse error [line %d] %s", module->_qip_module->errors[0]->line_no, bdata(module->_qip_module->errors[0]->message));
}
check(module->_qip_module->error_count == 0, "Parse errors found");
// Retrieve Event functions for dynamic property info.
sky_qip_update_dynamic_offsets_func update_dynamic_offsets = NULL;
rc = qip_module_get_class_method(module->_qip_module, &event_str, &udo_str, (void*)&update_dynamic_offsets);
check(rc == 0 && update_dynamic_offsets != NULL, "Unable to find Event.updateDynamicOffsets() function");
// Retrieve dynamic property info.
qip_fixed_array *offsets = qip_fixed_array_create(sizeof(int64_t), module->event_property_count);
update_dynamic_offsets(NULL, offsets);
// Simplify arrays.
module->event_property_offsets = (int64_t*)offsets->elements;
offsets->elements = NULL;
qip_fixed_array_free(offsets);
// Retrieve main function.
rc = qip_module_get_main_function(module->_qip_module, &module->main_function);
check(rc == 0, "Unable to retrieve main function");
return 0;
error:
return -1;
}
| 37.927215 | 155 | 0.640634 | [
"object"
] |
4b8871e42000fee34b3fce0c9c0dc1671adb21a1 | 13,689 | h | C | src/core/cfg.h | jmgc/pyston | 9f672c1bbb75710ac17dd3d9107da05c8e9e8e8f | [
"BSD-2-Clause",
"Apache-2.0"
] | null | null | null | src/core/cfg.h | jmgc/pyston | 9f672c1bbb75710ac17dd3d9107da05c8e9e8e8f | [
"BSD-2-Clause",
"Apache-2.0"
] | null | null | null | src/core/cfg.h | jmgc/pyston | 9f672c1bbb75710ac17dd3d9107da05c8e9e8e8f | [
"BSD-2-Clause",
"Apache-2.0"
] | null | null | null | // Copyright (c) 2014-2016 Dropbox, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef PYSTON_CORE_CFG_H
#define PYSTON_CORE_CFG_H
/*
* This CFG is a relatively high-level CFG, closely corresponding to the input Python source. We break down
* control-flow constructs,
* but it doesn't do things like decompose IfExpressions or short-circuit conditional expressions.
* Those will have to get broken into low-level control flow, so this CFG doesn't exactly correspond to the llvm-level
* one we will eventually
* generate; this one is (at least for now) meant to be a slightly-lowered version of the input AST, for doing
* relatively high-level things such
* as type analysis, liveness, etc, and then using as the source representation for the next lowering pass (emitting
* llvm SSA)
*/
#include <vector>
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/BitVector.h"
#include "core/bst.h"
#include "core/common.h"
#include "core/stringpool.h"
namespace pyston {
class BST_stmt;
class Box;
class CFG;
class ParamNames;
class ScopeInfo;
// Simple class to override the default value of an int.
template <int D = -1> class DefaultedInt {
private:
int x;
public:
DefaultedInt() : x(D) {}
DefaultedInt(int x) : x(x) {}
DefaultedInt(const DefaultedInt& rhs) : x(rhs.x) {}
DefaultedInt(DefaultedInt&& rhs) : x(rhs.x) {}
void operator=(const DefaultedInt& rhs) { x = rhs.x; }
void operator=(DefaultedInt&& rhs) { x = rhs.x; }
template <typename T> bool operator<(T rhs) const { return x < rhs; }
template <typename T> bool operator>(T rhs) const { return x > rhs; }
template <typename T> bool operator<=(T rhs) const { return x <= rhs; }
template <typename T> bool operator>=(T rhs) const { return x >= rhs; }
operator int() const { return x; }
};
class CFGBlock {
public:
CFG* const cfg;
// Baseline JIT helper fields:
// contains address to the start of the code of this basic block
void* code;
// contains the address of the entry function
std::pair<CFGBlock*, Box*>(*entry_code)(void* interpeter, CFGBlock* block, Box** vregs);
llvm::TinyPtrVector<CFGBlock*> predecessors;
const char* info;
int idx; // index in the CFG
int offset_of_first_stmt; // offset of this block into the bytecode array in bytes
#ifndef NDEBUG
// only one block at a time is allowed to add instructions to the CFG
bool allowed_to_add_stuff = false;
#endif
// returns the successors by looking at the terminator (which requires iterating over all instructions in the block)
llvm::SmallVector<CFGBlock*, 2> successors() const;
CFGBlock(CFG* cfg, int idx, const char* info = NULL)
: cfg(cfg), code(NULL), entry_code(NULL), info(info), idx(idx), offset_of_first_stmt(-1) {}
BST_stmt* body() {
auto it = begin();
return it != end() ? *it : NULL;
}
int sizeInBytes() const {
int size = 0;
for (BST_stmt* stmt : *this) {
size += stmt->size_in_bytes();
}
return size;
}
BST_stmt* getTerminator() const {
// TODO: this is inefficient
for (BST_stmt* stmt : *this) {
if (stmt->is_terminator())
return stmt;
}
return NULL;
}
bool isPlaced() const { return offset_of_first_stmt != -1; }
void connectTo(CFGBlock* successor, bool allow_backedge = false);
void unconnectFrom(CFGBlock* successor);
void print(const CodeConstants& code_constants, llvm::raw_ostream& stream = llvm::outs());
class iterator {
private:
BST_stmt* stmt;
public:
iterator(BST_stmt* stmt) : stmt(stmt) {}
bool operator!=(const iterator& rhs) const { return stmt != rhs.stmt; }
bool operator==(const iterator& rhs) const { return stmt == rhs.stmt; }
iterator& operator++() __attribute__((always_inline)) {
if (likely(stmt)) {
if (unlikely(stmt->is_terminator()))
*this = CFGBlock::end();
else
stmt = (BST_stmt*)&((unsigned char*)stmt)[stmt->size_in_bytes()];
}
return *this;
}
BST_stmt* operator*() const { return stmt; }
};
inline iterator begin() const;
static iterator end() { return iterator(NULL); }
};
// the vregs are split into three parts.
// user visible: used for all non compiler generated names, name could be used in a single block or multiple
// all frames contain atleast this vregs in order to do frame introspection
// cross block : used for compiler generated names which get used in several blocks or which have closure scope
// single block: used by compiler created names which are only used in a single block.
// get reused for different names
//
// we assign the lowest numbers to the user visible ones, followed by the cross block ones and finally the single block
// ones. we do this because not all tiers use all of the vregs and it still makes it fast to switch between tiers.
//
// usage by our different tiers:
// interpreter : [user visible] [cross block] [single block]
// baseline jit: [user visible] [cross block]
// llvm jit : [user visible]
class VRegInfo {
private:
#ifndef NDEBUG
// this maps use too much memory, we only use them in the debug build for asserts
llvm::DenseMap<InternedString, DefaultedInt<VREG_UNDEFINED>> sym_vreg_map_user_visible;
llvm::DenseMap<InternedString, DefaultedInt<VREG_UNDEFINED>> sym_vreg_map;
#endif
// Reverse map, from vreg->symbol name.
// Entries won't exist for all vregs (=no entries for reused vregs)
std::vector<InternedString> vreg_sym_map;
int num_vregs_cross_block = -1;
int num_vregs_user_visible = -1;
int num_vregs = -1;
public:
#ifndef NDEBUG
// map of all assigned names. if the name is block local the vreg number is not unique because this vregs get reused
// between blocks.
const llvm::DenseMap<InternedString, DefaultedInt<VREG_UNDEFINED>>& getSymVRegMap() const { return sym_vreg_map; }
const llvm::DenseMap<InternedString, DefaultedInt<VREG_UNDEFINED>>& getUserVisibleSymVRegMap() const {
return sym_vreg_map_user_visible;
}
int getVReg(InternedString name) const {
assert(hasVRegsAssigned());
ASSERT(sym_vreg_map.count(name), "%s", name.c_str());
auto it = sym_vreg_map.find(name);
assert(it != sym_vreg_map.end());
assert(it->second != -1);
return it->second;
}
#endif
llvm::ArrayRef<InternedString> getVRegSymUserVisibleMap() const {
return llvm::makeArrayRef(vreg_sym_map).slice(0, num_vregs_user_visible);
}
// Not all vregs correspond to a name; many are our compiler-generated variables.
bool vregHasName(int vreg) const { return vreg < num_vregs_cross_block; }
// Testing flag to turn off the "vreg reuse" optimization.
#define REUSE_VREGS 1
InternedString getName(int vreg) const {
assert(hasVRegsAssigned());
assert(vreg >= 0 && vreg < num_vregs);
#if REUSE_VREGS
assert(vregHasName(vreg));
#endif
return vreg_sym_map[vreg];
}
bool isUserVisibleVReg(int vreg) const { return vreg < num_vregs_user_visible; }
bool isCrossBlockVReg(int vreg) const { return !isUserVisibleVReg(vreg) && vreg < num_vregs_cross_block; }
bool isBlockLocalVReg(int vreg) const { return vreg >= num_vregs_cross_block; }
int getTotalNumOfVRegs() const { return num_vregs; }
int getNumOfUserVisibleVRegs() const { return num_vregs_user_visible; }
int getNumOfCrossBlockVRegs() const { return num_vregs_cross_block; }
bool hasVRegsAssigned() const { return num_vregs != -1; }
void assignVRegs(const CodeConstants& code_constants, CFG* cfg, const ParamNames& param_names,
llvm::DenseMap<class TrackingVRegPtr, InternedString>& id_vreg);
};
// Control Flow Graph
class CFG {
private:
int next_idx;
VRegInfo vreg_info;
public:
std::vector<CFGBlock*> blocks;
BSTAllocator bytecode;
public:
CFG() : next_idx(0) {}
~CFG() {
for (auto&& block : blocks) {
delete block;
}
}
CFGBlock* getStartingBlock() { return blocks[0]; }
VRegInfo& getVRegInfo() { return vreg_info; }
// Creates a block which must be placed later, using placeBlock().
// Must be placed on same CFG it was created on.
// You can also safely delete it without placing it.
CFGBlock* addDeferredBlock() {
CFGBlock* block = new CFGBlock(this, -1);
return block;
}
void placeBlock(CFGBlock* block) {
assert(!block->isPlaced());
#ifndef NDEBUG
// check that there is no block with the same offset of first stmt
assert(!block->allowed_to_add_stuff);
std::unordered_map<int /* offset */, int> check_no_dup_blocks;
for (auto&& b : blocks) {
b->allowed_to_add_stuff = false;
++check_no_dup_blocks[b->offset_of_first_stmt];
}
++check_no_dup_blocks[bytecode.getSize()];
assert(check_no_dup_blocks[bytecode.getSize()] == 1);
for (auto&& e : check_no_dup_blocks) {
assert(e.second == 1);
}
#endif
assert(block->idx == -1);
block->idx = next_idx;
next_idx++;
blocks.push_back(block);
block->offset_of_first_stmt = bytecode.getSize();
#ifndef NDEBUG
block->allowed_to_add_stuff = true;
#endif
}
BST_stmt* getStmtFromOffset(int offset) {
if (offset == -1)
return NULL;
return (BST_stmt*)&bytecode.getData()[offset];
}
void print(const CodeConstants& code_constants, llvm::raw_ostream& stream = llvm::outs());
};
CFGBlock::iterator CFGBlock::begin() const {
if (offset_of_first_stmt >= cfg->bytecode.getSize())
return end();
return iterator((BST_stmt*)&cfg->bytecode.getData()[offset_of_first_stmt]);
}
class VRegSet {
private:
llvm::BitVector v;
public:
VRegSet(int num_vregs) : v(num_vregs, false) {}
// TODO: what is the referenc type here?
bool operator[](int vreg) const {
assert(vreg >= 0 && vreg < v.size());
return v[vreg];
}
void set(int vreg) {
assert(vreg >= 0 && vreg < v.size());
v[vreg] = true;
}
int numSet() const { return v.count(); }
class iterator {
public:
const VRegSet& set;
int i;
iterator(const VRegSet& set, int i) : set(set), i(i) {}
iterator& operator++() {
i = set.v.find_next(i);
return *this;
}
bool operator==(const iterator& rhs) const { return i == rhs.i; }
bool operator!=(const iterator& rhs) const { return !(*this == rhs); }
int operator*() { return i; }
};
iterator begin() const { return iterator(*this, v.find_first()); }
iterator end() const { return iterator(*this, -1); }
};
// VRegMap: A compact way of representing a value per vreg.
//
// One thing to note is that every vreg will get a value by default
// (the default value of T()), and fetching an unset vreg will return
// that value.
//
// Iterating will skip over these values though. If you want to see them,
// you can iterate from 0 to numVregs().
template <typename T> class VRegMap {
private:
// TODO: switch just to a T*?
std::vector<T> v;
public:
VRegMap(int num_vregs) : v(num_vregs) {}
T& operator[](int vreg) {
assert(vreg >= 0 && vreg < v.size());
return v[vreg];
}
const T& operator[](int vreg) const {
assert(vreg >= 0 && vreg < v.size());
return v[vreg];
}
void clear() {
int n = v.size();
for (int i = 0; i < n; i++) {
v[i] = T();
}
}
int numSet() {
int n = v.size();
int r = 0;
for (int i = 0; i < n; i++) {
if (v[i] != T())
r++;
}
return r;
}
class iterator {
public:
const VRegMap<T>& map;
int i;
iterator(const VRegMap<T>& map, int i) : map(map), i(i) {}
// TODO: make this skip unset values?
iterator& operator++() {
do {
i++;
} while (i < map.numVregs() && map[i] == T());
return *this;
}
bool operator==(const iterator& rhs) const { return i == rhs.i; }
bool operator!=(const iterator& rhs) const { return !(*this == rhs); }
std::pair<int, const T&> operator*() { return std::pair<int, const T&>(i, map[i]); }
int first() const { return i; }
const T& second() const { return map[i]; }
};
int numVregs() const { return v.size(); }
iterator begin() const {
iterator it = iterator(*this, -1);
++it;
return it;
}
iterator end() const { return iterator(*this, this->v.size()); }
};
BoxedCode* computeAllCFGs(AST* ast, bool globals_from_module, FutureFlags future_flags, BoxedString* fn,
BoxedModule* bm);
void printCFG(CFG* cfg, const CodeConstants& code_constants);
}
#endif
| 32.515439 | 120 | 0.632917 | [
"vector"
] |
4b92c6e1dedece93350b0f6fc8a3f619bf54d35f | 2,294 | h | C | src/common/dns_config.h | nerva-pool/nerva-pool-miner | a99abb46a4a732b0e820b1d73d3402c4879c898e | [
"MIT"
] | 25 | 2018-05-26T06:10:54.000Z | 2021-09-29T12:00:48.000Z | src/common/dns_config.h | nerva-pool/nerva-pool-miner | a99abb46a4a732b0e820b1d73d3402c4879c898e | [
"MIT"
] | 5 | 2018-08-21T03:37:21.000Z | 2019-09-03T04:51:42.000Z | src/common/dns_config.h | angrywasp/nerva | 5c4b280c844571690af5fe8d203c71c4372f6a9f | [
"MIT"
] | 31 | 2018-07-24T19:02:41.000Z | 2021-04-09T08:36:21.000Z | // Copyright (c) 2019, The NERVA Project
#ifndef _XNV_DNS_CONFIG_
#define _XNV_DNS_CONFIG_
#include <vector>
#include <string>
#include "cryptonote_config.h"
namespace dns_config
{
static const std::vector<std::string> SEED_NODES = { };
static const std::vector<std::string> TXT_SEED_NODES = {
"seed.getnerva.org"
};
static const std::vector<std::string> CHECKPOINTS = {
"checkpoint.getnerva.org"
};
static const std::vector<std::string> UPDATE = {
"update.getnerva.org"
};
static const std::vector<std::string> DOWNLOAD = {
"download.getnerva.org"
};
static const std::string ROOT_DOMAIN = "getnerva.org";
namespace testnet
{
static const std::vector<std::string> SEED_NODES = { };
static const std::vector<std::string> TXT_SEED_NODES = {
"seed-tn.getnerva.org"
};
static const std::vector<std::string> CHECKPOINTS = {
"checkpoint-tn.getnerva.org"
};
}
void init(const bool testnet);
std::vector<std::string> get_update_records();
std::vector<std::string> get_download_records();
std::vector<std::string> get_seed_node_records();
bool has_update_records();
bool has_download_records();
bool has_seed_node_records();
bool is_dnssec_ok();
struct dns_config_t
{
std::vector<std::string> const SEED_NODES;
std::vector<std::string> const TXT_SEED_NODES;
std::vector<std::string> const CHECKPOINTS;
};
inline const dns_config_t &get_config(cryptonote::network_type nettype)
{
static const dns_config_t mainnet = {
::dns_config::SEED_NODES,
::dns_config::TXT_SEED_NODES,
::dns_config::CHECKPOINTS
};
static const dns_config_t testnet = {
::dns_config::testnet::SEED_NODES,
::dns_config::testnet::TXT_SEED_NODES,
::dns_config::testnet::CHECKPOINTS
};
static const dns_config_t empty = { {}, {} };
switch (nettype)
{
case cryptonote::MAINNET:
return mainnet;
case cryptonote::TESTNET:
return testnet;
default:
return empty;
}
}
}
#endif | 25.775281 | 75 | 0.601569 | [
"vector"
] |
4b9a2c1c4c487790df6304cfbf1bbce701470d83 | 22,369 | c | C | labTools/Tasks/task_dotsy.c | TheGoldLab/Lab_Rex | 5a68671f3f7feed689d74bcbdf366faad2410e17 | [
"Apache-2.0"
] | null | null | null | labTools/Tasks/task_dotsy.c | TheGoldLab/Lab_Rex | 5a68671f3f7feed689d74bcbdf366faad2410e17 | [
"Apache-2.0"
] | null | null | null | labTools/Tasks/task_dotsy.c | TheGoldLab/Lab_Rex | 5a68671f3f7feed689d74bcbdf366faad2410e17 | [
"Apache-2.0"
] | null | null | null | /*
** task_dotsy.c
**
** 2afc task for yl's mt/lip stim experiments
**
** basic task: association rule for direction/saccade governed by
** MT dir + offset/LIP RF
**
** MT stim block: Stim_flag = 1;
** random trials w/ following properties:
** 1. signed coh <= Max_coh2stim && smode == 1
** 2. signed coh <= Max_coh2stim && smode == 0
** 3. signed coh > Max_coh2stim && smode == 0
**
** LIP stim block: Stim_flag = 2;
** block of randomized Stim_block_len stim trial
** followed by a single random non-stim trial
** repeated until all trials are fulfilled
** e.g., if Stim_block_len = 3
** pointer array: SSSNSSSNSSSN
** where S = stim, N = nonstim
**
** ie. there will be num_cohs*Stim_block_len*num_blocks stim trials
** num_cohs* num_blocks nonstim trials
** If Stim_block_len == 0 or NULLI, only stim trials
** will be used.
**
**
** 2011/03/17 yl from task_dotsj.c
** 2011/05/11 yl fixed ecode issue w/ t1_x
** 2011/05/19 yl LIP stim now supports all-stim blocks
** 2011/05/24 yl implements stim_flag == 0 => no-stim, randomized
** LIP stim trials: just increments pointer after every trial
** 2012/02/05 yl adds "Rew_prob" item to menu.
*/
#include "../toys.h"
#include "../task.h"
#include "../task_utilities.h"
/* ===== PRIVATE MACROS/CONSTANTS ===== */
#define NUM_GR_MENUS 6
#define TI "setup"
#define TIMV(ta,n) pl_list_get_v((ta)->task_menus->lists[0], (n))
#define GETMVI(ta,i,k) PL_L2PV((ta)->task_menus->lists[i],k)
/* PRIVATE DATA STRUCTURES */
/* ===== PRIVATE ROUTINES ===== */
/* standard for every task file */
void dotsy_make_trials (_PRtask);
_PRtrial dotsy_get_trial (_PRtask, int);
void dotsy_set_trial (_PRtrial);
/* helper fxn for making trials
** yl_task_make_trialP_... makes an array of (possibly shuffled) trials
** yl_get_..._trial grabs the next trial from the above array
*/
void yl_task_make_trialP_MT (_PRtask, int); /* creates array in order - from pr_task_make_trialP_all */
_PRtrial yl_get_MT_trial (_PRtask, int, int); /* randomizes trials from yl_..._trialP_MT; from tu_get_random */
void yl_task_make_trialP_LIP (_PRtask, int); /* creates random stim trials + nonstim trials */
_PRtrial yl_get_LIP_trial (_PRtask, int, int); /* from tu_get_block */
/* helper fxn for displaying trials */
void yl_task_print (_PRtask, int);
void yl_trial_print (_PRtrial); /* counts # of times that trial is used */
void yl_trialPs_print (_PRtrial *, int, int);/* prints all the trial IDs in order */
/* PRIVATE VARIABLES */
enum MENU_INDEX {
TI_MENU,
GRAPHICS_MENU,
DOTS_MENU,
COH_MENU
};
/*
** TASK: DOTS
** 1 dXdots object
** 3 dXtarget objects (fp, 2 targets)
*/
struct _TAtask_struct gl_dotsy_task[] = {
/* name */
"dotsy",
/* menus */
{
/*
** Task info: 'setup' menu
*/
{ TI, 1 },
{ "Trial_order", 0, 1.0 }, /* 0 = randomize, 1 = in order*/
{ "Trial_blocks", 1, 1.0 }, /* # trials per cond */
{ "Angle_MT", 0, 1.0 }, /* angle of the MT cell */
{ "Angle_offset", 90, 1.0 }, /* offset from MT tuning for dots */
{ "Pos_x_MT", 0, 0.1 }, /* ctr of MT RF */
{ "Pos_y_MT", 0, 0.1 },
{ "Pos_r_LIP", 0, 0.1 }, /* LIP RF */
{ "Pos_t_LIP", 0, 1.0 },
{ "Stim_flag", 0, 1.0 }, /* 1 = MT stim, 2 = LIP stim */
{ "Max_coh2stim", 500, 0.1 }, /* for MT stim trials */
{ "Stim_block_len" , 10, 1.0 }, /* for LIP stim trials */
{ "Rew_prob", NULLI, 0.1 }, /* used by 785yl */
{ "Drop_codes", 1, 1.0 },
{ NULL },
/*
** Six 'standard' graphics menu
** 0 - fixation
** 1 - dots aperture
** 2 - target centroid
** 3 - target 1
** 4 - target 2
** 5 - dots direction
*/
{ "graphics", NUM_GR_MENUS },
TU_XYRT_LIST,
{ DX_DIAM, 11, 0.1 },
{ DX_CLUT, 12, 1.0 },
{ NULL },
/*
** One dots object menu
*/
{ "dots", 1 },
{ DX_SEED, 0, 0.1 },
{ DX_SPEED, 0, 0.1 },
{ DX_COH, 0, 0.1 },
{ DX_DIR, 0, 0.1 },
{ NULL },
/*
** Coherence menu
*/
{ "coherence", 1 },
{ "Coherence_0", 1, 0.1 },
{ "Coherence_1", 500, 0.1 },
{ "Coherence_2", 1000, 0.1 },
{ "Coherence_3", NULLI, 0.1 },
{ "Coherence_4", NULLI, 0.1 },
{ "Coherence_5", NULLI, 0.1 },
{ "Coherence_6", NULLI, 0.1 },
{ "Coherence_7", NULLI, 0.1 },
{ "Coherence_8", NULLI, 0.1 },
{ "Coherence_9", NULLI, 0.1 },
{ NULL },
/* END OF MENUS */
{ NULL }
},
/*
** Graphics objects, by name
*/
{ { "dXtarget", 3 },
{ "dXdots", 1 },
{ NULL }
},
/*
** User functions
*/
{ { NULL }
},
/*
** Task methods
*/
&dotsy_make_trials,
&dotsy_get_trial,
&dotsy_set_trial,
};
/* PUBLIC ROUTINE: dotsy_make_trials
**
*/
void dotsy_make_trials(_PRtask task)
{
/* convention: make coh = 1 signify 0% coherence so we can use signed coh
** will set to 0% coherence in set_trials
** the angle of dots will be determined by the Angle_MT menu value
**/
int *cohs = NULL, coh_n=0; /* array of unsigned coherence */
int *signcohs = NULL, signcohs_n; /* array of signed coherences */
int i; /* counter for later */
int sflag, *smodes = NULL, smodes_n; /* from "Stim_flag", array of stim modes */
/* get the coherences */
while(GETMVI(task,COH_MENU,coh_n) != NULLI && coh_n < 10) coh_n++;
signcohs_n = coh_n*2;
signcohs = SAFE_ZALLOC(long, signcohs_n);
for(i = 0; i < coh_n; i++) {
signcohs[2*i] = GETMVI(task,COH_MENU,i);
signcohs[2*i+1] = -GETMVI(task,COH_MENU,i);
}
/* printf("eyeh %d\n", eyeh); */
/* printf("coh_n %d\n", coh_n); */
/* Make array of stim modes
** sflag = 0: no stim
** sflag = 1: MT stim
** sflag = 2: LIP stim
** smode is either 0 or 1.
** During trial, we will grab from Stim_flag menu to determine what kind of stim
*/
sflag = TIMV(task, "Stim_flag");
if(sflag == 0) {
/* stim mode will consist only of 0s */
smodes_n = 1;
smodes = SAFE_ZALLOC(int, smodes_n);
smodes[0] = 0;
} else {
/* stim mode consists of {0, 1} */
smodes_n = 2;
smodes = SAFE_ZALLOC(int, smodes_n);
smodes[0] = 0;
smodes[1] = 1;
}
/*
** utility to make trial set for scoh/smode pairs
*/
tu_make_trials2D(task,
"scoh", signcohs_n, signcohs, 0.1,
"smode", smodes_n, smodes, 1.0);
/*
** Free stuff
*/
SAFE_FREE(cohs); SAFE_FREE(signcohs);
SAFE_FREE(smodes);
/* SAFE_FREE(angs);*/
}
/* PUBLIC ROUTINE: dotsy_get_trial
**
** Returns:
** _PRtrial if trials remain
** NULL otherwise
*/
_PRtrial dotsy_get_trial(_PRtask task, int reset_flag)
{
int trial_blocks = TIMV(task, "Trial_blocks");
int sflag = TIMV(task, "Stim_flag");
int maxcoh = TIMV(task, "Max_coh2stim");
switch(sflag) {
/* No stim */
case 0:
/* printf("no stim\n");*/
return(tu_get_random(task, trial_blocks, reset_flag));
/* MT stim */
case 1:
/* printf("MT stim\n"); */
return(yl_get_MT_trial(task, trial_blocks, reset_flag));
/* LIP stim */
case 2:
/* printf("LIP stim\n"); */
return(yl_get_LIP_trial(task, trial_blocks, reset_flag));
/* REPEAT */
default:
if(task->trialPs && task->trialPs_index >= 0 &&
task->trialPs_index < task->trialPs_length)
return(task->trialPs[task->trialPs_index]);
else
return(NULL);
}
}
/* PUBLIC ROUTINE: dotsy_set_trial
**
** Note that here we mostly access groups/lists/properties
** by INDEX, not NAME, so be careful if anything
** above changes.
*/
void dotsy_set_trial(_PRtrial trial)
{
_PLlist tim = trial->task->task_menus->lists[0],
tgm = trial->task->task_menus->lists[1],
tdm = trial->task->task_menus->lists[2];
/* tim = setup menu
** tgm = graphics menu
** tdm = dots men
*/
int
/* the following are arrays of indices
** of target objects (fp, t1, t2) in
** the task graphics menu and the
** dXtargets objects, respectively
*/
tti[] = {0, 3, 4},
gti[] = {0, 1, 2},
gdi[] = {0};
/* current trial's parameters */
int scoh; /* signed coh */
int mt_ang, offset_ang;
int dots_ang; /* dots angle - to be computed */
int t1ang, t2ang; /* target 1 (correct), target 2 (incorrect) */
/* get the current trial's signed coh (scoh) */
scoh = PL_L2PV(trial->list,0);
/* get current task's Angle_MT */
mt_ang = TIMV(trial->task, "Angle_MT");
/* printf("scoh %d, dots_ang %d \n", scoh, dots_ang); */
/* make working copies of the task object menu values */
pl_list_set_v2w(tgm);
pl_list_set_v2w(tdm);
/*
** conditionally set graphics/dots menus
*/
/* things independent of scoh sign *****/
/* graphics menu */
PL_CSET( PL_L2PWS(tgm, kX, 1), TIMV(trial->task, "Pos_x_MT") ); /* dots: 1, 0. x = Pos_x_MT */
PL_CSET( PL_L2PWS(tgm, kY, 1), TIMV(trial->task, "Pos_y_MT") ); /* dots: 1, 1. y = Pos_y_MT */
PL_CSET( PL_L2PWS(tgm, kT, 2), TIMV(trial->task, "Pos_t_LIP") ); /* ctr: 2, 5. t = Pos_t_LIP */
PL_CSET( PL_L2PWS(tgm, kR, 3), TIMV(trial->task, "Pos_r_LIP") ); /* trg1: 3, 4. r = Pos_r_LIP */
PL_CSET( PL_L2PWS(tgm, kR, 4), TIMV(trial->task, "Pos_r_LIP") ); /* trg2: 4, 4. r = Pos_r_LIP */
/* things that depend on scoh sign *****/
offset_ang = TIMV(trial->task, "Angle_offset");
if (scoh > 0) {
dots_ang = mt_ang + offset_ang;
t1ang = 0; t2ang = 180;
} else {
dots_ang = (mt_ang + offset_ang + 180) % 360;
t1ang = 180; t2ang = 0;
}
/* debugging stuff */
/* printf("dots_ang %d, t1ang %d, t2ang %d\n", dots_ang, t1ang, t2ang); */
/* dots menu */
if(abs(scoh) == 1) { scoh = 0; } /* make sure to recode +/- 1 as 0% coh */
PL_CSET( PL_L2PW(tdm, 2), abs(scoh) ); /* 2. coherence */
PL_CSET( PL_L2PW(tdm, 3), dots_ang ); /* 3. direction of dots */
/* graphics menu again */
PL_CSET( PL_L2PWS(tgm, kT, 3), t1ang); /* trg1: 3, 5. t */
PL_CSET( PL_L2PWS(tgm, kT, 4), t2ang); /* trg2: 4, 5. t */
/* debugging stuff added by YL */
/* printf("before compute: WS tgm,0,1 %d\n", PL_L2PWS(tgm,0,1));
** printf("before compute: VS tgm,0,1 %d\n", PL_L2PVS(tgm,0,1));
*/
/* compute xys */
tu_compute_xyrt(tgm);
/* printf(" after compute: WS tgm,0,1 %d\n", PL_L2PWS(tgm,0,1));
** printf(" after compute: VS tgm,0,1 %d\n", PL_L2PVS(tgm,0,1));
*/
/* Set x, y positions in
** actual dXtarget objects
** Note: the indices here are based on the graphics objects
** fixation point (obj 0)
** target 1 (obj 1)
** target 2 (obj 2)
*/
dx_set_by_indexIV(DXF_NODRAW, 0, 3, gti,
1, PL_L2PWS(tgm, 0, 0), PL_L2PWS(tgm, 0, 3), PL_L2PWS(tgm, 0, 4),
2, PL_L2PWS(tgm, 1, 0), PL_L2PWS(tgm, 1, 3), PL_L2PWS(tgm, 1, 4),
3, PL_L2PWS(tgm, TU_XYRT_LEN, 0), PL_L2PWS(tgm, TU_XYRT_LEN, 3), PL_L2PWS(tgm, TU_XYRT_LEN, 4),
4, PL_L2PWS(tgm, TU_XYRT_LEN+1, 0), PL_L2PWS(tgm, TU_XYRT_LEN+1, 3), PL_L2PWS(tgm, TU_XYRT_LEN+1, 4),
ENDI);
/* Second, set properties of the dXdots object */
dx_set_by_nameIV(DXF_D1, DX_DOTS, 1, gdi,
DX_X, PL_L2PWS(tgm, 0, 1),
DX_Y, PL_L2PWS(tgm, 1, 1),
DX_DIAM, PL_L2PWS(tgm, TU_XYRT_LEN, 1),
DX_CLUT, PL_L2PWS(tgm, TU_XYRT_LEN+1, 1),
DX_COH, PL_L2PW(tdm, 2),
DX_DIR, PL_L2PW(tdm, 3),
DX_SPEED, PL_L2PW(tdm, 1),
DX_SEED, tu_get_seed(PL_L2PW(tdm, 0), PL_L2PW(tdm,2), PL_L2PW(tdm,3)) ,
NULL);
/* Drop codes */
if(TIMV(trial->task, "Drop_codes") != 0){
pl_ecodes_by_nameV(dx_get_object(DX_TARGET), 7000,
DX_X, 0, I_FIXXCD,
DX_Y, 0, I_FIXYCD,
DX_CLUT, 0, I_FIXLCD,
DX_X, 1, I_TRG1XCD,
DX_Y, 1, I_TRG1YCD,
DX_CLUT, 1, I_TRG1LCD,
DX_X, 2, I_TRG2XCD,
DX_Y, 2, I_TRG2YCD,
DX_CLUT, 2, I_TRG2LCD,
NULL);
pl_ecodes_by_nameV(dx_get_object(DX_DOTS), 7000,
DX_X, 0, I_STXCD,
DX_Y, 0, I_STYCD,
DX_DIAM, 0, I_STDIACD,
DX_COH, 0, I_COHCD,
DX_DIR, 0, I_DOTDIRCD,
DX_SPEED, 0, I_SPDCD,
DX_SEED, 0, I_DTVARCD,
NULL);
}
}
/* PRIVATE ROUTINE: yl_get_MT_trials()
**
** generates randomized trials for MT stim
** trials where coh < Max_coh2stim OR stim == 0
** this is modelled after tu_get_random
**
** Arguments:
** task: current task (see paradigm_rec)
** num_blocks: # reps of trials to use to generate the full block
** reset_flag: if TRUE, set pointer back to start of trialPs & makes new block
*/
_PRtrial yl_get_MT_trial(_PRtask task, int num_blocks, int reset_flag)
{
int last_score = task->pmf ? task->pmf->last_score : 0;
/* if a block has been made */
if(task->trialPs) {
/* check previous score ... */
if(last_score < 0) {
/* if fixation break or no choice
** - make sure we repeat this condition
** swap trial with later trial
*/
pr_task_swap_trialP(task);
} else if((++(task->trialPs_index)) == task->trialPs_length) { /* try to increment the pointer */
/* reached the end, clear pointer array
** so next time through it gets re-randomized
*/
SAFE_FREE(task->trialPs);
task->trialPs_length = 0;
}
} else { /* if no block has been made */
/* this is the first time, so toggle reset_flag */
reset_flag = 1;
}
/* check to make block */
if(reset_flag && !task->trialPs) {
yl_task_make_trialP_MT(task, num_blocks); /* 1. just make copies of trials for the block */
pr_task_randomize_trialP(task); /* 2. randomize pointers in the block */
yl_task_print(task, 0);
}
/* check if there is a list of pointers */
if(!task->trialPs)
return(NULL);
/* return pointer to the current trial */
return(task->trialPs[task->trialPs_index]);
}
/* PRIVATE ROUTINE: yl_task_make_trialP_MT
**
** make an array of pointers to MT stim trials w/i task
** grabs all trials that satisfy the following criteria:
** 1. smode = 0,
** OR
** 2. abs(scoh) < maxcoh
** gets randomized in yl_get_MT_trial
**
**
** modified from pr_task_make_trialP_all
**
*/
void yl_task_make_trialP_MT(_PRtask task, int num_blocks)
{
int maxcoh = TIMV(task, "Max_coh2stim");
int trial_count = 0; /* counts # trials in trials array that fulfill criterion */
register int i,j,k;
int total;
/* check for task */
if(!task)
return;
/* free the current pointers */
SAFE_FREE(task->trialPs);
/* check for trials, blocks */
if(!task->trials || num_blocks < 1)
return;
/* count the # of trials in 'trials' array that fulfill criterion */
for(i=0;i<task->trials_length;i++) {
/* smode == 0 || coh <= maxcoh */
int scoh = PL_L2PV(task->trials[i]->list,0);
int smode = PL_L2PV(task->trials[i]->list,1);
if(smode == 0 || abs(scoh) <= maxcoh) trial_count++;
}
/* Allocate the array of pointers */
total = trial_count * num_blocks;
task->trialPs = SAFE_ZALLOC(_PRtrial, total);
/* conditinally fill the array with repeated blocks of pointers
** to trials, in order
*/
for(k=0,i=0;i<num_blocks;i++)
for(j=0;j<task->trials_length;j++) {
int scoh = PL_L2PV(task->trials[j]->list,0);
int smode = PL_L2PV(task->trials[j]->list,1);
if(smode == 0 || abs(scoh) <=maxcoh)
task->trialPs[k++] = task->trials[j];
}
task->trialPs_length = total;
task->trialPs_index = 0; /* start at the first trial */
}
/* PRIVATE ROUTINE: yl_get_LIP_trial
**
** picks the next trial for LIP stim block
** the hard work is in yl_task_make_trialP_LIP
**
** based on tu_get_block - but just picks the next trial, even if monkey fxbr or nochoice
*/
_PRtrial yl_get_LIP_trial(_PRtask task, int num_blocks, int reset_flag)
{
int last_score = task->pmf ? task->pmf->last_score : 0;
/* Conditionally make a single block...
** This will also reset the index to 0
*/
if(task->trialPs == NULL) {
yl_task_make_trialP_LIP(task, num_blocks); /* make a list of the trials */
yl_task_print(task, 0);
/* check that it worked */
if(task->trialPs == NULL)
return(NULL);
/* Else if subj made a choice - increment the pointer and check for
** end of the array
*/
} else if( /* last_score >= 0 && */
++(task->trialPs_index) >= task->trialPs_length) {
/* end of the line ... check for reset */
if(reset_flag > 0)
/* reset pointer back to the beginning of the array */
task->trialPs_index = 0;
else
/* no reset, end of the line */
return(NULL);
}
return(task->trialPs[task->trialPs_index]);
}
/* PRIVATE ROUTINE: yl_task_make_trialP_LIP
**
** generates a list of trial pointers with:
** randomized stim trials
** punctuated by a random nonstim trial every Stim_block_len trials
** ie. there will be num_cohs*Stim_block_len*num_blocks stim trials
** num_cohs* num_blocks nonstim trials
**
** block of randomized Stim_block_len stim trial
** followed by a single random non-stim trial
** repeated until all trials are fulfilled
** e.g., if Stim_block_len = 3
** pointer array: SSSNSSSNSSSN
** where S = stim, N = nonstim
**
** strategy:
** 1. build separate lists of Stim and Nstim arrays
** 2. randomize each of those separately
** 3. concatenate them together
**
** 2011/05/19 yl: if Stim_block_len = 0 or NULLI, use ONLY stim trials
*/
void yl_task_make_trialP_LIP(_PRtask task, int num_blocks)
{
register int i,j,k;
int stim_blen = TIMV(task,"Stim_block_len");
int num_cohs = task->trials_rows; /* # of coherences */
int stim_len, nstim_len, total;
bool stim_only = stim_blen==0 || stim_blen == NULLI;
_PRtrial *dummyStimPs, *dummyNstimPs, *tp1;
/* check for task */
if(!task) return;
/* free the current pointers */
SAFE_FREE(task->trialPs);
/* check for trials, blocks */
if(!task->trials || num_blocks < 1) return;
/* allocate space for the two dummy pointer arrays */
if(stim_only)
{
stim_len = num_cohs * num_blocks;
nstim_len = 0;
} else {
stim_len = num_cohs * num_blocks * stim_blen;
nstim_len = num_cohs * num_blocks;
}
dummyStimPs = SAFE_ZALLOC(_PRtrial, stim_len);
if(!stim_only)
dummyNstimPs = SAFE_ZALLOC(_PRtrial, nstim_len);
/*
** ==== fill the two arrays in order ====
** 1. the nonstim trials - these would be in the 1st column
*/
if(!stim_only)
{
for(k=0,i=0; i<num_blocks; i++) {
/* for each coh */
for(j=0; j<num_cohs; j++)
/* grab from the 1st column */
dummyNstimPs[k++] = task->trials[j*task->trials_columns+0];
}
}
/*
** 2. the stim trials - these would be in the 2nd column
*/
k=0;
while(k<stim_len) {
/* for each coh */
for(j=0; j<num_cohs; j++)
/* grab from the 2nd column */
dummyStimPs[k++] = task->trials[j*task->trials_columns+1];
}
/*
** ==== randomize w/i each set ====
** I do this by swapping the dummy trial pointers w/ the task trial pointers
*/
/* 1. randomize for the nonstim trials */
if(!stim_only)
{ task->trialPs = dummyNstimPs;
task->trialPs_length = nstim_len;
pr_task_randomize_trialP(task);
dummyNstimPs = task->trialPs;
}
/* 2.randomize for stim trials */
task->trialPs = dummyStimPs;
task->trialPs_length = stim_len;
pr_task_randomize_trialP(task);
dummyStimPs = task->trialPs; /* for stim_only blocks, this would be done */
/* SAFE_FREE(task->trialPs);*/ /* <= DO I NEED TO DO THIS? I THINK I DELETE EVERYTHING */
/* now we want to put those two arrays together */
/* first - allocate space */
total = nstim_len + stim_len;
if(!stim_only)
{
tp1 = task->trialPs = SAFE_ZALLOC(_PRtrial, total);
/* now - fill the array */
j=0;
for(i=0; i<stim_len; i++) {
/* grab from the stim block */
*tp1++ = dummyStimPs[i];
/* every stim_blen-th trial ...
** grab from the nstim block
*/
if((i+1)%stim_blen == 0)
*tp1++ = dummyNstimPs[j++];
}
}
/* set the trialP index */
task->trialPs_length = total;
task->trialPs_index = 0;
/* don't forget to free the memory! */
if(!stim_only)
{ SAFE_FREE(dummyStimPs);
SAFE_FREE(dummyNstimPs);
}
/* for stim-only trials, dummyStimPs *is* task->trialPs */
}
/* PRIVATE ROUTINE: yl_task_print
**
** print useful info about a task
** including # of times each trial type is repeated
**
** Parameters:
** print_all: if TRUE, prints all the trial IDs in order
*/
void yl_task_print(_PRtask task, int print_all)
{
register int i, num_trials, num_cols;
if(!task) { printf(" ** NULL TASK ** \n"); return; }
/* task info */
printf("\n\n***** yl_task_print *****\n");
printf(" ** TASK (%d,%s): %d (%dr x %dc; i=%d) trials; %d (i=%d) trialPs.\n",
task->id, task->type, task->trials_length,
task->trials_rows, task->trials_columns,
task->trials_index, task->trialPs_length,
task->trialPs_index);
/* loop through the types of trials */
for(i=0; i<task->trials_length;i++) {
yl_trial_print(task->trials[i]);
}
if(TIMV(task, "Stim_flag")==2) num_cols =1+TIMV(task,"Stim_block_len");
else num_cols = 10;
/* conditionally print all trials */
if(print_all) {
yl_trialPs_print(task->trialPs, task->trialPs_length, num_cols);
}
printf("*************************\n\n");
}
/* PRIVATE ROUTINE: yl_trialPs_print
**
** print all the id's of array of trials in order
**
** Parameters:
** trialPs = array of trials
** len = length of array
** num_cols = # of columns for print out
*/
void yl_trialPs_print(_PRtrial *trialPs, int len, int num_cols)
{ register int i;
printf("\n");
for(i=0;i<len;i++) {
printf(" %d ", trialPs[i]->id);
if((i+1)% num_cols == 0) {
printf("\n");
}
}
printf("\n");
}
/* PRIVATE ROUTINE: yl_trial_print
**
** prints info that trial
** includes count of that trial type in that block
** mod from pr_trial_print
**
*/
void yl_trial_print(_PRtrial trial)
{
register int i;
int num_trials = 0; /* # reps for that trial */
if(!trial) {
printf(" NULL TRIAL\n"); return;
}
/* loop through trialPs to count num_trials for this trial*/
for(i=0; i<trial->task->trialPs_length; i++) {
if(trial->task->trialPs[i] == trial) num_trials++;
}
printf(" TR (%2d) x%d: ", trial->id, num_trials);
/* loop through the properties */
if(trial->list && trial->list->properties_length) {
/* print the property values */
for(i=0;i<trial->list->properties_length;i++)
printf("%s=%3d ",
trial->list->properties[i]->name,
(int) (trial->list->properties[i]->values[0]));
printf("\n");
} else {
printf("No properties\n");
}
}
#/** PhEDIT attribute block
#-11:16777215
#0:12367:default:-3:-3:0
#12367:13512:monospace9:0:-1:0
#13512:15641:default:-3:-3:0
#15641:15666:monospace9:0:-1:0
#15666:22134:default:-3:-3:0
#** PhEDIT attribute block ends (-0000234)**/
| 26.885817 | 119 | 0.625866 | [
"object",
"3d"
] |
4b9cdb01202b2cddcd07aed4bed623a8ad30998f | 3,715 | h | C | qt-creator-opensource-src-4.6.1/src/libs/clangsupport/dynamicastmatcherdiagnosticcontainer.h | kevinlq/Qt-Creator-Opensource-Study | b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f | [
"MIT"
] | 5 | 2018-12-22T14:49:13.000Z | 2022-01-13T07:21:46.000Z | qt-creator-opensource-src-4.6.1/src/libs/clangsupport/dynamicastmatcherdiagnosticcontainer.h | kevinlq/Qt-Creator-Opensource-Study | b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f | [
"MIT"
] | null | null | null | qt-creator-opensource-src-4.6.1/src/libs/clangsupport/dynamicastmatcherdiagnosticcontainer.h | kevinlq/Qt-Creator-Opensource-Study | b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f | [
"MIT"
] | 8 | 2018-07-17T03:55:48.000Z | 2021-12-22T06:37:53.000Z | /****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
#pragma once
#include "dynamicastmatcherdiagnosticmessagecontainer.h"
#include "dynamicastmatcherdiagnosticcontextcontainer.h"
namespace ClangBackEnd {
class DynamicASTMatcherDiagnosticContainer
{
public:
DynamicASTMatcherDiagnosticContainer() = default;
DynamicASTMatcherDiagnosticContainer(DynamicASTMatcherDiagnosticMessageContainers &&messages,
DynamicASTMatcherDiagnosticContextContainers &&contexts)
: m_messages(std::move(messages)),
m_contexts(std::move(contexts))
{
}
const DynamicASTMatcherDiagnosticMessageContainers &messages() const
{
return m_messages;
}
const DynamicASTMatcherDiagnosticContextContainers &contexts() const
{
return m_contexts;
}
void insertMessage(V2::SourceRangeContainer &&sourceRange,
ClangQueryDiagnosticErrorType errorType,
Utils::SmallStringVector &&arguments) {
m_messages.emplace_back(std::move(sourceRange), errorType, std::move(arguments));
}
void insertContext(V2::SourceRangeContainer &&sourceRange,
ClangQueryDiagnosticContextType contextType,
Utils::SmallStringVector &&arguments) {
m_contexts.emplace_back(std::move(sourceRange), contextType, std::move(arguments));
}
friend QDataStream &operator<<(QDataStream &out, const DynamicASTMatcherDiagnosticContainer &container)
{
out << container.m_messages;
out << container.m_contexts;
return out;
}
friend QDataStream &operator>>(QDataStream &in, DynamicASTMatcherDiagnosticContainer &container)
{
in >> container.m_messages;
in >> container.m_contexts;
return in;
}
friend bool operator==(const DynamicASTMatcherDiagnosticContainer &first,
const DynamicASTMatcherDiagnosticContainer &second)
{
return first.m_messages == second.m_messages
&& first.m_contexts == second.m_contexts;
}
DynamicASTMatcherDiagnosticContainer clone() const
{
return *this;
}
private:
DynamicASTMatcherDiagnosticMessageContainers m_messages;
DynamicASTMatcherDiagnosticContextContainers m_contexts;
};
using DynamicASTMatcherDiagnosticContainers = std::vector<DynamicASTMatcherDiagnosticContainer>;
CLANGSUPPORT_EXPORT QDebug operator<<(QDebug debug, const DynamicASTMatcherDiagnosticContainer &container);
} // namespace ClangBackEnd
| 35.721154 | 107 | 0.688829 | [
"vector"
] |
4ba1ea5bf2f58126924a1b0ee70097497b9c148c | 8,119 | h | C | dev/Code/Framework/AzCore/AzCore/Slice/SliceMetadataInfoComponent.h | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 8 | 2019-10-07T16:33:47.000Z | 2020-12-07T03:59:58.000Z | dev/Code/Framework/AzCore/AzCore/Slice/SliceMetadataInfoComponent.h | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | null | null | null | dev/Code/Framework/AzCore/AzCore/Slice/SliceMetadataInfoComponent.h | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 4 | 2019-08-05T07:25:46.000Z | 2020-12-07T05:12:55.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.
*
*/
/**
* @file
* Declaration of the SliceMetadataInfoComponent class and supporting types.
*/
#pragma once
#include <AzCore/Component/Component.h>
#include <AzCore/Component/EntityBus.h>
#include <AzCore/Slice/SliceMetadataInfoBus.h>
#include <AzCore/Component/ComponentExport.h>
namespace AZ
{
/**
* Slice Metadata Entity Information Component
* This component maintains a list of all of the entities that are associated with a slice metadata
* entity. An associated entity is defined as one that is new to the slice at the nested level
* that the metadata entity is associated with, that is, it wasn't inherited from a base slice. All
* entities in every slice are associated with exactly one metadata entity. In addition to associated
* editor entities, this component also tracks any metadata entities belonging to any root slices
* referenced by the associated slice as well as, if applicable, the metadata entity belonging to the
* slice holding the reference to the associated slice.
*/
class SliceMetadataInfoComponent
: public AZ::Component
, public SliceMetadataInfoRequestBus::Handler
, public AZ::EntityBus::MultiHandler
, public SliceMetadataInfoManipulationBus::Handler
{
public:
using EntityIdSet = AZStd::unordered_set<AZ::EntityId>;
AZ_COMPONENT(SliceMetadataInfoComponent, "{25EE4D75-8A17-4449-81F4-E561005BAABD}");
/**
* Metadata Info Component Constructor
* @param persistent True if this info component should be persistent. A persistent component
* will not emit a notification when it has no dependencies. Only the actual
* destruction of the metadata entity will remove it from the context.
*/
SliceMetadataInfoComponent(bool persistent = false);
/**
* Destructor (Default)
*/
~SliceMetadataInfoComponent() override; // = default;
/**
* Component Descriptor - Component Reflection
* @param context A reflection context
*/
static void Reflect(AZ::ReflectContext* context);
//////////////////////////////////////////////////////////////////////////
// SliceMetadataInfoManipulationBus
void AddChildMetadataEntity(EntityId childEntityId) override;
void RemoveChildMetadataEntity(EntityId childEntityId) override;
void SetParentMetadataEntity(EntityId parentEntityId) override;
void AddAssociatedEntity(EntityId associatedEntityId) override;
void RemoveAssociatedEntity(EntityId associatedEntityId) override;
void MarkAsPersistent(bool persistent) override;
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// AZ::Component
void Activate() override;
void Deactivate() override;
//////////////////////////////////////////////////////////////////////////
protected:
// The slice component needs to modify new and existing metadata info components
// before they can register their handlers.
friend SliceComponent;
//////////////////////////////////////////////////////////////////////////
// EntityBus
void OnEntityDestruction(const AZ::EntityId& entityId) override;
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// SliceMetadataInfoRequestBus
bool IsAssociated(EntityId entityId) override;
void GetAssociatedEntities(AZStd::unordered_set<EntityId>& associatedEntityIds) override;
AZ::EntityId GetParentId() override;
void GetChildIDs(AZStd::unordered_set<EntityId>& childEntityIds) override;
size_t GetAssociationCount() override;
//////////////////////////////////////////////////////////////////////////
/**
* Component Descriptor - Provided Services
* @param provided An array to fill out with all the services this component is dependent on
*/
static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided);
/**
* Component Descriptor - Incompatible Services
* @param incompatible An array to fill out with all the services this component is incompatible with
*/
static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible);
/**
* Gets the number of objects that are attached to this metadata entity. This includes both associated
* editor entities and child metadata entities belonging to referenced slices.
* If the dependency count is zero, this will send an OnMetadataDependenciesRemoved notification.
* Because this could result in the destruction of the metadata entity, be careful when calling this.
* This function does nothing if the component is marked as persistent.
* Note: This function can trigger the removal of the owning entity from the metadata context but can
* not trigger the deletion of the entity itself.
*/
void CheckDependencyCount();
/**
* Handles the runtime export of the SliceMetadataInfoComponent.
* The SliceMetadataInfo component shouldn't exist at runtime, so the export function returns a null component.
* @param thisComponent The source component that is being exported.
* @param platformTags The set of platforms to export for.
* @return The exported component, along with a flag on whether or not to delete it at the end of the export process.
*/
AZ::ExportedComponent ExportComponent(AZ::Component* thisComponent, const AZ::PlatformTagSet& platformTags);
SliceMetadataInfoNotificationBus::BusPtr m_notificationBus; /**< A bus pointer for emitting addressed notifications */
//! Entity Association Data
EntityIdSet m_associatedEntities; /**< A list of editor entities associated with this slice metadata
* An associated entity is one that is new to this slice as opposed to an entity cloned
* from a referenced slice. Every editor entity should always be associated with exactly
* one metadata entity. Entities that are not part of slices are associated with the
* metadata component belonging to the root slice. */
// Slice Hierarchy Data
AZ::EntityId m_parent; /**< If the associated slice instance belongs to another slice, this is the ID of the metadata entity
* associated with that parent slice instance. Note: The root entity will never show up as a parent.
* Slices that are not instances belonging to a non-root slice have no parent. */
EntityIdSet m_children; /**< The IDs of each metadata entity associated with an slice instance belonging to the associated slice. */
bool m_persistent; /**< The persistence flag indicates that the object is valid even without dependencies and will not emit the
* OnMetadataDependenciesRemoved notification when it's dependency count goes to 0.
* For example: The Root Slice. */
};
} // namespace AZ
| 52.380645 | 140 | 0.63062 | [
"object"
] |
4ba20a3d7707242b949695218bbf9e413a1c67d7 | 20,605 | c | C | middleware/src/usb_device_endpoint_functions.c | newbs/usb | 5aeafc26849673a357a6110713524387f2f5f84d | [
"0BSD"
] | 2 | 2020-09-18T02:16:01.000Z | 2021-06-17T10:52:38.000Z | middleware/src/usb_device_endpoint_functions.c | newbs/usb | 5aeafc26849673a357a6110713524387f2f5f84d | [
"0BSD"
] | null | null | null | middleware/src/usb_device_endpoint_functions.c | newbs/usb | 5aeafc26849673a357a6110713524387f2f5f84d | [
"0BSD"
] | 1 | 2021-11-17T08:21:58.000Z | 2021-11-17T08:21:58.000Z | /**************************************************************************
USB Device Layer Endpoint Read Write functions Implementation
Company:
Microchip Technology Inc.
File Name:
usb_device_endpoint_transfer.c
Summary:
This file contains implementations of both private and public functions
of the USB Device Layer Enadpoint Transfer. Add this file to your project
only if the application wants to write data to an Endpoint directly. Example
USB Vendor devices.
Description:
This file contains the USB Device Layer Endpoint Transfer Implementation.
**************************************************************************/
// DOM-IGNORE-BEGIN
/*******************************************************************************
* Copyright (C) 2018 Microchip Technology Inc. and its subsidiaries.
*
* Subject to your compliance with these terms, you may use Microchip software
* and any derivatives exclusively with Microchip products. It is your
* responsibility to comply with third party license terms applicable to your
* use of third party software (including open source software) that may
* accompany Microchip software.
*
* THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER
* EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED
* WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A
* PARTICULAR PURPOSE.
*
* IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE,
* INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND
* WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS
* BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE
* FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN
* ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY,
* THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE.
*******************************************************************************/
// DOM-IGNORE-END
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include "configuration.h"
#include "usb/src/usb_external_dependencies.h"
#include "usb/usb_common.h"
#include "usb/usb_chapter_9.h"
#include "usb/usb_device.h"
#include "usb/src/usb_device_function_driver.h"
#include "usb/src/usb_device_local.h"
/* USB Device Endpoint IRP array. */
USB_DEVICE_IRP gUSBDeviceEndpointIRP[USB_DEVICE_ENDPOINT_QUEUE_DEPTH_COMBINED];
/* Array for tracking Read/Write Queue size for each USB Device instance */
USB_DEVICE_Q_SIZE_ENDPOINT qSizeEndpoint[USB_DEVICE_INSTANCES_NUMBER];
// *****************************************************************************
// *****************************************************************************
// Section: USB Device Layer System Interface functions.
// *****************************************************************************
// *****************************************************************************
// ******************************************************************************
/* Function:
USB_DEVICE_RESULT USB_DEVICE_EndpointWrite
(
USB_DEVICE_HANDLE usbDeviceHandle,
USB_DEVICE_TRANSFER_HANDLE * transferHandle,
USB_ENDPOINT_ADDRESS endpoint,
const void * data,
size_t size,
USB_DEVICE_TRANSFER_FLAGS flags
)
Summary:
This function requests a data write to a USB Device Endpoint.
Description:
Refer to usb_device.h for usage information.
Returns:
Refer to usb_device.h for usage information.
*/
USB_DEVICE_RESULT USB_DEVICE_EndpointWrite
(
USB_DEVICE_HANDLE usbDeviceHandle,
USB_DEVICE_TRANSFER_HANDLE * transferHandle,
USB_ENDPOINT_ADDRESS endpoint,
const void * data,
size_t size,
USB_DEVICE_TRANSFER_FLAGS flags
)
{
int count = 0;
USB_DEVICE_OBJ* devClientHandle;
USB_ERROR irpSubmitError;
SYS_MODULE_INDEX deviceInstanceNumber;
USB_DEVICE_Q_SIZE_ENDPOINT* thisEndpointQueueSize;
USB_DEVICE_IRP * irp ;
OSAL_RESULT osalError;
*transferHandle = USB_DEVICE_TRANSFER_HANDLE_INVALID;
OSAL_CRITSECT_DATA_TYPE IntState;
/* Validate the handle */
devClientHandle = _USB_DEVICE_ClientHandleValidate(usbDeviceHandle);
if (devClientHandle == NULL)
{
SYS_DEBUG(0, "USB Device Layer: Invalid Client Handle");
return(USB_DEVICE_RESULT_ERROR_DEVICE_HANDLE_INVALID);
}
/* Get Device Instance Number */
deviceInstanceNumber = devClientHandle->usbDevLayerIndex;
/* Get Handle to the Endpoint Queue Size structure */
thisEndpointQueueSize = &qSizeEndpoint[deviceInstanceNumber];
/* Make sure that we are with in the queue size for this instance */
if(thisEndpointQueueSize->qSizeCurrentEpWrite >= thisEndpointQueueSize->qSizeMaxEpWrite)
{
SYS_DEBUG(0, "Write Queue is full");
return(USB_DEVICE_RESULT_ERROR_TRANSFER_QUEUE_FULL);
}
/*Obtain mutex to get access to a shared resource, check return value*/
osalError = OSAL_MUTEX_Lock(&(devClientHandle->mutexEndpointIRP), OSAL_WAIT_FOREVER);
if(osalError != OSAL_RESULT_TRUE)
{
/*Do not proceed lock was not obtained, or error occurred, let user know about error*/
return (USB_DEVICE_RESULT_ERROR);
}
/* Check if the if there is free slot available in queue */
for(count = 0; count < (USB_DEVICE_ENDPOINT_QUEUE_DEPTH_COMBINED) ; count ++ )
{
if(gUSBDeviceEndpointIRP[count].status <
(USB_DEVICE_IRP_STATUS)USB_DEVICE_IRP_FLAG_DATA_PENDING)
{
/* This means the IRP is free. Configure the IRP
* update the current queue size and then submit */
irp = &gUSBDeviceEndpointIRP[count];
irp->data = (void *)data;
irp->size = size;
irp->flags = flags;
irp->callback = &_USB_DEVICE_EndpointWriteCallBack;
irp->userData = (uintptr_t)devClientHandle;
(* transferHandle) = ( USB_DEVICE_TRANSFER_HANDLE )irp;
/* Prevent other tasks pre-empting this sequence of code */
IntState = OSAL_CRIT_Enter(OSAL_CRIT_TYPE_HIGH);
(thisEndpointQueueSize->qSizeCurrentEpWrite)++;
OSAL_CRIT_Leave(OSAL_CRIT_TYPE_HIGH, IntState);
irpSubmitError = USB_DEVICE_IRPSubmit( (USB_DEVICE_HANDLE)devClientHandle, endpoint, irp);
/* If IRP Submit function returned any error, then invalidate the
Transfer handle. */
if (irpSubmitError != USB_ERROR_NONE )
{
/* Prevent other tasks pre-empting this sequence of code */
IntState = OSAL_CRIT_Enter(OSAL_CRIT_TYPE_HIGH);
/* Update the read queue size */
(thisEndpointQueueSize->qSizeCurrentEpWrite)--;
OSAL_CRIT_Leave(OSAL_CRIT_TYPE_HIGH, IntState);
*transferHandle = USB_DEVICE_TRANSFER_HANDLE_INVALID;
}
/*Release mutex, done with shared resource*/
osalError = OSAL_MUTEX_Unlock(&(devClientHandle->mutexEndpointIRP));
if(osalError != OSAL_RESULT_TRUE)
{
/*Do not proceed lock was not obtained, or error occurred, let user know about error*/
return (USB_DEVICE_RESULT_ERROR);
}
return(irpSubmitError);
}
}
/*Release mutex, done with shared resource*/
osalError = OSAL_MUTEX_Unlock(&(devClientHandle->mutexEndpointIRP));
if(osalError != OSAL_RESULT_TRUE)
{
/*Do not proceed, unlock was not completed, or error occurred, let user know about error*/
return (USB_DEVICE_RESULT_ERROR);
}
/* We could not find a spare IRP */
SYS_DEBUG(0, "USB Device Endpoint Write: Transfer queue is full");
return USB_DEVICE_RESULT_ERROR_TRANSFER_QUEUE_FULL;
}
/******************************************************************************
Function:
USB_DEVICE_RESULT USB_DEVICE_EndpointRead
(
USB_DEVICE_HANDLE usbDeviceHandle,
USB_DEVICE_TRANSFER_HANDLE * transferHandle,
USB_ENDPOINT_ADDRESS endpoint,
void * buffer,
size_t bufferSize
);
Summary:
Reads data received from host on the requested endpoint.
Description:
Refer to usb_device.h for usage information.
Returns:
Refer to usb_device.h for usage information.
*/
USB_DEVICE_RESULT USB_DEVICE_EndpointRead
(
USB_DEVICE_HANDLE usbDeviceHandle,
USB_DEVICE_TRANSFER_HANDLE * transferHandle,
USB_ENDPOINT_ADDRESS endpoint,
void * buffer,
size_t bufferSize
)
{
int count = 0;
USB_DEVICE_OBJ* devClientHandle;
USB_ERROR irpSubmitError;
SYS_MODULE_INDEX deviceInstanceNumber;
USB_DEVICE_Q_SIZE_ENDPOINT* thisEndpointQueueSize;
USB_DEVICE_IRP * irp = gUSBDeviceEndpointIRP;
OSAL_RESULT osalError;
*transferHandle = USB_DEVICE_TRANSFER_HANDLE_INVALID;
OSAL_CRITSECT_DATA_TYPE IntState;
/* Validate the handle */
devClientHandle = _USB_DEVICE_ClientHandleValidate(usbDeviceHandle);
if (devClientHandle == NULL)
{
SYS_DEBUG(0, "USB Device Layer: Invalid Client Handle");
return(USB_DEVICE_RESULT_ERROR_DEVICE_HANDLE_INVALID);
}
/* Get Device Instance Number */
deviceInstanceNumber = devClientHandle->usbDevLayerIndex;
/* Get Handle to the Endpoint Queue Size structure */
thisEndpointQueueSize = &qSizeEndpoint[deviceInstanceNumber];
/* Make sure that we are with in the queue size for this instance */
if(thisEndpointQueueSize->qSizeCurrentEpRead >= thisEndpointQueueSize->qSizeMaxEpRead)
{
SYS_ASSERT(false, "Read Queue is full");
return(USB_DEVICE_RESULT_ERROR_TRANSFER_QUEUE_FULL);
}
/*Obtain mutex to get access to a shared resource, check return value*/
osalError = OSAL_MUTEX_Lock(&(devClientHandle->mutexEndpointIRP), OSAL_WAIT_FOREVER);
if(osalError != OSAL_RESULT_TRUE)
{
/*Do not proceed lock was not obtained, or error occurred, let user know about error*/
return (USB_DEVICE_RESULT_ERROR);
}
/* Check if the if there is free slot available in queue */
for(count = 0; count < (USB_DEVICE_ENDPOINT_QUEUE_DEPTH_COMBINED) ; count ++ )
{
if(gUSBDeviceEndpointIRP[count].status <
(USB_DEVICE_IRP_STATUS)USB_DEVICE_IRP_FLAG_DATA_PENDING)
{
/* This means the IRP is free. Configure the IRP
* update the current queue size and then submit */
irp = &gUSBDeviceEndpointIRP[count];
irp->data = buffer;
irp->size = bufferSize;
irp->callback = &_USB_DEVICE_EndpointReadCallBack;
irp->userData = (uintptr_t)devClientHandle;
(*transferHandle) = (USB_DEVICE_TRANSFER_HANDLE ) irp;
/* Prevent other tasks pre-empting this sequence of code */
IntState = OSAL_CRIT_Enter(OSAL_CRIT_TYPE_HIGH);
(thisEndpointQueueSize->qSizeCurrentEpRead)++;
OSAL_CRIT_Leave(OSAL_CRIT_TYPE_HIGH, IntState);
irpSubmitError = USB_DEVICE_IRPSubmit((USB_DEVICE_HANDLE)devClientHandle, endpoint, irp);
/* If IRP Submit function returned any error, then invalidate the
Transfer handle. */
if (irpSubmitError != USB_ERROR_NONE )
{
/* Prevent other tasks pre-empting this sequence of code */
IntState = OSAL_CRIT_Enter(OSAL_CRIT_TYPE_HIGH);
/* Update the read queue size */
(thisEndpointQueueSize->qSizeCurrentEpRead)--;
OSAL_CRIT_Leave(OSAL_CRIT_TYPE_HIGH, IntState);
*transferHandle = USB_DEVICE_TRANSFER_HANDLE_INVALID;
}
/*Release mutex, done with shared resource*/
osalError = OSAL_MUTEX_Unlock(&(devClientHandle->mutexEndpointIRP));
if(osalError != OSAL_RESULT_TRUE)
{
/*Do not proceed lock was not obtained, or error occurred, let user know about error*/
return (USB_DEVICE_RESULT_ERROR);
}
return(irpSubmitError);
}
}
/*Release mutex, done with shared resource*/
osalError = OSAL_MUTEX_Unlock(&(devClientHandle->mutexEndpointIRP));
if(osalError != OSAL_RESULT_TRUE)
{
/*Do not proceed, unlock was not complete, or error occurred, let user know about error*/
return (USB_DEVICE_RESULT_ERROR);
}
/* Could not find a free IRP. */
SYS_DEBUG(0, "USB Device Endpoint Read: Transfer queue is full");
return USB_DEVICE_RESULT_ERROR_TRANSFER_QUEUE_FULL;
}
/******************************************************************************
Function:
USB_DEVICE_RESULT USB_DEVICE_EndpointTransferCancel
(
USB_DEVICE_HANDLE usbDeviceHandle,
USB_ENDPOINT_ADDRESS endpoint,
USB_DEVICE_TRANSFER_HANDLE transferHandle
);
Summary:
This function cancels a transfer scheduled on an endpoint.
Description:
Refer to usb_device.h for usage information.
Returns:
Refer to usb_device.h for usage information.
*/
USB_DEVICE_RESULT USB_DEVICE_EndpointTransferCancel
(
USB_DEVICE_HANDLE usbDeviceHandle,
USB_ENDPOINT_ADDRESS endpoint,
USB_DEVICE_TRANSFER_HANDLE transferHandle
)
{
USB_DEVICE_OBJ* devClientHandle;
USB_DEVICE_IRP * irp ;
USB_ERROR irpCancelError;
/* Validate the handle */
devClientHandle = _USB_DEVICE_ClientHandleValidate(usbDeviceHandle);
if (devClientHandle == NULL)
{
SYS_DEBUG(0, "USB Device Layer: Invalid Client Handle");
return(USB_DEVICE_RESULT_ERROR_DEVICE_HANDLE_INVALID);
}
if (transferHandle == USB_DEVICE_TRANSFER_HANDLE_INVALID)
{
SYS_DEBUG(0, "USB_Device_Endpoint_Transfer_Cancel: Invalid Transfer Handle");
return USB_DEVICE_RESULT_ERROR;
}
irp = (USB_DEVICE_IRP*)transferHandle;
if (irp->status == USB_DEVICE_IRP_STATUS_PENDING)
{
irpCancelError = USB_DEVICE_IRPCancelAll((USB_DEVICE_HANDLE)devClientHandle,endpoint );
return irpCancelError;
}
SYS_DEBUG(0, "USB_Device_Endpoint_Transfer_Cancel: Transfer could not be cancelled");
return USB_DEVICE_RESULT_ERROR;
}
// ******************************************************************************
/* Function:
void _USB_DEVICE_VENDOR_EndpointWriteCallBack( void * irp )
Summary:
Endpoint write callback.
Description:
This function is called when a endpoint write is complete.
Remarks:
This is a local function and should not be called directly by the application.
*/
void _USB_DEVICE_EndpointWriteCallBack( USB_DEVICE_IRP * irp )
{
/* An endpoint write has completed */
USB_DEVICE_EVENT_DATA_ENDPOINT_WRITE_COMPLETE eventData;
SYS_MODULE_INDEX deviceInstanceNumber;
USB_DEVICE_Q_SIZE_ENDPOINT* thisEndpointQueueSize;
USB_DEVICE_OBJ* devClientHandle;
/* Get Handle to the Device Object */
devClientHandle = (USB_DEVICE_OBJ*)irp->userData;
/* Get Device instance Number */
deviceInstanceNumber = devClientHandle->usbDevLayerIndex;
/* Get Handle to the Endpoint Queue Size */
thisEndpointQueueSize = &qSizeEndpoint[deviceInstanceNumber];
/* Update Queue Size. We have freed one read queue element as we have
completed a Transfer */
thisEndpointQueueSize->qSizeCurrentEpWrite --;
if( devClientHandle->callBackFunc != NULL )
{
/* Get data size received from Host */
eventData.length = irp->size;
/* Get Transfer Handle */
eventData.transferHandle = ( USB_DEVICE_TRANSFER_HANDLE )irp;
/* Get transfer status */
if ((irp->status == USB_DEVICE_IRP_STATUS_COMPLETED)
|| (irp->status == USB_DEVICE_IRP_STATUS_COMPLETED_SHORT))
{
/* Transfer completed successfully */
eventData.status = USB_DEVICE_RESULT_OK;
}
else if (irp->status == USB_DEVICE_IRP_STATUS_ABORTED_ENDPOINT_HALT)
{
/* Transfer canceled due to Endpoint Halt */
eventData.status = USB_DEVICE_RESULT_ERROR_ENDPOINT_HALTED;
}
else if (irp->status == USB_DEVICE_IRP_STATUS_TERMINATED_BY_HOST)
{
/* Transfer Canceled by Host (Host sent a Clear feature )*/
eventData.status = USB_DEVICE_RESULT_ERROR_TERMINATED_BY_HOST;
}
else
{
/* Transfer was not completed successfully */
eventData.status = USB_DEVICE_RESULT_ERROR;
}
/* Send an event to application letting it know that a endpoint write
* has completed */
devClientHandle->callBackFunc(
USB_DEVICE_EVENT_ENDPOINT_WRITE_COMPLETE,
&eventData,
devClientHandle->context);
}
}
// ******************************************************************************
/* Function:
void _USB_DEVICE_VENDOR_EndpointReadCallBack( void * irp )
Summary:
Endpoint read callback.
Description:
This function is called when an endpoint read has completed.
Remarks:
This is a local function and should not be called directly by the application.
*/
void _USB_DEVICE_EndpointReadCallBack( USB_DEVICE_IRP * irp )
{
USB_DEVICE_EVENT_DATA_ENDPOINT_READ_COMPLETE eventData;
SYS_MODULE_INDEX deviceInstanceNumber;
USB_DEVICE_Q_SIZE_ENDPOINT* thisEndpointQueueSize;
USB_DEVICE_OBJ* devClientHandle;
/* Get Handle to the Device Object */
devClientHandle = (USB_DEVICE_OBJ*)irp->userData;
/* Get Device instance Number */
deviceInstanceNumber = devClientHandle->usbDevLayerIndex;
/* Get Handle to the Endpoint Queue Size */
thisEndpointQueueSize = &qSizeEndpoint[deviceInstanceNumber];
/* Update Queue Size. We have freed one read queue element as we have
completed a Transfer */
thisEndpointQueueSize->qSizeCurrentEpRead --;
if( devClientHandle->callBackFunc != NULL )
{
/* Get data size received from Host */
eventData.length = irp->size;
/* Get Transfer Handle */
eventData.transferHandle = ( USB_DEVICE_TRANSFER_HANDLE )irp;
/* Get transfer status */
if ((irp->status == USB_DEVICE_IRP_STATUS_COMPLETED)
|| (irp->status == USB_DEVICE_IRP_STATUS_COMPLETED_SHORT))
{
/* Transfer completed successfully */
eventData.status = USB_DEVICE_RESULT_OK;
}
else if (irp->status == USB_DEVICE_IRP_STATUS_ABORTED_ENDPOINT_HALT)
{
/* Transfer canceled due to Endpoint Halt */
eventData.status = USB_DEVICE_RESULT_ERROR_ENDPOINT_HALTED;
}
else if (irp->status == USB_DEVICE_IRP_STATUS_TERMINATED_BY_HOST)
{
/* Transfer Canceled by Host (Host sent a Clear feature )*/
eventData.status = USB_DEVICE_RESULT_ERROR_TERMINATED_BY_HOST;
}
else
{
/* Transfer was not completed successfully */
eventData.status = USB_DEVICE_RESULT_ERROR;
}
/* Send an event to application letting it know that a endpoint read
* has completed */
devClientHandle->callBackFunc(
USB_DEVICE_EVENT_ENDPOINT_READ_COMPLETE ,
&eventData,
(uintptr_t)devClientHandle->context );
}
}
void _USB_DEVICE_Initialize_Endpoint_Q_Size(SYS_MODULE_INDEX index, uint16_t qSizeRead, uint16_t qSizeWrite )
{
USB_DEVICE_Q_SIZE_ENDPOINT* thisEndpointQueue = &qSizeEndpoint[index];
thisEndpointQueue->qSizeMaxEpRead = qSizeRead;
thisEndpointQueue->qSizeMaxEpWrite = qSizeWrite;
thisEndpointQueue->qSizeCurrentEpRead = 0;
thisEndpointQueue->qSizeCurrentEpWrite = 0;
}
void _USB_DEVICE_EndpointQueueSizeReset(SYS_MODULE_INDEX index)
{
int iEntry;
/* This function is called when the device layer receives
* a Set Configuration request */
USB_DEVICE_Q_SIZE_ENDPOINT* thisEndpointQueue = &qSizeEndpoint[index];
thisEndpointQueue->qSizeCurrentEpRead = 0;
thisEndpointQueue->qSizeCurrentEpWrite = 0;
for(iEntry = 0; iEntry < USB_DEVICE_ENDPOINT_QUEUE_DEPTH_COMBINED; iEntry ++)
{
/* Get back all the IRPs */
gUSBDeviceEndpointIRP[iEntry].status = USB_DEVICE_IRP_STATUS_COMPLETED;
}
}
/********************End of file********************************/
| 37.126126 | 109 | 0.651492 | [
"object"
] |
4ba4ba3a342c6a0583eafb28bc946e9942d8de7d | 44,716 | h | C | surface/include/pcl/surface/openNURBS/opennurbs_curve.h | yxlao/StanfordPCL | 98a8663f896c1ba880d14efa2338b7cfbd01b6ef | [
"MIT"
] | null | null | null | surface/include/pcl/surface/openNURBS/opennurbs_curve.h | yxlao/StanfordPCL | 98a8663f896c1ba880d14efa2338b7cfbd01b6ef | [
"MIT"
] | null | null | null | surface/include/pcl/surface/openNURBS/opennurbs_curve.h | yxlao/StanfordPCL | 98a8663f896c1ba880d14efa2338b7cfbd01b6ef | [
"MIT"
] | null | null | null | /* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2011 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
////////////////////////////////////////////////////////////////
//
// Definition of virtual parametric curve
//
////////////////////////////////////////////////////////////////
#if !defined(OPENNURBS_CURVE_INC_)
#define OPENNURBS_CURVE_INC_
class ON_Curve;
class ON_Plane;
class ON_Arc;
class ON_NurbsCurve;
class ON_CurveTree;
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
class ON_CLASS ON_MeshCurveParameters {
public:
ON_MeshCurveParameters();
// If main_seg_count <= 0, then both these parameters are ignored.
// If main_seg_count > 0, then sub_seg_count must be >= 1. In this
// case the curve will be broken into main_seg_count equally spaced
// chords. If needed, each of these chords can be split into as many
// sub_seg_count sub-parts if the subdivision is necessary for the
// mesh to meet the other meshing constraints. In particular, if
// sub_seg_count = 0, then the curve is broken into main_seg_count
// pieces and no further testing is performed.
int m_main_seg_count;
int m_sub_seg_count;
int m_reserved1;
int m_reserved2;
// Maximum angle (in radians) between unit tangents at adjacent
// vertices.
double m_max_ang_radians;
// Maximum permitted value of
// distance chord midpoint to curve) / (length of chord)
double m_max_chr;
// If max_aspect < 1.0, the parameter is ignored.
// If 1 <= max_aspect < sqrt(2), it is treated as if
// max_aspect = sqrt(2).
// This parameter controls the maximum permitted value of
// (length of longest chord) / (length of shortest chord)
double m_max_aspect;
// If tolerance = 0, the parameter is ignored.
// This parameter controls the maximum permitted value of the
// distance from the curve to the mesh.
double m_tolerance;
// If m_min_edge_length = 0, the parameter is ignored.
// This parameter controls the minimum permitted edge length.
double m_min_edge_length;
// If max_edge_length = 0, the parameter is ignored.
// This parameter controls the maximum permitted edge length.
double m_max_edge_length;
double m_reserved3;
double m_reserved4;
};
class ON_CLASS ON_Curve : public ON_Geometry {
// pure virtual class for curve objects
// Any object derived from ON_Curve should have a
// ON_OBJECT_DECLARE(ON_...);
// as the last line of its class definition and a
// ON_OBJECT_IMPLEMENT( ON_..., ON_baseclass );
// in a .cpp file.
//
// See the definition of ON_Object for details.
ON_OBJECT_DECLARE(ON_Curve);
public:
// virtual ON_Object::DestroyRuntimeCache override
void DestroyRuntimeCache(bool bDelete = true);
public:
ON_Curve();
ON_Curve(const ON_Curve &);
ON_Curve &operator=(const ON_Curve &);
virtual ~ON_Curve();
// virtual ON_Object::SizeOf override
unsigned int SizeOf() const;
/*
Description:
Get a duplicate of the curve.
Returns:
A duplicate of the curve.
Remarks:
The caller must delete the returned curve.
For non-ON_CurveProxy objects, this simply duplicates the curve using
ON_Object::Duplicate.
For ON_CurveProxy objects, this duplicates the actual proxy curve
geometry and, if necessary, trims and reverse the result to that
the returned curve's parameterization and locus match the proxy curve's.
*/
virtual ON_Curve *DuplicateCurve() const;
// Description:
// overrides virtual ON_Object::ObjectType.
// Returns:
// ON::curve_object
ON::object_type ObjectType() const;
/*
Description:
Get tight bounding box of the curve.
Parameters:
tight_bbox - [in/out] tight bounding box
bGrowBox -[in] (default=false)
If true and the input tight_bbox is valid, then returned
tight_bbox is the union of the input tight_bbox and the
curve's tight bounding box.
xform -[in] (default=NULL)
If not NULL, the tight bounding box of the transformed
curve is calculated. The curve is not modified.
Returns:
True if the returned tight_bbox is set to a valid
bounding box.
*/
bool GetTightBoundingBox(ON_BoundingBox &tight_bbox, int bGrowBox = false,
const ON_Xform *xform = 0) const;
////////////////////////////////////////////////////////////////////
// curve interface
// Description:
// Gets domain of the curve
// Parameters:
// t0 - [out]
// t1 - [out] domain is [*t0, *t1]
// Returns:
// true if successful.
ON_BOOL32 GetDomain(double *t0, double *t1) const;
// Returns:
// domain of the curve.
virtual ON_Interval Domain() const = 0;
/*
Description:
Set the domain of the curve.
Parameters:
domain - [in] increasing interval
Returns:
true if successful.
*/
bool SetDomain(ON_Interval domain);
// Description:
// Set the domain of the curve
// Parameters:
// t0 - [in]
// t1 - [in] new domain will be [t0,t1]
// Returns:
// true if successful.
virtual ON_BOOL32 SetDomain(double t0, double t1);
/*
Description:
If this curve is closed, then modify it so that
the start/end point is at curve parameter t.
Parameters:
t - [in] curve parameter of new start/end point. The
returned curves domain will start at t.
Returns:
true if successful.
*/
virtual ON_BOOL32 ChangeClosedCurveSeam(double t);
/*
Description:
Change the dimension of a curve.
Parameters:
desired_dimension - [in]
Returns:
true if the curve's dimension was already desired_dimension
or if the curve's dimension was successfully changed to
desired_dimension.
*/
virtual bool ChangeDimension(int desired_dimension);
// Description:
// Get number of nonempty smooth (c-infinity) spans in curve
// Returns:
// Number of nonempty smooth (c-infinity) spans.
virtual int SpanCount() const = 0;
// Description:
// Get number of parameters of "knots".
// Parameters:
// knots - [out] an array of length SpanCount()+1 is filled in
// with the parameters where the curve is not smooth (C-infinity).
// Returns:
// true if successful
virtual ON_BOOL32 GetSpanVector(double *knots) const = 0; //
//////////
// If t is in the domain of the curve, GetSpanVectorIndex() returns the
// span vector index "i" such that span_vector[i] <= t <= span_vector[i+1].
// The "side" parameter determines which span is selected when t is at the
// end of a span.
virtual ON_BOOL32 GetSpanVectorIndex(
double t, // [IN] t = evaluation parameter
int side, // [IN] side 0 = default, -1 = from below, +1 = from above
int *span_vector_index, // [OUT] span vector index
ON_Interval *span_domain // [OUT] domain of the span containing "t"
) const;
// Description:
// Returns maximum algebraic degree of any span
// or a good estimate if curve spans are not algebraic.
// Returns:
// degree
virtual int Degree() const = 0;
// Description:
// Returns maximum algebraic degree of any span
// or a good estimate if curve spans are not algebraic.
// Returns:
// degree
virtual ON_BOOL32 GetParameterTolerance( // returns tminus < tplus:
// parameters tminus <= s <= tplus
double t, // [IN] t = parameter in domain
double *tminus, // [OUT] tminus
double *tplus // [OUT] tplus
) const;
// Description:
// Test a curve to see if the locus if its points is a line segment.
// Parameters:
// tolerance - [in] // tolerance to use when checking linearity
// Returns:
// true if the ends of the curve are farther than tolerance apart
// and the maximum distance from any point on the curve to
// the line segment connecting the curve's ends is <= tolerance.
virtual ON_BOOL32 IsLinear(double tolerance = ON_ZERO_TOLERANCE) const;
/*
Description:
Several types of ON_Curve can have the form of a polyline including
a degree 1 ON_NurbsCurve, an ON_PolylineCurve, and an ON_PolyCurve
all of whose segments are some form of polyline. IsPolyline tests
a curve to see if it can be represented as a polyline.
Parameters:
pline_points - [out] if not NULL and true is returned, then the
points of the polyline form are returned here.
t - [out] if not NULL and true is returned, then the parameters of
the polyline points are returned here.
Returns:
@untitled table
0 curve is not some form of a polyline
>=2 number of points in polyline form
*/
virtual int IsPolyline(ON_SimpleArray<ON_3dPoint> *pline_points = NULL,
ON_SimpleArray<double> *pline_t = NULL) const;
// Description:
// Test a curve to see if the locus if its points is an arc or circle.
// Parameters:
// plane - [in] if not NULL, test is performed in this plane
// arc - [out] if not NULL and true is returned, then arc parameters
// are filled in
// tolerance - [in] tolerance to use when checking
// Returns:
// ON_Arc.m_angle > 0 if curve locus is an arc between
// specified points. If ON_Arc.m_angle is 2.0*ON_PI, then the curve
// is a circle.
virtual ON_BOOL32 IsArc(const ON_Plane *plane = NULL, ON_Arc *arc = NULL,
double tolerance = ON_ZERO_TOLERANCE) const;
/*
Description:
Parameters:
t - [in] curve parameter
plane - [in]
if not NULL, test is performed in this plane
arc - [out]
if not NULL and true is returned, then arc parameters
are filled in
tolerance - [in]
tolerance to use when checking
t0 - [out]
if not NULL, and then *t0 is set to the parameter
at the start of the G2 curve segment that was
tested.
t1 - [out]
if not NULL, and then *t0 is set to the parameter
at the start of the G2 curve segment that was
tested.
Returns:
True if the paramter t is on a arc segment of the curve.
*/
bool IsArcAt(double t, const ON_Plane *plane = 0, ON_Arc *arc = 0,
double tolerance = ON_ZERO_TOLERANCE, double *t0 = 0,
double *t1 = 0) const;
virtual bool IsEllipse(const ON_Plane *plane = NULL,
ON_Ellipse *ellipse = NULL,
double tolerance = ON_ZERO_TOLERANCE) const;
// Description:
// Test a curve to see if it is planar.
// Parameters:
// plane - [out] if not NULL and true is returned,
// the plane parameters are filled in.
// tolerance - [in] tolerance to use when checking
// Returns:
// true if there is a plane such that the maximum distance from
// the curve to the plane is <= tolerance.
virtual ON_BOOL32 IsPlanar(ON_Plane *plane = NULL,
double tolerance = ON_ZERO_TOLERANCE) const;
// Description:
// Test a curve to see if it lies in a specific plane.
// Parameters:
// test_plane - [in]
// tolerance - [in] tolerance to use when checking
// Returns:
// true if the maximum distance from the curve to the
// test_plane is <= tolerance.
virtual ON_BOOL32 IsInPlane(const ON_Plane &test_plane,
double tolerance = ON_ZERO_TOLERANCE) const = 0;
/*
Description:
Decide if it makes sense to close off this curve by moving
the endpoint to the start based on start-end gap size and length
of curve as approximated by chord defined by 6 points.
Parameters:
tolerance - [in] maximum allowable distance between start and end.
if start - end gap is greater than tolerance, returns
false min_abs_size - [in] if greater than 0.0 and none of the interior
sampled points are at least min_abs_size from start, returns false.
min_rel_size - [in] if greater than 1.0 and chord length is less than
min_rel_size*gap, returns false.
Returns:
true if start and end points are close enough based on above conditions.
*/
bool IsClosable(double tolerance, double min_abs_size = 0.0,
double min_rel_size = 10.0) const;
// Description:
// Test a curve to see if it is closed.
// Returns:
// true if the curve is closed.
virtual ON_BOOL32 IsClosed() const;
// Description:
// Test a curve to see if it is periodic.
// Returns:
// true if the curve is closed and at least C2 at the start/end.
virtual ON_BOOL32 IsPeriodic() const;
/*
Description:
Search for a derivatitive, tangent, or curvature
discontinuity.
Parameters:
c - [in] type of continity to test for.
t0 - [in] Search begins at t0. If there is a discontinuity
at t0, it will be ignored. This makes it
possible to repeatedly call GetNextDiscontinuity
and step through the discontinuities.
t1 - [in] (t0 != t1) If there is a discontinuity at t1 is
will be ingored unless c is a locus discontinuity
type and t1 is at the start or end of the curve.
t - [out] if a discontinuity is found, then *t reports the
parameter at the discontinuity.
hint - [in/out] if GetNextDiscontinuity will be called
repeatedly, passing a "hint" with initial value *hint=0
will increase the speed of the search.
dtype - [out] if not NULL, *dtype reports the kind of
discontinuity found at *t. A value of 1 means the first
derivative or unit tangent was discontinuous. A value
of 2 means the second derivative or curvature was
discontinuous. A value of 0 means teh curve is not
closed, a locus discontinuity test was applied, and
t1 is at the start of end of the curve.
cos_angle_tolerance - [in] default = cos(1 degree) Used only
when c is ON::G1_continuous or ON::G2_continuous. If the
cosine of the angle between two tangent vectors is
<= cos_angle_tolerance, then a G1 discontinuity is reported.
curvature_tolerance - [in] (default = ON_SQRT_EPSILON) Used
only when c is ON::G2_continuous. If K0 and K1 are
curvatures evaluated from above and below and
|K0 - K1| > curvature_tolerance, then a curvature
discontinuity is reported.
Returns:
Parametric continuity tests c = (C0_continuous, ..., G2_continuous):
true if a parametric discontinuity was found strictly
between t0 and t1. Note well that all curves are
parametrically continuous at the ends of their domains.
Locus continuity tests c = (C0_locus_continuous, ...,G2_locus_continuous):
true if a locus discontinuity was found strictly between
t0 and t1 or at t1 is the at the end of a curve.
Note well that all open curves (IsClosed()=false) are locus
discontinuous at the ends of their domains. All closed
curves (IsClosed()=true) are at least C0_locus_continuous at
the ends of their domains.
*/
virtual bool GetNextDiscontinuity(
ON::continuity c, double t0, double t1, double *t, int *hint = NULL,
int *dtype = NULL,
double cos_angle_tolerance = ON_DEFAULT_ANGLE_TOLERANCE_COSINE,
double curvature_tolerance = ON_SQRT_EPSILON) const;
/*
Description:
Test continuity at a curve parameter value.
Parameters:
c - [in] type of continuity to test for. Read ON::continuity
comments for details.
t - [in] parameter to test
hint - [in] evaluation hint
point_tolerance - [in] if the distance between two points is
greater than point_tolerance, then the curve is not C0.
d1_tolerance - [in] if the difference between two first derivatives is
greater than d1_tolerance, then the curve is not C1.
d2_tolerance - [in] if the difference between two second derivatives is
greater than d2_tolerance, then the curve is not C2.
cos_angle_tolerance - [in] default = cos(1 degree) Used only when
c is ON::G1_continuous or ON::G2_continuous. If the cosine
of the angle between two tangent vectors
is <= cos_angle_tolerance, then a G1 discontinuity is reported.
curvature_tolerance - [in] (default = ON_SQRT_EPSILON) Used only when
c is ON::G2_continuous or ON::Gsmooth_continuous.
ON::G2_continuous:
If K0 and K1 are curvatures evaluated
from above and below and |K0 - K1| > curvature_tolerance,
then a curvature discontinuity is reported.
ON::Gsmooth_continuous:
If K0 and K1 are curvatures evaluated from above and below
and the angle between K0 and K1 is at least twice angle tolerance
or ||K0| - |K1|| > (max(|K0|,|K1|) > curvature_tolerance,
then a curvature discontinuity is reported.
Returns:
true if the curve has at least the c type continuity at
the parameter t.
*/
virtual bool
IsContinuous(ON::continuity c, double t, int *hint = NULL,
double point_tolerance = ON_ZERO_TOLERANCE,
double d1_tolerance = ON_ZERO_TOLERANCE,
double d2_tolerance = ON_ZERO_TOLERANCE,
double cos_angle_tolerance = ON_DEFAULT_ANGLE_TOLERANCE_COSINE,
double curvature_tolerance = ON_SQRT_EPSILON) const;
// Description:
// Reverse the direction of the curve.
// Returns:
// true if curve was reversed.
// Remarks:
// If reveresed, the domain changes from [a,b] to [-b,-a]
virtual ON_BOOL32 Reverse() = 0;
/*
Description:
Force the curve to start at a specified point.
Parameters:
start_point - [in]
Returns:
true if successful.
Remarks:
Some end points cannot be moved. Be sure to check return
code.
See Also:
ON_Curve::SetEndPoint
ON_Curve::PointAtStart
ON_Curve::PointAtEnd
*/
virtual ON_BOOL32 SetStartPoint(ON_3dPoint start_point);
/*
Description:
Force the curve to end at a specified point.
Parameters:
end_point - [in]
Returns:
true if successful.
Remarks:
Some end points cannot be moved. Be sure to check return
code.
See Also:
ON_Curve::SetStartPoint
ON_Curve::PointAtStart
ON_Curve::PointAtEnd
*/
virtual ON_BOOL32 SetEndPoint(ON_3dPoint end_point);
// Description:
// Evaluate point at a parameter.
// Parameters:
// t - [in] evaluation parameter
// Returns:
// Point (location of curve at the parameter t).
// Remarks:
// No error handling.
// See Also:
// ON_Curve::EvPoint
// ON_Curve::PointAtStart
// ON_Curve::PointAtEnd
ON_3dPoint PointAt(double t) const;
// Description:
// Evaluate point at the start of the curve.
// Parameters:
// t - [in] evaluation parameter
// Returns:
// Point (location of the start of the curve.)
// Remarks:
// No error handling.
// See Also:
// ON_Curve::PointAt
ON_3dPoint PointAtStart() const;
// Description:
// Evaluate point at the end of the curve.
// Parameters:
// t - [in] evaluation parameter
// Returns:
// Point (location of the end of the curve.)
// Remarks:
// No error handling.
// See Also:
// ON_Curve::PointAt
ON_3dPoint PointAtEnd() const;
// Description:
// Evaluate first derivative at a parameter.
// Parameters:
// t - [in] evaluation parameter
// Returns:
// First derivative of the curve at the parameter t.
// Remarks:
// No error handling.
// See Also:
// ON_Curve::Ev1Der
ON_3dVector DerivativeAt(double t) const;
// Description:
// Evaluate unit tangent vector at a parameter.
// Parameters:
// t - [in] evaluation parameter
// Returns:
// Unit tangent vector of the curve at the parameter t.
// Remarks:
// No error handling.
// See Also:
// ON_Curve::EvTangent
ON_3dVector TangentAt(double t) const;
// Description:
// Evaluate the curvature vector at a parameter.
// Parameters:
// t - [in] evaluation parameter
// Returns:
// curvature vector of the curve at the parameter t.
// Remarks:
// No error handling.
// See Also:
// ON_Curve::EvCurvature
ON_3dVector CurvatureAt(double t) const;
// Description:
// Return a 3d frame at a parameter.
// Parameters:
// t - [in] evaluation parameter
// plane - [out] the frame is returned here
// Returns:
// true if successful
// See Also:
// ON_Curve::PointAt, ON_Curve::TangentAt,
// ON_Curve::Ev1Der, Ev2Der
ON_BOOL32 FrameAt(double t, ON_Plane &plane) const;
// Description:
// Evaluate point at a parameter with error checking.
// Parameters:
// t - [in] evaluation parameter
// point - [out] value of curve at t
// side - [in] optional - determines which side to evaluate from
// =0 default
// <0 to evaluate from below,
// >0 to evaluate from above
// hint - [in/out] optional evaluation hint used to speed repeated
// evaluations
// Returns:
// false if unable to evaluate.
// See Also:
// ON_Curve::PointAt
// ON_Curve::EvTangent
// ON_Curve::Evaluate
ON_BOOL32 EvPoint(double t, ON_3dPoint &point, int side = 0,
int *hint = 0) const;
// Description:
// Evaluate first derivative at a parameter with error checking.
// Parameters:
// t - [in] evaluation parameter
// point - [out] value of curve at t
// first_derivative - [out] value of first derivative at t
// side - [in] optional - determines which side to evaluate from
// =0 default
// <0 to evaluate from below,
// >0 to evaluate from above
// hint - [in/out] optional evaluation hint used to speed repeated
// evaluations
// Returns:
// false if unable to evaluate.
// See Also:
// ON_Curve::EvPoint
// ON_Curve::Ev2Der
// ON_Curve::EvTangent
// ON_Curve::Evaluate
ON_BOOL32 Ev1Der(double t, ON_3dPoint &point, ON_3dVector &first_derivative,
int side = 0, int *hint = 0) const;
// Description:
// Evaluate second derivative at a parameter with error checking.
// Parameters:
// t - [in] evaluation parameter
// point - [out] value of curve at t
// first_derivative - [out] value of first derivative at t
// second_derivative - [out] value of second derivative at t
// side - [in] optional - determines which side to evaluate from
// =0 default
// <0 to evaluate from below,
// >0 to evaluate from above
// hint - [in/out] optional evaluation hint used to speed repeated
// evaluations
// Returns:
// false if unable to evaluate.
// See Also:
// ON_Curve::Ev1Der
// ON_Curve::EvCurvature
// ON_Curve::Evaluate
ON_BOOL32 Ev2Der(double t, ON_3dPoint &point, ON_3dVector &first_derivative,
ON_3dVector &second_derivative, int side = 0,
int *hint = 0) const;
/*
Description:
Evaluate unit tangent at a parameter with error checking.
Parameters:
t - [in] evaluation parameter
point - [out] value of curve at t
tangent - [out] value of unit tangent
side - [in] optional - determines which side to evaluate from
=0 default
<0 to evaluate from below,
>0 to evaluate from above
hint - [in/out] optional evaluation hint used to speed repeated
evaluations Returns: false if unable to evaluate. See Also:
ON_Curve::TangentAt
ON_Curve::Ev1Der
*/
ON_BOOL32 EvTangent(double t, ON_3dPoint &point, ON_3dVector &tangent,
int side = 0, int *hint = 0) const;
/*
Description:
Evaluate unit tangent and curvature at a parameter with error checking.
Parameters:
t - [in] evaluation parameter
point - [out] value of curve at t
tangent - [out] value of unit tangent
kappa - [out] value of curvature vector
side - [in] optional - determines which side to evaluate from
=0 default
<0 to evaluate from below,
>0 to evaluate from above
hint - [in/out] optional evaluation hint used to speed repeated
evaluations Returns: false if unable to evaluate. See Also:
ON_Curve::CurvatureAt
ON_Curve::Ev2Der
ON_EvCurvature
*/
ON_BOOL32 EvCurvature(double t, ON_3dPoint &point, ON_3dVector &tangent,
ON_3dVector &kappa, int side = 0,
int *hint = 0) const;
/*
Description:
This evaluator actually does all the work. The other ON_Curve
evaluation tools call this virtual function.
Parameters:
t - [in] evaluation parameter ( usually in Domain() ).
der_count - [in] (>=0) number of derivatives to evaluate
v_stride - [in] (>=Dimension()) stride to use for the v[] array
v - [out] array of length (der_count+1)*v_stride
curve(t) is returned in (v[0],...,v[m_dim-1]),
curve'(t) is retuned in (v[v_stride],...,v[v_stride+m_dim-1]),
curve"(t) is retuned in (v[2*v_stride],...,v[2*v_stride+m_dim-1]),
etc.
side - [in] optional - determines which side to evaluate from
=0 default
<0 to evaluate from below,
>0 to evaluate from above
hint - [in/out] optional evaluation hint used to speed repeated
evaluations Returns: false if unable to evaluate. See Also:
ON_Curve::EvPoint
ON_Curve::Ev1Der
ON_Curve::Ev2Der
*/
virtual ON_BOOL32 Evaluate(double t, int der_count, int v_stride, double *v,
int side = 0, int *hint = 0) const = 0;
/*
Parameters:
min_length -[in]
minimum length of a linear span
tolerance -[in]
distance tolerance to use when checking linearity.
Returns
true if the span is a non-degenrate line. This means:
- dimension = 2 or 3
- The length of the the line segment from the span's initial
point to the span's control point is >= min_length.
- The maximum distance from the line segment to the span
is <= tolerance and the span increases monotonically
in the direction of the line segment.
*/
bool FirstSpanIsLinear(double min_length, double tolerance) const;
bool LastSpanIsLinear(double min_length, double tolerance) const;
// Description:
// Removes portions of the curve outside the specified interval.
// Parameters:
// domain - [in] interval of the curve to keep. Portions of the
// curve before curve(domain[0]) and after curve(domain[1]) are
// removed.
// Returns:
// true if successful.
virtual ON_BOOL32 Trim(const ON_Interval &domain);
// Description:
// Pure virtual function. Default returns false.
// Where possible, analytically extends curve to include domain.
// Parameters:
// domain - [in] if domain is not included in curve domain,
// curve will be extended so that its domain includes domain.
// Will not work if curve is closed. Original curve is identical
// to the restriction of the resulting curve to the original curve domain,
// Returns:
// true if successful.
virtual bool Extend(const ON_Interval &domain);
/*
Description:
Splits (divides) the curve at the specified parameter.
The parameter must be in the interior of the curve's domain.
The pointers passed to Split must either be NULL or point to
an ON_Curve object of the same type. If the pointer is NULL,
then a curve will be created in Split(). You may pass "this"
as left_side or right_side.
Parameters:
t - [in] parameter to split the curve at in the
interval returned by Domain().
left_side - [out] left portion of curve returned here
right_side - [out] right portion of curve returned here
Returns:
true - The curve was split into two pieces.
false - The curve could not be split. For example if the
parameter is too close to an endpoint.
Example:
For example, if crv were an ON_NurbsCurve, then
ON_NurbsCurve right_side;
crv.Split( crv.Domain().Mid() &crv, &right_side );
would split crv at the parametric midpoint, put the left side
in crv, and return the right side in right_side.
*/
virtual ON_BOOL32 Split(double t, ON_Curve *&left_side,
ON_Curve *&right_side) const;
/*
Description:
Get a NURBS curve representation of this curve.
Parameters:
nurbs_curve - [out] NURBS representation returned here
tolerance - [in] tolerance to use when creating NURBS
representation.
subdomain - [in] if not NULL, then the NURBS representation
for this portion of the curve is returned.
Returns:
0 unable to create NURBS representation
with desired accuracy.
1 success - returned NURBS parameterization
matches the curve's to wthe desired accuracy
2 success - returned NURBS point locus matches
the curve's to the desired accuracy and the
domain of the NURBS curve is correct. On
However, This curve's parameterization and
the NURBS curve parameterization may not
match to the desired accuracy. This situation
happens when getting NURBS representations of
curves that have a transendental parameterization
like circles
Remarks:
This is a low-level virtual function. If you do not need
the parameterization information provided by the return code,
then ON_Curve::NurbsCurve may be easier to use.
See Also:
ON_Curve::NurbsCurve
*/
virtual int GetNurbForm(ON_NurbsCurve &nurbs_curve, double tolerance = 0.0,
const ON_Interval *subdomain = NULL) const;
/*
Description:
Does a NURBS curve representation of this curve.
Parameters:
Returns:
0 unable to create NURBS representation
with desired accuracy.
1 success - NURBS parameterization
matches the curve's to wthe desired accuracy
2 success - NURBS point locus matches
the curve's and the
domain of the NURBS curve is correct.
However, This curve's parameterization and
the NURBS curve parameterization may not
match. This situation
happens when getting NURBS representations of
curves that have a transendental parameterization
like circles
Remarks:
This is a low-level virtual function.
See Also:
ON_Curve::GetNurbForm
ON_Curve::NurbsCurve
*/
virtual int HasNurbForm() const;
/*
Description:
Get a NURBS curve representation of this curve.
Parameters:
pNurbsCurve - [in/out] if not NULL, this ON_NurbsCurve
will be used to store the NURBS representation
of the curve will be returned.
tolerance - [in] tolerance to use when creating NURBS
representation.
subdomain - [in] if not NULL, then the NURBS representation
for this portion of the curve is returned.
Returns:
NULL or a NURBS representation of the curve.
Remarks:
See ON_Surface::GetNurbForm for important details about
the NURBS surface parameterization.
See Also:
ON_Curve::GetNurbForm
*/
ON_NurbsCurve *NurbsCurve(ON_NurbsCurve *pNurbsCurve = NULL,
double tolerance = 0.0,
const ON_Interval *subdomain = NULL) const;
// Description:
// Convert a NURBS curve parameter to a curve parameter
//
// Parameters:
// nurbs_t - [in] nurbs form parameter
// curve_t - [out] curve parameter
//
// Remarks:
// If GetNurbForm returns 2, this function converts the curve
// parameter to the NURBS curve parameter.
//
// See Also:
// ON_Curve::GetNurbForm, ON_Curve::GetNurbFormParameterFromCurveParameter
virtual ON_BOOL32
GetCurveParameterFromNurbFormParameter(double nurbs_t,
double *curve_t) const;
// Description:
// Convert a curve parameter to a NURBS curve parameter.
//
// Parameters:
// curve_t - [in] curve parameter
// nurbs_t - [out] nurbs form parameter
//
// Remarks:
// If GetNurbForm returns 2, this function converts the curve
// parameter to the NURBS curve parameter.
//
// See Also:
// ON_Curve::GetNurbForm, ON_Curve::GetCurveParameterFromNurbFormParameter
virtual ON_BOOL32
GetNurbFormParameterFromCurveParameter(double curve_t,
double *nurbs_t) const;
/*
Description:
Mesh a curve into line segments.
Parameters:
mp - [in]
Parameters that determine how the curve will be
approximated by a polyline.
polyline - [in]
If not NULL, the polyline approximation will be appended
to this polyline.
bSkipFirstPoint - [in]
If true, the starting point of the approximation
will not be added to the returned polyline. This
parameter is useful when getting a polyline approximation
of a sequence of contiguous curves.
domain - [in]
If not NULL, the polyline approximation will be restricted
to this domain.
Returns:
A pointer to the polyline approximation.
*/
class ON_PolylineCurve *MeshCurve(ON_MeshCurveParameters &mp,
ON_PolylineCurve *polyline,
bool bSkipFirstPoint,
const ON_Interval *domain) const;
// The non-const version of MeshCurve() exists because a version of the
// SDK was shipped with the "const" tag missing. The non-const
// version does not modify this.
class ON_PolylineCurve *MeshCurve(ON_MeshCurveParameters &mp,
ON_PolylineCurve *polyline,
bool bSkipFirstPoint,
const ON_Interval *domain);
protected:
bool ParameterSearch(double t, int &index, bool bEnableSnap,
const ON_SimpleArray<double> &m_t,
double RelTol = ON_SQRT_EPSILON) const;
};
#if defined(ON_DLL_TEMPLATE)
// This stuff is here because of a limitation in the way Microsoft
// handles templates and DLLs. See Microsoft's knowledge base
// article ID Q168958 for details.
#pragma warning(push)
#pragma warning(disable : 4231)
ON_DLL_TEMPLATE template class ON_CLASS ON_SimpleArray<ON_Curve *>;
#pragma warning(pop)
#endif
class ON_CLASS ON_CurveArray : public ON_SimpleArray<ON_Curve *> {
public:
ON_CurveArray(int = 0);
~ON_CurveArray(); // deletes any non-NULL curves
bool Write(ON_BinaryArchive &) const;
bool Read(ON_BinaryArchive &);
void Destroy(); // deletes curves, sets pointers to NULL, sets count to zero
bool
Duplicate(ON_CurveArray &) const; // operator= copies the pointer values
// duplicate copies the curves themselves
/*
Description:
Get tight bounding box of the bezier.
Parameters:
tight_bbox - [in/out] tight bounding box
bGrowBox -[in] (default=false)
If true and the input tight_bbox is valid, then returned
tight_bbox is the union of the input tight_bbox and the
tight bounding box of the bezier curve.
xform -[in] (default=NULL)
If not NULL, the tight bounding box of the transformed
bezier is calculated. The bezier curve is not modified.
Returns:
True if the returned tight_bbox is set to a valid
bounding box.
*/
bool GetTightBoundingBox(ON_BoundingBox &tight_bbox, int bGrowBox = false,
const ON_Xform *xform = 0) const;
};
/*
Description:
Trim a curve.
Parameters:
curve - [in] curve to trim (not modified)
trim_parameters - [in] trimming parameters
If curve is open, then trim_parameters must be an increasing
interval.If curve is closed, and trim_parameters ins a
decreasing interval, then the portion of the curve across the
start/end is returned.
Returns:
trimmed curve or NULL if input is invalid.
*/
ON_DECL
ON_Curve *ON_TrimCurve(const ON_Curve &curve, ON_Interval trim_parameters);
/*
Description:
Move ends of curves to a common point. Neither curve can be closed or an
ON_CurveProxy. If one is an arc or polycurve with arc at end to change, and the
other is not, then the arc is left unchanged and the other curve is moved to the
arc endpoint. Otherwise, both are moved to the midpoint of the segment between
the ends. Parameters: Crv0 - [in] first curve to modify. [out] with one endpoint
possibly changed. end0 - [in] if 0, change start of Crv0. Otherwise change end.
Crv1 - [in] second curve to modify.
[out] with one endpoint possibly changed.
end1 - [in] if 0, change start of Crv1. Otherwise change end.
Returns:
true if the endpoints match. Falsse otherwise,
*/
ON_DECL
bool ON_ForceMatchCurveEnds(ON_Curve &Crv0, int end0, ON_Curve &Crv1, int end1);
/*
Description:
Join all contiguous curves of an array of ON_Curves.
Parameters:
InCurves - [in] Array of curves to be joined (not modified)
OutCurves - [out] Resulting joined curves and copies of curves that were not
joined to anything are appended. join_tol - [in] Distance tolerance used to
decide if endpoints are close enough bPreserveDirection - [in] If true, curve
endpoints will be compared to curve startpoints. If false, all start and
endpoints will be compared, and copies of input curves may be reversed in
output. key - [out] if key is not null, InCurves[i] was joined into
OutCurves[key[i]]. Returns: Number of curves added to Outcurves Remarks: Closed
curves are copied to OutCurves. Curves that cannot be joined to others are
copied to OutCurves. When curves are joined, the results are ON_PolyCurves. All
members of InCurves must have same dimension, at most 3.
*/
ON_DECL
int ON_JoinCurves(const ON_SimpleArray<const ON_Curve *> &InCurves,
ON_SimpleArray<ON_Curve *> &OutCurves, double join_tol,
bool bPreserveDirection = false,
ON_SimpleArray<int> *key = 0);
/*
Description:
Sort a list of lines so they are geometrically continuous.
Parameters:
line_count - [in] number of lines
line_list - [in] array of lines
index - [out] The input index[] is an array of line_count unused
integers. The returned index[] is a permutation of {0,1,...,line_count-1} so
that the list of lines is in end-to-end order. bReverse - [out] The input
bReverse[] is an array of line_count unused bools. If the returned value of
bReverse[j] is true, then line_list[index[j]] needs to be reversed. Returns:
True if successful, false if not.
*/
ON_DECL
bool ON_SortLines(int line_count, const ON_Line *line_list, int *index,
bool *bReverse);
/*
Description:
Sort a list of lines so they are geometrically continuous.
Parameters:
line_list - [in] array of lines
index - [out] The input index[] is an array of line_count unused
integers. The returned index[] is a permutation of {0,1,...,line_count-1} so
that the list of lines is in end-to-end order. bReverse - [out] The input
bReverse[] is an array of line_count unused bools. If the returned value of
bReverse[j] is true, then line_list[index[j]] needs to be reversed. Returns:
True if successful, false if not.
*/
ON_DECL
bool ON_SortLines(const ON_SimpleArray<ON_Line> &line_list, int *index,
bool *bReverse);
/*
Description:
Sort a list of open curves so end of a curve matches the start of the next
curve. Parameters: curve_count - [in] number of curves curve_list - [in] array
of curve pointers index - [out] The input index[] is an array of
curve_count unused integers. The returned index[] is a permutation of
{0,1,...,curve_count-1} so that the list of curves is in end-to-end order.
bReverse - [out] The input bReverse[] is an array of curve_count unused
bools. If the returned value of bReverse[j] is true, then curve_list[index[j]]
needs to be reversed. Returns: True if successful, false if not.
*/
ON_DECL
bool ON_SortCurves(int curve_count, const ON_Curve *const *curve_list,
int *index, bool *bReverse);
/*
Description:
Sort a list of curves so end of a curve matches the start of the next curve.
Parameters:
curve - [in] array of curves to sort. The curves themselves are not
modified. index - [out] The input index[] is an array of curve_count
unused integers. The returned index[] is a permutation of
{0,1,...,curve_count-1} so that the list of curves is in end-to-end order.
bReverse - [out] The input bReverse[] is an array of curve_count unused
bools. If the returned value of bReverse[j] is true, then curve[index[j]] needs
to be reversed. Returns: True if successful, false if not.
*/
ON_DECL
bool ON_SortCurves(const ON_SimpleArray<const ON_Curve *> &curves,
ON_SimpleArray<int> &index, ON_SimpleArray<bool> &bReverse);
/*
Description:
Sort a list of curves so end of a curve matches the start of the next curve.
Parameters:
curve_count - [in] number of curves
curve - [in] array of curve pointers
index - [out] The input index[] is an array of curve_count unused
integers. The returned index[] is a permutation of {0,1,...,curve_count-1} so
that the list of curves is in end-to-end order. bReverse - [out] The input
bReverse[] is an array of curve_count unused bools. If the returned value of
bReverse[j] is true, then curve[index[j]] needs to be reversed. Returns: True if
successful, false if not.
*/
ON_DECL
bool ON_SortCurves(const ON_SimpleArray<ON_Curve *> &curves,
ON_SimpleArray<int> &index, ON_SimpleArray<bool> &bReverse);
/*
Description:
Determine the orientaion (counterclockwise or clockwise) of a closed
planar curve.
Paramters:
curve - [in] simple (no self intersections) closed planar curve
xform - [in] Transformation to map the curve to the xy plane. If the
curve is parallel to the xy plane, you may pass NULL.
Returns:
+1: The curve's orientation is counter clockwise in the xy plane.
-1: The curve's orientation is clockwise in the xy plane.
0: Unable to compute the curve's orientation.
*/
ON_DECL
int ON_ClosedCurveOrientation(const ON_Curve &curve, const ON_Xform *xform);
#endif
| 38.481928 | 80 | 0.6374 | [
"mesh",
"geometry",
"object",
"vector",
"3d"
] |
4bb35bccb0db8bea70a6916b24e1a88ad943e68d | 1,976 | h | C | VTK/GUISupport/Qt/Chart/vtkQtPointMarker.h | matthb2/ParaView-beforekitwareswtichedtogit | e47e57d6ce88444d9e6af9ab29f9db8c23d24cef | [
"BSD-3-Clause"
] | 1 | 2021-07-31T19:38:03.000Z | 2021-07-31T19:38:03.000Z | VTK/GUISupport/Qt/Chart/vtkQtPointMarker.h | matthb2/ParaView-beforekitwareswtichedtogit | e47e57d6ce88444d9e6af9ab29f9db8c23d24cef | [
"BSD-3-Clause"
] | null | null | null | VTK/GUISupport/Qt/Chart/vtkQtPointMarker.h | matthb2/ParaView-beforekitwareswtichedtogit | e47e57d6ce88444d9e6af9ab29f9db8c23d24cef | [
"BSD-3-Clause"
] | 2 | 2019-01-22T19:51:40.000Z | 2021-07-31T19:38:05.000Z | /*=========================================================================
Program: Visualization Toolkit
Module: $RCSfile$
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/*-------------------------------------------------------------------------
Copyright 2008 Sandia Corporation.
Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
/// \file vtkQtPointMarker.h
/// \date February 12, 2008
#ifndef _vtkQtPointMarker_h
#define _vtkQtPointMarker_h
#include "vtkQtChartExport.h"
#include <QSizeF>
#include <QRectF>
class QPainter;
/// \class vtkQtPointMarker
/// \brief
/// The vtkQtPointMarker class is used to draw a shape at a point.
class VTKQTCHART_EXPORT vtkQtPointMarker
{
public:
enum MarkerStyle
{
NoMarker = 0, ///< Nothing is drawn.
Cross, ///< Draws a cross.
Plus, ///< Draws a plus.
Square, ///< Draws a square.
Circle, ///< Draws a circle.
Diamond, ///< Draws a diamond.
/// The next available style for extension classes.
UserStyle = 32
};
public:
vtkQtPointMarker(const QSizeF &size, MarkerStyle style=Circle);
virtual ~vtkQtPointMarker();
virtual void paint(QPainter *painter);
QSizeF getSize() const;
void setSize(const QSizeF &size);
MarkerStyle getStyle() const {return this->Style;}
void setStyle(MarkerStyle style);
protected:
QRectF Rect;
private:
MarkerStyle Style;
};
#endif
| 26.702703 | 75 | 0.595142 | [
"shape"
] |
15db8d935db8ebf233fb52b1616136a8429149b2 | 315 | h | C | Python/ATK/EQ/SecondOrderFilter.h | D-J-Roberts/AudioTK | accf009d7238f32702eb1d5ee23c5148fc68e3bd | [
"BSD-3-Clause"
] | 249 | 2015-01-05T13:36:26.000Z | 2022-03-15T18:47:46.000Z | Python/ATK/EQ/SecondOrderFilter.h | D-J-Roberts/AudioTK | accf009d7238f32702eb1d5ee23c5148fc68e3bd | [
"BSD-3-Clause"
] | 22 | 2015-07-28T15:20:24.000Z | 2020-07-11T14:18:19.000Z | Python/ATK/EQ/SecondOrderFilter.h | D-J-Roberts/AudioTK | accf009d7238f32702eb1d5ee23c5148fc68e3bd | [
"BSD-3-Clause"
] | 48 | 2015-08-15T12:08:13.000Z | 2021-04-07T02:33:07.000Z | /**
* \file SecondOrderFilter.h
*/
#ifndef PYTHON_ATK_EQ_SECONDORDERFILTERS_H
#define PYTHON_ATK_EQ_SECONDORDERFILTERS_H
#include <pybind11/pybind11.h>
void populate_SecondOrderFilter(pybind11::module& m,
#if ATK_ENABLE_INSTANTIATION
const pybind11::object& f1,
#endif
const pybind11::object& f2);
#endif
| 18.529412 | 52 | 0.790476 | [
"object"
] |
15dc181913d12d3c87029ddc61a96f56c7cb99c4 | 11,004 | c | C | src/db.inherit.c | belisariussmith/tinymuse | 90d4a8383505bfe8c32e253f8fcd00757e473862 | [
"MIT"
] | 1 | 2020-05-02T21:52:14.000Z | 2020-05-02T21:52:14.000Z | src/db.inherit.c | belisariussmith/tinymuse | 90d4a8383505bfe8c32e253f8fcd00757e473862 | [
"MIT"
] | null | null | null | src/db.inherit.c | belisariussmith/tinymuse | 90d4a8383505bfe8c32e253f8fcd00757e473862 | [
"MIT"
] | null | null | null | // $Header: /u/cvsroot/muse/src/db/inherit.c,v 1.6 1993/03/21 00:49:57 nils Exp $
#include <stdio.h>
#include "tinymuse.h"
#include "externs.h"
#include "config.h"
#include "db.h"
void put_atrdefs(FILE *file, ATRDEF *defs)
{
extern void putstring P((FILE *, char *));
for (; defs; defs = defs->next)
{
fputc('/', file);
putref(file, defs->a.flags);
putref(file, defs->a.obj);
putstring(file, defs->a.name);
}
fputs("\\\n", file);
}
///////////////////////////////////////////////////////////////////////////////
// get_atrdefs()
///////////////////////////////////////////////////////////////////////////////
// Used when reading in an object from the database. This typically reads
// in three lines, the first being the attribute flags, the object id, and then
// the name.
// Continues reading in atrdefs until it catches the termination char '\'
///////////////////////////////////////////////////////////////////////////////
ATRDEF *get_atrdefs(FILE *file, ATRDEF *olddefs)
{
extern char *getstring_noalloc P((FILE *));
char k;
ATRDEF *ourdefs = NULL;
ATRDEF *endptr = NULL;
int attribute = 0;
for (;;)
{
k = fgetc(file);
switch (k)
{
case '\\':
if (fgetc(file) != '\n')
{
log_error ("No atrdef newline.");
}
return ourdefs;
break;
case '/':
// An ATRDEF
// Get the attribute first
attribute = getref(file);
// Is it a valid one?
if (attribute > 8191)
{
// Invalid attribute
attribute = getref(file); // Read to ignore
attribute = getref(file); // Read to ignore
// Hop to next one
break;
}
if (!endptr)
{
if (olddefs)
{
// Previous atrdefs defined, so add to linked list
endptr = ourdefs = olddefs;
olddefs = olddefs->next;
}
else
{
// No previous atrdef defined, so allocate for a new one
endptr = ourdefs = malloc( sizeof(ATRDEF));
}
}
else
{
if (olddefs)
{
endptr->next = olddefs;
olddefs = olddefs->next;
endptr = endptr->next;
}
else
{
// No atrdef defined for next in linked list, so allocate for a new one
endptr->next = malloc( sizeof(ATRDEF));
endptr = endptr->next;
}
}
endptr->a.flags = attribute;
endptr->a.obj = getref(file);
endptr->next = NULL;
endptr->a.name = NULL;
SET (endptr->a.name, getstring_noalloc(file));
break;
default:
log_error ("Illegal character in get_atrdefs");
return 0;
}
}
}
static void remove_attribute(dbref obj, ATTR *atr)
{
int i;
atr_add (obj, atr, "");
for (i = 0; db[obj].children && db[obj].children[i] != NOTHING; i++)
{
remove_attribute (db[obj].children[i], atr);
}
}
void do_undefattr(dbref player, char *arg1)
{
dbref obj;
ATTR *atr;
ATRDEF *d;
ATRDEF *prev = NULL;
if (!parse_attrib(player, arg1, &obj, &atr, POW_MODIFY))
{
send_message(player, "No match.");
return;
}
for (d = db[obj].atrdefs; d; prev = d, d = d->next)
{
if (&(d->a) == atr)
{
if (prev)
{
prev->next = d->next;
}
else
{
db[obj].atrdefs = d->next;
}
remove_attribute (obj, atr);
if (0 == --d->a.refcount)
{
// this should always happen, but...
free(d->a.name);
free(d);
}
send_message(player, "Deleted.");
return;
}
}
send_message(player, "No match.");
}
void do_defattr(dbref player, char *arg1, char *arg2)
{
ATTR *atr;
char *flag_parse;
int atr_flags = 0;
dbref thing;
char *attribute;
int i;
if (!(attribute = strchr(arg1, '/')))
{
send_message(player, "no match");
return;
}
*(attribute++) = '\0';
thing = match_controlled(player, arg1, POW_MODIFY);
if (thing == NOTHING)
{
return;
}
if (!ok_attribute_name (attribute))
{
send_message(player,"Illegal attribute name.");
return;
}
while ((flag_parse = parse_up(&arg2,' ')))
{
if (flag_parse == NULL)
{
// empty if, so we can do else(s):
}
else if (!string_compare(flag_parse, "wizard"))
{
atr_flags |= AF_WIZARD;
}
else if (!string_compare(flag_parse, "osee"))
{
atr_flags |= AF_OSEE;
}
else if (!string_compare(flag_parse, "dark"))
{
atr_flags |= AF_DARK;
}
else if (!string_compare(flag_parse, "inherit"))
{
atr_flags |= AF_INHERIT;
}
else if (!string_compare(flag_parse, "unsaved"))
{
atr_flags |= AF_UNIMP;
}
else if (!string_compare(flag_parse, "date"))
{
atr_flags |= AF_DATE;
}
else if (!string_compare(flag_parse, "lock"))
{
atr_flags |= AF_LOCK;
}
else if (!string_compare(flag_parse, "function"))
{
atr_flags |= AF_FUNC;
}
else if (!string_compare(flag_parse, "dbref"))
{
atr_flags |= AF_DBREF;
}
else if (!string_compare(flag_parse, "haven"))
{
atr_flags |= AF_HAVEN;
}
else
{
send_message(player, "Unknown attribute option: %s",flag_parse);
}
}
atr = atr_str (thing, thing, attribute);
if (atr && atr->obj == thing)
{
atr->flags = atr_flags;
send_message(player, "Options set.");
return;
}
{
ATRDEF *attributes;
for (attributes = db[thing].atrdefs, i = 0; attributes; attributes = attributes->next, i++);
if (i > 90 && !power(player, POW_SECURITY))
{
send_message(player, "Sorry, you can't have that many attribute defs on an object.");
return;
}
if (atr)
{
send_message(player, "Sorry, attribute shadows a builtin attribute or one on a parent.");
return;
}
// Instantiate / Initialize the attributes
attributes = malloc( sizeof(ATRDEF));
attributes->a.name = NULL;
SET (attributes->a.name, attribute);
attributes->a.flags = atr_flags;
attributes->a.obj = thing;
attributes->a.refcount = 1;
attributes->next = db[thing].atrdefs;
// Now assign it
db[thing].atrdefs = attributes;
}
send_message(player, "Attribute defined.");
}
static int is_a_internal(dbref thing, dbref parent, int dep)
{
if (thing == parent)
{
return TRUE;
}
if (dep < 0)
{
return TRUE;
}
if (!db[thing].parents)
{
return FALSE;
}
for (int j = 0; db[thing].parents[j] != NOTHING; j++)
{
if (is_a_internal (db[thing].parents[j], parent, dep-1))
{
return TRUE;
}
}
return FALSE;
}
int is_a(dbref thing, dbref parent)
{
if (thing == NOTHING)
{
return TRUE;
}
return (is_a_internal(thing, parent, 20)); // 20 is the max depth
}
void do_delparent(dbref player, char *arg1, char *arg2)
{
dbref thing;
dbref parent;
int can_doit = FALSE;
thing = match_controlled(player, arg1 , POW_MODIFY);
if (thing == NOTHING)
{
return;
}
mark_hearing(thing);
parent = match_thing (player, arg2);
if (parent == NOTHING)
{
return;
}
if (!(db[parent].flags&BEARING) && !controls(player,parent,POW_MODIFY))
{
send_message(player, "Sorry, you can't unparent from that.");
can_doit = TRUE;
}
for (int i = 0; db[thing].parents && db[thing].parents[i] != NOTHING; i++)
{
if (db[thing].parents[i] == parent)
{
can_doit |= 2;
}
}
if (!(can_doit&2))
{
send_message(player, "Sorry, it doesn't have that as its parent.");
}
if (can_doit != 2)
{
return;
}
REMOVE_FIRST_L (db[thing].parents, parent);
REMOVE_FIRST_L (db[parent].children, thing);
send_message(player, "%s is no longer a parent of %s.", unparse_object_a (player, parent), unparse_object_a (player, thing));
check_hearing();
did_it(thing, parent, A_UNPARENT, NULL, A_OUNPARENT, NULL, A_AUNPARENT);
did_it(player, parent, A_UNPARENT, NULL, A_OUNPARENT, NULL, A_AUNPARENT);
}
void do_addparent(dbref player, char *arg1, char *arg2)
{
dbref thing;
dbref parent;
int i;
int can_doit = FALSE;
thing = match_controlled(player, arg1 , POW_MODIFY);
if (thing == NOTHING)
{
return;
}
mark_hearing(thing);
parent = match_thing(player, arg2);
if (parent == NOTHING)
{
return;
}
if (is_a(parent, thing))
{
send_message(player, "but %s is a descendant of %s!", unparse_object_a (player, parent), unparse_object_a (player, thing));
can_doit |= 4;
}
if (!(db[parent].flags&BEARING) && !controls(player,parent,POW_MODIFY))
{
send_message(player, "Sorry, you can't parent to that.");
can_doit |= 1;
}
for (i = 0; db[thing].parents && db[thing].parents[i] != NOTHING; i++)
{
if (db[thing].parents[i] == parent)
{
can_doit |= 2;
}
}
if (can_doit & 2)
{
send_message(player, "Sorry, it already has that as its parent.");
}
if (can_doit != 0)
{
return;
}
PUSH_L (db[thing].parents, parent);
PUSH_L (db[parent].children, thing);
send_message(player, "%s is now a parent of %s.", unparse_object_a (player, parent), unparse_object_a (player, thing));
check_hearing();
did_it(thing, parent, A_PARENT, NULL, A_OPARENT, NULL, A_APARENT);
did_it(player, parent, A_PARENT, NULL, A_OPARENT, NULL, A_APARENT);
}
| 24.453333 | 131 | 0.481643 | [
"object"
] |
15e27283021c067c376eb6bbc907de3f76c679c3 | 2,184 | h | C | llvm/include/llvm/Analysis/ScalarEvolutionAliasAnalysis.h | lxbndr/llvm-project | 2b715b15f5f4c6dd60f05d1b62f9c404e8b56e34 | [
"Apache-2.0"
] | null | null | null | llvm/include/llvm/Analysis/ScalarEvolutionAliasAnalysis.h | lxbndr/llvm-project | 2b715b15f5f4c6dd60f05d1b62f9c404e8b56e34 | [
"Apache-2.0"
] | null | null | null | llvm/include/llvm/Analysis/ScalarEvolutionAliasAnalysis.h | lxbndr/llvm-project | 2b715b15f5f4c6dd60f05d1b62f9c404e8b56e34 | [
"Apache-2.0"
] | null | null | null | //===- ScalarEvolutionAliasAnalysis.h - SCEV-based AA -----------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
/// \file
/// This is the interface for a SCEV-based alias analysis.
///
//===----------------------------------------------------------------------===//
#ifndef LLVM_ANALYSIS_SCALAREVOLUTIONALIASANALYSIS_H
#define LLVM_ANALYSIS_SCALAREVOLUTIONALIASANALYSIS_H
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Pass.h"
namespace llvm {
class Function;
class ScalarEvolution;
class SCEV;
/// A simple alias analysis implementation that uses ScalarEvolution to answer
/// queries.
class SCEVAAResult : public AAResultBase<SCEVAAResult> {
ScalarEvolution &SE;
public:
explicit SCEVAAResult(ScalarEvolution &SE) : SE(SE) {}
SCEVAAResult(SCEVAAResult &&Arg) : AAResultBase(std::move(Arg)), SE(Arg.SE) {}
AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB,
AAQueryInfo &AAQI);
bool invalidate(Function &F, const PreservedAnalyses &PA,
FunctionAnalysisManager::Invalidator &Inv);
private:
Value *GetBaseValue(const SCEV *S);
};
/// Analysis pass providing a never-invalidated alias analysis result.
class SCEVAA : public AnalysisInfoMixin<SCEVAA> {
friend AnalysisInfoMixin<SCEVAA>;
static AnalysisKey Key;
public:
typedef SCEVAAResult Result;
SCEVAAResult run(Function &F, FunctionAnalysisManager &AM);
};
/// Legacy wrapper pass to provide the SCEVAAResult object.
class SCEVAAWrapperPass : public FunctionPass {
std::unique_ptr<SCEVAAResult> Result;
public:
static char ID;
SCEVAAWrapperPass();
SCEVAAResult &getResult() { return *Result; }
const SCEVAAResult &getResult() const { return *Result; }
bool runOnFunction(Function &F) override;
void getAnalysisUsage(AnalysisUsage &AU) const override;
};
/// Creates an instance of \c SCEVAAWrapperPass.
FunctionPass *createSCEVAAWrapperPass();
}
#endif
| 28.363636 | 80 | 0.684524 | [
"object"
] |
15e93bae12bab2baf43758f889cdd6b26cb893b4 | 32,304 | h | C | webkit/glue/webview_delegate.h | bluebellzhy/chromium | 008c4fef2676506869a0404239da31e83fd6ccc7 | [
"BSD-3-Clause"
] | 1 | 2016-05-08T15:35:17.000Z | 2016-05-08T15:35:17.000Z | webkit/glue/webview_delegate.h | bluebellzhy/chromium | 008c4fef2676506869a0404239da31e83fd6ccc7 | [
"BSD-3-Clause"
] | null | null | null | webkit/glue/webview_delegate.h | bluebellzhy/chromium | 008c4fef2676506869a0404239da31e83fd6ccc7 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2006-2008 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.
// WebCore provides hooks for several kinds of functionality, allowing separate
// classes termed "delegates" to receive notifications (in the form of direct
// function calls) when certain events are about to occur or have just occurred.
// In some cases, the delegate implements the needed functionality; in others,
// the delegate has some control over the behavior but doesn't actually
// implement it. For example, the UI delegate is responsible for showing a
// dialog box or otherwise handling a JavaScript window.alert() call, via the
// RunJavaScriptAlert() method. On the other hand, the editor delegate doesn't
// actually handle editing functionality, although it could (for example)
// override whether a content-editable node accepts editing focus by returning
// false from ShouldBeginEditing(). (It would also possible for a more
// special-purpose editing delegate to act on the edited node in some way, e.g.
// to highlight modified text in the DidChangeContents() method.)
// WebKit divides the delegated tasks into several different classes, but we
// combine them into a single WebViewDelegate. This single delegate encompasses
// the needed functionality of the WebKit UIDelegate, ContextMenuDelegate,
// PolicyDelegate, FrameLoadDelegate, and EditorDelegate; additional portions
// of ChromeClient and FrameLoaderClient not delegated in the WebKit
// implementation; and some WebView additions.
#ifndef WEBKIT_GLUE_WEBVIEW_DELEGATE_H__
#define WEBKIT_GLUE_WEBVIEW_DELEGATE_H__
#include <string>
#include <vector>
#include "base/basictypes.h"
#include "googleurl/src/gurl.h"
#include "webkit/glue/context_node_types.h"
#include "webkit/glue/webwidget_delegate.h"
#include "webkit/glue/window_open_disposition.h"
namespace gfx {
class Point;
class Rect;
}
struct PasswordForm;
struct WebDropData;
struct WebPreferences;
class SkBitmap;
class WebError;
class WebFrame;
class WebHistoryItem;
class WebPluginDelegate;
class WebRequest;
class WebResponse;
class WebView;
class WebWidget;
enum WebNavigationType {
WebNavigationTypeLinkClicked,
WebNavigationTypeFormSubmitted,
WebNavigationTypeBackForward,
WebNavigationTypeReload,
WebNavigationTypeFormResubmitted,
WebNavigationTypeOther
};
enum NavigationGesture {
NavigationGestureUser, // User initiated navigation/load. This is not
// currently used due to the untrustworthy nature
// of userGestureHint (wasRunByUserGesture). See
// bug 1051891.
NavigationGestureAuto, // Non-user initiated navigation / load. For example
// onload or setTimeout triggered document.location
// changes, and form.submits. See bug 1046841 for
// some cases that should be treated this way but
// aren't yet.
NavigationGestureUnknown, // What we assign when userGestureHint returns true
// because we can't trust it.
};
// Interface passed in to the WebViewDelegate to receive notification of the
// result of an open file dialog.
class WebFileChooserCallback {
public:
WebFileChooserCallback() {}
virtual ~WebFileChooserCallback() {}
virtual void OnFileChoose(const std::wstring& file_name) { }
private:
DISALLOW_EVIL_CONSTRUCTORS(WebFileChooserCallback);
};
// Inheritance here is somewhat weird, but since a WebView is a WebWidget,
// it makes sense that a WebViewDelegate is a WebWidgetDelegate.
class WebViewDelegate : virtual public WebWidgetDelegate {
public:
// WebView additions -------------------------------------------------------
// This method is called to create a new WebView. The WebView should not be
// made visible until the new WebView's Delegate has its Show method called.
// The returned WebView pointer is assumed to be owned by the host window,
// and the caller of CreateWebView should not release the given WebView.
// user_gesture is true if a user action initiated this call.
virtual WebView* CreateWebView(WebView* webview, bool user_gesture) {
return NULL;
}
// This method is called to create a new WebWidget to act as a popup
// (like a drop-down menu).
virtual WebWidget* CreatePopupWidget(WebView* webview) {
return NULL;
}
// This method is called to create a WebPluginDelegate implementation when a
// new plugin is instanced. See webkit_glue::CreateWebPluginDelegateHelper
// for a default WebPluginDelegate implementation.
// TODO(port): clsid is very Win- and ActiveX-specific; refactor to be more
// platform-neutral
virtual WebPluginDelegate* CreatePluginDelegate(
WebView* webview,
const GURL& url,
const std::string& mime_type,
const std::string& clsid,
std::string* actual_mime_type) {
return NULL;
}
// This method is called when default plugin has been correctly created and
// initialized, and found that the missing plugin is available to install or
// user has started installation.
virtual void OnMissingPluginStatus(WebPluginDelegate* delegate, int status) {
}
// This method is called to open a URL in the specified manner.
virtual void OpenURL(WebView* webview, const GURL& url,
WindowOpenDisposition disposition) {
}
// Notifies how many matches have been found so far, for a given request_id.
// |final_update| specifies whether this is the last update (all frames have
// completed scoping).
virtual void ReportFindInPageMatchCount(int count, int request_id,
bool final_update) {
}
// Notifies the browser what tick-mark rect is currently selected. Parameter
// |request_id| lets the recipient know which request this message belongs to,
// so that it can choose to ignore the message if it has moved on to other
// things. |selection_rect| is expected to have coordinates relative to the
// top left corner of the web page area and represent where on the screen the
// selection rect is currently located.
virtual void ReportFindInPageSelection(int request_id,
int active_match_ordinal,
const gfx::Rect& selection_rect) {
}
// This function is called to retrieve a resource bitmap from the
// renderer that was cached as a result of the renderer receiving a
// ViewMsg_Preload_Bitmap message from the browser.
virtual const SkBitmap* GetPreloadedResourceBitmap(int resource_id) {
return NULL;
}
// Returns whether this WebView was opened by a user gesture.
virtual bool WasOpenedByUserGesture(WebView* webview) const {
return true;
}
// FrameLoaderClient -------------------------------------------------------
// Notifies the delegate that a load has begun.
virtual void DidStartLoading(WebView* webview) {
}
// Notifies the delegate that all loads are finished.
virtual void DidStopLoading(WebView* webview) {
}
// The original version of this is WindowScriptObjectAvailable, below. This
// is a Chrome-specific version that serves the same purpose, but has been
// renamed since we haven't implemented WebScriptObject. Our embedding
// implementation binds native objects to the window via the webframe instead.
// TODO(pamg): If we do implement WebScriptObject, we may wish to switch to
// using the original version of this function.
virtual void WindowObjectCleared(WebFrame* webframe) {
}
// PolicyDelegate ----------------------------------------------------------
// This method is called to notify the delegate, and let it modify a
// proposed navigation. It will be called before loading starts, and
// on every redirect.
//
// disposition specifies what should normally happen for this
// navigation (open in current tab, start a new tab, start a new
// window, etc). This method can return an altered disposition, and
// take any additional separate action it wants to.
//
// is_redirect is true if this is a redirect rather than user action.
virtual WindowOpenDisposition DispositionForNavigationAction(
WebView* webview,
WebFrame* frame,
const WebRequest* request,
WebNavigationType type,
WindowOpenDisposition disposition,
bool is_redirect) {
return disposition;
}
// FrameLoadDelegate -------------------------------------------------------
// Notifies the delegate that the provisional load of a specified frame in a
// given WebView has started. By the time the provisional load for a frame has
// started, we know whether or not the current load is due to a client
// redirect or not, so we pass this information through to allow us to set
// the referrer properly in those cases. The consumed_client_redirect_src is
// an empty invalid GURL in other cases.
virtual void DidStartProvisionalLoadForFrame(
WebView* webview,
WebFrame* frame,
NavigationGesture gesture) {
}
// Called when a provisional load is redirected (see GetProvisionalDataSource
// for more info on provisional loads). This happens when the server sends
// back any type of redirect HTTP response.
//
// The redirect information can be retrieved from the provisional data
// source's redirect chain, which will be updated prior to this callback.
// The last element in that vector will be the new URL (which will be the
// same as the provisional data source's current URL), and the next-to-last
// element will be the referring URL.
virtual void DidReceiveProvisionalLoadServerRedirect(WebView* webview,
WebFrame* frame) {
}
// @method webView:didFailProvisionalLoadWithError:forFrame:
// @abstract Notifies the delegate that the provisional load has failed
// @param webView The WebView sending the message
// @param error The error that occurred
// @param frame The frame for which the error occurred
// @discussion This method is called after the provisional data source has
// failed to load. The frame will continue to display the contents of the
// committed data source if there is one.
virtual void DidFailProvisionalLoadWithError(WebView* webview,
const WebError& error,
WebFrame* frame) {
}
// If the provisional load fails, we try to load a an error page describing
// the user about the load failure. |html| is the UTF8 text to display. If
// |html| is empty, we will fall back on a local error page.
virtual void LoadNavigationErrorPage(WebFrame* frame,
const WebRequest* failed_request,
const WebError& error,
const std::string& html,
bool replace) {
}
// Notifies the delegate that the load has changed from provisional to
// committed. This method is called after the provisional data source has
// become the committed data source.
//
// In some cases, a single load may be committed more than once. This
// happens in the case of multipart/x-mixed-replace, also known as "server
// push". In this case, a single location change leads to multiple documents
// that are loaded in sequence. When this happens, a new commit will be sent
// for each document.
//
// The "is_new_navigation" flag will be true when a new session history entry
// was created for the load. The frame's GetHistoryState method can be used
// to get the corresponding session history state.
virtual void DidCommitLoadForFrame(WebView* webview, WebFrame* frame,
bool is_new_navigation) {
}
//
// @method webView:didReceiveTitle:forFrame:
// @abstract Notifies the delegate that the page title for a frame has been received
// @param webView The WebView sending the message
// @param title The new page title
// @param frame The frame for which the title has been received
// @discussion The title may update during loading; clients should be prepared for this.
// - (void)webView:(WebView *)sender didReceiveTitle:(NSString *)title forFrame:(WebFrame *)frame;
virtual void DidReceiveTitle(WebView* webview,
const std::wstring& title,
WebFrame* frame) {
}
//
// @method webView:didFinishLoadForFrame:
// @abstract Notifies the delegate that the committed load of a frame has completed
// @param webView The WebView sending the message
// @param frame The frame that finished loading
// @discussion This method is called after the committed data source of a frame has successfully loaded
// and will only be called when all subresources such as images and stylesheets are done loading.
// Plug-In content and JavaScript-requested loads may occur after this method is called.
// - (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame;
virtual void DidFinishLoadForFrame(WebView* webview,
WebFrame* frame) {
}
//
// @method webView:didFailLoadWithError:forFrame:
// @abstract Notifies the delegate that the committed load of a frame has failed
// @param webView The WebView sending the message
// @param error The error that occurred
// @param frame The frame that failed to load
// @discussion This method is called after a data source has committed but failed to completely load.
// - (void)webView:(WebView *)sender didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame;
virtual void DidFailLoadWithError(WebView* webview,
const WebError& error,
WebFrame* forFrame) {
}
// Notifies the delegate of a DOMContentLoaded event.
// This is called when the html resource has been loaded, but
// not necessarily all subresources (images, stylesheets). So, this is called
// before DidFinishLoadForFrame.
virtual void DidFinishDocumentLoadForFrame(WebView* webview, WebFrame* frame) {
}
// This method is called when we load a resource from an in-memory cache.
// A return value of |false| indicates the load should proceed, but WebCore
// appears to largely ignore the return value.
virtual bool DidLoadResourceFromMemoryCache(WebView* webview,
const WebRequest& request,
const WebResponse& response,
WebFrame* frame) {
return false;
}
// This is called after javascript onload handlers have been fired.
virtual void DidHandleOnloadEventsForFrame(WebView* webview, WebFrame* frame) {
}
// This method is called when anchors within a page have been clicked.
// It is very similar to DidCommitLoadForFrame.
virtual void DidChangeLocationWithinPageForFrame(WebView* webview,
WebFrame* frame,
bool is_new_navigation) {
}
// This is called when the favicon for a frame has been received.
virtual void DidReceiveIconForFrame(WebView* webview, WebFrame* frame) {
}
// Notifies the delegate that a frame will start a client-side redirect. When
// this function is called, the redirect has not yet been started (it may
// not even be scheduled to happen until some point in the future). When the
// redirect has been cancelled or has succeeded, DidStopClientRedirect will
// be called.
//
// WebKit considers meta refreshes, and setting document.location (regardless
// of when called) as client redirects (possibly among others).
//
// This function is intended to continue progress feedback while a
// client-side redirect is pending. Watch out: WebKit seems to call us twice
// for client redirects, resulting in two calls of this function.
virtual void WillPerformClientRedirect(WebView* webview,
WebFrame* frame,
const GURL& src_url,
const GURL& dest_url,
unsigned int delay_seconds,
unsigned int fire_date) {
}
// Notifies the delegate that a pending client-side redirect has been
// cancelled (for example, if the frame changes before the timeout) or has
// completed successfully. A client-side redirect is the result of setting
// document.location, for example, as opposed to a server side redirect
// which is the result of HTTP headers (see DidReceiveServerRedirect).
//
// On success, this will be called when the provisional load that the client
// side redirect initiated is committed.
//
// See the implementation of FrameLoader::clientRedirectCancelledOrFinished.
virtual void DidCancelClientRedirect(WebView* webview,
WebFrame* frame) {
}
// Notifies the delegate that the load about to be committed for the specified
// webview and frame was due to a client redirect originating from source URL.
// The information/notification obtained from this method is relevant until
// the next provisional load is started, at which point it becomes obsolete.
virtual void DidCompleteClientRedirect(WebView* webview,
WebFrame* frame,
const GURL& source) {
}
//
// @method webView:willCloseFrame:
// @abstract Notifies the delegate that a frame will be closed
// @param webView The WebView sending the message
// @param frame The frame that will be closed
// @discussion This method is called right before WebKit is done with the frame
// and the objects that it contains.
// - (void)webView:(WebView *)sender willCloseFrame:(WebFrame *)frame;
virtual void WillCloseFrame(WebView* webview, WebFrame* frame) {
}
// ResourceLoadDelegate ----------------------------------------------------
// Associates the given identifier with the initial resource request.
// Resource load callbacks will use the identifier throughout the life of the
// request.
virtual void AssignIdentifierToRequest(WebView* webview,
uint32 identifier,
const WebRequest& request) {
}
// Notifies the delegate that a request is about to be sent out, giving the
// delegate the opportunity to modify the request. Note that request is
// writable here, and changes to the URL, for example, will change the request
// to be made.
virtual void WillSendRequest(WebView* webview,
uint32 identifier,
WebRequest* request) {
}
// Notifies the delegate that a subresource load has succeeded.
virtual void DidFinishLoading(WebView* webview, uint32 identifier) {
}
// Notifies the delegate that a subresource load has failed, and why.
virtual void DidFailLoadingWithError(WebView* webview,
uint32 identifier,
const WebError& error) {
}
// ChromeClient ------------------------------------------------------------
// Appends a line to the application's error console. The message contains
// an error description or other information, the line_no provides a line
// number (e.g. for a JavaScript error report), and the source_id contains
// a URL or other description of the source of the message.
virtual void AddMessageToConsole(WebView* webview,
const std::wstring& message,
unsigned int line_no,
const std::wstring& source_id) {
}
// Notification of possible password forms to be filled/submitted by
// the password manager
virtual void OnPasswordFormsSeen(WebView* webview,
const std::vector<PasswordForm>& forms) {
}
//
virtual void OnUnloadListenerChanged(WebView* webview, WebFrame* webframe) {
}
// UIDelegate --------------------------------------------------------------
// Asks the browser to show a modal HTML dialog. The dialog is passed the
// given arguments as a JSON string, and returns its result as a JSON string
// through json_retval.
virtual void ShowModalHTMLDialog(const GURL& url, int width, int height,
const std::string& json_arguments,
std::string* json_retval) {
}
// Displays a JavaScript alert panel associated with the given view. Clients
// should visually indicate that this panel comes from JavaScript. The panel
// should have a single OK button.
virtual void RunJavaScriptAlert(WebView* webview,
const std::wstring& message) {
}
// Displays a JavaScript confirm panel associated with the given view.
// Clients should visually indicate that this panel comes
// from JavaScript. The panel should have two buttons, e.g. "OK" and
// "Cancel". Returns true if the user hit OK, or false if the user hit Cancel.
virtual bool RunJavaScriptConfirm(WebView* webview,
const std::wstring& message) {
return false;
}
// Displays a JavaScript text input panel associated with the given view.
// Clients should visually indicate that this panel comes from JavaScript.
// The panel should have two buttons, e.g. "OK" and "Cancel", and an area to
// type text. The default_value should appear as the initial text in the
// panel when it is shown. If the user hit OK, returns true and fills result
// with the text in the box. The value of result is undefined if the user
// hit Cancel.
virtual bool RunJavaScriptPrompt(WebView* webview,
const std::wstring& message,
const std::wstring& default_value,
std::wstring* result) {
return false;
}
// Displays a "before unload" confirm panel associated with the given view.
// The panel should have two buttons, e.g. "OK" and "Cancel", where OK means
// that the navigation should continue, and Cancel means that the navigation
// should be cancelled, leaving the user on the current page. Returns true
// if the user hit OK, or false if the user hit Cancel.
virtual bool RunBeforeUnloadConfirm(WebView* webview,
const std::wstring& message) {
return true; // OK, continue to navigate away
}
// Tells the client that we're hovering over a link with a given URL,
// if the node is not a link, the URL will be an empty GURL.
virtual void UpdateTargetURL(WebView* webview,
const GURL& url) {
}
// Called to display a file chooser prompt. The prompt should be pre-
// populated with the given initial_filename string. The WebViewDelegate
// will own the WebFileChooserCallback object and is responsible for
// freeing it.
virtual void RunFileChooser(const std::wstring& initial_filename,
WebFileChooserCallback* file_chooser) {
delete file_chooser;
}
// @abstract Shows a context menu with commands relevant to a specific
// element on the current page.
// @param webview The WebView sending the delegate method.
// @param type The type of node(s) the context menu is being invoked on
// @param x The x position of the mouse pointer (relative to the webview)
// @param y The y position of the mouse pointer (relative to the webview)
// @param link_url The absolute URL of the link that contains the node the
// mouse right clicked on
// @param image_url The absolute URL of the image that the mouse right
// clicked on
// @param page_url The URL of the page the mouse right clicked on
// @param frame_url The URL of the subframe the mouse right clicked on
// @param selection_text The raw text of the selection that the mouse right
// clicked on
// @param misspelled_word The editable (possibily) misspelled word
// in the Editor on which dictionary lookup for suggestions will be done.
// @param edit_flags Which edit operations the renderer believes are available
// @param frame_encoding Which indicates the encoding of current focused
// sub frame.
virtual void ShowContextMenu(WebView* webview,
ContextNode::Type type,
int x,
int y,
const GURL& link_url,
const GURL& image_url,
const GURL& page_url,
const GURL& frame_url,
const std::wstring& selection_text,
const std::wstring& misspelled_word,
int edit_flags,
const std::string& security_info) {
}
// Starts a drag session with the supplied contextual information.
// webview: The WebView sending the delegate method.
// drop_data: a WebDropData struct which should contain all the necessary
// information for dragging data out of the webview.
virtual void StartDragging(WebView* webview, const WebDropData& drop_data) { }
// Returns the focus to the client.
// reverse: Whether the focus should go to the previous (if true) or the next
// focusable element.
virtual void TakeFocus(WebView* webview, bool reverse) {
}
// Displays JS out-of-memory warning in the infobar
virtual void JSOutOfMemory() {
}
// EditorDelegate ----------------------------------------------------------
// These methods exist primarily to allow a specialized executable to record
// edit events for testing purposes. Most embedders are not expected to
// override them. In fact, by default these editor delegate methods aren't
// even called by the EditorClient, for performance reasons. To enable them,
// call WebView::SetUseEditorDelegate(true) for each WebView.
virtual bool ShouldBeginEditing(WebView* webview, std::wstring range) {
return true;
}
virtual bool ShouldEndEditing(WebView* webview, std::wstring range) {
return true;
}
virtual bool ShouldInsertNode(WebView* webview,
std::wstring node,
std::wstring range,
std::wstring action) {
return true;
}
virtual bool ShouldInsertText(WebView* webview,
std::wstring text,
std::wstring range,
std::wstring action) {
return true;
}
virtual bool ShouldChangeSelectedRange(WebView* webview,
std::wstring fromRange,
std::wstring toRange,
std::wstring affinity,
bool stillSelecting) {
return true;
}
virtual bool ShouldDeleteRange(WebView* webview, std::wstring range) {
return true;
}
virtual bool ShouldApplyStyle(WebView* webview,
std::wstring style,
std::wstring range) {
return true;
}
virtual bool SmartInsertDeleteEnabled() {
return false;
}
virtual void DidBeginEditing() { }
virtual void DidChangeSelection() { }
virtual void DidChangeContents() { }
virtual void DidEndEditing() { }
// Notification that a user metric has occurred.
virtual void UserMetricsRecordAction(const std::wstring& action) { }
virtual void UserMetricsRecordComputedAction(const std::wstring& action) {
UserMetricsRecordAction(action);
}
// -------------------------------------------------------------------------
// Notification that a request to download an image has completed. |errored|
// indicates if there was a network error. The image is empty if there was
// a network error, the contents of the page couldn't by converted to an
// image, or the response from the host was not 200.
// NOTE: image is empty if the response didn't contain image data.
virtual void DidDownloadImage(int id,
const GURL& image_url,
bool errored,
const SkBitmap& image) {
}
enum ErrorPageType {
DNS_ERROR,
HTTP_404,
CONNECTION_ERROR,
};
// If providing an alternate error page (like link doctor), returns the URL
// to fetch instead. If an invalid url is returned, just fall back on local
// error pages. |error_name| tells the delegate what type of error page we
// want (e.g., 404 vs dns errors).
virtual GURL GetAlternateErrorPageURL(const GURL& failedURL,
ErrorPageType error_type) {
return GURL();
}
// History Related ---------------------------------------------------------
// Returns the session history entry at a distance |offset| relative to the
// current entry. Returns NULL on failure.
virtual WebHistoryItem* GetHistoryEntryAtOffset(int offset) {
return NULL;
}
// Asynchronously navigates to the history entry at the given offset.
virtual void GoToEntryAtOffsetAsync(int offset) {
}
// Returns how many entries are in the back and forward lists, respectively.
virtual int GetHistoryBackListCount() {
return 0;
}
virtual int GetHistoryForwardListCount() {
return 0;
}
// Notification that the form state of an element in the document, scroll
// position, or possibly something else has changed that affects session
// history (HistoryItem). This function will be called frequently, so the
// implementor should not perform intensive operations in this notification.
virtual void OnNavStateChanged(WebView* webview) { }
// -------------------------------------------------------------------------
// Tell the delegate the tooltip text for the current mouse position.
virtual void SetTooltipText(WebView* webview,
const std::wstring& tooltip_text) { }
// Downloading -------------------------------------------------------------
virtual void DownloadUrl(const GURL& url, const GURL& referrer) { }
// Editor Client -----------------------------------------------------------
// Returns true if the word is spelled correctly. The word may begin or end
// with whitespace or punctuation, so the implementor should be sure to handle
// these cases.
//
// If the word is misspelled (returns false), the given first and last
// indices (inclusive) will be filled with the offsets of the boundary of the
// word within the given buffer. The out pointers must be specified. If the
// word is correctly spelled (returns true), they will be set to (0,0).
virtual void SpellCheck(const std::wstring& word, int& misspell_location,
int& misspell_length) {
misspell_location = misspell_length = 0;
}
// Changes the state of the input method editor.
virtual void SetInputMethodState(bool enabled) { }
// Asks the user to print the page or a specific frame. Called in response to
// a window.print() call.
virtual void ScriptedPrint(WebFrame* frame) { }
virtual void WebInspectorOpened(int num_resources) { }
// Called when the FrameLoader goes into a state in which a new page load
// will occur.
virtual void TransitionToCommittedForNewPage() { }
// Called when an item was added to the history
virtual void DidAddHistoryItem() { }
WebViewDelegate() { }
virtual ~WebViewDelegate() { }
private:
DISALLOW_EVIL_CONSTRUCTORS(WebViewDelegate);
};
#endif // WEBKIT_GLUE_WEBVIEW_DELEGATE_H__
| 44.191518 | 106 | 0.657039 | [
"object",
"vector"
] |
15eef3bb09df405ac9dc38e943e4c0f247e2983c | 469 | h | C | Design_patterns_in_modern_cpp/src/100_Chapter_10/Workspace.h | NaPiZip/Programming_basics_c- | d84bf4baa25fbcf28b12fb06be7a6270c143effc | [
"MIT"
] | null | null | null | Design_patterns_in_modern_cpp/src/100_Chapter_10/Workspace.h | NaPiZip/Programming_basics_c- | d84bf4baa25fbcf28b12fb06be7a6270c143effc | [
"MIT"
] | null | null | null | Design_patterns_in_modern_cpp/src/100_Chapter_10/Workspace.h | NaPiZip/Programming_basics_c- | d84bf4baa25fbcf28b12fb06be7a6270c143effc | [
"MIT"
] | null | null | null | // Copyright 2019, Nawin
#ifndef _HEADER_WORKSPACE
#define _HEADER_WORKSPACE
#include <string>
#include <vector>
struct IBuffer {};
struct TableBuffer : IBuffer {
struct TableColumnSpec
{
std::string header;
int width;
enum class TableColumnAlignment {
Left,
Center,
Right
} alignment;
};
TableBuffer(std::vector<TableColumnSpec> spec, int total_height) {
}
};
#endif // _HEADER_WORKSPACE
| 16.75 | 69 | 0.639659 | [
"vector"
] |
15f244cb17680f190b5958cce9ec2dbc1d8cf2dd | 291 | h | C | include/render/render.h | adaxiik/OpenGL-Ray | e5ef981a4bda6829dc6c4bb3bc7210f430907c72 | [
"MIT"
] | null | null | null | include/render/render.h | adaxiik/OpenGL-Ray | e5ef981a4bda6829dc6c4bb3bc7210f430907c72 | [
"MIT"
] | null | null | null | include/render/render.h | adaxiik/OpenGL-Ray | e5ef981a4bda6829dc6c4bb3bc7210f430907c72 | [
"MIT"
] | null | null | null | #pragma once
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include "../../include/render/setup.h"
#define CIMGUI_DEFINE_ENUMS_AND_STRUCTS
#include <cimgui.h>
#include <imgui_impl_glfw.h>
#include <imgui_impl_opengl3.h>
void RenderScreen(Application *app);
void UpdateGUI(Application *app); | 29.1 | 39 | 0.776632 | [
"render"
] |
c60081ddb9a1138ba032068088735990b15b3830 | 54,334 | c | C | apache 2.2/src/mod_csrfprotector.c | joliver82/mod_csrfprotector | baa1384c742953341a79e0c1fb08aafe8ea286ea | [
"Apache-2.0"
] | null | null | null | apache 2.2/src/mod_csrfprotector.c | joliver82/mod_csrfprotector | baa1384c742953341a79e0c1fb08aafe8ea286ea | [
"Apache-2.0"
] | null | null | null | apache 2.2/src/mod_csrfprotector.c | joliver82/mod_csrfprotector | baa1384c742953341a79e0c1fb08aafe8ea286ea | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2014 OWASP Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* limitations under the License.
*
* Source code of mod_csrfprotector, Apache Module to mitigate
* CSRF vulnerability in server.
*/
/** standard c libs **/
#include "stdio.h"
#include "stdlib.h"
#include "time.h"
/** openSSL **/
#include "openssl/rand.h"
#include "openssl/sha.h"
/** apache **/
#include "ap_config.h"
#include "ap_provider.h"
#include "httpd.h"
#include "http_core.h"
#include "http_config.h"
#include "http_log.h"
#include "http_protocol.h"
#include "http_request.h"
#include "util_filter.h"
#include "ap_regex.h"
/** APRs **/
#include "apr_hash.h"
#include "apr_general.h"
#include "apr_buckets.h"
#include "apr_lib.h"
#include "apr_strings.h"
/** SQLite library **/
#include "sqlite/sqlite3.h"
/** definations **/
#define CSRFP_NAME_VERSION "CSRFP 0.0.1"
#define CSRFP_TOKEN "csrfp_token"
#define CSRFP_TOKEN_NAME_MAXLENGTH 40
#define CSRFP_SESS_TOKEN "CSRFPSESSID"
#define DEFAULT_POST_ENCTYPE "application/x-www-form-urlencoded"
#define CSRFP_REGEN_TOKEN "true"
#define CSRFP_CHUNKED_ONLY 0
#define CSRFP_OVERLAP_BUCKET_SIZE 8
#define CSRFP_OVERLAP_BUCKET_DEFAULT "--------"
#define CSRFP_URI_MAXLENGTH 512
#define CSRFP_ERROR_MESSAGE_MAXLENGTH 1024
#define CSRFP_DISABLED_JS_MESSAGE_MAXLENGTH 512
#define CSRFP_VERIFYGETFOR_MAXLENGTH 512
#define CSRFP_GET_RULE_MAX_LENGTH 256
#define DEFAULT_TOKEN_LENGTH 15
#define DEFAULT_TOKEN_MINIMUM_LENGTH 12
#define DEFAULT_ERROR_MESSAGE "<h2>ACCESS FORBIDDEN BY OWASP CSRF_PROTECTOR!</h2>"
#define DEFAULT_REDIRECT_URL ""
#define DEFAULT_JS_FILE_PATH "http://localhost/csrfp_js/csrfprotector.js"
#define DEFAULT_DISABLED_JS_MESSSAGE "This site attempts to protect users against" \
" <a href=\"https://www.owasp.org/index.php/Cross-Site_Request_Forgery_%28CSRF%29\">" \
" Cross-Site Request Forgeries </a> attacks. In order to do so, you must have JavaScript " \
" enabled in your web browser otherwise this site will fail to work correctly for you. " \
" See details of your web browser for how to enable JavaScript."
#define CSRFP_IGNORE_PATTERN ".*(jpg)|(jpeg)|(gif)|(png)|(js)|(css)|(xml)|(xsl)|(json)|(txt)|(csv)$"
#define CSRFP_IGNORE_TEXT "csrfp_ignore_set"
#define SQL_SESSID_DEFAULT_LENGTH 10
#define TOKEN_EXPIRY_MAXTIME 1800
#define DATABASE_DEFAULT_LOCATION "/tmp/csrfp.db"
#define RESEED_RAND_AT 10000
//=============================================================
// Definations of all data structures to be used later
//=============================================================
/*
* Variable: Flag
* enumerator - for storing TRUE FALSE values for CSRFP
*/
typedef enum
{
CSRFP_TRUE,
CSRFP_FALSE // Added CSRFP_ prefix to preven enum redeclaration error in OS X
} Flag; // Flag enum for stating weather to use...
// ... mod or not
/*
* Variable: csrfp_actions
* enumerator - lists the actions to be taken in case of failed validation
*/
typedef enum
{
forbidden,
strip,
redirect,
message,
internal_server_error
} csrfp_actions; // Action enum listing all actions
/*
* Variable: Filter_Statae
* enumerator - lists the state through which the output filter goes
*/
typedef enum
{
op_init, // States output filter has initiated
op_body_init, // States <body was found, <noscript inserted
op_body_end, // States </body> found, <script inserted
op_end // States output fiter task has finished
} Filter_State; // enum of output filter states
/*
* Variable: Filter_Cookie_Length_State
* enumerator - lists the state of token cookie
*/
typedef enum
{
nmodified, // States Cookie Length not modified
modified // States Cookie Length modified
} Filter_Cookie_Length_State; // list of cookie length states
/*
* Variable: csrfp_config
* structure - structure of the csrfp configuration
*/
typedef struct
{
Flag flag; // Flag to check if CSRFP is disabled...
// ... true by default
csrfp_actions action; // Action Codes, Default - forbidden
char *errorRedirectionUri; // Uri to redirect in case action == redirect
char *errorCustomMessage; // Message to show in case action == message
char *jsFilePath; // Absolute path for JS file
int tokenLength; // Length of CSRFP_TOKEN, Default 20
char *tokenName; // Name of the CSRFP token
char *disablesJsMessage; // Message to be shown in <noscript>
ap_regex_t *ignore_pattern; // Path pattern for which validation...
// ...is Not needed
} csrfp_config; // CSRFP configuraion
/*
* Variable: csrfp_opf_ctx
* structure - structure of the csrfp output filter configuration
*/
typedef struct
{
char *search; // Stores the item being serched (regex)
Filter_State state; // Stores the current state of filter
char *script; // Will store the js code to be inserted
char *noscript; // Will store the <noscript>..</noscript>...
// ...Info to be inserted
Filter_Cookie_Length_State clstate; // State of Content-Length header false - for not ...
// ...modified, true for modified or need not modify
char *overlap_buf; // Buffer to store content of current bb->b buffer ...
// ... for next iteration in op filter [el]
} csrfp_opf_ctx; // CSRFP output filter context
static csrfp_config *config;
/*
* Variable: getRuleNode
* structure - linked list node for storing the GET rules
*/
typedef struct getRuleNode
{
ap_regex_t *pattern;
const char *patternString;
struct getRuleNode *next;
};
struct getRuleNode *getTop = NULL, *getPointer = NULL;
//=============================================================
// Globals
//=============================================================
module AP_MODULE_DECLARE_DATA csrf_protector_module;
// Declarations for functions
static char *generateToken(request_rec *r, int length);
static const char *csrfp_strncasestr(const char *s1, const char *s2, int len);
static apr_table_t *csrfp_get_query(request_rec *r);
static char* getCookieToken(request_rec *r, char *key);
static csrfp_opf_ctx *csrfp_get_rctx(request_rec *r);
//Declarations for SQLite based functions
static void csrfp_sql_table_clean(request_rec *r, sqlite3 *db);
static sqlite3 *csrfp_sql_init(request_rec *r);
static int csrfp_sql_match(request_rec *r, sqlite3 *db, const char *sessid, const char *value);
static int csrfp_sql_addn(request_rec *r, sqlite3 *db, const char *sessid, const char *value);
static char* csrfp_sql_get_token(request_rec *r, sqlite3 *db, const char *sessid);
static int csrfp_sql_update_counter(request_rec *r, sqlite3 *db);
//=============================================================
// Functions
//=============================================================
/*
* Function: csrfp_strncasestr
* Similar to standard strstr() but case insensitive and lenght limitation
* (char which is not 0 terminated).
*
* Parameters:
* s1 - String to search in
* s2 - Pattern to ind
* len - Length of s1
*
* Rreturns:
* char* - pointer to the beginning of the substring s2 within s1, or NULL
* if the substring is not found
*/
static const char *csrfp_strncasestr(const char *s1, const char *s2, int len) {
const char *e1 = &s1[len-1];
char *p1, *p2;
if (*s2 == '\0') {
/* an empty s2 */
return((char *)s1);
}
while(1) {
for ( ; (*s1 != '\0') && (s1 <= e1) && (apr_tolower(*s1) != apr_tolower(*s2)); s1++);
if (*s1 == '\0' || s1 > e1) {
return(NULL);
}
/* found first character of s2, see if the rest matches */
p1 = (char *)s1;
p2 = (char *)s2;
for (++p1, ++p2; (apr_tolower(*p1) == apr_tolower(*p2)) && (p1 <= e1); ++p1, ++p2) {
if((p1 > e1) && (*p2 != '\0')) {
// reached the end without match
return NULL;
}
if (*p2 == '\0') {
/* both strings ended together */
return((char *)s1);
}
}
if (*p2 == '\0') {
/* second string ended, a match */
break;
}
/* didn't find a match here, try starting at next character in s1 */
s1++;
}
return((char *)s1);
}
/*
* Function: getCurrentUrl
* Function to retrun current url
*
* Parameters:
* r - request_rec object
*
* Returns:
* current url (char *)
*/
static char* getCurrentUrl(request_rec *r)
{
char *retval;
retval = apr_pstrcat(r->pool, r->hostname, r->uri, NULL);
return retval;
}
/*
* Function: generateToken
* Function to generate a pseudo random no to function as
* CSRFP_TOKEN
*
* Parameters:
* r - request_rec object
* length - length of token to generate
*
* Returns:
* token - csrftoken ,string
*/
static char* generateToken(request_rec *r, int length)
{
const char *charset = apr_psprintf(r->pool, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890");
char *token = NULL;
token = apr_pcalloc(r->pool, sizeof(char) * length);
unsigned char buf[length];
RAND_pseudo_bytes(buf, sizeof(buf));
int i, len = strlen(charset);
for (i = 0; i < length; i++) {
token[i] = charset[((int)buf[i]) % (len - 1)];
}
token[length] = '\0';
return token;
}
/*
* Funciton: csrfp_get_query
* Returns a table containing the query name/value pairs.
*
* Parameters:
* r - request_rec object
*
* Returns:
* tbl - Table of NULL if no parameter are available
*/
static apr_table_t *csrfp_get_query(request_rec *r)
{
apr_table_t *tbl = NULL;
const char *args = r->args;
if(args == NULL) {
return NULL;
}
tbl = apr_table_make(r->pool, 10);
while(args[0]) {
char *value = ap_getword(r->pool, &args, '&');
char *name = ap_getword_nc(r->pool, &value, '=');
if(name) {
apr_table_addn(tbl, name, value);
}
}
return tbl;
}
/*
* Function: setTokenCookie
* Function to append new CSRFP_TOKEN to output header
*
* Parameters:
* r - request_rec object
*
* Returns:
* void
*/
static void setTokenCookie(request_rec *r, sqlite3 *db)
{
csrfp_config *conf = ap_get_module_config(r->server->module_config,
&csrf_protector_module);
char *token = NULL, *cookie = NULL, *sessid = NULL;
//SESSION PART
sessid = getCookieToken(r, CSRFP_SESS_TOKEN);
if (sessid == NULL) {
// Generate a new token
token = generateToken(r, conf->tokenLength);
sessid = generateToken(r, SQL_SESSID_DEFAULT_LENGTH);
}
else {
token = csrfp_sql_get_token(r, db, sessid);
if (token == NULL) {
token = generateToken(r, conf->tokenLength);
}
}
// Send token as cookie header #todo - set expiry time of this token
cookie = apr_psprintf(r->pool, "%s=%s; Version=1; Path=/;", conf->tokenName, token);
apr_table_addn(r->headers_out, "Set-Cookie", cookie);
cookie = apr_psprintf(r->pool, "%s=%s; Version=1; Path=/; HttpOnly;", CSRFP_SESS_TOKEN, sessid);
apr_table_addn(r->headers_out, "Set-Cookie", cookie);
// Add / Update it to database
csrfp_sql_addn(r, db, sessid, token);
// Update counter & reseed if needed
int counter = csrfp_sql_update_counter(r, db);
if (counter == RESEED_RAND_AT) {
//Reseed the RAND value, get rand values from /dev/urandom & reseed
char buf[conf->tokenLength];
FILE *fp;
if (!fp) {
apr_table_addn(r->headers_out, "rand-reseed-error", "Unable to open /dev/urandom");
// ^ #todo: change this with some error message to client -- ask Kevin
}
fp = fopen("/dev/urandom", "r");
fread(&buf, 1, conf->tokenLength, fp);
fclose(fp);
RAND_seed(buf, sizeof(buf));
// Now reset the counter
const char *sql = apr_psprintf(r->pool, "UPDATE CSRFP_COUNTER SET counter = 0");
char *zErrMsg = NULL;
int rc = sqlite3_exec(db, sql, 0, 0, &zErrMsg);
if (rc != SQLITE_OK) {
#ifdef DEBUG
apr_table_addn(r->headers_out, "sql-counter-reset-error", zErrMsg);
#endif
}
}
}
/*
* Function: getCookieToken
* Function to return the token value from cookie
*
* Parameters:
* r - request_rec
*
* Returns:
* CSRFP_TOKEN - if exist in cookie, else null
*/
static char* getCookieToken(request_rec *r, char *key)
{
char *value, *buffer, *end;
const char *cookie = apr_table_get(r->headers_in, "Cookie");
if (cookie) {
value = ap_strstr_c(cookie, key);
if (value) {
value += strlen(key) + 1;
buffer = apr_pstrdup(r->pool, value);
end = strchr(buffer, ';');
if (end) {
*end = '\0';
}
return buffer;
}
}
return NULL;
}
/*
* Function: validateToken
* Function to validate GET token, csrfp_token in GET query parameter
*
* Parameters:
* r - request_rec pointer
*
* Return:
* int, 0 - for failed validation, 1 - for passed
*/
static int validateToken(request_rec *r, sqlite3 *db)
{
csrfp_config *conf = ap_get_module_config(r->server->module_config,
&csrf_protector_module);
//get table of all GET key-value pairs
apr_table_t *GET = NULL;
GET = csrfp_get_query(r);
const char *tokenValue = NULL;
// Extracting token
if (GET) {
tokenValue = apr_table_get(GET, conf->tokenName);
}
else {
tokenValue = apr_table_get(r->headers_in, conf->tokenName);
}
// Verifying token
if (!tokenValue) return 0;
else {
char *sessid = getCookieToken(r, CSRFP_SESS_TOKEN);
if (sessid == NULL) {
return 0;
}
if ( !csrfp_sql_match(r, db, sessid, tokenValue)) return 1;
//token doesn't match
return 0;
}
}
/*
* Function: getOutputContentType
* Returns content type of output generated by content generator
*
* Parametes:
* r - request_rec object
*
* Returns:
* content type - string
*/
static const char *getOutputContentType(request_rec *r) {
const char* type = NULL;
type = apr_table_get(r->headers_out, "Content-Type");
if (type == NULL) {
// maybe an error page
type = apr_table_get(r->err_headers_out, "Content-Type");
}
if (type == NULL) {
type = r->content_type;
}
return type;
}
/*
* Function: csrfp_get_rctx
* Get or create (and init) the pre request context used by the output filter
*
* Parametes:
* r - request_rec object
*
* Returns:
* context object for output filter ( csrfp_opf_ctx* )
*/
static csrfp_opf_ctx *csrfp_get_rctx(request_rec *r) {
csrfp_opf_ctx *rctx = ap_get_module_config(r->request_config, &csrf_protector_module);
if(rctx == NULL) {
csrfp_config *conf = ap_get_module_config(r->server->module_config,
&csrf_protector_module);
rctx = apr_pcalloc(r->pool, sizeof(csrfp_opf_ctx));
rctx->state = op_init;
rctx->search = apr_psprintf(r->pool, "<body");
// Allocate memory and init <noscript> content to be injected
rctx->noscript = apr_psprintf(r->pool, "\n<noscript>\n%s\n</noscript>",
conf->disablesJsMessage);
// Parse the getRule linked list and generate the rule string to be appended to js
struct getRuleNode *p = getTop;
char *getRuleString = NULL;
while (p != NULL) {
if (getRuleString)
getRuleString = apr_pstrcat(r->pool, getRuleString, ",'" , p->patternString , "'", NULL);
else
getRuleString = apr_pstrcat(r->pool, "'" , p->patternString , "'", NULL);
p = p->next;
}
// Allocate memory and init <script> content to be injected
rctx->script = apr_psprintf(r->pool, "\n<script type=\"text/javascript\""
" src=\"%s\"></script>\n"
"<script type=\"text/JavaScript\">\n"
"window.onload = function() {\n"
"\t CSRFP.checkForUrls = [%s];\n"
"\t CSRFP.CSRFP_TOKEN = '%s';\n"
"\t csrfprotector_init();\n"
"}\n</script>\n",
conf->jsFilePath,
(getRuleString == NULL)?"": getRuleString,
conf->tokenName);
rctx->clstate = nmodified;
rctx->overlap_buf = apr_pcalloc(r->pool, CSRFP_OVERLAP_BUCKET_SIZE);
apr_cpystrn(rctx->overlap_buf,
CSRFP_OVERLAP_BUCKET_DEFAULT, CSRFP_OVERLAP_BUCKET_SIZE);
// globalise this configuration
ap_set_module_config(r->request_config, &csrf_protector_module, rctx);
}
return rctx;
}
/*
* Function: csrfp_inject
* Injects a new bucket containing a reference to the javascript.
*
* Parametes:
* r - request_rec object
* bb - bucket_brigade object
* b Bucket to split and insert date new bucket at the postion of the marker
* rctx - Request context containing the state of the parser
* buf - String representation of the bucket
* sz - Position to split the bucket and insert the new content
* flag - 0 - for <noscript> insertion, 1 for <script> insertion
*
* Returns:
* Bucket to continue searching (at the marker)
*/
static apr_bucket *csrfp_inject(request_rec *r, apr_bucket_brigade *bb, apr_bucket *b,
csrfp_opf_ctx *rctx, const char *buf,
apr_size_t sz, int flag) {
apr_bucket *e;
apr_bucket_split(b, sz);
b = APR_BUCKET_NEXT(b);
const char* insert = (flag == 1)? rctx->script : rctx->noscript;
e = apr_bucket_pool_create(insert, strlen(insert), r->pool, bb->bucket_alloc);
APR_BUCKET_INSERT_BEFORE(b, e);
if (flag) {
// script has been injected
rctx->state = op_body_end;
rctx->search = NULL;
} else {
// <noscript> has been injected
rctx->state = op_body_init;
apr_cpystrn(rctx->search, "</body>", strlen("</body>"));
}
return b;
}
/*
* Function: logCSRFAttack
* Function to log an attack
*
* Parameters:
* r - request_rec object
*
* Returns:
* void
*/
static void logCSRFAttack(request_rec *r)
{
csrfp_config *conf = ap_get_module_config(r->server->module_config,
&csrf_protector_module);
int isGet = (!strcmp(r->method, "GET"));
const char *POSTArgs; //#todo a way to log POST arguments
// Log the failure
ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
"CSRF ATTACK, %s, action=%d, method=%s, arguments=%s, url=%s%s",
conf->action == strip ? "strip & served" : "denied",
conf->action,
(isGet)? "GET" : "POST",
(isGet)? r->args: "POSTArgs", //remove ""
"https(s)://",
getCurrentUrl(r));
}
/*
* Function: failedValidationAction
* Returns appropriate status code, as per configuration
* For failed validation action
*
* Parameters:
* r - request_rec object
*
* Returns:
* int - status code for action
*/
static int failedValidationAction(request_rec *r)
{
csrfp_config *conf = ap_get_module_config(r->server->module_config,
&csrf_protector_module);
logCSRFAttack(r); // Log this attack
switch (conf->action)
{
case forbidden:
return HTTP_FORBIDDEN;
break;
case strip:
// Strip POST values - and forward the request
if (!strcmp(r->method, "GET")
&& r->args) {
apr_cpystrn(r->args, "\0", 1);
} else if (!strcmp(r->method, "POST")) {
ap_discard_request_body(r);
apr_table_addn(r->headers_out, "POST_DATA_CLEARING", "reached");
}
return OK;
break;
case redirect:
// Redirect to custom uri
if (strlen(conf->errorRedirectionUri) > 0) {
apr_table_add(r->headers_out, "Location", conf->errorRedirectionUri);
return HTTP_MOVED_PERMANENTLY;
} else {
return HTTP_FORBIDDEN;
}
break;
case message:
// Show custom Error Message
ap_rprintf(r, "<h2>%s</h2>", conf->errorCustomMessage);
return DONE;
break;
case internal_server_error:
// Show internel Server error
return HTTP_INTERNAL_SERVER_ERROR;
break;
default:
// Default action is FORBIDDEN
return HTTP_FORBIDDEN;
break;
}
}
/*
* Function: needvalidation
* Function to decide weather to validate current request
* Depending upon requested file, matched against ignore pattern
*
* Parameters:
* r - request_rec object
*
* Returns:
* int, - 1 if validation needed, 0 otherwise
*/
static int needvalidation(request_rec *r)
{
if (apr_table_get(r->subprocess_env, CSRFP_IGNORE_TEXT))
return 0;
csrfp_config *conf = ap_get_module_config(r->server->module_config,
&csrf_protector_module);
if(r->parsed_uri.path) {
const char *path = strrchr(r->parsed_uri.path, '/');
// faster than match against a long string
if(path == NULL) {
path = r->parsed_uri.path;
}
if(ap_regexec(conf->ignore_pattern, path, 0, NULL, 0) == 0) {
apr_table_addn(r->subprocess_env, CSRFP_IGNORE_TEXT, "m");
return 0;
}
}
return 1;
}
//=============================================================
// All SQLite related functions
//=============================================================
/*
* Function: csrfp_sql_init
* Function to initiate the sql process for code validation
*
* Parameters:
* r - request_rec object
*
* Returns:
* db, SQLITE database object on success
*/
static sqlite3 *csrfp_sql_init(request_rec *r)
{
csrfp_config *conf = ap_get_module_config(r->server->module_config,
&csrf_protector_module);
sqlite3 *db;
int rc = sqlite3_open_v2(DATABASE_DEFAULT_LOCATION, &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
if (rc != SQLITE_OK) {
#ifdef DEBUG
apr_table_addn(r->headers_out, "sql-init-open-error", sqlite3_errmsg(db));
#endif
return NULL;
}
//#todo: make sessid, token length configurable. also timestamp length
// & compile this sql string based on those values here
const char* sql = apr_psprintf(r->pool, "CREATE TABLE IF NOT EXISTS CSRFP(" \
"sessid char(%d) PRIMARY KEY NOT NULL," \
"token char(%d) NOT NULL,"\
"timestamp int NOT NULL );", 20, conf->tokenLength);
// Error reporting
char *zErrMsg = 0;
/* Execute SQL statement */
rc = sqlite3_exec(db, sql, 0, 0, &zErrMsg);
if( rc != SQLITE_OK ){
#ifdef DEBUG
apr_table_addn(r->headers_out, "sql-init-exec-error", zErrMsg);
#endif
return NULL;
}
// Create a table for storing, the requests count
sql = apr_psprintf(r->pool, "CREATE TABLE IF NOT EXISTS CSRFP_COUNTER (" \
"counter int NOT NULL );");
rc = sqlite3_exec(db, sql, 0, 0, &zErrMsg);
if( rc != SQLITE_OK ){
#ifdef DEBUG
apr_table_addn(r->headers_out, "sql-init-counter-error", zErrMsg);
#endif
return NULL;
}
return db;
}
/*
* Function: csrfp_sql_update_counter
* Function to add / Update counter value for reseeding
*
* Parameters:
* r - request_rec object
* db - sqlite database object
*
* Returns:
* integer, current counter
*/
static int csrfp_sql_update_counter(request_rec *r, sqlite3 *db)
{
// Check if exist -- true > update, false > insert 1
int counter = 1;
int shouldUpdate = 0;
sqlite3_stmt *res;
const char *tail;
// #todo: you might want to create a seperate pool for this & destroy it later
const char *sql = apr_psprintf(r->pool, "SELECT counter FROM CSRFP_COUNTER");
int rc = sqlite3_prepare_v2(db, sql, 1000, &res, &tail);
if (rc != SQLITE_OK) {
#ifdef DEBUG
apr_table_addn(r->headers_out, "sql-update-counter-select-error", tail);
#endif
return rc;
} else {
while (sqlite3_step(res) == SQLITE_ROW) {
counter = atoi(sqlite3_column_text(res, 0));
++shouldUpdate;
break;
}
}
sqlite3_reset(res);
char *zErrMsg = NULL;
if (shouldUpdate != 0) {
//means entry exist -- update
sql = apr_psprintf(r->pool, "UPDATE CSRFP_COUNTER SET counter = counter + 1");
rc = sqlite3_exec(db, sql, 0, 0, &zErrMsg);
if (rc != SQLITE_OK) {
#ifdef DEBUG
apr_table_addn(r->headers_out, "sql-update-counter-update-error", zErrMsg);
#endif
return rc;
}
counter++;
} else {
// Insert
sql = apr_psprintf(r->pool, "INSERT INTO CSRFP_COUNTER (counter) VALUES (1)");
rc = sqlite3_exec(db, sql, 0, 0, &zErrMsg);
if (rc != SQLITE_OK) {
#ifdef DEBUG
apr_table_addn(r->headers_out, "sql-update-counter-insert-error", zErrMsg);
#endif
return rc;
}
}
#ifdef DEBUG
apr_table_addn(r->headers_out, "sql-update-counter-value", apr_itoa(r->pool, counter));
#endif
return counter;
}
/*
* Function: csrfp_sql_get_token
* Function to get token for session
*
* Parameters:
* r - request_rec object
* db - sqlite database object
* sessid - session id for this user
*
* Returns:
* char*
*/
static char* csrfp_sql_get_token(request_rec *r, sqlite3 *db, const char *sessid)
{
char *result = NULL;
sqlite3_stmt *res;
const char *tail;
const char *sql = apr_psprintf(r->pool, "SELECT token FROM CSRFP WHERE sessid = '%s'", sessid);
int rc = sqlite3_prepare_v2(db, sql, 1000, &res, &tail);
if (rc != SQLITE_OK) {
#ifdef DEBUG
apr_table_addn(r->headers_out, "sql-addn-select-error", tail);
#endif
return rc;
} else {
while (sqlite3_step(res) == SQLITE_ROW) {
result = strdup((const char*)sqlite3_column_text(res, 0));
break;
}
}
sqlite3_reset(res);
return result;
}
/*
* Function: csrfp_sql_addn
* Function to add / Update token value in the db
*
* Parameters:
* r - request_rec object
* db - sqlite database object
* sessid - session id for this user
* value- value of the token
*
* Returns:
* integer, SQLITE_OK on success
*/
static int csrfp_sql_addn(request_rec *r, sqlite3 *db, const char *sessid, const char *value)
{
// sessid of value cannot be null
if (sessid == NULL || value == NULL)
return -1;
int timestamp = (unsigned)time(NULL);
// Check if session id exists in db
int shouldUpdate = 0;
sqlite3_stmt *res;
const char *tail;
// #todo: you might want to create a seperate pool for this & destroy it later
const char *sql = apr_psprintf(r->pool, "SELECT sessid FROM CSRFP WHERE sessid = '%s'", sessid);
int rc = sqlite3_prepare_v2(db, sql, 1000, &res, &tail);
if (rc != SQLITE_OK) {
#ifdef DEBUG
apr_table_addn(r->headers_out, "sql-addn-select-error", tail);
#endif
return rc;
} else {
while (sqlite3_step(res) == SQLITE_ROW) {
++shouldUpdate;
break;
}
}
sqlite3_reset(res);
char *zErrMsg = NULL;
if (shouldUpdate == 0) {
// Insert
const char *sql_ = apr_psprintf(r->pool, "INSERT INTO CSRFP (sessid, token, timestamp) VALUES ('%s', '%s', %d)", sessid, value, timestamp);
rc = sqlite3_exec(db, sql_, 0, 0, &zErrMsg);
if (rc != SQLITE_OK) {
#ifdef DEBUG
apr_table_addn(r->headers_out, "sql-addn-insert-error", zErrMsg);
#endif
return rc;
}
} else {
// Update
const char *sql_ = apr_psprintf(r->pool, "UPDATE CSRFP SET token = '%s', timestamp = %d WHERE sessid = '%s'", value, timestamp, sessid);
rc = sqlite3_exec(db, sql_, 0, 0, &zErrMsg);
if (rc != SQLITE_OK) {
#ifdef DEBUG
apr_table_addn(r->headers_out, "sql-addn-update-error", zErrMsg);
#endif
return rc;
}
}
return SQLITE_OK;
}
/*
* Funciton: csrfp_sql_match
* Function to match value in db to value sent as param
*
* Parameters:
* r - request_rec object
* db - sqlite database object
* sessid - session id for this user
* value - value to match
*
* Returns:
* 0 for correct match
*/
static int csrfp_sql_match(request_rec *r, sqlite3 *db, const char *sessid, const char *value)
{
// sessid of value cannot be null
if (sessid == NULL || value == NULL)
return -1;
int timestamp = (unsigned)time(NULL);
// Check if session id exists in db
sqlite3_stmt *res;
const char *tail;
// #todo: you might want to create a seperate pool for this & destroy it later
char *sql = apr_psprintf(r->pool, "SELECT timestamp FROM CSRFP WHERE sessid = '%s' AND token = '%s'", sessid, value);
int rc = sqlite3_prepare_v2(db, sql,1000, &res, &tail);
if (rc != SQLITE_OK) {
#ifdef DEBUG
apr_table_addn(r->headers_out, "sql-match-select-error", tail);
#endif
return rc;
} else {
while (sqlite3_step(res) == SQLITE_ROW) {
if (timestamp > (atoi(sqlite3_column_text(res, 0)) + TOKEN_EXPIRY_MAXTIME)) {
ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
"CSRFP csrfp_sql_match return -1");
sqlite3_reset(res);
return -1;
}
ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
"CSRFP csrfp_sql_match return 0");
sqlite3_reset(res);
return 0;
}
ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
"CSRFP csrfp_sql_match return 1");
return 1;
}
}
/*
* Function: csrfp_sql_table_clean
* Function to clear expired tokens from db
*
* Parameters:
* r - request_rec object
* db - sqlite database object
*
* Returns:
* void
*/
static void csrfp_sql_table_clean(request_rec *r, sqlite3 *db)
{
int timestamp = (unsigned)time(NULL) - TOKEN_EXPIRY_MAXTIME;
char *sql = apr_psprintf(r->pool, "DELETE FROM CSRFP WHERE timestamp < '%d'", timestamp);
char *zErrMsg;
int rc = sqlite3_exec(db, sql, 0, 0, &zErrMsg);
if (rc != SQLITE_OK) {
#ifdef DEBUG
apr_table_addn(r->headers_out, "sql-clean-error", zErrMsg);
#endif
ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
"CSRFP cleaning %s.", zErrMsg);
}
}
//=====================================================================
// Handlers -- call back functions for different hooks
//=====================================================================
/*
* Function: csrfp_header_parser
* Callback function for header parser by Hook Registering function
*
* Parameters:
* r - request_rec object
*
* Return:
* status code, int
*/
static int csrfp_header_parser(request_rec *r)
{
csrfp_config *conf = ap_get_module_config(r->server->module_config,
&csrf_protector_module);
if (conf->flag == CSRFP_FALSE)
return OK;
if (!needvalidation(r)) {
// No need of validation, go ahead!
return OK;
}
// Start the sql connection
sqlite3 *db = csrfp_sql_init(r);
if (db == NULL) {
ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
"CSRFP UNABLE TO ACCESS DB OBJECT IN HEADER PARSER");
// #todo: ask Kevin/Abbas about this once
// Commented to avoid pages to be written
//ap_rprintf(r, "OWASP CSRF Protector - SQLITE3 Database Open Error");
return DONE;
}
// If request type is POST
// Need to check configs weather or not a validation is needed POST
if ( !strcmp(r->method, "POST")
&& !validateToken(r, db)) {
// Log this -- [x]
// Take actions as per configuration
return failedValidationAction(r);
} else if ( !strcmp(r->method, "GET") ) {
struct getRuleNode *p = getTop;
while (p != NULL) {
const char *currentUrl = apr_pstrcat(r->pool, "http://", getCurrentUrl(r), NULL);
const char *currentUrlSecure = apr_pstrcat(r->pool, "https://", getCurrentUrl(r), NULL);
if (ap_regexec(p->pattern, currentUrl, 0, NULL, 0) == 0
|| ap_regexec(p->pattern, currentUrlSecure, 0, NULL, 0) == 0) {
if (!validateToken(r, db)) {
// Means pattern matched && validation failed
// Log this -- [x]
// Take actions as per configuration
// Close the sql connection
sqlite3_close(db);
return failedValidationAction(r);
}
}
p = p->next;
}
}
// Close the sql connection
sqlite3_close(db);
// Information for output_filter to regenrate token and
// append it to output header -- Regenrate token
// Section to regenrate and send new Cookie Header (csrfp_token) to client
apr_table_add(r->subprocess_env, "regen_csrfptoken", CSRFP_REGEN_TOKEN);
// Add environment variable for php to inform request has been
// validated by mod_csrfp
apr_table_add(r->subprocess_env, "mod_csrfp_enabled", "true");
// Appends X-Protected-By header to output header
apr_table_addn(r->headers_out, "X-Protected-By", CSRFP_NAME_VERSION);
return OK;
}
/*
* Function: csrfp_out_filter
* Filters output generated by content generator and modify content
*
* Parameters:
* f - apache filter object
* bb - apache brigade object
*
* Returns:
* apr_status_t code
*/
static apr_status_t csrfp_out_filter(ap_filter_t *f, apr_bucket_brigade *bb)
{
request_rec *r = f->r;
/**
* if request file is image or js, ignore the filter on the top itself
*/
if (!needvalidation(r)) {
// No need of validation, go ahead!
ap_remove_output_filter(f);
return ap_pass_brigade(f->next, bb);
}
// Get the context config
csrfp_opf_ctx *rctx = csrfp_get_rctx(r);
/*
* - Determine if it's html and force chunked response
* - search <body to insert <noscript> .. </noscript> info
* - search </body> to insert script
* - set csrfp_token cookie
* - end (all done)
*/
if(rctx->state == op_init) {
const char *type = getOutputContentType(r);
if(type == NULL || ( strncasecmp(type, "text/html", 9) != 0
&& strncasecmp(type, "text/xhtml", 10) != 0) ) {
// we don't want to parse this response (no html)
rctx->state = op_end;
rctx->search = NULL;
ap_remove_output_filter(f);
} else {
// start searching head/body to inject our script
// -- need to modify the Content-Length header
if(CSRFP_CHUNKED_ONLY) {
// send as chunked response
apr_table_unset(r->headers_out, "Content-Length");
apr_table_unset(r->err_headers_out, "Content-Length");
r->chunked = 1;
rctx->clstate = modified; // Content-Length need not be modified anymore
} else {
// Modify the content-length header -- if available
/**
* #todo: probably Content-Length is not generated by the time this hook is called
* So we might want this be done by later hook
* Calculate the content-length value?
*/
int errh = 0;
const char* cl = apr_table_get(r->headers_out, "Content-Length");
if(!cl) {
errh = 1;
cl = apr_table_get(r->err_headers_out, "Content-Length");
}
if(cl) {
// adjust non-chunked response
char *length;
apr_off_t s;
char *errp = NULL;
if(apr_strtoff(&s, cl, &errp, 10) == APR_SUCCESS) {
s = s + strlen(rctx->script) + strlen(rctx->noscript);
length = apr_psprintf(r->pool, "%"APR_OFF_T_FMT, s);
if(!errh) {
apr_table_set(r->headers_out, "Content-Length", length);
} else {
apr_table_set(r->err_headers_out, "Content-Length", length);
}
} else {
// fallback to chunked
r->chunked = 1;
if(!errh) {
apr_table_unset(r->headers_out, "Content-Length");
} else {
apr_table_unset(r->err_headers_out, "Content-Length");
}
}
rctx->clstate = modified; // Content-Length need not be modified anymore
} else {
// This means Content-Length header has not yet been generated
// #todo need to do something about this
}
}
}
}
// start searching within this brigade...
if (rctx->search) {
apr_bucket *b;
// Create custo pool for Output Filter
apr_pool_t *pool;
apr_pool_create(&pool, r->pool);
for (b = APR_BRIGADE_FIRST(bb); b != APR_BRIGADE_SENTINEL(bb); b = APR_BUCKET_NEXT(b)) {
if (APR_BUCKET_IS_EOS(b)) {
/* If we ever see an EOS, make sure to FLUSH. */
apr_bucket *flush = apr_bucket_flush_create(f->c->bucket_alloc);
APR_BUCKET_INSERT_BEFORE(b, flush);
}
if (!(APR_BUCKET_IS_METADATA(b))) {
const char *buf;
apr_size_t nbytes;
int findBracketOnly = 0;
/**
* Concept: While searching for a string say '<body(.*)>' in a buffer
* 4 cases are possible in a bucket
* 1. '<body' found & '>' found
* 2. '<body' found & '>' not found i.e. '>' in next bucket
* 3. '<body' not found, but cause of bucket overlap, for ex
* ... '<bo' in one bucket, 'dy(.*)>' in another
* 4. '<body' not found, no overlap issue
*/
restart:
if (apr_bucket_read(b, &buf, &nbytes, APR_BLOCK_READ) == APR_SUCCESS) {
if (nbytes > 0) {
// Create a new string = overlap_buf + buf
const char *nbuf = apr_pstrcat(pool, rctx->overlap_buf,
buf, NULL);
const char *marker = NULL;
apr_size_t sz;
marker = csrfp_strncasestr(nbuf, rctx->search, nbytes);
//apr_table_addn(r->headers_out, "xyz", marker);
if (marker || findBracketOnly) {
// ..search was found
if (rctx->state == op_init
|| findBracketOnly) {
// Seach for '<body' now searching for first '>'
// Or checking if it does not exist in current bucket
apr_size_t buflen = strlen(buf);
// Setting for case - 2, '<body' found in prev bucket
apr_size_t markerlen = 0;
apr_size_t sz = 0;
const char *c = buf;
if (!findBracketOnly) {
// setting for case - 1 '<body' in same bucket
markerlen = strlen(marker);
sz = buflen - markerlen;
c = marker;
}
int offset = 0, flag = 0;
for ( ; *c != '>'; offset++, c++) {
if ((offset + markerlen) == buflen) {
++flag;
break;
}
}
if (!flag) {
// case - 1, <body and > in same bucket
sz += ++offset;
b = csrfp_inject(r, bb, b, rctx, buf, sz, 0);
findBracketOnly = 0;
} else {
// case - 2, <body found, need to find > in next buffer
b = APR_BUCKET_NEXT(b);
++findBracketOnly;
}
goto restart;
} else if (rctx->state == op_body_init) {
apr_size_t sz = strlen(buf) - strlen(marker) + sizeof("</body>") - 1;
b = csrfp_inject(r, bb, b, rctx, buf, sz, 1);
}
} else {
// case - 3 or 4 '<body' not found in current bucket
const char *cptr = buf + (sizeof buf) - CSRFP_OVERLAP_BUCKET_SIZE;
apr_cpystrn(rctx->overlap_buf, cptr, CSRFP_OVERLAP_BUCKET_SIZE);
}
}
}
}
}
apr_pool_destroy(pool);
}
const char *regenToken = apr_table_get(r->subprocess_env, "regen_csrfptoken");
if (regenToken && !strcasecmp(regenToken, CSRFP_REGEN_TOKEN)) {
/*
* - Regenrate token
* - Send it as output header
*/
// Start the sql connection
sqlite3 *db = csrfp_sql_init(r);
if (db == NULL) {
ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
"CSRFP UNABLE TO ACCESS DB OBJECT IN FILTER FUNCTION");
} else {
setTokenCookie(r, db);
}
// Clean old expired values
csrfp_sql_table_clean(r, db);
// Close the sql connection
sqlite3_close(db);
}
return ap_pass_brigade(f->next, bb);
}
/*
* Function: csrfp_insert_filter
* Registers in filter -- csrfp_in_filter
*
* Parameters:
* r - request_rec object
*
* Returns:
* void
*/
static void csrfp_insert_filter(request_rec *r)
{
ap_add_output_filter("csrfp_out_filter", NULL, r, r->connection);
}
/**
* Handler to allocate memory to config object
* And allocae default values to variabled
*
* @param: standard parameters, @return void
*/
static void *csrfp_srv_config_create(apr_pool_t *p, server_rec *s)
{
// Registering default configurations
config = apr_pcalloc(p, sizeof(csrfp_config));
config->flag = CSRFP_TRUE;
config->action = forbidden;
config->tokenLength = DEFAULT_TOKEN_LENGTH;
// Allocate memory & assign default value for tokenName
config->tokenName = apr_pcalloc(p, CSRFP_TOKEN_NAME_MAXLENGTH);
apr_cpystrn(config->tokenName, CSRFP_TOKEN,
CSRFP_TOKEN_NAME_MAXLENGTH);
// Allocates memory, and assign defalut value For jsFilePath
config->jsFilePath = apr_pcalloc(p, CSRFP_URI_MAXLENGTH);
apr_cpystrn(config->jsFilePath, DEFAULT_JS_FILE_PATH,
CSRFP_URI_MAXLENGTH);
// Allocates memory, and assign defalut value For errorRedirectionUri
config->errorRedirectionUri = apr_pcalloc(p, CSRFP_URI_MAXLENGTH);
apr_cpystrn(config->errorRedirectionUri, DEFAULT_REDIRECT_URL,
CSRFP_URI_MAXLENGTH);
// Allocates memory, and assign defalut value For errorCustomMessage
config->errorCustomMessage = apr_pcalloc(p, CSRFP_ERROR_MESSAGE_MAXLENGTH);
apr_cpystrn(config->errorCustomMessage, DEFAULT_ERROR_MESSAGE,
CSRFP_ERROR_MESSAGE_MAXLENGTH);
// Allocates memory, and assign defalut value For disablesJsMessage
config->disablesJsMessage = apr_pcalloc(p, CSRFP_DISABLED_JS_MESSAGE_MAXLENGTH);
apr_cpystrn(config->disablesJsMessage, DEFAULT_DISABLED_JS_MESSSAGE,
CSRFP_DISABLED_JS_MESSAGE_MAXLENGTH);
// Allocate memory and set regex for ignore-pattern regex object
config->ignore_pattern = ap_pregcomp(p, CSRFP_IGNORE_PATTERN, AP_REG_ICASE);
return config;
}
//=============================================================
// Configuration handler functions
//=============================================================
/** csrfEnable **/
const char *csrfp_enable_cmd(cmd_parms *cmd, void *cfg, const char *arg)
{
if(!strcasecmp(arg, "off")) config->flag = CSRFP_FALSE;
else config->flag = CSRFP_TRUE;
return NULL;
}
/** tokenName **/
const char *csrfp_tokenName_cmd(cmd_parms *cmd, void *cfg, const char *arg)
{
if(strlen(arg) > 0) {
apr_cpystrn(config->tokenName, arg,
CSRFP_TOKEN_NAME_MAXLENGTH);
}
// Else default value will be set
return NULL;
}
/** csrfAction **/
const char *csrfp_action_cmd(cmd_parms *cmd, void *cfg, const char *arg)
{
if(!strcasecmp(arg, "forbidden"))
config->action = forbidden;
else if (!strcasecmp(arg, "strip"))
config->action = strip;
else if (!strcasecmp(arg, "redirect"))
config->action = redirect;
else if (!strcasecmp(arg, "message"))
config->action = message;
else if (!strcasecmp(arg, "internal_server_error"))
config->action = internal_server_error;
else config->action = forbidden; //default
return NULL;
}
/** errorRedirectionUri **/
const char *csrfp_errorRedirectionUri_cmd(cmd_parms *cmd, void *cfg, const char *arg)
{
if(strlen(arg) > 0) {
apr_cpystrn(config->errorRedirectionUri, arg,
CSRFP_URI_MAXLENGTH);
}
else config->errorRedirectionUri = NULL;
return NULL;
}
/** errorCustomMessage **/
const char *csrfp_errorCustomMessage_cmd(cmd_parms *cmd, void *cfg, const char *arg)
{
if(strlen(arg) > 0) {
apr_cpystrn(config->errorCustomMessage, arg,
CSRFP_ERROR_MESSAGE_MAXLENGTH);
}
else config->errorCustomMessage = NULL;
return NULL;
}
/** jsFilePath **/
const char *csrfp_jsFilePath_cmd(cmd_parms *cmd, void *cfg, const char *arg)
{
if(strlen(arg) > 0) {
apr_cpystrn(config->jsFilePath, arg,
CSRFP_URI_MAXLENGTH);
}
//no else as default config shall come to effect
return NULL;
}
/** tokenLength **/
const char *csrfp_tokenLength_cmd(cmd_parms *cmd, void *cfg, const char *arg)
{
if(strlen(arg) > 0) {
int length = atoi(arg);
if (length < DEFAULT_TOKEN_MINIMUM_LENGTH
|| !length)
return NULL;
config->tokenLength = length;
}
//no else as default config shall come to effect
return NULL;
}
/** disablesJsMessage **/
const char *csrfp_disablesJsMessage_cmd(cmd_parms *cmd, void *cfg, const char *arg)
{
if(strlen(arg) > 0) {
apr_cpystrn(config->disablesJsMessage, arg,
CSRFP_DISABLED_JS_MESSAGE_MAXLENGTH);
}
//no else as default config shall come to effect
return NULL;
}
/** verifyGetFor **/
const char *csrfp_verifyGetFor_cmd(cmd_parms *cmd, void *cfg, const char *arg)
{
if(strlen(arg) > 0) {
// Create a Node
struct getRuleNode *p;
p = apr_pcalloc(cmd->pool, sizeof (struct getRuleNode));
p->next = NULL;
p->patternString = apr_pstrdup(cmd->pool, arg);
p->pattern = apr_pcalloc(cmd->pool, sizeof (p->pattern));
ap_regcomp(p->pattern, arg, 0);
// Add to linked list
if (getTop == NULL) {
// First element
getTop = p;
getPointer = p;
} else {
getPointer->next = p;
getPointer = p;
}
}
return NULL;
}
/** Directives from httpd.conf or .htaccess **/
static const command_rec csrfp_directives[] =
{
AP_INIT_TAKE1("csrfpEnable", csrfp_enable_cmd, NULL,
RSRC_CONF|ACCESS_CONF,
"csrfpEnable 'on'|'off', enables the module. Default is 'on'"),
AP_INIT_TAKE1("csrfpAction", csrfp_action_cmd, NULL,
RSRC_CONF,
"Defines Action to be taken in case of failed validation"),
AP_INIT_TAKE1("errorRedirectionUri", csrfp_errorRedirectionUri_cmd, NULL,
RSRC_CONF,
"Defines URL to redirect if action = redirect"),
AP_INIT_TAKE1("errorCustomMessage", csrfp_errorCustomMessage_cmd, NULL,
RSRC_CONF,
"Defines Custom Error Message if action = message"),
AP_INIT_TAKE1("jsFilePath", csrfp_jsFilePath_cmd, NULL,
RSRC_CONF,
"Absolute url of the js file"),
AP_INIT_TAKE1("tokenLength", csrfp_tokenLength_cmd, NULL,
RSRC_CONF,
"Defines length of csrfp_token in cookie"),
AP_INIT_TAKE1("tokenName", csrfp_tokenName_cmd, NULL,
RSRC_CONF,
"Name of the csrf token, 'default is csrfp_token'"),
AP_INIT_TAKE1("disablesJsMessage", csrfp_disablesJsMessage_cmd, NULL,
RSRC_CONF,
"<noscript> message to be shown to user"),
AP_INIT_ITERATE("verifyGetFor", csrfp_verifyGetFor_cmd, NULL,
RSRC_CONF|ACCESS_CONF,
"Pattern of urls for which GET request CSRF validation is enabled"),
{ NULL }
};
/**
* Hook registering function for mod_csrfp
* @param: pool, apr_pool_t
*/
static void csrfp_register_hooks(apr_pool_t *pool)
{
// Handler to modify output filter
ap_register_output_filter("csrfp_out_filter", csrfp_out_filter, NULL, AP_FTYPE_RESOURCE);
// Create hooks in the request handler, so we get called when a request arrives
ap_hook_insert_filter(csrfp_insert_filter, NULL, NULL, APR_HOOK_REALLY_FIRST);
// Handler to parse incoming request and validate incoming request
ap_hook_fixups(csrfp_header_parser, NULL, NULL, APR_HOOK_LAST);
}
//===================================================================
// Apache Module Defination
//===================================================================
module AP_MODULE_DECLARE_DATA csrf_protector_module =
{
STANDARD20_MODULE_STUFF,
NULL,
NULL,
csrfp_srv_config_create, /* Server config create function */
NULL,
csrfp_directives, /* Any directives we may have for httpd */
csrfp_register_hooks /* Our hook registering function */
};
| 34.04386 | 148 | 0.554515 | [
"object"
] |
c6051f37400d9936dbeb2106e774bb86d0cf6036 | 6,127 | h | C | export/debug/windows/obj/include/openfl/display/SimpleButton.h | bobisdabbing/Vs-The-United-Lands-stable | 0807e58b6d8ad1440bdd350bf006b37a1b7ca9b5 | [
"MIT"
] | 1 | 2021-07-19T05:10:43.000Z | 2021-07-19T05:10:43.000Z | export/debug/windows/obj/include/openfl/display/SimpleButton.h | bobisdabbing/Vs-The-United-Lands-stable | 0807e58b6d8ad1440bdd350bf006b37a1b7ca9b5 | [
"MIT"
] | null | null | null | export/debug/windows/obj/include/openfl/display/SimpleButton.h | bobisdabbing/Vs-The-United-Lands-stable | 0807e58b6d8ad1440bdd350bf006b37a1b7ca9b5 | [
"MIT"
] | null | null | null | // Generated by Haxe 4.1.5
#ifndef INCLUDED_openfl_display_SimpleButton
#define INCLUDED_openfl_display_SimpleButton
#ifndef HXCPP_H
#include <hxcpp.h>
#endif
#ifndef INCLUDED_openfl_display_InteractiveObject
#include <openfl/display/InteractiveObject.h>
#endif
HX_DECLARE_CLASS2(lime,app,IModule)
HX_DECLARE_CLASS2(openfl,_Vector,IVector)
HX_DECLARE_CLASS2(openfl,_Vector,ObjectVector)
HX_DECLARE_CLASS2(openfl,display,DisplayObject)
HX_DECLARE_CLASS2(openfl,display,DisplayObjectContainer)
HX_DECLARE_CLASS2(openfl,display,IBitmapDrawable)
HX_DECLARE_CLASS2(openfl,display,InteractiveObject)
HX_DECLARE_CLASS2(openfl,display,SimpleButton)
HX_DECLARE_CLASS2(openfl,display,Stage)
HX_DECLARE_CLASS2(openfl,events,Event)
HX_DECLARE_CLASS2(openfl,events,EventDispatcher)
HX_DECLARE_CLASS2(openfl,events,IEventDispatcher)
HX_DECLARE_CLASS2(openfl,events,MouseEvent)
HX_DECLARE_CLASS2(openfl,geom,Matrix)
HX_DECLARE_CLASS2(openfl,geom,Rectangle)
HX_DECLARE_CLASS2(openfl,media,SoundTransform)
namespace openfl{
namespace display{
class HXCPP_CLASS_ATTRIBUTES SimpleButton_obj : public ::openfl::display::InteractiveObject_obj
{
public:
typedef ::openfl::display::InteractiveObject_obj super;
typedef SimpleButton_obj OBJ_;
SimpleButton_obj();
public:
enum { _hx_ClassId = 0x0a9c7d56 };
void __construct( ::openfl::display::DisplayObject upState, ::openfl::display::DisplayObject overState, ::openfl::display::DisplayObject downState, ::openfl::display::DisplayObject hitTestState);
inline void *operator new(size_t inSize, bool inContainer=true,const char *inName="openfl.display.SimpleButton")
{ return ::hx::Object::operator new(inSize,inContainer,inName); }
inline void *operator new(size_t inSize, int extra)
{ return ::hx::Object::operator new(inSize+extra,true,"openfl.display.SimpleButton"); }
static ::hx::ObjectPtr< SimpleButton_obj > __new( ::openfl::display::DisplayObject upState, ::openfl::display::DisplayObject overState, ::openfl::display::DisplayObject downState, ::openfl::display::DisplayObject hitTestState);
static ::hx::ObjectPtr< SimpleButton_obj > __alloc(::hx::Ctx *_hx_ctx, ::openfl::display::DisplayObject upState, ::openfl::display::DisplayObject overState, ::openfl::display::DisplayObject downState, ::openfl::display::DisplayObject hitTestState);
static void * _hx_vtable;
static Dynamic __CreateEmpty();
static Dynamic __Create(::hx::DynamicArray inArgs);
//~SimpleButton_obj();
HX_DO_RTTI_ALL;
::hx::Val __Field(const ::String &inString, ::hx::PropertyAccess inCallProp);
static bool __GetStatic(const ::String &inString, Dynamic &outValue, ::hx::PropertyAccess inCallProp);
::hx::Val __SetField(const ::String &inString,const ::hx::Val &inValue, ::hx::PropertyAccess inCallProp);
static bool __SetStatic(const ::String &inString, Dynamic &ioValue, ::hx::PropertyAccess inCallProp);
void __GetFields(Array< ::String> &outFields);
static void __register();
void __Mark(HX_MARK_PARAMS);
void __Visit(HX_VISIT_PARAMS);
bool _hx_isInstanceOf(int inClassId);
::String __ToString() const { return HX_("SimpleButton",e4,57,52,ed); }
static ::Dynamic _hx___constructor;
static Dynamic _hx___constructor_dyn() { return _hx___constructor;}
bool enabled;
bool trackAsMenu;
bool useHandCursor;
::openfl::display::DisplayObject _hx___currentState;
::openfl::display::DisplayObject _hx___downState;
::openfl::display::DisplayObject _hx___hitTestState;
bool _hx___ignoreEvent;
::openfl::display::DisplayObject _hx___overState;
::openfl::_Vector::ObjectVector _hx___previousStates;
::openfl::media::SoundTransform _hx___soundTransform;
::openfl::display::DisplayObject _hx___upState;
void _hx___getBounds( ::openfl::geom::Rectangle rect, ::openfl::geom::Matrix matrix);
void _hx___getRenderBounds( ::openfl::geom::Rectangle rect, ::openfl::geom::Matrix matrix);
::String _hx___getCursor();
bool _hx___hitTest(Float x,Float y,bool shapeFlag,::Array< ::Dynamic> stack,bool interactiveOnly, ::openfl::display::DisplayObject hitObject);
bool _hx___hitTestMask(Float x,Float y);
void _hx___setStageReference( ::openfl::display::Stage stage);
void _hx___setTransformDirty();
void _hx___update(bool transformOnly,bool updateChildren);
void _hx___updateTransforms( ::openfl::geom::Matrix overrideTransform);
::openfl::display::DisplayObject get_downState();
::Dynamic get_downState_dyn();
::openfl::display::DisplayObject set_downState( ::openfl::display::DisplayObject downState);
::Dynamic set_downState_dyn();
::openfl::display::DisplayObject get_hitTestState();
::Dynamic get_hitTestState_dyn();
::openfl::display::DisplayObject set_hitTestState( ::openfl::display::DisplayObject hitTestState);
::Dynamic set_hitTestState_dyn();
::openfl::display::DisplayObject get_overState();
::Dynamic get_overState_dyn();
::openfl::display::DisplayObject set_overState( ::openfl::display::DisplayObject overState);
::Dynamic set_overState_dyn();
::openfl::media::SoundTransform get_soundTransform();
::Dynamic get_soundTransform_dyn();
::openfl::media::SoundTransform set_soundTransform( ::openfl::media::SoundTransform value);
::Dynamic set_soundTransform_dyn();
::openfl::display::DisplayObject get_upState();
::Dynamic get_upState_dyn();
::openfl::display::DisplayObject set_upState( ::openfl::display::DisplayObject upState);
::Dynamic set_upState_dyn();
::openfl::display::DisplayObject set___currentState( ::openfl::display::DisplayObject value);
::Dynamic set___currentState_dyn();
void _hx___this_onMouseDown( ::openfl::events::MouseEvent event);
::Dynamic _hx___this_onMouseDown_dyn();
void _hx___this_onMouseOut( ::openfl::events::MouseEvent event);
::Dynamic _hx___this_onMouseOut_dyn();
void _hx___this_onMouseOver( ::openfl::events::MouseEvent event);
::Dynamic _hx___this_onMouseOver_dyn();
void _hx___this_onMouseUp( ::openfl::events::MouseEvent event);
::Dynamic _hx___this_onMouseUp_dyn();
};
} // end namespace openfl
} // end namespace display
#endif /* INCLUDED_openfl_display_SimpleButton */
| 41.120805 | 250 | 0.777542 | [
"object"
] |
c612ed6890de96044a82feb8c21e496c2b5638c3 | 4,680 | h | C | headers/Message.h | KhaledSoliman/P2P-Image-App | ef3cdd083aef1871f8383e44205c81aab2799257 | [
"MIT"
] | null | null | null | headers/Message.h | KhaledSoliman/P2P-Image-App | ef3cdd083aef1871f8383e44205c81aab2799257 | [
"MIT"
] | 11 | 2019-10-23T17:10:36.000Z | 2019-11-22T19:59:48.000Z | headers/Message.h | KhaledSoliman/Distributed-Systems-Fall19 | ef3cdd083aef1871f8383e44205c81aab2799257 | [
"MIT"
] | null | null | null | #ifndef DISTRIBUTED_SYSTEMS_FALL19_MESSAGE_H
#define DISTRIBUTED_SYSTEMS_FALL19_MESSAGE_H
#include <cstdio>
#include <string>
#include <boost/date_time/posix_time/time_serialize.hpp>
#include <boost/date_time/local_time/local_time.hpp>
#include <boost/serialization/access.hpp>
#define MAX_MESSAGE_SIZE 4096
#define MAX_READ_MESSAGE_SIZE 10240
#define USER_MESSAGE_MAX_SIZE 10000000
class Message {
public:
enum MessageType {
Request = 0,
Reply = 1
};
enum OperationType {
ECHO,
ACK,
HELLO,
FEED,
LOGIN,
LOGOUT,
SEARCH,
REGISTER,
ADD_IMAGE,
DOWNLOAD_IMAGE,
VIEW_IMAGE,
DELETE_IMAGE,
ADD_VIEWER,
DENY_VIEWER,
REMOVE_VIEWER,
GET_REQUESTS,
GET_PENDING_REQUESTS,
GET_REMAINING_VIEWS,
UPDATE_VIEW_LIMIT,
AUTH_HELLO,
SHOW_ONLINE,
FEED_PROFILE,
};
struct RPC_ID {
static int currentMessageId;
int messageId;
boost::posix_time::ptime time;
bool fragmented;
int fragmentId;
std::string address;
int portNumber;
RPC_ID() {
this->messageId = RPC_ID::incrementMessageId();
this->fragmentId = 0;
this->fragmented = false;
this->time = boost::posix_time::second_clock::local_time();
}
RPC_ID(const std::string& address, int portNumber) {
this->address = address;
this->portNumber = portNumber;
this->messageId = RPC_ID::incrementMessageId();
this->fragmentId = 0;
this->fragmented = false;
this->time = boost::posix_time::second_clock::local_time();
}
const boost::posix_time::ptime &getTime() const {
return time;
}
void setTime(const boost::posix_time::ptime &time) {
this->time = time;
}
const std::string &getAddress() const {
return address;
}
void setAddress(const std::string &address) {
this->address = address;
}
int getPortNumber() const {
return portNumber;
}
void setPortNumber(int portNumber) {
this->portNumber = portNumber;
}
static int getCurrentMessageId() {
return currentMessageId;
}
static void setCurrentMessageId(int currentMessageId) {
RPC_ID::currentMessageId = currentMessageId;
}
int static incrementMessageId() {
return RPC_ID::currentMessageId++;
}
bool isFragmented() const {
return fragmented;
}
void setFragmented(bool fragmented) {
this->fragmented = fragmented;
}
int getFragmentId() const {
return fragmentId;
}
void setFragmentId(int fragmentId) {
this->fragmentId = fragmentId;
}
int getMessageId() const {
return messageId;
}
void setMessageId(int messageId) {
this->messageId = messageId;
}
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive &ar, const unsigned int version) {
ar & messageId & address & portNumber & time & fragmentId & fragmented;
}
};
Message(MessageType messageType, OperationType operation, std::string message, size_t messageSize, RPC_ID rpcId);
Message();
explicit Message(char *marshalled_base64);
std::string marshal();
int getOperation();
RPC_ID getRPCId();
std::string getMessage();
size_t getMessageSize();
MessageType getMessageType();
void setOperation(OperationType _operation);
void setMessage(std::string message, size_t message_size);
void setMessageType(MessageType message_type);
static bool verifyFragmentation(const std::string &marshalled);
static std::vector<std::string> split(const std::string &str, int splitLength);
std::vector<Message *> fragment(std::string &marshalled);
~Message();
private:
MessageType messageType;
OperationType operation;
std::string message;
size_t messageSize;
RPC_ID rpcId;
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive &ar, const unsigned int /* file_version */) {
ar & messageType & operation & message & messageSize & rpcId;
}
};
BOOST_CLASS_TRACKING(Message, boost::serialization::track_always);
#endif //DISTRIBUTED_SYSTEMS_FALL19_MESSAGE_H
| 24.248705 | 117 | 0.608333 | [
"vector"
] |
c618fd139a45e4d8822615202a86d8017449e3bc | 4,696 | h | C | src/glow/GlVertexArray.h | cagcoach/glow | 97336cd5e229aa57bcd413e66bc529f6f1f1f69b | [
"MIT"
] | 19 | 2018-02-20T15:41:54.000Z | 2022-02-23T19:01:08.000Z | src/glow/GlVertexArray.h | cagcoach/glow | 97336cd5e229aa57bcd413e66bc529f6f1f1f69b | [
"MIT"
] | 9 | 2018-03-13T08:34:33.000Z | 2020-07-14T20:39:01.000Z | src/glow/GlVertexArray.h | cagcoach/glow | 97336cd5e229aa57bcd413e66bc529f6f1f1f69b | [
"MIT"
] | 10 | 2018-03-12T13:29:13.000Z | 2021-05-04T09:04:26.000Z | #ifndef INCLUDE_RV_GLVERTEXARRAY_H_
#define INCLUDE_RV_GLVERTEXARRAY_H_
#include "GlObject.h"
#include "GlBuffer.h"
#include <memory>
#include <map>
namespace glow {
/** \brief data type of the vertex attribute. **/
enum class AttributeType {
BYTE = GL_BYTE,
UNSIGNED_BYTE = GL_UNSIGNED_BYTE,
SHORT = GL_SHORT,
UNSIGNED_SHORT = GL_UNSIGNED_SHORT,
INT = GL_INT,
UNSIGNED_INT = GL_UNSIGNED_INT,
HALF_FLOAT = GL_HALF_FLOAT,
FLOAT = GL_FLOAT,
DOUBLE = GL_DOUBLE,
FIXED = GL_FIXED,
INT_2_10_10_10_REV = GL_INT_2_10_10_10_REV,
UNSIGNED_INT_2_10_10_10_REV = GL_UNSIGNED_INT_2_10_10_10_REV,
UNSIGNED_INT_10F_11F_11F_REV = GL_UNSIGNED_INT_10F_11F_11F_REV
};
/** \brief representation of a Vertex Array Object.
*
* In core profile OpenGL, the vertex array object is needed for specification of the vertex
* attributes. Therefore, this class provides a convenient access to a Vertex Array Object
* with resource management.
*
* It furthermore enables a more "natural" usage of vertex buffer objects with vertex arrays
* by making the actual definition of attributes a part of this object.
*
*
* \author behley
*
* TODO: Compatibility with glBindVertexBuffer / glVertexBindingDivisor? Available with OpenGL version 4.3
**/
class GlVertexArray : public GlObject {
public:
GlVertexArray();
~GlVertexArray();
/** \brief bind the vertex array object. **/
void bind() override;
/** \brief release the vertex array object. **/
void release() override;
// template<typename T>
// void unbindVertexBuffer()
/** \brief set the vertex attribute pointer for the given vertex buffer
*
* Vertex attributes define the layout of the data inside memory. This actually maps
* an array or its contents to a attribute in the vertex shader and activates the attribute.
*
* \param idx index of the vertex attribute
* \param buffer vertex buffer represented by a GlBuffer object.
* \param size size or number of components of the attribute (1,2,3, or 4)
* \param type data type of the attribute inside the vertex buffer.
* \param normalized should the data be normalized?
* \param stride specifies the byte offset between consecutive generic vertex attributes
* \param offset specifies the byte offset of the first component of the first generic vertex attribute
* in the array in the data store of the buffer.
**/
template <typename T>
void setVertexAttribute(uint32_t idx, GlBuffer<T>& buffer, int32_t size, AttributeType type, bool normalized,
uint32_t stride, GLvoid* offset);
/** \brief enable vertex attribute with given index \a idx **/
void enableVertexAttribute(uint32_t idx);
/** \brief disable vertex attribute with given index \a idx **/
void disableVertexAttribute(uint32_t idx);
protected:
/** \brief bind vertex array object only if needed and return overwritten vertex array object. **/
GLuint bindTransparently();
/** \brief release vertex array object and restore state before calling bindTranparently. **/
void releaseTransparently(GLuint old_vao);
static GLuint boundVAO_;
// TODO: should we also check if the vertex attributes are set when enabled?
struct VertexAttributeState {
public:
GlObject* buffer{0};
bool initialized{false};
bool enabled{false};
};
// only needed for book keeping purposes.
std::map<uint32_t, std::shared_ptr<GLuint> > vertexBuffers_;
};
template <typename T>
void GlVertexArray::setVertexAttribute(uint32_t idx, GlBuffer<T>& buffer, int32_t numComponents, AttributeType type,
bool normalized, uint32_t stride_in_bytes, GLvoid* offset) {
// replaces & frees shared pointer if present; copies the shared pointer of buffer => buffer is not deleted.
vertexBuffers_[idx] = buffer.ptr_;
// assert(buffer.target() == BufferTarget::ARRAY_BUFFER); What about element indexes?
GLuint oldvao = bindTransparently();
buffer.bind();
if (type == AttributeType::INT || type == AttributeType::UNSIGNED_INT) {
glVertexAttribIPointer(static_cast<GLuint>(idx), static_cast<GLint>(numComponents), static_cast<GLenum>(type),
static_cast<GLuint>(stride_in_bytes), offset);
} else {
glVertexAttribPointer(static_cast<GLuint>(idx), static_cast<GLint>(numComponents), static_cast<GLenum>(type),
static_cast<GLboolean>(normalized), static_cast<GLuint>(stride_in_bytes), offset);
}
glEnableVertexAttribArray(static_cast<GLuint>(idx));
releaseTransparently(oldvao);
buffer.release();
CheckGlError();
}
} /* namespace rv */
#endif /* INCLUDE_RV_GLVERTEXARRAY_H_ */
| 36.6875 | 116 | 0.72402 | [
"object"
] |
c61a63dff85b61ed577d2edc71c73da3781741c4 | 195 | c | C | upnp/src/api/EventSubscribe.c | xhpohanka/pupnp | 7a5b068266b6b6870c3398a79c59eb60e09f1f4d | [
"BSD-3-Clause"
] | 5 | 2017-03-14T16:55:42.000Z | 2019-07-26T14:47:48.000Z | upnp/src/api/EventSubscribe.c | xhpohanka/pupnp | 7a5b068266b6b6870c3398a79c59eb60e09f1f4d | [
"BSD-3-Clause"
] | null | null | null | upnp/src/api/EventSubscribe.c | xhpohanka/pupnp | 7a5b068266b6b6870c3398a79c59eb60e09f1f4d | [
"BSD-3-Clause"
] | 9 | 2015-11-30T08:52:07.000Z | 2022-03-02T17:30:03.000Z |
/*!
* \file
*
* \brief UpnpEventSubscribe object implementation.
*
* \author Marcelo Roberto Jimenez
*/
#include "config.h"
#define TEMPLATE_GENERATE_SOURCE
#include "EventSubscribe.h"
| 13 | 51 | 0.717949 | [
"object"
] |
c61ac5a4910a1d517e96dcc6a82d22df79bd19bd | 1,471 | h | C | src/devices/sound/upd934g.h | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 26 | 2015-03-31T06:25:51.000Z | 2021-12-14T09:29:04.000Z | src/devices/sound/upd934g.h | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | null | null | null | src/devices/sound/upd934g.h | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 10 | 2015-03-27T05:45:51.000Z | 2022-02-04T06:57:36.000Z | // license: BSD-3-Clause
// copyright-holders: Dirk Best
/***************************************************************************
NEC μPD934G
Percussion Generator
***************************************************************************/
#ifndef MAME_SOUND_UPD934G_H
#define MAME_SOUND_UPD934G_H
#pragma once
//**************************************************************************
// TYPE DEFINITIONS
//**************************************************************************
class upd934g_device : public device_t, public device_sound_interface
{
public:
static constexpr feature_type imperfect_features() { return feature::SOUND; }
// construction/destruction
upd934g_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock);
// configuration
auto data_callback() { return m_data_cb.bind(); }
void write(offs_t offset, uint8_t data);
protected:
// device-level overrides
virtual void device_start() override;
virtual void device_reset() override;
virtual void sound_stream_update(sound_stream &stream, std::vector<read_stream_view> const &inputs, std::vector<write_stream_view> &outputs) override;
private:
devcb_read8 m_data_cb;
sound_stream *m_stream;
uint16_t m_addr[16];
struct
{
uint16_t pos;
int playing;
int volume;
}
m_channel[4];
int m_sample;
bool m_ready;
};
// device type definition
DECLARE_DEVICE_TYPE(UPD934G, upd934g_device)
#endif // MAME_SOUND_UPD934G_H
| 23.349206 | 151 | 0.60571 | [
"vector"
] |
c6394d4d36d0ad3ed2400ea4ac7699cede6d0f23 | 3,548 | h | C | Extensions/CCSendMessages/CCSendMessages.h | cocos2d/cocos2d-iphone-extensions | 48996164f1b948b3bd000392809eca4e4de5cf9e | [
"MIT"
] | 49 | 2015-01-29T14:46:08.000Z | 2022-01-31T07:34:11.000Z | Extensions/CCSendMessages/CCSendMessages.h | cocos2d/cocos2d-iphone-extensions | 48996164f1b948b3bd000392809eca4e4de5cf9e | [
"MIT"
] | 1 | 2018-11-06T06:17:21.000Z | 2018-11-06T06:17:21.000Z | Extensions/CCSendMessages/CCSendMessages.h | cocos2d/cocos2d-iphone-extensions | 48996164f1b948b3bd000392809eca4e4de5cf9e | [
"MIT"
] | 31 | 2015-01-29T14:46:09.000Z | 2022-03-11T05:01:41.000Z | /*
* CCSendMessages
*
* Cocos2D-iPhone-Extensions v0.2.1
* https://github.com/cocos2d/cocos2d-iphone-extensions
*
* Copyright (c) 2011 by Darren Clark
* http://darrenclark.ca/
*
* 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.
*
*/
#import <Foundation/Foundation.h>
#import "cocos2d.h"
@class CCStoredMessages;
/** @class CCSendMessages CCActionInstant that sends messsages to a target when it is run.
*
* It is different than the CCCallFunc classes in that any message can be sent
* to a target regardless of the number/type of arguments.
*
* NOTE: Any selector in the NSObject class and any selector in the NSObject and
* NSCopying protocals cannot be added via -addMessage.
* If you need to call one of those selectors, create an NSInvocation and add it
* via -addInvocation:.
*
* Usage:
* Create a CCSendMessages instance with a target using -initWithTarget: or
* +actionWithTarget:
*
* Add message call(s) to it:
* (assuming sendMessages is your CCSendMessages object)
* [[sendMessages addMessage] setOpacity:0.5];
* [[sendMessages addMessage] long:0.5 selector:obj example:ccp(3,3)];
*
* Run it on a CCNode with -runAction:, or add it to a
* CCSequence to run it later on!
*
* Also, arguments don't have to be Objective-C objects.
*
* @version 0.2.1
*/
@interface CCSendMessages : CCActionInstant {
@private
id messagesTarget_;
CCStoredMessages *messages_;
}
/** Creates CCSendMessages action with given target. @see initWithTarget: */
+ (id)actionWithTarget:(id)t;
/** Init CCSendMessages action with given target
* @param t Target, which will receive messages.
*/
- (id)initWithTarget:(id)t;
/** Returns CCStoredMessages that is stored internally to capture Objective-C messages. */
- (id)addMessage;
/** Adds NSInvocation to internal CCStoredMessages, use this method to send NSObject
* & NSCopying selectors to a target.
*/
- (void)addInvocation:(NSInvocation *)invocation;
/** Sends all captured messages to a target.
*
* You don't need to use this method directly - use CCNode#runAction: instead.
*/
- (void)execute;
@end
// CCStoredMessages
// Simply a class to capture messages sent to it
//
// Public ivars are used instead of properties so
// that a wider range of selectors can be used
// (because this class cannot capture selectors it
// responds to). Also, because of this, most logic
// is handled in CCSendMessages
@interface CCStoredMessages : NSObject {
@public
id target_;
NSMutableArray *invocations_;
}
@end | 31.963964 | 90 | 0.737599 | [
"object"
] |
765d2042ac24f77d41121beae545918574a39fbe | 5,407 | h | C | include/kimm_husky_controllers/husky_franka_hqp.h | ggory15/kimm_husky_controllers | ec654bfd59eaf5ed3bc4045e024e05d35f775a49 | [
"MIT"
] | null | null | null | include/kimm_husky_controllers/husky_franka_hqp.h | ggory15/kimm_husky_controllers | ec654bfd59eaf5ed3bc4045e024e05d35f775a49 | [
"MIT"
] | null | null | null | include/kimm_husky_controllers/husky_franka_hqp.h | ggory15/kimm_husky_controllers | ec654bfd59eaf5ed3bc4045e024e05d35f775a49 | [
"MIT"
] | null | null | null | //Pinocchio Header
#include <pinocchio/fwd.hpp>
#include <pinocchio/algorithm/joint-configuration.hpp>
//ROS Header
#include "ros/ros.h"
#include "std_msgs/String.h"
#include "std_msgs/Float32MultiArray.h"
#include "std_msgs/Float32.h"
#include "sensor_msgs/JointState.h"
#include "geometry_msgs/Transform.h"
#include "std_msgs/Int16.h"
//SYSTEM Header
#include <sys/ioctl.h>
#include <termios.h>
#include <unistd.h>
// for hqp controller
#include <kimm_hqp_controller/robot/robot_wrapper.hpp>
#include <kimm_hqp_controller/formulation/inverse_dynamics_formulation_acc.hpp>
#include <kimm_hqp_controller/tasks/task_se3_equality.hpp>
#include <kimm_hqp_controller/tasks/task_joint_posture.hpp>
#include <kimm_hqp_controller/tasks/task_joint_bound.hpp>
#include <kimm_hqp_controller/tasks/task_mobile_base.hpp>
#include <kimm_hqp_controller/trajectory/trajectory_euclidian.hpp>
#include <kimm_hqp_controller/trajectory/trajectory_se3.hpp>
#include <kimm_hqp_controller/solver/solver_HQP_factory.hxx>
#include <kimm_hqp_controller/solver/util.hpp>
#include <kimm_hqp_controller/math/util.hpp>
// service
#include "kimm_joint_planner_ros_interface/action_joint_path.h"
#include "kimm_se3_planner_ros_interface/action_se3_path.h"
#include "kimm_path_planner_ros_interface/action_mobile_path.h"
using namespace std;
using namespace Eigen;
typedef Eigen::Matrix<double, 7, 1> Vector7d;
typedef struct State {
VectorXd q_;
VectorXd v_;
VectorXd dv_;
VectorXd torque_;
} state;
typedef struct Mob{
MatrixXd lambda_inv_;
MatrixXd lambda_, mass_, mass_inv_;
MatrixXd J_trans_;
MatrixXd J_trans_inv_;
VectorXd d_force_;
VectorXd d_torque_, torque_d_, torque_d_prev_;
VectorXd g_, nle_, coriolis_;
double gamma_, beta_;
VectorXd p_k_prev_, p_k_, alpha_k_;
} mob;
namespace RobotController{
class HuskyFrankaWrapper{
public:
HuskyFrankaWrapper(const std::string & robot_node, const bool & issimulation, ros::NodeHandle & node);
~HuskyFrankaWrapper(){};
void initialize();
void ctrl_update(const int& ); // msg for chaning controller
void franka_update(const sensor_msgs::JointState::ConstPtr&); // franka state update
void franka_update(const Vector7d&, const Vector7d&); // franka state update
void husky_update(const sensor_msgs::JointState::ConstPtr&); // husky state update
void husky_update(const Vector3d&, const Vector3d&, const Vector2d&, const Vector2d&); // husky state update
void compute(const double &); // computation by hqp controller
void franka_output(VectorXd & qacc); // joint torque of franka
void husky_output(VectorXd & qvel); // joint velocity of husky
void mass(MatrixXd & mass_mat);
void nle(VectorXd & nle_vec);
void J(MatrixXd & J);
void g(VectorXd & g_vec);
void ee_state(Vector3d & pos, Eigen::Quaterniond & quat);
void base_state(Vector3d & base);
int ctrltype(){
return ctrl_mode_;
}
void state(State & state_robot){
state_robot = state_;
}
private:
bool issimulation_, mode_change_, update_weight_;
double stime_, time_, node_index_, node_num_, prev_node_;
std::string robot_node_;
State state_;
int ctrl_mode_;
Eigen::VectorXd q_ref_;
pinocchio::SE3 H_ee_ref_, H_mobile_ref_;
//hqp
std::shared_ptr<kimmhqp::robot::RobotWrapper> robot_;
pinocchio::Model model_;
pinocchio::Data data_;
std::shared_ptr<kimmhqp::InverseDynamicsFormulationAccForce> tsid_;
std::shared_ptr<kimmhqp::tasks::TaskJointPosture> postureTask_;
std::shared_ptr<kimmhqp::tasks::TaskSE3Equality> eeTask_;
std::shared_ptr<kimmhqp::tasks::TaskJointBounds> torqueBoundsTask_;
std::shared_ptr<kimmhqp::tasks::TaskMobileEquality> mobileTask_, mobileTask2_;
std::shared_ptr<kimmhqp::trajectory::TrajectoryEuclidianCubic> trajPosture_Cubic_;
std::shared_ptr<kimmhqp::trajectory::TrajectoryEuclidianConstant> trajPosture_Constant_;
std::shared_ptr<kimmhqp::trajectory::TrajectoryEuclidianTimeopt> trajPosture_Timeopt_;
std::shared_ptr<kimmhqp::trajectory::TrajectorySE3Cubic> trajEE_Cubic_, trajMobile_Cubic_;
std::shared_ptr<kimmhqp::trajectory::TrajectorySE3Constant> trajEE_Constant_, trajMobile_Constant_;
std::shared_ptr<kimmhqp::trajectory::TrajectorySE3Timeopt> trajEE_Timeopt_, trajMobile_Timeopt_;
kimmhqp::trajectory::TrajectorySample sampleMobile_, sampleEE_, samplePosture_;
kimmhqp::solver::SolverHQPBase * solver_;
int na_, nq_, nv_;
//service
kimm_path_planner_ros_interface::action_mobile_path action_mobile_srv_;
kimm_joint_planner_ros_interface::action_joint_path action_joint_srv_;
kimm_se3_planner_ros_interface::action_se3_path action_se3_srv_;
ros::ServiceClient joint_action_client_, se3_action_client_, mobile_action_client_;
//ros
ros::NodeHandle n_node_;
};
} // namespace
| 38.621429 | 120 | 0.692806 | [
"model",
"transform"
] |
765fa7b727f3dd1e068c0a90412230b876cc6525 | 29,889 | c | C | models/gnc/src/Ins_c.c | cihuang123/Next-simulation | e8552a5804184b30022d103d47c8728fb242b5bc | [
"BSD-3-Clause"
] | null | null | null | models/gnc/src/Ins_c.c | cihuang123/Next-simulation | e8552a5804184b30022d103d47c8728fb242b5bc | [
"BSD-3-Clause"
] | null | null | null | models/gnc/src/Ins_c.c | cihuang123/Next-simulation | e8552a5804184b30022d103d47c8728fb242b5bc | [
"BSD-3-Clause"
] | 2 | 2021-05-05T14:59:37.000Z | 2021-06-17T03:19:45.000Z | #include "Ins_c.h"
/********************************************************************
*
* Earth gravity field JGM3
* Gravitational coefficients C, S are efficiently stored in a single
* array CS. The lower triangle matrix CS holds the non-sectorial C
* coefficients C_n,m (n!=m). Sectorial C coefficients C_n,n are the
* diagonal elements of CS and the upper triangular matrix stores
* the S_n,m (m!=0) coefficients in columns, for the same degree n.
* Mapping of CS to C, S is achieved through
* C_n,m = CS(n,m), S_n,m = CS(m-1,n)
*
*********************************************************************/
#define N_JGM3 20
#define Max_DM_UT1_UT_Index 954
extern const double DM_UT1_UT[Max_DM_UT1_UT_Index];
static double INS_CS_JGM3[N_JGM3+1][N_JGM3+1] = {
{ 1.000000e+00, 0.000000e+00, 1.543100e-09, 2.680119e-07, -4.494599e-07,
-8.066346e-08, 2.116466e-08, 6.936989e-08, 4.019978e-08, 1.423657e-08,
-8.128915e-08, -1.646546e-08, -2.378448e-08, 2.172109e-08, 1.443750e-08,
4.154186e-09, 1.660440e-08, -1.427822e-08, -1.817656e-08, 7.160542e-11,
2.759192e-09 },
{ 0.000000e+00, 0.000000e+00, -9.038681e-07, -2.114024e-07, 1.481555e-07,
-5.232672e-08, -4.650395e-08, 9.282314e-09, 5.381316e-09, -2.228679e-09,
-3.057129e-09, -5.097360e-09, 1.416422e-09, -2.545587e-09, -1.089217e-10,
-1.045474e-09, 7.856272e-10, 2.522818e-10, 3.427413e-10, -1.008909e-10,
3.216826e-10 },
{-1.082627e-03, -2.414000e-10, 1.574536e-06, 1.972013e-07, -1.201129e-08,
-7.100877e-09, 1.843134e-10, -3.061150e-09, -8.723520e-10, -5.633921e-10,
-8.989333e-10, -6.863521e-10, 9.154575e-11, 3.005522e-10, 5.182512e-11,
3.265044e-11, -4.271981e-11, 1.297841e-11, -4.278803e-12, -1.190759e-12,
3.778260e-11 },
{ 2.532435e-06, 2.192799e-06, 3.090160e-07, 1.005589e-07, 6.525606e-09,
3.873005e-10, -1.784491e-09, -2.636182e-10, 9.117736e-11, 1.717309e-11,
-4.622483e-11, -2.677798e-11, 9.170517e-13, -2.960682e-12, -3.750977e-12,
1.116419e-12, 5.250141e-12, 2.159727e-12, 1.105860e-13, -3.556436e-13,
-1.178441e-12 },
{ 1.619331e-06, -5.087253e-07, 7.841223e-08, 5.921574e-08, -3.982396e-09,
-1.648204e-09, -4.329182e-10, 6.397253e-12, 1.612521e-11, -5.550919e-12,
-3.122269e-12, 1.982505e-12, 2.033249e-13, 1.214266e-12, -2.217440e-13,
8.637823e-14, -1.205563e-14, 2.923804e-14, 1.040715e-13, 9.006136e-14,
-1.823414e-14 },
{ 2.277161e-07, -5.371651e-08, 1.055905e-07, -1.492615e-08, -2.297912e-09,
4.304768e-10, -5.527712e-11, 1.053488e-11, 8.627743e-12, 2.940313e-12,
-5.515591e-13, 1.346234e-13, 9.335408e-14, -9.061871e-15, 2.365713e-15,
-2.505252e-14, -1.590014e-14, -9.295650e-15, -3.743268e-15, 3.176649e-15,
-5.637288e-17 },
{-5.396485e-07, -5.987798e-08, 6.012099e-09, 1.182266e-09, -3.264139e-10,
-2.155771e-10, 2.213693e-12, 4.475983e-13, 3.814766e-13, -1.846792e-13,
-2.650681e-15, -3.728037e-14, 7.899913e-15, -9.747983e-16, -3.193839e-16,
2.856094e-16, -2.590259e-16, -1.190467e-16, 8.666599e-17, -8.340023e-17,
-8.899420e-19 },
{ 3.513684e-07, 2.051487e-07, 3.284490e-08, 3.528541e-09, -5.851195e-10,
5.818486e-13, -2.490718e-11, 2.559078e-14, 1.535338e-13, -9.856184e-16,
-1.052843e-14, 1.170448e-15, 3.701523e-16, -1.095673e-16, -9.074974e-17,
7.742869e-17, 1.086771e-17, 4.812890e-18, 2.015619e-18, -5.594661e-18,
1.459810e-18 },
{ 2.025187e-07, 1.603459e-08, 6.576542e-09, -1.946358e-10, -3.189358e-10,
-4.615173e-12, -1.839364e-12, 3.429762e-13, -1.580332e-13, 7.441039e-15,
-7.011948e-16, 2.585245e-16, 6.136644e-17, 4.870630e-17, 1.489060e-17,
1.015964e-17, -5.700075e-18, -2.391386e-18, 1.794927e-18, 1.965726e-19,
-1.128428e-19 },
{ 1.193687e-07, 9.241927e-08, 1.566874e-09, -1.217275e-09, -7.018561e-12,
-1.669737e-12, 8.296725e-13, -2.251973e-13, 6.144394e-14, -3.676763e-15,
-9.892610e-17, -1.736649e-17, 9.242424e-18, -4.153238e-18, -6.937464e-20,
3.275583e-19, 1.309613e-19, 1.026767e-19, -1.437566e-20, -1.268576e-20,
-6.100911e-21 },
{ 2.480569e-07, 5.175579e-08, -5.562846e-09, -4.195999e-11, -4.967025e-11,
-3.074283e-12, -2.597232e-13, 6.909154e-15, 4.635314e-15, 2.330148e-15,
4.170802e-16, -1.407856e-17, -2.790078e-19, -6.376262e-20, -1.849098e-19,
3.595115e-20, -2.537013e-21, 4.480853e-21, 4.348241e-22, 1.197796e-21,
-1.138734e-21 },
{-2.405652e-07, 9.508428e-09, 9.542030e-10, -1.409608e-10, -1.685257e-11,
1.489441e-12, -5.754671e-15, 1.954262e-15, -2.924949e-16, -1.934320e-16,
-4.946396e-17, 9.351706e-18, -9.838299e-20, 1.643922e-19, -1.658377e-20,
2.905537e-21, 4.983891e-22, 6.393876e-22, -2.294907e-22, 6.437043e-23,
6.435154e-23 },
{ 1.819117e-07, -3.068001e-08, 6.380398e-10, 1.451918e-10, -2.123815e-11,
8.279902e-13, 7.883091e-15, -4.131557e-15, -5.708254e-16, 1.012728e-16,
-1.840173e-18, 4.978700e-19, -2.108949e-20, 2.503221e-20, 3.298844e-21,
-8.660491e-23, 6.651727e-24, 5.110031e-23, -3.635064e-23, -1.311958e-23,
1.534228e-24 },
{ 2.075677e-07, -2.885131e-08, 2.275183e-09, -6.676768e-11, -3.452537e-13,
1.074251e-12, -5.281862e-14, 3.421269e-16, -1.113494e-16, 2.658019e-17,
4.577888e-18, -5.902637e-19, -5.860603e-20, -2.239852e-20, -6.914977e-23,
-6.472496e-23, -2.741331e-23, 2.570941e-24, -1.074458e-24, -4.305386e-25,
-2.046569e-25 },
{-1.174174e-07, -9.997710e-09, -1.347496e-09, 9.391106e-11, 3.104170e-13,
3.932888e-13, -1.902110e-14, 2.787457e-15, -2.125248e-16, 1.679922e-17,
1.839624e-18, 7.273780e-20, 4.561174e-21, 2.347631e-21, -7.142240e-22,
-2.274403e-24, -2.929523e-24, 1.242605e-25, -1.447976e-25, -3.551992e-26,
-7.473051e-28 },
{ 1.762727e-08, 6.108862e-09, -7.164511e-10, 1.128627e-10, -6.013879e-12,
1.293499e-13, 2.220625e-14, 2.825477e-15, -1.112172e-16, 3.494173e-18,
2.258283e-19, -1.828153e-21, -6.049406e-21, -5.705023e-22, 1.404654e-23,
-9.295855e-24, 5.687404e-26, 1.057368e-26, 4.931703e-27, -1.480665e-27,
2.400400e-29 },
{-3.119431e-08, 1.356279e-08, -6.713707e-10, -6.451812e-11, 4.698674e-12,
-9.690791e-14, 6.610666e-15, -2.378057e-16, -4.460480e-17, -3.335458e-18,
-1.316568e-19, 1.643081e-20, 1.419788e-21, 9.260416e-23, -1.349210e-23,
-1.295522e-24, -5.943715e-25, -9.608698e-27, 3.816913e-28, -3.102988e-28,
-8.192994e-29 },
{ 1.071306e-07, -1.262144e-08, -4.767231e-10, 1.175560e-11, 6.946241e-13,
-9.316733e-14, -4.427290e-15, 4.858365e-16, 4.814810e-17, 2.752709e-19,
-2.449926e-20, -6.393665e-21, 8.842755e-22, 4.178428e-23, -3.177778e-24,
1.229862e-25, -8.535124e-26, -1.658684e-26, -1.524672e-28, -2.246909e-29,
-5.508346e-31 },
{ 4.421672e-08, 1.958333e-09, 3.236166e-10, -5.174199e-12, 4.022242e-12,
3.088082e-14, 3.197551e-15, 9.009281e-17, 2.534982e-17, -9.526323e-19,
1.741250e-20, -1.569624e-21, -4.195542e-22, -6.629972e-24, -6.574751e-25,
-2.898577e-25, 7.555273e-27, 3.046776e-28, 3.696154e-29, 1.845778e-30,
6.948820e-31 },
{-2.197334e-08, -3.156695e-09, 7.325272e-10, -1.192913e-11, 9.941288e-13,
3.991921e-14, -4.220405e-16, 7.091584e-17, 1.660451e-17, 9.233532e-20,
-5.971908e-20, 1.750987e-21, -2.066463e-23, -3.440194e-24, -1.487095e-25,
-4.491878e-26, -4.558801e-27, 5.960375e-28, 8.263952e-29, -9.155723e-31,
-1.237749e-31 },
{ 1.203146e-07, 3.688524e-09, 4.328972e-10, -6.303973e-12, 2.869669e-13,
-3.011115e-14, 1.539793e-15, -1.390222e-16, 1.766707e-18, 3.471731e-19,
-3.447438e-20, 8.760347e-22, -2.271884e-23, 5.960951e-24, 1.682025e-25,
-2.520877e-26, -8.774566e-28, 2.651434e-29, 8.352807e-30, -1.878413e-31,
4.054696e-32 }
};
int calculate_INS_derived_TEI(GPS_TIME gps, gsl_matrix *TEIC) {
UTC_TIME utc_caldate;
gsl_matrix *M_rotation, *M_nutation, *M_precession, *M_nut_n_pre;
double UTC, UT1, dUT1;
double t, t2, t3, thetaA, zetaA, zA;
double s_thetaA, c_thetaA, s_zetaA, c_zetaA, s_zA, c_zA;
double epsilonA = 0.0;
double temps_sideral = 0.0;
double delta_psi = 0.0;
double mjd;
int index;
M_rotation = gsl_matrix_calloc(3, 3);
M_nutation = gsl_matrix_calloc(3, 3);
M_precession = gsl_matrix_calloc(3, 3);
M_nut_n_pre = gsl_matrix_calloc(3, 3);
gsl_matrix_set_identity(M_nutation);
/*------------------------------------------------------------------ */
/* --------------- Interface to Global Variable ------------*/
/*------------------------------------------------------------------ */
/*------------------------------------------------------------- */
/*--------------- Calculate the UTC time -------------*/
/*------------------------------------------------------------- */
/* GPS time converted from GPS format to YYYY/MM/DD/MM/SS */
/* Correction for time difference btwn GPS & UTC is applied implicitly */
/***to prevent change origin gpstime data****/
GPS_TIME_2_UTC_TIME(gps, &utc_caldate);
UTC = utc_caldate.hour * 3600.0 + utc_caldate.min * 60.0 + utc_caldate.sec;
GPS_TIME_2_Modified_julian_date(gps, &mjd);
index = (int)(mjd - 55197.00); /* get dUT1 = Ut1 - UT from table*/
if ((index >= 0) && (index < Max_DM_UT1_UT_Index)) { /*MJD = 55197.00 (1-1-2010)~ 56150.00(8-11-2012) */
dUT1 = DM_UT1_UT[index];
} else {
dUT1 = -0.008853655954360; /* mean value during 19760519~20120811, FSW: dUT1 = 0.4; */
}
UT1 = UTC + dUT1;
/*----------------------------------------------------------- */
/*-------------- Precession Matrix ------------------- */
/*----------------------------------------------------------- */
double jd;
MJD_2_JD(mjd, &jd);
t = (jd - 2451545.0) / 36525.0; /* J2000.5 : Julian Day is 2451545, unit in day */
t2 = t * t;
t3 = t2 * t;
thetaA = 2004.3109 * t - 0.42665 * t2 - 0.041833 * t3; /* unit : arcsec */
zetaA = 2306.2181 * t + 0.30188 * t2 + 0.017998 * t3; /* unit : arcsec */
zA = 2306.2181 * t + 1.09468 * t2 + 0.018203 * t3; /* unit : arcsec */
s_thetaA = sin(thetaA * __DM_arcsec2r);
c_thetaA = cos(thetaA * __DM_arcsec2r);
s_zetaA = sin(zetaA * __DM_arcsec2r);
c_zetaA = cos(zetaA * __DM_arcsec2r);
s_zA = sin(zA * __DM_arcsec2r);
c_zA = cos(zA * __DM_arcsec2r);
gsl_matrix_set(M_precession, 0, 0, -s_zA * s_zetaA + c_zA * c_thetaA * c_zetaA);
gsl_matrix_set(M_precession, 0, 1, -s_zA * c_zetaA - c_zA * c_thetaA * s_zetaA);
gsl_matrix_set(M_precession, 0, 2, -c_zA * s_thetaA);
gsl_matrix_set(M_precession, 1, 0, c_zA * s_zetaA + s_zA * c_thetaA * c_zetaA);
gsl_matrix_set(M_precession, 1, 1, c_zA * c_zetaA - s_zA * c_thetaA * s_zetaA);
gsl_matrix_set(M_precession, 1, 2, -s_zA * s_thetaA);
gsl_matrix_set(M_precession, 2, 0, s_thetaA * c_zetaA);
gsl_matrix_set(M_precession, 2, 1, -s_zetaA * s_thetaA);
gsl_matrix_set(M_precession, 2, 2, c_thetaA);
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, M_nutation, M_precession, 0.0, M_nut_n_pre); //M_nut_n_pre = M_nutation * M_precession
/*----------------------------------------------------------- */
/*------------------- Rotation Matrix --------------------*/
/*----------------------------------------------------------- */
temps_sideral = UT1 + (24110.54841 + 8640184.812866 * t + 0.093104 * t2 - 0.0000062 * t3);
temps_sideral = temps_sideral * __DM_sec2r + delta_psi * cos(epsilonA) * __DM_arcsec2r; /* unit: radian */
gsl_matrix_set(M_rotation, 0, 0, cos(temps_sideral));
gsl_matrix_set(M_rotation, 0, 1, sin(temps_sideral));
gsl_matrix_set(M_rotation, 0, 2, 0.0);
gsl_matrix_set(M_rotation, 1, 0, -sin(temps_sideral));
gsl_matrix_set(M_rotation, 1, 1, cos(temps_sideral));
gsl_matrix_set(M_rotation, 1, 2, 0.0);
gsl_matrix_set(M_rotation, 2, 0, 0.0);
gsl_matrix_set(M_rotation, 2, 1, 0.0);
gsl_matrix_set(M_rotation, 2, 2, 1.0);
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, M_rotation, M_nut_n_pre, 0.0, TEIC);
gsl_matrix_free(M_rotation);
gsl_matrix_free(M_nutation);
gsl_matrix_free(M_precession);
gsl_matrix_free(M_nut_n_pre);
return 0;
}
int build_WEII(gsl_matrix *WEII) {
gsl_matrix_set(WEII, 0, 1, -__WEII3);
gsl_matrix_set(WEII, 1, 0, __WEII3);
return 0;
}
/*******************************************************************************
* AccelHarmonic
*
* Purpose:
*
* Computes the acceleration of a launch vehicle due to
* -The Earth's harmonic gravity field
*
* Input:
* r Launch Vehicle position vector in ECI coordinate
* E Transformation matrix from ECI to ECEF coordinate
* GM Gravitational coefficient
* R_ref Earth mean Radius
* CS Spherical harmonic coefficients (un-normalized)
* n_max Maxium degree
* m_max Maxium orger (m_max<=n_max; m_max=0 for zonals, only)
*
* Output:
* acc Gravitational acceleration
*
********************************************************************************/
int AccelHarmonic(const gsl_vector *SBII, double CS[21][21], int n_max, int m_max, const gsl_matrix *TEIC, gsl_vector *acc_out) {
int n, m; /* Loop counters */
double r_sqr, rho, Fac; /* Auxiliary quantities */
double x0, y0, z0; /* Normalized coordinates */
double ax, ay, az; /* Acceleration vector */
double C, S; /* Gravitational coefficients */
gsl_vector *r_bf, *a_bf;
r_bf = gsl_vector_calloc(3);
a_bf = gsl_vector_calloc(3);
double V[N_JGM3+2][N_JGM3+2] = {
{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}
}; /* Harmonic functions */
double W[N_JGM3+2][N_JGM3+2] = {
{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}
}; /* work array (0..n_max+1,0..n_max+1) */
/* Earth-fixed position */
gsl_blas_dgemv(CblasNoTrans, 1.0, TEIC, SBII, 0.0, r_bf); // r_bf = TEIC * SBII
gsl_blas_ddot(r_bf, r_bf, &r_sqr); /* Square of distance */
rho = __SMAJOR_AXIS * __SMAJOR_AXIS / r_sqr;
x0 = __SMAJOR_AXIS * gsl_vector_get(r_bf, 0) / r_sqr;
y0 = __SMAJOR_AXIS * gsl_vector_get(r_bf, 1) / r_sqr;
z0 = __SMAJOR_AXIS * gsl_vector_get(r_bf, 2) / r_sqr;
/*******************************
*
* Evaluate harmonic functions
* V_nm = (R_ref/r)^(n+1) * P_nm(sin(phi)) * cos(m*lambda)
* and
* W_nm = (R_ref/r)^(n+1) * P_nm(sin(phi)) * sin(m*lambda)
* up to degree and order n_max+1
*
********************************/
/* Calculate zonal terms V(n,0); set W(n,0)=0.0 */
V[0][0] = __SMAJOR_AXIS / sqrt(r_sqr);
W[0][0] = 0.0;
V[1][0] = z0 * V[0][0];
W[1][0] = 0.0;
for (n = 2; n <= n_max+1; n++) {
V[n][0] = ((2*n-1) * z0 * V[n-1][0] - (n-1) * rho * V[n-2][0]) / n;
W[n][0] = 0.0;
}
/* Calculate tesseral and sectorial terms */
for (m = 1; m <= m_max+1; m++) {
/* Calculate V(m,m) .. V(n_max+1,m) */
V[m][m] = (2*m-1) * (x0 * V[m-1][m-1] - y0 * W[m-1][m-1]);
W[m][m] = (2*m-1) * (x0 * W[m-1][m-1] + y0 * V[m-1][m-1]);
if (m <= n_max) {
V[m+1][m] = (2*m+1) * z0 * V[m][m];
W[m+1][m] = (2*m+1) * z0 * W[m][m];
}
for (n = m+2; n <= n_max+1; n++) {
V[n][m] = ((2*n-1) * z0 * V[n-1][m] - (n+m-1) * rho * V[n-2][m]) / (n-m);
W[n][m] = ((2*n-1) * z0 * W[n-1][m] - (n+m-1) * rho * W[n-2][m]) / (n-m);
}
}
/* Calculate accelerations ax,ay,az */
ax = ay = az = 0.0;
for (m = 0; m <= m_max; m++) {
for (n = m; n <= n_max ; n++) {
if (m == 0) {
C = CS[n][0]; /* = C_n,0 */
ax -= C * V[n+1][1];
ay -= C * W[n+1][1];
az -= (n+1)*C * V[n+1][0];
} else {
C = CS[n][m]; /* = C_n,m */
S = CS[m-1][n]; /* = S_n,m */
Fac = 0.5 * (n-m+1) * (n-m+2);
ax += + 0.5 * (- C * V[n+1][m+1] - S * W[n+1][m+1])
+ Fac * (+ C * V[n+1][m-1] + S * W[n+1][m-1]);
ay += + 0.5 * (- C * W[n+1][m+1] + S * V[n+1][m+1])
+ Fac * (- C * W[n+1][m-1] + S * V[n+1][m-1]);
az += (n-m+1) * (- C * V[n+1][m] - S * W[n+1][m]);
}
}
}
/* Body-fixed acceleration */
gsl_vector_set(a_bf, 0, (__GM / (__SMAJOR_AXIS * __SMAJOR_AXIS)) * ax);
gsl_vector_set(a_bf, 1, (__GM / (__SMAJOR_AXIS * __SMAJOR_AXIS)) * ay);
gsl_vector_set(a_bf, 2, (__GM / (__SMAJOR_AXIS * __SMAJOR_AXIS)) * az);
/* Inertial acceleration */
gsl_blas_dgemv(CblasTrans, 1.0, TEIC, a_bf, 0.0, acc_out); // acc_out = trans(TEIC) * a_bf
gsl_vector_free(r_bf);
gsl_vector_free(a_bf);
return 0;
}
int DCM_2_Euler_angle(const gsl_matrix *TBD, double *phibdc, double *thtbdc, double *psibdc) {
double cthtbd;
// double mroll = 0.0;
double tbd13 = gsl_matrix_get(TBD, 0, 2);
double tbd11 = gsl_matrix_get(TBD, 0, 0);
double tbd33 = gsl_matrix_get(TBD, 2, 2);
double tbd12 = gsl_matrix_get(TBD, 0, 1);
double tbd23 = gsl_matrix_get(TBD, 1, 2);
// *geodetic Euler angles
// computed pitch angle: 'thtbdc'
// note: when |tbd13| >= 1, thtbdc = +- pi/2, but cos(thtbdc) is
// forced to be a small positive number to prevent division by zero
if (fabs(tbd13) < 1) {
*thtbdc = asin(-tbd13);
cthtbd = cos(*thtbdc);
} else {
*thtbdc = ___PI / 2 * sign(-tbd13);
cthtbd = __EPS;
}
// computed yaw angle: 'psibdc'
double cpsi = tbd11 / cthtbd;
if (fabs(cpsi) > 1) {
cpsi = 1 * sign(cpsi);
}
*psibdc = acos(cpsi) * sign(tbd12);
// computed roll angle: 'phibdc'
double cphi = tbd33 / cthtbd;
if (fabs(cphi) > 1) {
cphi = 1 * sign(cphi);
}
*phibdc = acos(cphi) * sign(tbd23);
return 0;
}
int calculate_INS_derived_phip(gsl_vector *VBECB, double *phipc) {
// double VBECB0 = gsl_vector_get(VBECB, 0);
double VBECB1 = gsl_vector_get(VBECB, 1);
double VBECB2 = gsl_vector_get(VBECB, 2);
if (VBECB1 == 0.0 && VBECB2 == 0.0) {
*phipc = 0.0;
} else if (fabs(VBECB1) < __EPS) {
// note: if vbeb2 is <EPS the value if phipc is forced to be 0 or PI
// to prevent oscillations
if (VBECB2 > 0.0) *phipc = 0.0;
if (VBECB2 < 0.0) *phipc = ___PI;
} else {
*phipc = atan2(VBECB1, VBECB2);
}
return 0;
}
int calculate_INS_derived_thtvd(gsl_vector *VBECD, double *thtvd) {
double VBECD0 = gsl_vector_get(VBECD, 0);
double VBECD1 = gsl_vector_get(VBECD, 1);
double VBECD2 = gsl_vector_get(VBECD, 2);
if (VBECD0 == 0.0 && VBECD1 == 0.0) {
*thtvd = 0.0;
} else {
*thtvd = atan2(-VBECD2, sqrt(VBECD0 * VBECD0 + VBECD1 * VBECD1));
}
return 0;
}
int calculate_INS_derived_psivd(gsl_vector *VBECD, double *psivd) {
double VBECD0 = gsl_vector_get(VBECD, 0);
double VBECD1 = gsl_vector_get(VBECD, 1);
if (VBECD0 == 0.0 && VBECD1 == 0.0) {
*psivd = 0.0;
} else {
*psivd = atan2(VBECD1, VBECD0);
}
return 0;
}
int calculate_INS_derived_alpp(gsl_vector *VBECB, double *alpp) {
double dum = gsl_vector_get(VBECB, 0) / gsl_blas_dnrm2(VBECB);
if (fabs(dum) > 1.0) {
dum = 1.0 * sign(dum);
}
*alpp = acos(dum);
return 0;
}
int calculate_INS_derived_beta(gsl_vector *VBECB, double *beta) {
*beta = asin(gsl_vector_get(VBECB, 1) / gsl_blas_dnrm2(VBECB));
return 0;
}
int calculate_INS_derived_alpha(gsl_vector *VBECB, double *alpha) {
*alpha = atan2(gsl_vector_get(VBECB, 2), gsl_vector_get(VBECB, 0));
return 0;
}
int build_VBEB(double _alpha0x, double _beta0x, double _dvbe, gsl_vector *VBEB) {
double salp = sin(_alpha0x * __RAD);
double calp = cos(_alpha0x * __RAD);
double sbet = sin(_beta0x * __RAD);
double cbet = cos(_beta0x * __RAD);
// double vbeb3 = salp * cbet * _dvbe;
gsl_vector_set(VBEB, 0, calp * cbet * _dvbe);
gsl_vector_set(VBEB, 1, sbet * _dvbe);
gsl_vector_set(VBEB, 2, salp * cbet * _dvbe);
return 0;
}
int INS_update(const double int_step, double *dvbec, unsigned int liftoff, double *alphacx, double *betacx
, double *alppcx, double *phipcx, double *loncx, double *latcx, double *altc, double *psivdcx, double *thtvdcx
, double *phibdcx, double *thtbdcx, double *psibdcx
, gsl_vector *PHI, gsl_vector *DELTA_VEL
, gsl_vector *PHI_HIGH, gsl_vector *PHI_LOW, GPS_TIME gps, gsl_matrix *TEIC
, gsl_vector *SBIIC, gsl_vector *VBIIC, gsl_vector *VBIIC_old, gsl_vector *GRAVGI, gsl_matrix *TBIC, gsl_vector *SBEEC
, gsl_vector *VBEEC, gsl_matrix *WEII, gsl_matrix *TLI, gsl_matrix *TDCI
, gsl_matrix *TBICI, gsl_matrix *TBDC, gsl_vector *TBDCQ) {
gsl_vector *VBIIC_tmp1, *VBIIC_tmp2, *VBEEC_tmp1, *VBEEC_tmp2, *VBECB, *VBECB_tmp, *VBECD, *VBECD_tmp;
gsl_matrix *TBIC_tmp1, *TBIC_tmp2;
VBIIC_tmp1 = gsl_vector_calloc(3);
VBIIC_tmp2 = gsl_vector_calloc(3);
VBEEC_tmp1 = gsl_vector_calloc(3);
VBEEC_tmp2 = gsl_vector_calloc(3);
VBECB = gsl_vector_calloc(3);
VBECB_tmp = gsl_vector_calloc(3);
VBECD = gsl_vector_calloc(3);
VBECD_tmp = gsl_vector_calloc(3);
TBIC_tmp1 = gsl_matrix_calloc(3, 3);
TBIC_tmp2 = gsl_matrix_calloc(3, 3);
calculate_INS_derived_TEI(gps, TEIC);
AccelHarmonic(SBIIC, INS_CS_JGM3, 20, 20, TEIC, GRAVGI);
gsl_vector_memcpy(VBIIC_tmp2, GRAVGI);
/* TBIC = build_321_rotation_matrix(PHI) * TBIC */
build_321_rotation_matrix(PHI, TBIC_tmp1);
gsl_matrix_memcpy(TBIC_tmp2, TBIC);
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, TBIC_tmp1, TBIC_tmp2, 0.0, TBIC);
/* VBIIC += trans(TBIC) * DELTA_VEL + GRAVGI * int_step */
gsl_blas_dgemv(CblasTrans, 1.0, TBIC, DELTA_VEL, 0.0, VBIIC_tmp1);
gsl_blas_dscal(int_step, VBIIC_tmp2);
gsl_vector_add(VBIIC, VBIIC_tmp1);
gsl_vector_add(VBIIC, VBIIC_tmp2);
/* SBIIC += VBIIC_old * int_step */
gsl_blas_dscal(int_step, VBIIC_old);
gsl_vector_add(SBIIC, VBIIC_old);
gsl_vector_memcpy(VBIIC_old, VBIIC); // VBIIC_old = VBIIC
/* SBEEC = TEIC * SBIIC */
gsl_blas_dgemv(CblasNoTrans, 1.0, TEIC, SBIIC, 0.0, SBEEC);
/* VBEEC = TEIC * VBIIC - WEII * SBEEC */
gsl_blas_dgemv(CblasNoTrans, 1.0, TEIC, VBIIC, 0.0, VBEEC_tmp1);
gsl_blas_dgemv(CblasNoTrans, 1.0, WEII, SBEEC, 0.0, VBEEC_tmp2);
for (int i = 0; i < 3; i++) gsl_vector_set(VBEEC, i, gsl_vector_get(VBEEC_tmp1, i) - gsl_vector_get(VBEEC_tmp2, i));
gsl_blas_dgemv(CblasTrans, 1.0, TEIC, VBEEC, 0.0, VBECB_tmp);
gsl_blas_dgemv(CblasNoTrans, 1.0, TBIC, VBECB_tmp, 0.0, VBECB);
*dvbec = gsl_blas_dnrm2(VBECB);
if (liftoff == 1) {
// computing indidence angles from INS
calculate_INS_derived_alpha(VBECB, alphacx);
*alphacx *= __DEG;
calculate_INS_derived_beta(VBECB, betacx);
*betacx *= __DEG;
calculate_INS_derived_alpp(VBECB, alppcx);
*alppcx *= __DEG;
calculate_INS_derived_phip(VBECB, phipcx);
*phipcx *= __DEG;
}
cad_geo84_in(SBIIC, TEIC, loncx, latcx, altc);
*loncx *= __DEG;
*latcx *= __DEG;
// getting T.M. of geodetic wrt inertial coord
cad_tdi84(*loncx * __RAD, *latcx * __RAD, *altc, TEIC, TDCI);
// getting Launch site T.M. of inertial coord
if (liftoff == 0) gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, TLI, TDCI, 0.0, TBICI); // TBICI = TLI * TDCI
// computing geodetic velocity from INS
gsl_blas_dgemv(CblasNoTrans, 1.0, TEIC, VBEEC, 0.0, VBECD_tmp);
gsl_blas_dgemv(CblasTrans, 1.0, TDCI, VBECD_tmp, 0.0, VBECD);
// computing flight path angles
calculate_INS_derived_psivd(VBECD, psivdcx);
*psivdcx *= __DEG;
calculate_INS_derived_thtvd(VBECD, thtvdcx);
*thtvdcx *= __DEG;
// computing Euler angles from INS
gsl_blas_dgemm(CblasNoTrans, CblasTrans, 1.0, TBIC, TDCI, 0.0, TBDC);
Matrix2Quaternion_C(TBDC, TBDCQ);
DCM_2_Euler_angle(TBDC, phibdcx, thtbdcx, psibdcx);
*phibdcx *= __DEG;
*thtbdcx *= __DEG;
*psibdcx *= __DEG;
gsl_vector_free(VBIIC_tmp1);
gsl_vector_free(VBIIC_tmp2);
gsl_vector_free(VBEEC_tmp1);
gsl_vector_free(VBEEC_tmp2);
gsl_vector_free(VBECB);
gsl_vector_free(VBECB_tmp);
gsl_vector_free(VBECD);
gsl_vector_free(VBECD_tmp);
gsl_matrix_free(TBIC_tmp1);
gsl_matrix_free(TBIC_tmp2);
return 0;
}
int load_location(double lonx, double latx, double alt) {
loncx = lonx;
latcx = latx;
altc = alt;
return 0;
}
int load_angle(double yaw, double roll, double pitch, GPS_TIME gps_time) {
phibdcx = roll;
thtbdcx = pitch;
psibdcx = yaw;
calculate_INS_derived_TEI(gps_time, TEIC);
build_psi_tht_phi_TM_C(psibdcx * __RAD, thtbdcx * __RAD, phibdcx * __RAD, TBDC);
build_psi_tht_phi_TM_C(psibdcx * __RAD, thtbdcx * __RAD, phibdcx * __RAD, TLI);
cad_tdi84(loncx * __RAD, latcx * __RAD, altc, TEIC, TDCI);
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, TBDC, TDCI, 0.0, TBIC);
Matrix2Quaternion_C(TBIC, TBIC_Q);
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, TLI, TDCI, 0.0, TBICI);
return 0;
}
int load_geodetic_velocity(double alpha0x, double beta0x, double dvbe) {
gsl_vector *VBEB, *VBIIC_tmp1, *VBIIC_tmp2, *VBIIC_tmp3, *VBIIC_tmp4;
VBEB = gsl_vector_calloc(3);
VBIIC_tmp1 = gsl_vector_calloc(3);
VBIIC_tmp2 = gsl_vector_calloc(3);
VBIIC_tmp3 = gsl_vector_calloc(3);
VBIIC_tmp4 = gsl_vector_calloc(3);
build_VBEB(alpha0x, beta0x, dvbe, VBEB);
gsl_blas_dgemv(CblasTrans, 1.0, TBDC, VBEB, 0.0, VBECD);
cad_in_geo84(loncx * __RAD, latcx * __RAD, altc, TEIC, SBIIC);
/** VBIIC calculate **/
VBIIC = gsl_vector_calloc(3);
gsl_blas_dgemv(CblasNoTrans, 1.0, TEIC, SBIIC, 0.0, VBIIC_tmp4);
gsl_blas_dgemv(CblasNoTrans, 1.0, WEII, VBIIC_tmp4, 0.0, VBIIC_tmp3);
gsl_blas_dgemv(CblasTrans, 1.0, TEIC, VBIIC_tmp3, 0.0, VBIIC_tmp2);
gsl_blas_dgemv(CblasTrans, 1.0, TDCI, VBECD, 0.0, VBIIC_tmp1);
gsl_vector_add(VBIIC, VBIIC_tmp1);
gsl_vector_add(VBIIC, VBIIC_tmp2);
gsl_vector_memcpy(VBIIC_old, VBIIC);
return 0;
}
int INS_init(GPS_TIME gps_time) {
INS_alloc();
build_WEII(WEII);
calculate_INS_derived_TEI(gps_time, TEIC);
cad_in_geo84(loncx * __RAD, latcx * __RAD, altc, TEIC, SBIIC);
AccelHarmonic(SBIIC, INS_CS_JGM3, 20, 20, TEIC, GRAVGI);
gsl_blas_dgemv(CblasNoTrans, 1.0, TEIC, SBIIC, 0.0, SBEEC);
gsl_vector *VBEEC_tmp1;
VBEEC_tmp1 = gsl_vector_calloc(3);
gsl_vector_set_zero(VBEEC);
gsl_blas_dgemv(CblasNoTrans, 1.0, TEIC, VBIIC, 0.0, VBEEC);
gsl_blas_dgemv(CblasNoTrans, 1.0, WEII, SBEEC, 0.0, VBEEC_tmp1);
gsl_vector_sub(VBEEC, VBEEC_tmp1);
return 0;
}
int INS_alloc() {
/** Matrix **/
WEII = gsl_matrix_calloc(3, 3);
TBIC = gsl_matrix_calloc(3, 3);
TDCI = gsl_matrix_calloc(3, 3);
TEIC = gsl_matrix_calloc(3, 3);
TBDC = gsl_matrix_calloc(3, 3);
TBICI = gsl_matrix_calloc(3, 3);
TLI = gsl_matrix_calloc(3, 3);
/** Vector **/
EVBI = gsl_vector_calloc(3);
EVBID = gsl_vector_calloc(3);
ESBI = gsl_vector_calloc(3);
ESBID = gsl_vector_calloc(3);
RICI = gsl_vector_calloc(3);
RICID = gsl_vector_calloc(3);
TBIC_Q = gsl_vector_calloc(4);
TBIDC_Q = gsl_vector_calloc(4);
SBIIC = gsl_vector_calloc(3);
VBIIC = gsl_vector_calloc(3);
SBEEC = gsl_vector_calloc(3);
VBEEC = gsl_vector_calloc(3);
WBICI = gsl_vector_calloc(3);
EGRAVI = gsl_vector_calloc(3);
VBECD = gsl_vector_calloc(3);
INS_I_ATT_ERR = gsl_vector_calloc(3);
TESTV = gsl_vector_calloc(3);
TMP_old = gsl_vector_calloc(3);
VBIIC_old = gsl_vector_calloc(3);
POS_ERR = gsl_vector_calloc(3);
GRAVGI = gsl_vector_calloc(3);
TBDCQ = gsl_vector_calloc(4);
VBIIC_old_old = gsl_vector_calloc(3);
PHI_C = gsl_vector_calloc(3);
DELTA_VEL_C = gsl_vector_calloc(3);
PHI_LOW_C = gsl_vector_calloc(3);
PHI_HIGH_C = gsl_vector_calloc(3);
return 0;
}
| 41.744413 | 139 | 0.569273 | [
"vector"
] |
766d77ce3ef0776aaae53f32e434cdc87422a709 | 59,018 | h | C | UI-Qt/QXNames.h | frinkr/FontViewer | 69b5706e557ecd33515c5c8d6ba8fc1d6f06e0c0 | [
"MIT"
] | 2 | 2019-05-08T06:31:34.000Z | 2020-08-30T00:35:09.000Z | UI-Qt/QXNames.h | frinkr/FontViewer | 69b5706e557ecd33515c5c8d6ba8fc1d6f06e0c0 | [
"MIT"
] | 1 | 2018-05-07T09:29:02.000Z | 2018-05-07T09:29:02.000Z | UI-Qt/QXNames.h | frinkr/FontViewer | 69b5706e557ecd33515c5c8d6ba8fc1d6f06e0c0 | [
"MIT"
] | 2 | 2018-09-10T07:16:28.000Z | 2022-01-07T06:41:01.000Z | #pragma once
#include <map>
#include <vector>
#include "FontX/FXTag.h"
#include "FontX/FXHelper.h"
class QXNames {
public:
static std::vector<std::string> HeadGetFlagDescription(uint16_t flag) {
static const std::map<size_t, const char *> map = {
{0, "Baseline at Y = 0"},
{1, "Left sidebearing at X = 0"},
{2, "Instructions depends on point size"},
{3, "Force ppem to integer values"},
{4, "Instructions may alter advance width"},
{11, "Font data is ‘lossless’ compressed"},
{12, "Font converted"},
{13, "Font optimized for ClearType"},
{14, "Last Resort font"},
};
std::vector<std::string> descs;
for (auto kv: map)
descs.push_back(std::string(kv.second) + ": " + ((flag & (1 << kv.first))? "YES": "NO"));
return descs;
}
static std::vector<std::string> HeadGetMacStyleDescription(uint16_t flag) {
static const char * names[] = {"Bold", "Italic", "Underline", "Outline", "Shadow", "Condensed", "Extended"};
std::vector<std::string> descs;
for (size_t i = 0; i < sizeof(names)/sizeof(names[0]); ++ i) {
if (flag & (1 << i))
descs.push_back(names[i]);
}
return descs;
}
static const char * OS2GetWeightClassName(uint16_t value) {
switch (value) {
case 100: return "Thin";
case 200: return "Extra-light (Ultra-light)";
case 300: return "Light";
case 400: return "Normal (Regular)";
case 500: return "Medium";
case 600: return "Semi-bold (Demi-bold)";
case 700: return "Bold";
case 800: return "Extra-bold (Ultra-bold)";
case 900: return "Black (Heavy)";
default: return "Unknown";
}
}
static const char * OS2GetWidthClassName(uint16_t value) {
switch (value) {
case 1: return "Ultra-condensed";
case 2: return "Extra-condensed";
case 3: return "Condensed";
case 4: return "Semi-condensed";
case 5: return "Medium (normal)";
case 6: return "Semi-expanded";
case 7: return "Expanded";
case 8: return "Extra-expanded";
case 9: return "Ultra-expanded";
default: return "Unknown";
}
}
static std::vector<std::string> OS2GetFsTypeDescription(uint16_t value) {
if (!value)
return {"Installable Embedding"};
std::vector<std::string> names;
if (value & (1 << 1)) names.push_back("Restricted License Embedding");
if (value & (1 << 2)) names.push_back("Preview & Print Embedding");
if (value & (1 << 3)) names.push_back("Editable Embedding");
if (value & (1 << 8)) names.push_back("No Subsetting");
if (value & (1 << 9)) names.push_back("Bitmap Embedding Only");
return names;
}
static const char * OS2GetFamilyClassName(uint16_t value) {
unsigned short family = ((value & 0xFF00) >> 8);
const char * names [] = {"No classification",
"OldStyle Serifs",
"Transitional Serifs",
"Modern Serifs",
"Clarendon Serifs",
"Slab Serifs",
"Reserved",
"Freeform Serifs",
"Sans Serif",
"Ornamentals",
"Scripts",
"reserved",
"Symbolic",
"reserved",
"reserved",
};
if (family < sizeof(names)/sizeof(names[0]))
return names[family];
return "Unknown Family Class";
}
static const char * OS2GetSubFamilyClassName(uint16_t value) {
uint16_t family = ((value & 0xFF00) >> 8);
uint16_t subFamily = (value & 0xFF);
std::vector<const char *> subFamilyNames;
switch (family) {
case 1: subFamilyNames = {"No classification",
"IBM Rounded Legibility",
"Garalde",
"Venetian",
"Modified Venetian",
"Dutch Modern",
"Dutch Traditional",
"Contemporary",
"Calligraphic",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
"Miscellaneous"};
break;
case 2: subFamilyNames = {"No Classification",
"Direct Line",
"Script",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
"Miscellaneous"};
break;
case 3: subFamilyNames = {"No Classification",
"Italian",
"Script",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
"Miscellaneous"};
break;
case 4: subFamilyNames = {"No Classification",
"Clarendon",
"Modern",
"Traditional",
"Newspaper",
"Stub Serif",
"Monotone",
"Typewriter",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
"Miscellaneous"};
break;
case 5: subFamilyNames = {"No classification",
"Monotone",
"Humanist",
"Geometric",
"Swiss",
"Typewriter",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
"Miscellaneous"};
break;
case 7: subFamilyNames = {"No classification",
"Modern",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
"Miscellaneous"};
break;
case 8: subFamilyNames = {"No classification",
"IBM Neo-grotesque Gothic",
"Humanist",
"Low-x Round Geometric",
"High-x Round Geometric",
"Neo-grotesque Gothic",
"Modified neo-grotesque Gothic",
"Reserved",
"Reserved",
"Typewriter Gothic",
"Matrix",
"Reserved",
"Reserved",
"Reserved",
"Reserved",
"Miscellaneous"};
break;
case 9: subFamilyNames = {"No classification",
"Engraver",
"Black Letter",
"Decorative",
"Three Dimensional",
"Reserved",
"Reserved",
"Reserved",
"Reserved",
"Reserved",
"Reserved",
"Reserved",
"Reserved",
"Reserved",
"Reserved",
"Miscellaneous"};
break;
case 10: subFamilyNames = {"No classification",
"Uncial",
"Brush Joined",
"Formal Joined",
"Monotone Joined",
"Calligraphic",
"Brush Unjoined",
"Formal Unjoined",
"Monotone Unjoined",
"Reserved",
"Reserved",
"Reserved",
"Reserved",
"Reserved",
"Reserved",
"Miscellaneous"};
break;
case 12: subFamilyNames = {"No classification",
"Reserved",
"Reserved",
"Mixed Serif",
"Reserved",
"Reserved",
"Oldstyle Serif",
"Neo-grotesque Sans Serif",
"Reserved",
"Reserved",
"Reserved",
"Reserved",
"Reserved",
"Reserved",
"Reserved",
"Miscellaneous"};
break;
default:
break;
}
if (subFamily < subFamilyNames.size())
return subFamilyNames[subFamily];
return "Unknown SubFamily Class";
}
static std::string OS2GetFamilyClassFullName(uint16_t value) {
return OS2GetFamilyClassName(value) + std::string(OS2GetSubFamilyClassName(value));
}
static auto OS2GetUnicodeRanges(uint32_t range1, uint32_t range2, uint32_t range3, uint32_t range4) {
std::vector<std::vector<const char *> > allBlockNames
= {{"Basic Latin"},
{"Latin-1 Supplement"},
{"Latin Extended-A"},
{"Latin Extended-B"},
{"IPA Extensions", "Phonetic Extensions", "Phonetic Extensions Supplement"},
{"Spacing Modifier Letters", "Modifier Tone Letters"},
{"Combining Diacritical Marks", "Combining Diacritical Marks Supplement"},
{"Greek and Coptic"},
{"Coptic"},
{"Cyrillic", "Cyrillic Supplement", "Cyrillic Extended-A", "Cyrillic Extended-B"},
{"Armenian"},
{"Hebrew"},
{"Vai"},
{"Arabic", "Arabic Supplement"},
{"NKo"},
{"Devanagari"},
{"Bengali"},
{"Gurmukhi"},
{"Gujarati"},
{"Oriya"},
{"Tamil"},
{"Telugu"},
{"Kannada"},
{"Malayalam"},
{"Thai"},
{"Lao"},
{"Georgian", "Georgian Supplement"},
{"Balinese"},
{"Hangul Jamo"},
{"Latin Extended Additional", "Latin Extended-C", "Latin Extended-D"},
{"Greek Extended"},
{"General Punctuation", "Supplemental Punctuation"},
{"Superscripts And Subscripts"},
{"Currency Symbols"},
{"Combining Diacritical Marks For Symbols"},
{"Letterlike Symbols"},
{"Number Forms"},
{"Arrows", "Supplemental Arrows-A", "Supplemental Arrows-B", "Miscellaneous Symbols and Arrows"},
{"Mathematical Operators", "Supplemental Mathematical Operators", "Miscellaneous Mathematical Symbols-A", "Miscellaneous Mathematical Symbols-B"},
{"Miscellaneous Technical"},
{"Control Pictures"},
{"Optical Character Recognition"},
{"Enclosed Alphanumerics"},
{"Box Drawing"},
{"Block Elements"},
{"Geometric Shapes"},
{"Miscellaneous Symbols"},
{"Dingbats"},
{"CJK Symbols And Punctuation"},
{"Hiragana"},
{"Katakana", "Katakana Phonetic Extensions"},
{"Bopomofo", "Bopomofo Extended"},
{"Hangul Compatibility Jamo"},
{"Phags-pa"},
{"Enclosed CJK Letters And Months"},
{"CJK Compatibility"},
{"Hangul Syllables"},
{"High Surrogates", "High Private Use Surrogates", "Low Surrogates"},
{"Phoenician"},
{"CJK Unified Ideographs", "CJK Radicals Supplement", "Kangxi Radicals", "Ideographic Description Characters", "CJK Unified Ideographs Extension A", "CJK Unified Ideographs Extension B", "Kanbun"},
{"Private Use Area"},
{"CJK Strokes", "CJK Compatibility Ideographs", "CJK Compatibility Ideographs Supplement"},
{"Alphabetic Presentation Forms"},
{"Arabic Presentation Forms-A"},
{"Combining Half Marks"},
{"Vertical Forms", "CJK Compatibility Forms"},
{"Small Form Variants"},
{"Arabic Presentation Forms-B"},
{"Halfwidth And Fullwidth Forms"},
{"Specials"},
{"Tibetan"},
{"Syriac"},
{"Thaana"},
{"Sinhala"},
{"Myanmar"},
{"Ethiopic", "Ethiopic Supplement", "Ethiopic Extended"},
{"Cherokee"},
{"Unified Canadian Aboriginal Syllabics"},
{"Ogham"},
{"Runic"},
{"Khmer", "Khmer Symbols"},
{"Mongolian"},
{"Braille Patterns"},
{"Yi Syllables", "Yi Radicals"},
{"Tagalog", "Hanunoo", "Buhid", "Tagbanwa"},
{"Old Italic"},
{"Gothic"},
{"Deseret"},
{"Byzantine Musical Symbols", "Musical Symbols", "Ancient Greek Musical Notation"},
{"Mathematical Alphanumeric Symbols"},
{"Supplementary Private Use Area-A", "Supplementary Private Use Area-B"},
{"Variation Selectors", "Variation Selectors Supplement"},
{"Tags"},
{"Limbu"},
{"Tai Le"},
{"New Tai Lue"},
{"Buginese"},
{"Glagolitic"},
{"Tifinagh"},
{"Yijing Hexagram Symbols"},
{"Syloti Nagri"},
{"Linear B Syllabary", "Linear B Ideograms", "Aegean Numbers"},
{"Ancient Greek Numbers"},
{"Ugaritic"},
{"Old Persian"},
{"Shavian"},
{"Osmanya"},
{"Cypriot Syllabary"},
{"Kharoshthi"},
{"Tai Xuan Jing Symbols"},
{"Cuneiform", "Cuneiform Numbers and Punctuation"},
{"Counting Rod Numerals"},
{"Sundanese"},
{"Lepcha"},
{"Ol Chiki"},
{"Saurashtra"},
{"Kayah Li"},
{"Rejang"},
{"Cham"},
{"Ancient Symbols"},
{"Phaistos Disc"},
{"Carian", "Lycian", "Lydian"},
{"Domino Tiles", "Mahjong Tiles"},
};
std::vector<std::string> blockNames;
uint32_t range[] = {range1, range2, range3, range4};
for (size_t i = 0; i < allBlockNames.size(); ++ i) {
unsigned char k = i % 32;
unsigned char f = i / 32;
if (range[f] & (1 << k)) {
auto & names = allBlockNames[i];
blockNames.insert(blockNames.end(), names.begin(), names.end());
}
}
return blockNames;
}
static auto OS2GetFsSelectionDescription(uint16_t value) {
std::vector<std::string> names;
if (value & (1 << 0)) names.push_back("Italic");
if (value & (1 << 1)) names.push_back("Underscore");
if (value & (1 << 2)) names.push_back("Negative");
if (value & (1 << 3)) names.push_back("Outlined");
if (value & (1 << 4)) names.push_back("Strikeout");
if (value & (1 << 5)) names.push_back("Bold");
if (value & (1 << 6)) names.push_back("Regular");
if (value & (1 << 7)) names.push_back("Use Typo Metrics");
if (value & (1 << 8)) names.push_back("WWS");
if (value & (1 << 9)) names.push_back("Oblique");
return names;
}
static auto OS2GetCodePageRanges(uint32_t range1, uint32_t range2) {
std::vector<std::pair<const char *, const char *>> allCodePages
= {
{"1252" , "Latin 1"},
{"1250" , "Latin 2: Eastern Europe"},
{"1251" , "Cyrillic"},
{"1253" , "Greek"},
{"1254" , "Turkish"},
{"1255" , "Hebrew"},
{"1256" , "Arabic"},
{"1257" , "Windows Baltic"},
{"1258" , "Vietnamese"},
{"udef" , "Reserved for Alternate ANSI"},
{"udef" , "Reserved for Alternate ANSI"},
{"udef" , "Reserved for Alternate ANSI"},
{"udef" , "Reserved for Alternate ANSI"},
{"udef" , "Reserved for Alternate ANSI"},
{"udef" , "Reserved for Alternate ANSI"},
{"udef" , "Reserved for Alternate ANSI"},
{"874" , "Thai"},
{"932" , "JIS/Japan"},
{"936" , "Chinese: Simplified chars--PRC and Singapore"},
{"949" , "Korean Wansung"},
{"950" , "Chinese: Traditional chars--Taiwan and Hong Kong"},
{"1361" , "Korean Johab"},
{"udef" , "Reserved for Alternate ANSI & OEM"},
{"udef" , "Reserved for Alternate ANSI & OEM"},
{"udef" , "Reserved for Alternate ANSI & OEM"},
{"udef" , "Reserved for Alternate ANSI & OEM"},
{"udef" , "Reserved for Alternate ANSI & OEM"},
{"udef" , "Reserved for Alternate ANSI & OEM"},
{"udef" , "Reserved for Alternate ANSI & OEM"},
{"udef" , "Macintosh Character Set (US Roman)"},
{"udef" , "OEM Character Set"},
{"udef" , "Symbol Character Set"},
{"udef" , "Reserved for OEM"},
{"udef" , "Reserved for OEM"},
{"udef" , "Reserved for OEM"},
{"udef" , "Reserved for OEM"},
{"udef" , "Reserved for OEM"},
{"udef" , "Reserved for OEM"},
{"udef" , "Reserved for OEM"},
{"udef" , "Reserved for OEM"},
{"udef" , "Reserved for OEM"},
{"udef" , "Reserved for OEM"},
{"udef" , "Reserved for OEM"},
{"udef" , "Reserved for OEM"},
{"udef" , "Reserved for OEM"},
{"udef" , "Reserved for OEM"},
{"udef" , "Reserved for OEM"},
{"udef" , "Reserved for OEM"},
{"869" , "IBM Greek"},
{"866" , "MS-DOS Russian"},
{"865" , "MS-DOS Nordic"},
{"864" , "Arabic"},
{"863" , "MS-DOS Canadian French"},
{"862" , "Hebrew"},
{"861" , "MS-DOS Icelandic"},
{"860" , "MS-DOS Portuguese"},
{"857" , "IBM Turkish"},
{"855" , "IBM Cyrillic; primarily Russian"},
{"852" , "Latin 2"},
{"775" , "MS-DOS Baltic"},
{"737" , "Greek; former 437 G"},
{"708" , "Arabic; ASMO 708"},
{"850" , "WE/Latin 1"},
{"437" , "US"},
};
std::vector<std::string> codePages;
uint32_t range[] = {range1, range2};
for (size_t i = 0; i < allCodePages.size(); ++ i) {
unsigned char k = i % 32;
unsigned char f = i / 32;
if (range[f] & (1 << k)) {
auto code = allCodePages[i].first;
auto name = allCodePages[i].second;
if (atoi(code))
codePages.push_back(code + std::string(" ") + name);
else
codePages.push_back(name);
}
}
return codePages;
}
template <typename T>
static const char * OS2PanoseSearchInArray(uint8_t value, const std::initializer_list<T> & array) {
auto itr = std::begin(array);
if (std::distance(itr, std::end(array)) <= value)
return "";
std::advance(itr, value);
return *itr;
}
static const char * OS2GetPanoseFamilyType(uint8_t value) {
return OS2PanoseSearchInArray(value, {
"Any",
"No Fit",
"Text and Display",
"Script",
"Decorative",
"Pictorial",
});
}
static const char * OS2GetPanoseSerifType(uint8_t value) {
return OS2PanoseSearchInArray(value, {
"Any",
"No Fit",
"Cove",
"Obtuse Cove",
"Square Cove",
"Obtuse Square Cove",
"Square",
"Thin",
"Bone",
"Exaggerated",
"Triangle",
"Normal Sans",
"Obtuse Sans",
"Perp Sans",
"Flared",
"Rounded",
});
}
static const char * OS2GetPanoseWeight(uint8_t value) {
return OS2PanoseSearchInArray(value, {
"Any",
"No Fit",
"Very Light",
"Light",
"Thin",
"Book",
"Medium",
"Demi",
"Bold",
"Heavy",
"Black",
"Nord",
});
}
static const char * OS2GetPanoseProportion(uint8_t value) {
return OS2PanoseSearchInArray(value, {
"Any",
"No Fit",
"Old Style",
"Modern",
"Even Width",
"Expanded",
"Condensed",
"Very Expanded",
"Very Condensed",
"Monospaced",
});
}
static const char * OS2GetPanoseContrast(uint8_t value) {
return OS2PanoseSearchInArray(value, {
"Any",
"No Fit",
"None",
"Very Low",
"Low",
"Medium Low",
"Medium",
"Medium High",
"High",
"Very High",
});
}
static const char * OS2GetPanoseStrokeVariation(uint8_t value) {
return OS2PanoseSearchInArray(value, {
"Any",
"No Fit",
"Gradual/Diagonal",
"Gradual/Transitional",
"Gradual/Vertical",
"Gradual/Horizontal",
"Rapid/Vertical",
"Rapid/Horizontal",
"Instant/Vertical",
});
}
static const char * OS2GetPanoseArmStyle(uint8_t value) {
return OS2PanoseSearchInArray(value, {
"Any",
"No Fit",
"Straight Arms/Horizontal",
"Straight Arms/Wedge",
"Straight Arms/Vertical",
"Straight Arms/Single Serif",
"Straight Arms/Double Serif",
"Non-Straight Arms/Horizontal",
"Non-Straight Arms/Wedge",
"Non-Straight Arms/Vertical",
"Non-Straight Arms/Single Serif",
"Non-Straight Arms/Double Serif",
});
}
static const char * OS2GetPanoseLetterform(uint8_t value) {
return OS2PanoseSearchInArray(value, {
"Any",
"No Fit",
"Normal/Contact",
"Normal/Weighted",
"Normal/Boxed",
"Normal/Flattened",
"Normal/Rounded",
"Normal/Off Center",
"Normal/Square",
"Oblique/Contact",
"Oblique/Weighted",
"Oblique/Boxed",
"Oblique/Flattened",
"Oblique/Rounded",
"Oblique/Off Center",
"Oblique/Square",
});
}
static const char * OS2GetPanoseMidline(uint8_t value) {
return OS2PanoseSearchInArray(value, {
"Any",
"No Fit",
"Standard/Trimmed",
"Standard/Pointed",
"Standard/Serifed",
"High/Trimmed",
"High/Pointed",
"High/Serifed",
"Constant/Trimmed",
"Constant/Pointed",
"Constant/Serifed",
"Low/Trimmed",
"Low/Pointed",
"Low/Serifed",
});
}
static const char * OS2GetPanoseXHeight(uint8_t value) {
return OS2PanoseSearchInArray(value, {
"Any",
"No Fit",
"Constant/Small",
"Constant/Standard",
"Constant/Large",
"Ducking/Small",
"Ducking/Standard",
"Ducking/Large",
});
}
static const char * PostGetMacintoshGlyphName(size_t index) {
const char * names [] =
{
".notdef",
".null",
"nonmarkingreturn",
"space",
"exclam",
"quotedbl",
"numbersign",
"dollar",
"percent",
"ampersand",
"quotesingle",
"parenleft",
"parenright",
"asterisk",
"plus",
"comma",
"hyphen",
"period",
"slash",
"zero",
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine",
"colon",
"semicolon",
"less",
"equal",
"greater",
"question",
"at",
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"H",
"I",
"J",
"K",
"L",
"M",
"N",
"O",
"P",
"Q",
"R",
"S",
"T",
"U",
"V",
"W",
"X",
"Y",
"Z",
"bracketleft",
"backslash",
"bracketright",
"asciicircum",
"underscore",
"grave",
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
"i",
"j",
"k",
"l",
"m",
"n",
"o",
"p",
"q",
"r",
"s",
"t",
"u",
"v",
"w",
"x",
"y",
"z",
"braceleft",
"bar",
"braceright",
"asciitilde",
"Adieresis",
"Aring",
"Ccedilla",
"Eacute",
"Ntilde",
"Odieresis",
"Udieresis",
"aacute",
"agrave",
"acircumflex",
"adieresis",
"atilde",
"aring",
"ccedilla",
"eacute",
"egrave",
"ecircumflex",
"edieresis",
"iacute",
"igrave",
"icircumflex",
"idieresis",
"ntilde",
"oacute",
"ograve",
"ocircumflex",
"odieresis",
"otilde",
"uacute",
"ugrave",
"ucircumflex",
"udieresis",
"dagger",
"degree",
"cent",
"sterling",
"section",
"bullet",
"paragraph",
"germandbls",
"registered",
"copyright",
"trademark",
"acute",
"dieresis",
"notequal",
"AE",
"Oslash",
"infinity",
"plusminus",
"lessequal",
"greaterequal",
"yen",
"mu",
"partialdiff",
"summation",
"product",
"pi",
"integral",
"ordfeminine",
"ordmasculine",
"Omega",
"ae",
"oslash",
"questiondown",
"exclamdown",
"logicalnot",
"radical",
"florin",
"approxequal",
"Delta",
"guillemotleft",
"guillemotright",
"ellipsis",
"nonbreakingspace",
"Agrave",
"Atilde",
"Otilde",
"OE",
"oe",
"endash",
"emdash",
"quotedblleft",
"quotedblright",
"quoteleft",
"quoteright",
"divide",
"lozenge",
"ydieresis",
"Ydieresis",
"fraction",
"currency",
"guilsinglleft",
"guilsinglright",
"fi",
"fl",
"daggerdbl",
"periodcentered",
"quotesinglbase",
"quotedblbase",
"perthousand",
"Acircumflex",
"Ecircumflex",
"Aacute",
"Edieresis",
"Egrave",
"Iacute",
"Icircumflex",
"Idieresis",
"Igrave",
"Oacute",
"Ocircumflex",
"apple",
"Ograve",
"Uacute",
"Ucircumflex",
"Ugrave",
"dotlessi",
"circumflex",
"tilde",
"macron",
"breve",
"dotaccent",
"ring",
"cedilla",
"hungarumlaut",
"ogonek",
"caron",
"Lslash",
"lslash",
"Scaron",
"scaron",
"Zcaron",
"zcaron",
"brokenbar",
"Eth",
"eth",
"Yacute",
"yacute",
"Thorn",
"thorn",
"minus",
"multiply",
"onesuperior",
"twosuperior",
"threesuperior",
"onehalf",
"onequarter",
"threequarters",
"franc",
"Gbreve",
"gbreve",
"Idotaccent",
"Scedilla",
"scedilla",
"Cacute",
"cacute",
"Ccaron",
"ccaron",
"dcroat",
};
return names[index];
}
std::string static GetTagDescription(FXTag tag, const std::map<std::string, std::string> & descriptionMap) {
auto tagStr = FXTag2Str(tag);
FXHelper::trim(tagStr);
auto itr = descriptionMap.find(tagStr);
if (itr != descriptionMap.end())
return itr->second;
return tagStr;
}
static std::string OTGetScriptFullName(FXTag tag) {
static std::map<std::string, std::string> names = {
{"arab", "Arabic"},
{"armn", "Armenian"},
{"avst", "Avestan"},
{"bali", "Balinese"},
{"bamu", "Bamum"},
{"batk", "Batak"},
{"beng", "Bengali"},
{"bng2", "Bengali v.2"},
{"bopo", "Bopomofo"},
{"brai", "Braille"},
{"brah", "Brahmi"},
{"bugi", "Buginese"},
{"buhd", "Buhid"},
{"byzm", "Byzantine Music"},
{"cans", "Canadian Syllabics"},
{"cari", "Carian"},
{"cakm", "Chakma"},
{"cham", "Cham"},
{"cher", "Cherokee"},
{"hani", "CJK Ideographic"},
{"copt", "Coptic"},
{"cprt", "Cypriot Syllabary"},
{"cyrl", "Cyrillic"},
{"DFLT", "Default"},
{"dsrt", "Deseret"},
{"deva", "Devanagari"},
{"dev2", "Devanagari v.2"},
{"egyp", "Egyptian heiroglyphs"},
{"ethi", "Ethiopic"},
{"geor", "Georgian"},
{"glag", "Glagolitic"},
{"goth", "Gothic"},
{"grek", "Greek"},
{"gujr", "Gujarati"},
{"gjr2", "Gujarati v.2"},
{"guru", "Gurmukhi"},
{"gur2", "Gurmukhi v.2"},
{"hang", "Hangul"},
{"jamo", "Hangul Jamo"},
{"hano", "Hanunoo"},
{"hebr", "Hebrew"},
{"kana", "Hiragana"},
{"armi", "Imperial Aramaic"},
{"phli", "Inscriptional Pahlavi"},
{"prti", "Inscriptional Parthian"},
{"java", "Javanese"},
{"kthi", "Kaithi"},
{"knda", "Kannada"},
{"knd2", "Kannada v.2"},
{"kana", "Katakana"},
{"kali", "Kayah Li"},
{"khar", "Kharosthi"},
{"khmr", "Khmer"},
{"lao", "Lao"},
{"latn", "Latin"},
{"lepc", "Lepcha"},
{"limb", "Limbu"},
{"linb", "Linear B"},
{"lisu", "Lisu (Fraser)"},
{"lyci", "Lycian"},
{"lydi", "Lydian"},
{"mlym", "Malayalam"},
{"mlm2", "Malayalam v.2"},
{"mand", "Mandaic Mandaean"},
{"math", "Mathematical Alphanumeric Symbols"},
{"mtei", "Meitei Mayek (Meithei Meetei)"},
{"merc", "Meroitic Cursive"},
{"mero", "Meroitic Hieroglyphs"},
{"mong", "Mongolian"},
{"musc", "Musical Symbols"},
{"mymr", "Myanmar"},
{"talu", "New Tai Lue"},
{"nko", "N'Ko"},
{"ogam", "Ogham"},
{"olck", "Ol Chiki"},
{"ital", "Old Italic"},
{"xpeo", "Old Persian Cuneiform"},
{"sarb", "Old South Arabian"},
{"orkh", "Old Turkic Orkhon Runic"},
{"orya", "Odia (formerly Oriya)"},
{"ory2", "Odia v.2 (formerly Oriya v.2)"},
{"osma", "Osmanya"},
{"phag", "Phags-pa"},
{"phnx", "Phoenician"},
{"rjng", "Rejang"},
{"runr", "Runic"},
{"samr", "Samaritan"},
{"saur", "Saurashtra"},
{"shrd", "Sharada"},
{"shaw", "Shavian"},
{"sinh", "Sinhala"},
{"sora", "Sora Sompeng"},
{"xsux", "Sumero-Akkadian Cuneiform"},
{"sund", "Sundanese"},
{"sylo", "Syloti Nagri"},
{"syrc", "Syriac"},
{"tglg", "Tagalog"},
{"tagb", "Tagbanwa"},
{"tale", "Tai Le"},
{"lana", "Tai Tham (Lanna)"},
{"tavt", "Tai Viet"},
{"takr", "Takri"},
{"taml", "Tamil"},
{"tml2", "Tamil v.2"},
{"telu", "Telugu"},
{"tel2", "Telugu v.2"},
{"thaa", "Thaana"},
{"thai", "Thai"},
{"tibt", "Tibetan"},
{"tfng", "Tifinagh"},
{"ugar", "Ugaritic Cuneiform"},
{"vai", "Vai"},
{"yi", "Yi"},
};
return GetTagDescription(tag, names);
}
static std::string OTGetLanguageFullName(FXTag tag) {
static std::map<std::string, std::string> names = {
{"ABA", "Abaza"},
{"ABK", "Abkhazian"},
{"ADY", "Adyghe"},
{"AFK", "Afrikaans"},
{"AFR", "Afar"},
{"AGW", "Agaw"},
{"ALS", "Alsatian"},
{"ALT", "Altai"},
{"AMH", "Amharic"},
{"APPH", "Phonetic transcription—Americanist conventions"},
{"ARA", "Arabic"},
{"ARI", "Aari"},
{"ARK", "Arakanese"},
{"ASM", "Assamese"},
{"ATH", "Athapaskan"},
{"AVR", "Avar"},
{"AWA", "Awadhi"},
{"AYM", "Aymara"},
{"AZE", "Azeri"},
{"BAD", "Badaga"},
{"BAG", "Baghelkhandi"},
{"BAL", "Balkar"},
{"BAU", "Baule"},
{"BBR", "Berber"},
{"BCH", "Bench"},
{"BCR", "Bible Cree"},
{"BEL", "Belarussian"},
{"BEM", "Bemba"},
{"BEN", "Bengali"},
{"BGR", "Bulgarian"},
{"BHI", "Bhili"},
{"BHO", "Bhojpuri"},
{"BIK", "Bikol"},
{"BIL", "Bilen"},
{"BKF", "Blackfoot"},
{"BLI", "Balochi"},
{"BLN", "Balante"},
{"BLT", "Balti"},
{"BMB", "Bambara"},
{"BML", "Bamileke"},
{"BOS", "Bosnian"},
{"BRE", "Breton"},
{"BRH", "Brahui"},
{"BRI", "Braj Bhasha"},
{"BRM", "Burmese"},
{"BSH", "Bashkir"},
{"BTI", "Beti"},
{"CAT", "Catalan"},
{"CEB", "Cebuano"},
{"CHE", "Chechen"},
{"CHG", "Chaha Gurage"},
{"CHH", "Chattisgarhi"},
{"CHI", "Chichewa"},
{"CHK", "Chukchi"},
{"CHP", "Chipewyan"},
{"CHR", "Cherokee"},
{"CHU", "Chuvash"},
{"CMR", "Comorian"},
{"COP", "Coptic"},
{"COS", "Corsican"},
{"CRE", "Cree"},
{"CRR", "Carrier"},
{"CRT", "Crimean Tatar"},
{"CSL", "Church Slavonic"},
{"CSY", "Czech"},
{"DAN", "Danish"},
{"DAR", "Dargwa"},
{"DCR", "Woods Cree"},
{"DEU", "German"},
{"dlft", "Default"},
{"DGR", "Dogri"},
{"DHV (deprecated)", "Dhivehi"},
{"DIV", "Dhivehi"},
{"DJR", "Djerma"},
{"DNG", "Dangme"},
{"DNK", "Dinka"},
{"DRI", "Dari"},
{"DUN", "Dungan"},
{"DZN", "Dzongkha"},
{"EBI", "Ebira"},
{"ECR", "Eastern Cree"},
{"EDO", "Edo"},
{"EFI", "Efik"},
{"ELL", "Greek"},
{"ENG", "English"},
{"ERZ", "Erzya"},
{"ESP", "Spanish"},
{"ETI", "Estonian"},
{"EUQ", "Basque"},
{"EVK", "Evenki"},
{"EVN", "Even"},
{"EWE", "Ewe"},
{"FAN", "French Antillean"},
{"FAR", "Farsi"},
{"FIN", "Finnish"},
{"FJI", "Fijian"},
{"FLE", "Flemish"},
{"FNE", "Forest Nenets"},
{"FON", "Fon"},
{"FOS", "Faroese"},
{"FRA", "French"},
{"FRI", "Frisian"},
{"FRL", "Friulian"},
{"FTA", "Futa"},
{"FUL", "Fulani"},
{"GAD", "Ga"},
{"GAE", "Gaelic"},
{"GAG", "Gagauz"},
{"GAL", "Galician"},
{"GAR", "Garshuni"},
{"GAW", "Garhwali"},
{"GEZ", "Ge'ez"},
{"GIL", "Gilyak"},
{"GMZ", "Gumuz"},
{"GON", "Gondi"},
{"GRN", "Greenlandic"},
{"GRO", "Garo"},
{"GUA", "Guarani"},
{"GUJ", "Gujarati"},
{"HAI", "Haitian"},
{"HAL", "Halam"},
{"HAR", "Harauti"},
{"HAU", "Hausa"},
{"HAW", "Hawaiin"},
{"HBN", "Hammer-Banna"},
{"HIL", "Hiligaynon"},
{"HIN", "Hindi"},
{"HMA", "High Mari"},
{"HND", "Hindko"},
{"HO", "Ho"},
{"HRI", "Harari"},
{"HRV", "Croatian"},
{"HUN", "Hungarian"},
{"HYE", "Armenian"},
{"IBO", "Igbo"},
{"IJO", "Ijo"},
{"ILO", "Ilokano"},
{"IND", "Indonesian"},
{"ING", "Ingush"},
{"INU", "Inuktitut"},
{"IPPH", "Phonetic transcription—IPA conventions"},
{"IRI", "Irish"},
{"IRT", "Irish Traditional"},
{"ISL", "Icelandic"},
{"ISM", "Inari Sami"},
{"ITA", "Italian"},
{"IWR", "Hebrew"},
{"JAV", "Javanese"},
{"JII", "Yiddish"},
{"JAN", "Japanese"},
{"JUD", "Judezmo"},
{"JUL", "Jula"},
{"KAB", "Kabardian"},
{"KAC", "Kachchi"},
{"KAL", "Kalenjin"},
{"KAN", "Kannada"},
{"KAR", "Karachay"},
{"KAT", "Georgian"},
{"KAZ", "Kazakh"},
{"KEB", "Kebena"},
{"KGE", "Khutsuri Georgian"},
{"KHA", "Khakass"},
{"KHK", "Khanty-Kazim"},
{"KHM", "Khmer"},
{"KHS", "Khanty-Shurishkar"},
{"KHV", "Khanty-Vakhi"},
{"KHW", "Khowar"},
{"KIK", "Kikuyu"},
{"KIR", "Kirghiz"},
{"KIS", "Kisii"},
{"KKN", "Kokni"},
{"KLM", "Kalmyk"},
{"KMB", "Kamba"},
{"KMN", "Kumaoni"},
{"KMO", "Komo"},
{"KMS", "Komso"},
{"KNR", "Kanuri"},
{"KOD", "Kodagu"},
{"KOH", "Korean Old Hangul"},
{"KOK", "Konkani"},
{"KON", "Kikongo"},
{"KOP", "Komi-Permyak"},
{"KOR", "Korean"},
{"KOZ", "Komi-Zyrian"},
{"KPL", "Kpelle"},
{"KRI", "Krio"},
{"KRK", "Karakalpak"},
{"KRL", "Karelian"},
{"KRM", "Karaim"},
{"KRN", "Karen"},
{"KRT", "Koorete"},
{"KSH", "Kashmiri"},
{"KSI", "Khasi"},
{"KSM", "Kildin Sami"},
{"KUI", "Kui"},
{"KUL", "Kulvi"},
{"KUM", "Kumyk"},
{"KUR", "Kurdish"},
{"KUU", "Kurukh"},
{"KUY", "Kuy"},
{"KYK", "Koryak"},
{"LAD", "Ladin"},
{"LAH", "Lahuli"},
{"LAK", "Lak"},
{"LAM", "Lambani"},
{"LAO", "Lao"},
{"LAT", "Latin"},
{"LAZ", "Laz"},
{"LCR", "L-Cree"},
{"LDK", "Ladakhi"},
{"LEZ", "Lezgi"},
{"LIN", "Lingala"},
{"LMA", "Low Mari"},
{"LMB", "Limbu"},
{"LMW", "Lomwe"},
{"LSB", "Lower Sorbian"},
{"LSM", "Lule Sami"},
{"LTH", "Lithuanian"},
{"LTZ", "Luxembourgish"},
{"LUB", "Luba"},
{"LUG", "Luganda"},
{"LUH", "Luhya"},
{"LUO", "Luo"},
{"LVI", "Latvian"},
{"MAJ", "Majang"},
{"MAK", "Makua"},
{"MAL", "Malayalam Traditional"},
{"MAN", "Mansi"},
{"MAP", "Mapudungun"},
{"MAR", "Marathi"},
{"MAW", "Marwari"},
{"MBN", "Mbundu"},
{"MCH", "Manchu"},
{"MCR", "Moose Cree"},
{"MDE", "Mende"},
{"MEN", "Me'en"},
{"MIZ", "Mizo"},
{"MKD", "Macedonian"},
{"MLE", "Male"},
{"MLG", "Malagasy"},
{"MLN", "Malinke"},
{"MLR", "Malayalam Reformed"},
{"MLY", "Malay"},
{"MND", "Mandinka"},
{"MNG", "Mongolian"},
{"MNI", "Manipuri"},
{"MNK", "Maninka"},
{"MNX", "Manx Gaelic"},
{"MOH", "Mohawk"},
{"MOK", "Moksha"},
{"MOL", "Moldavian"},
{"MON", "Mon"},
{"MOR", "Moroccan"},
{"MRI", "Maori"},
{"MTH", "Maithili"},
{"MTS", "Maltese"},
{"MUN", "Mundari"},
{"NAG", "Naga-Assamese"},
{"NAN", "Nanai"},
{"NAS", "Naskapi"},
{"NCR", "N-Cree"},
{"NDB", "Ndebele"},
{"NDG", "Ndonga"},
{"NEP", "Nepali"},
{"NEW", "Newari"},
{"NGR", "Nagari"},
{"NHC", "Norway House Cree"},
{"NIS", "Nisi"},
{"NIU", "Niuean"},
{"NKL", "Nkole"},
{"NKO", "N'Ko"},
{"NLD", "Dutch"},
{"NOG", "Nogai"},
{"NOR", "Norwegian"},
{"NSM", "Northern Sami"},
{"NTA", "Northern Tai"},
{"NTO", "Esperanto"},
{"NYN", "Nynorsk"},
{"OCI", "Occitan"},
{"OCR", "Oji-Cree"},
{"OJB", "Ojibway"},
{"ORI", "Odia(formerly Oriya)"},
{"ORO", "Oromo"},
{"OSS", "Ossetian"},
{"PAA", "Palestinian Aramaic"},
{"PAL", "Pali"},
{"PAN", "Punjabi"},
{"PAP", "Palpa"},
{"PAS", "Pashto"},
{"PGR", "Polytonic Greek"},
{"PIL", "Filipino"},
{"PLG", "Palaung"},
{"PLK", "Polish"},
{"PRO", "Provencal"},
{"PTG", "Portuguese"},
{"QIN", "Chin"},
{"RAJ", "Rajasthani"},
{"RCR", "R-Cree"},
{"RBU", "Russian Buriat"},
{"RIA", "Riang"},
{"RMS", "Rhaeto-Romanic"},
{"ROM", "Romanian"},
{"ROY", "Romany"},
{"RSY", "Rusyn"},
{"RUA", "Ruanda"},
{"RUS", "Russian"},
{"SAD", "Sadri"},
{"SAN", "Sanskrit"},
{"SAT", "Santali"},
{"SAY", "Sayisi"},
{"SEK", "Sekota"},
{"SEL", "Selkup"},
{"SGO", "Sango"},
{"SHN", "Shan"},
{"SIB", "Sibe"},
{"SID", "Sidamo"},
{"SIG", "Silte Gurage"},
{"SKS", "Skolt Sami"},
{"SKY", "Slovak"},
{"SLA", "Slavey"},
{"SLV", "Slovenian"},
{"SML", "Somali"},
{"SMO", "Samoan"},
{"SNA", "Sena"},
{"SND", "Sindhi"},
{"SNH", "Sinhalese"},
{"SNK", "Soninke"},
{"SOG", "Sodo Gurage"},
{"SOT", "Sotho"},
{"SQI", "Albanian"},
{"SRB", "Serbian"},
{"SRK", "Saraiki"},
{"SRR", "Serer"},
{"SSL", "South Slavey"},
{"SSM", "Southern Sami"},
{"SUR", "Suri"},
{"SVA", "Svan"},
{"SVE", "Swedish"},
{"SWA", "Swadaya Aramaic"},
{"SWK", "Swahili"},
{"SWZ", "Swazi"},
{"SXT", "Sutu"},
{"SYR", "Syriac"},
{"TAB", "Tabasaran"},
{"TAJ", "Tajiki"},
{"TAM", "Tamil"},
{"TAT", "Tatar"},
{"TCR", "TH-Cree"},
{"TEL", "Telugu"},
{"TGN", "Tongan"},
{"TGR", "Tigre"},
{"TGY", "Tigrinya"},
{"THA", "Thai"},
{"THT", "Tahitian"},
{"TIB", "Tibetan"},
{"TKM", "Turkmen"},
{"TMN", "Temne"},
{"TNA", "Tswana"},
{"TNE", "Tundra Nenets"},
{"TNG", "Tonga"},
{"TOD", "Todo"},
{"TRK", "Turkish"},
{"TSG", "Tsonga"},
{"TUA", "Turoyo Aramaic"},
{"TUL", "Tulu"},
{"TUV", "Tuvin"},
{"TWI", "Twi"},
{"UDM", "Udmurt"},
{"UKR", "Ukrainian"},
{"URD", "Urdu"},
{"USB", "Upper Sorbian"},
{"UYG", "Uyghur"},
{"UZB", "Uzbek"},
{"VEN", "Venda"},
{"VIT", "Vietnamese"},
{"WA", "Wa"},
{"WAG", "Wagdi"},
{"WCR", "West-Cree"},
{"WEL", "Welsh"},
{"WLF", "Wolof"},
{"XBD", "Tai Lue"},
{"XHS", "Xhosa"},
{"YAK", "Yakut"},
{"YBA", "Yoruba"},
{"YCR", "Y-Cree"},
{"YIC", "Yi Classic"},
{"YIM", "Yi Modern"},
{"ZHH", "Chinese Hong Kong"},
{"ZHP", "Chinese Phonetic"},
{"ZHS", "Chinese Simplified"},
{"ZHT", "Chinese Traditional"},
{"ZND", "Zande"},
{"ZUL", "Zulu"},
};
return GetTagDescription(tag, names);
}
static std::string OTGetFeatureFullName(FXTag tag) {
static std::map<std::string, std::string> names = {
{"aalt", "Access All Alternates"},
{"abvf", "Above-base Forms"},
{"abvm", "Above-base Mark Positioning"},
{"abvs", "Above-base Substitutions"},
{"afrc", "Alternative Fractions"},
{"akhn", "Akhands"},
{"blwf", "Below-base Forms"},
{"blwm", "Below-base Mark Positioning"},
{"blws", "Below-base Substitutions"},
{"calt", "Contextual Alternates"},
{"case", "Case-Sensitive Forms"},
{"ccmp", "Glyph Composition / Decomposition"},
{"cfar", "Conjunct Form After Ro"},
{"cjct", "Conjunct Forms"},
{"clig", "Contextual Ligatures"},
{"cpct", "Centered CJK Punctuation"},
{"cpsp", "Capital Spacing"},
{"cswh", "Contextual Swash"},
{"curs", "Cursive Positioning"},
{"cv01-cv99", "Character Variants"},
{"c2pc", "Petite Capitals From Capitals"},
{"c2sc", "Small Capitals From Capitals"},
{"dist", "Distances"},
{"dlig", "Discretionary Ligatures"},
{"dnom", "Denominators"},
{"expt", "Expert Forms"},
{"falt", "Final Glyph on Line Alternates"},
{"fin2", "Terminal Forms #2"},
{"fin3", "Terminal Forms #3"},
{"fina", "Terminal Forms"},
{"frac", "Fractions"},
{"fwid", "Full Widths"},
{"half", "Half Forms"},
{"haln", "Halant Forms"},
{"halt", "Alternate Half Widths"},
{"hist", "Historical Forms"},
{"hkna", "Horizontal Kana Alternates"},
{"hlig", "Historical Ligatures"},
{"hngl", "Hangul"},
{"hojo", "Hojo Kanji Forms (JIS X 0212-1990 Kanji Forms)"},
{"hwid", "Half Widths"},
{"init", "Initial Forms"},
{"isol", "Isolated Forms"},
{"ital", "Italics"},
{"jalt", "Justification Alternates"},
{"jp78", "JIS78 Forms"},
{"jp83", "JIS83 Forms"},
{"jp90", "JIS90 Forms"},
{"jp04", "JIS2004 Forms"},
{"kern", "Kerning"},
{"lfbd", "Left Bounds"},
{"liga", "Standard Ligatures"},
{"ljmo", "Leading Jamo Forms"},
{"lnum", "Lining Figures"},
{"locl", "Localized Forms"},
{"ltra", "Left-to-right alternates"},
{"ltrm", "Left-to-right mirrored forms"},
{"mark", "Mark Positioning"},
{"med2", "Medial Forms #2"},
{"medi", "Medial Forms"},
{"mgrk", "Mathematical Greek"},
{"mkmk", "Mark to Mark Positioning"},
{"mset", "Mark Positioning via Substitution"},
{"nalt", "Alternate Annotation Forms"},
{"nlck", "NLC Kanji Forms"},
{"nukt", "Nukta Forms"},
{"numr", "Numerators"},
{"onum", "Oldstyle Figures"},
{"opbd", "Optical Bounds"},
{"ordn", "Ordinals"},
{"ornm", "Ornaments"},
{"palt", "Proportional Alternate Widths"},
{"pcap", "Petite Capitals"},
{"pkna", "Proportional Kana"},
{"pnum", "Proportional Figures"},
{"pref", "Pre-Base Forms"},
{"pres", "Pre-base Substitutions"},
{"pstf", "Post-base Forms"},
{"psts", "Post-base Substitutions"},
{"pwid", "Proportional Widths"},
{"qwid", "Quarter Widths"},
{"rand", "Randomize"},
{"rkrf", "Rakar Forms"},
{"rlig", "Required Ligatures"},
{"rphf", "Reph Forms"},
{"rtbd", "Right Bounds"},
{"rtla", "Right-to-left alternates"},
{"rtlm", "Right-to-left mirrored forms"},
{"ruby", "Ruby Notation Forms"},
{"salt", "Stylistic Alternates"},
{"sinf", "Scientific Inferiors"},
{"size", "Optical size"},
{"smcp", "Small Capitals"},
{"smpl", "Simplified Forms"},
{"ss01", "Stylistic Set 1"},
{"ss02", "Stylistic Set 2"},
{"ss03", "Stylistic Set 3"},
{"ss04", "Stylistic Set 4"},
{"ss05", "Stylistic Set 5"},
{"ss06", "Stylistic Set 6"},
{"ss07", "Stylistic Set 7"},
{"ss08", "Stylistic Set 8"},
{"ss09", "Stylistic Set 9"},
{"ss10", "Stylistic Set 10"},
{"ss11", "Stylistic Set 11"},
{"ss12", "Stylistic Set 12"},
{"ss13", "Stylistic Set 13"},
{"ss14", "Stylistic Set 14"},
{"ss15", "Stylistic Set 15"},
{"ss16", "Stylistic Set 16"},
{"ss17", "Stylistic Set 17"},
{"ss18", "Stylistic Set 18"},
{"ss19", "Stylistic Set 19"},
{"ss20", "Stylistic Set 20"},
{"subs", "Subscript"},
{"sups", "Superscript"},
{"swsh", "Swash"},
{"titl", "Titling"},
{"tjmo", "Trailing Jamo Forms"},
{"tnam", "Traditional Name Forms"},
{"tnum", "Tabular Figures"},
{"trad", "Traditional Forms"},
{"twid", "Third Widths"},
{"unic", "Unicase"},
{"valt", "Alternate Vertical Metrics"},
{"vatu", "Vattu Variants"},
{"vert", "Vertical Writing"},
{"vhal", "Alternate Vertical Half Metrics"},
{"vjmo", "Vowel Jamo Forms"},
{"vkna", "Vertical Kana Alternates"},
{"vkrn", "Vertical Kerning"},
{"vpal", "Proportional Alternate Vertical Metrics"},
{"vrt2", "Vertical Alternates and Rotation"},
{"zero", "Slashed Zero"},
};
return GetTagDescription(tag, names);
}
};
| 35.660423 | 212 | 0.364651 | [
"vector"
] |
7674bbb66ccd22260ec40dc69fe63fda6785cfab | 1,425 | h | C | chromaprint/fingerprint_calculator.h | pvinis/music-player | 0e7d06c2a648ca9cfaa46418e6536f63ab42d088 | [
"BSD-2-Clause"
] | 56 | 2015-04-21T05:35:38.000Z | 2021-02-16T13:42:45.000Z | chromaprint/fingerprint_calculator.h | pvinis/music-player | 0e7d06c2a648ca9cfaa46418e6536f63ab42d088 | [
"BSD-2-Clause"
] | 13 | 2015-05-09T17:36:27.000Z | 2020-02-13T17:44:59.000Z | chromaprint/fingerprint_calculator.h | pvinis/music-player | 0e7d06c2a648ca9cfaa46418e6536f63ab42d088 | [
"BSD-2-Clause"
] | 27 | 2015-06-15T14:54:58.000Z | 2021-07-22T09:59:40.000Z | /*
* Chromaprint -- Audio fingerprinting toolkit
* Copyright (C) 2010 Lukas Lalinsky <lalinsky@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
* USA
*/
#ifndef CHROMAPRINT_FINGERPRINT_CALCULATOR_H_
#define CHROMAPRINT_FINGERPRINT_CALCULATOR_H_
#include <stdint.h>
#include <vector>
namespace Chromaprint
{
class Classifier;
class Image;
class IntegralImage;
class FingerprintCalculator
{
public:
FingerprintCalculator(const Classifier *classifiers, int num_classifiers);
std::vector<int32_t> Calculate(Image *image);
int32_t CalculateSubfingerprint(IntegralImage *image, int offset);
private:
const Classifier *m_classifiers;
int m_num_classifiers;
int m_max_filter_width;
};
};
#endif
| 27.403846 | 76 | 0.763509 | [
"vector"
] |
76869d0ee2278c7dd914c0f4da54a87c42521e3b | 30,030 | c | C | pyscf/lib/pbc/grid_ao.c | bogdanoff/pyscf | f6c9c6654dd9609c5e467a1edd5c2c076f793acc | [
"Apache-2.0"
] | null | null | null | pyscf/lib/pbc/grid_ao.c | bogdanoff/pyscf | f6c9c6654dd9609c5e467a1edd5c2c076f793acc | [
"Apache-2.0"
] | null | null | null | pyscf/lib/pbc/grid_ao.c | bogdanoff/pyscf | f6c9c6654dd9609c5e467a1edd5c2c076f793acc | [
"Apache-2.0"
] | null | null | null | /* Copyright 2014-2018 The PySCF Developers. 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.
*
* Author: Qiming Sun <osirpt.sun@gmail.com>
*/
#include <stdlib.h>
#include <math.h>
#include <complex.h>
#include "config.h"
#include "cint.h"
#include "vhf/fblas.h"
#include "gto/grid_ao_drv.h"
#define MIN(X,Y) ((X)<(Y)?(X):(Y))
#define MAX(X,Y) ((X)>(Y)?(X):(Y))
#define ALL_IMAGES 255
#define IMGBLK 40
#define OF_CMPLX 2
double CINTcommon_fac_sp(int l);
void GTOshell_eval_grid_cart(double *gto, double *ri, double *exps,
double *coord, double *alpha, double *coeff, double *env,
int l, int np, int nc, size_t nao, size_t ngrids, size_t bgrids);
void GTOshell_eval_grid_cart_deriv1(double *gto, double *ri, double *exps,
double *coord, double *alpha, double *coeff, double *env,
int l, int np, int nc, size_t nao, size_t ngrids, size_t bgrids);
void GTOshell_eval_grid_cart_deriv2(double *cgto, double *ri, double *exps,
double *coord, double *alpha, double *coeff, double *env,
int l, int np, int nc, size_t nao, size_t ngrids, size_t bgrids);
void GTOshell_eval_grid_cart_deriv3(double *cgto, double *ri, double *exps,
double *coord, double *alpha, double *coeff, double *env,
int l, int np, int nc, size_t nao, size_t ngrids, size_t bgrids);
void GTOshell_eval_grid_cart_deriv4(double *cgto, double *ri, double *exps,
double *coord, double *alpha, double *coeff, double *env,
int l, int np, int nc, size_t nao, size_t ngrids, size_t bgrids);
void GTOshell_eval_grid_cart(double *gto, double *ri, double *exps,
double *coord, double *alpha, double *coeff,
double *env, int l, int np, int nc,
size_t nao, size_t ngrids, size_t bgrids);
void GTOshell_eval_grid_ip_cart(double *gto, double *ri, double *exps,
double *coord, double *alpha, double *coeff,
double *env, int l, int np, int nc,
size_t nao, size_t ngrids, size_t bgrids);
/*
* Extend the meaning of non0table: given shell ID and block ID,
* non0table is the number of images in Ls that does not vanish.
* Ls should be sorted based on the distance to center cell.
*/
void PBCnr_ao_screen(unsigned char *non0table, double *coords, int ngrids,
double *Ls, int nimgs,
int *atm, int natm, int *bas, int nbas, double *env)
{
const int nblk = (ngrids+BLKSIZE-1) / BLKSIZE;
#pragma omp parallel
{
int i, j, m;
int np, nc, atm_id;
size_t bas_id, ib;
double rr, arr, maxc;
double logcoeff[NPRIMAX];
double dr[3];
double rL[3];
double *p_exp, *pcoeff, *ratm;
#pragma omp for nowait schedule(dynamic)
for (bas_id = 0; bas_id < nbas; bas_id++) {
np = bas[NPRIM_OF+bas_id*BAS_SLOTS];
nc = bas[NCTR_OF +bas_id*BAS_SLOTS];
p_exp = env + bas[PTR_EXP+bas_id*BAS_SLOTS];
pcoeff = env + bas[PTR_COEFF+bas_id*BAS_SLOTS];
atm_id = bas[ATOM_OF+bas_id*BAS_SLOTS];
ratm = env + atm[atm_id*ATM_SLOTS+PTR_COORD];
for (j = 0; j < np; j++) {
maxc = 0;
for (i = 0; i < nc; i++) {
maxc = MAX(maxc, fabs(pcoeff[i*np+j]));
}
logcoeff[j] = log(maxc);
}
for (ib = 0; ib < nblk; ib++) {
for (m = nimgs-1; m >= 0; m--) {
rL[0] = ratm[0] + Ls[m*3+0];
rL[1] = ratm[1] + Ls[m*3+1];
rL[2] = ratm[2] + Ls[m*3+2];
for (i = ib*BLKSIZE; i < MIN(ngrids, (ib+1)*BLKSIZE); i++) {
dr[0] = coords[0*ngrids+i] - rL[0];
dr[1] = coords[1*ngrids+i] - rL[1];
dr[2] = coords[2*ngrids+i] - rL[2];
rr = dr[0]*dr[0] + dr[1]*dr[1] + dr[2]*dr[2];
for (j = 0; j < np; j++) {
arr = p_exp[j] * rr;
if (arr-logcoeff[j] < EXPCUTOFF) {
non0table[ib*nbas+bas_id] = MIN(ALL_IMAGES, m+1);
goto next_blk;
}
}
}
}
non0table[ib*nbas+bas_id] = 0;
next_blk:;
}
}
}
}
static void _copy(double complex *out, double *ao_k,
size_t ngrids, size_t bgrids,
int nkpts, int ncomp, int nao, int ncol)
{
int i, j, k, ic;
double complex *pout;
double *ao_r, *ao_i;
int blksize = ncomp * ncol * bgrids;
for (k = 0; k < nkpts; k++) {
ao_r = ao_k + k*2 * blksize;
ao_i = ao_k +(k*2+1) * blksize;
for (ic = 0; ic < ncomp; ic++) {
pout = out + (k * ncomp + ic) * nao * ngrids;
for (j = 0; j < ncol; j++) {
for (i = 0; i < bgrids; i++) {
pout[j*ngrids+i] = (ao_r[j*bgrids+i] +
ao_i[j*bgrids+i]*_Complex_I);
} }
ao_r += ncol * bgrids;
ao_i += ncol * bgrids;
}
}
}
// grid2atm[nimgs,xyz,grid_id]
static void _fill_grid2atm(double *grid2atm, double *min_grid2atm,
double *coord, double *Ls, double *r_atm,
int atm_imag_max, size_t bgrids, size_t ngrids, int nimgs)
{
int ig, m;
double rL[3];
double dist;
double dist_min;
for (m = 0; m < nimgs; m++) {
if ((m < atm_imag_max || atm_imag_max == ALL_IMAGES)) {
rL[0] = r_atm[0] + Ls[m*3+0];
rL[1] = r_atm[1] + Ls[m*3+1];
rL[2] = r_atm[2] + Ls[m*3+2];
dist_min = 1e9;
for (ig = 0; ig < bgrids; ig++) {
grid2atm[0*BLKSIZE+ig] = coord[0*ngrids+ig] - rL[0];
grid2atm[1*BLKSIZE+ig] = coord[1*ngrids+ig] - rL[1];
grid2atm[2*BLKSIZE+ig] = coord[2*ngrids+ig] - rL[2];
dist = (grid2atm[0*BLKSIZE+ig]*grid2atm[0*BLKSIZE+ig] +
grid2atm[1*BLKSIZE+ig]*grid2atm[1*BLKSIZE+ig] +
grid2atm[2*BLKSIZE+ig]*grid2atm[2*BLKSIZE+ig]);
dist_min = MIN(dist, dist_min);
}
min_grid2atm[m] = sqrt(dist_min);
}
grid2atm += 3*BLKSIZE;
}
}
void PBCeval_cart_iter(FPtr_eval feval, FPtr_exp fexp,
size_t nao, size_t ngrids, size_t bgrids, size_t offao,
int param[], int *shls_slice, int *ao_loc, double *buf,
double *Ls, double complex *expLk,
int nimgs, int nkpts, int di_max, double complex *ao,
double *coord, double *rcut, unsigned char *non0table,
int *atm, int natm, int *bas, int nbas, double *env)
{
const int ncomp = param[TENSOR];
const int sh0 = shls_slice[0];
const int sh1 = shls_slice[1];
const char TRANS_N = 'N';
const char TRANS_T = 'T';
const double D1 = 1;
const int nkpts2 = nkpts * OF_CMPLX;
int i, j, k, l, np, nc, atm_id, bas_id, deg, ao_id;
int iL, iL0, iLcount, dimc;
int grid2atm_atm_id, count;
double fac;
double *p_exp, *pcoeff, *pcoord, *pao, *ri;
double *grid2atm = buf; // shape [nimgs,3,bgrids]
double *eprim = grid2atm + nimgs*3*BLKSIZE;
double *aobuf = eprim + NPRIMAX*BLKSIZE*2;
double *aobufk = aobuf + IMGBLK*ncomp*di_max*bgrids;
double *Lk_buf = aobufk + nkpts*ncomp*di_max*bgrids * OF_CMPLX;
double complex *zLk_buf = (double complex *)Lk_buf;
double *min_grid2atm = Lk_buf + IMGBLK * nkpts * OF_CMPLX;
double *pexpLk;
int img_idx[nimgs];
int atm_imag_max[natm];
for (i = 0; i < natm; i++) {
atm_imag_max[i] = 0;
}
for (bas_id = sh0; bas_id < sh1; bas_id++) {
atm_id = bas[bas_id*BAS_SLOTS+ATOM_OF];
atm_imag_max[atm_id] = MAX(atm_imag_max[atm_id], non0table[bas_id]);
}
grid2atm_atm_id = -1;
for (bas_id = sh0; bas_id < sh1; bas_id++) {
np = bas[bas_id*BAS_SLOTS+NPRIM_OF];
nc = bas[bas_id*BAS_SLOTS+NCTR_OF ];
l = bas[bas_id*BAS_SLOTS+ANG_OF ];
deg = (l+1)*(l+2)/2;
dimc = nc*deg * ncomp * bgrids;
fac = CINTcommon_fac_sp(l);
p_exp = env + bas[bas_id*BAS_SLOTS+PTR_EXP];
pcoeff = env + bas[bas_id*BAS_SLOTS+PTR_COEFF];
atm_id = bas[bas_id*BAS_SLOTS+ATOM_OF];
ri = env + atm[PTR_COORD+atm_id*ATM_SLOTS];
ao_id = ao_loc[bas_id] - ao_loc[sh0];
if (grid2atm_atm_id != atm_id) {
_fill_grid2atm(grid2atm, min_grid2atm, coord, Ls, ri,
atm_imag_max[atm_id], bgrids, ngrids, nimgs);
grid2atm_atm_id = atm_id;
}
for (i = 0; i < nkpts2*dimc; i++) {
aobufk[i] = 0;
}
for (iL0 = 0; iL0 < nimgs; iL0+=IMGBLK) {
iLcount = MIN(IMGBLK, nimgs - iL0);
count = 0;
for (iL = iL0; iL < iL0+iLcount; iL++) {
pcoord = grid2atm + iL * 3*BLKSIZE;
if ((iL < non0table[bas_id] || non0table[bas_id] == ALL_IMAGES) &&
(min_grid2atm[iL] < rcut[bas_id]) &&
(*fexp)(eprim, pcoord, p_exp, pcoeff, l, np, nc, bgrids, fac)) {
pao = aobuf + count * dimc;
(*feval)(pao, ri, eprim, pcoord, p_exp, pcoeff, env,
l, np, nc, nc*deg, bgrids, bgrids);
img_idx[count] = iL;
count += 1;
}
}
if (count > 0) {
if (img_idx[count-1] != iL0 + count-1) {
// some images are skipped
for (i = 0; i < count; i++) {
j = img_idx[i];
for (k = 0; k < nkpts; k++) {
zLk_buf[i*nkpts+k] = expLk[j*nkpts+k];
}
}
pexpLk = Lk_buf;
} else {
pexpLk = (double *)(expLk + nkpts * iL0);
}
dgemm_(&TRANS_N, &TRANS_T, &dimc, &nkpts2, &count,
&D1, aobuf, &dimc, pexpLk, &nkpts2, &D1, aobufk, &dimc);
}
}
_copy(ao+ao_id*ngrids+offao, aobufk,
ngrids, bgrids, nkpts, ncomp, nao, nc*deg);
}
}
void PBCeval_sph_iter(FPtr_eval feval, FPtr_exp fexp,
size_t nao, size_t ngrids, size_t bgrids, size_t offao,
int param[], int *shls_slice, int *ao_loc, double *buf,
double *Ls, double complex *expLk,
int nimgs, int nkpts, int di_max, double complex *ao,
double *coord, double *rcut, unsigned char *non0table,
int *atm, int natm, int *bas, int nbas, double *env)
{
const int ncomp = param[TENSOR];
const int sh0 = shls_slice[0];
const int sh1 = shls_slice[1];
const char TRANS_N = 'N';
const char TRANS_T = 'T';
const double D1 = 1;
const int nkpts2 = nkpts * OF_CMPLX;
int i, j, k, l, np, nc, atm_id, bas_id, deg, dcart, ao_id;
int iL, iL0, iLcount, dimc;
int grid2atm_atm_id, count;
double fac;
double *p_exp, *pcoeff, *pcoord, *pcart, *pao, *ri;
double *grid2atm = buf; // shape [nimgs,3,bgrids]
double *eprim = grid2atm + nimgs*3*BLKSIZE;
double *aobuf = eprim + NPRIMAX*BLKSIZE*2;
double *aobufk = aobuf + IMGBLK*ncomp*di_max*bgrids;
double *Lk_buf = aobufk + nkpts*ncomp*di_max*bgrids * OF_CMPLX;
double complex *zLk_buf = (double complex *)Lk_buf;
double *cart_gto = Lk_buf + IMGBLK * nkpts * OF_CMPLX;
double *min_grid2atm = cart_gto + ncomp*NCTR_CART*bgrids;
double *pexpLk;
int img_idx[nimgs];
int atm_imag_max[natm];
for (i = 0; i < natm; i++) {
atm_imag_max[i] = 0;
}
for (bas_id = sh0; bas_id < sh1; bas_id++) {
atm_id = bas[bas_id*BAS_SLOTS+ATOM_OF];
atm_imag_max[atm_id] = MAX(atm_imag_max[atm_id], non0table[bas_id]);
}
grid2atm_atm_id = -1;
for (bas_id = sh0; bas_id < sh1; bas_id++) {
np = bas[bas_id*BAS_SLOTS+NPRIM_OF];
nc = bas[bas_id*BAS_SLOTS+NCTR_OF ];
l = bas[bas_id*BAS_SLOTS+ANG_OF ];
deg = l * 2 + 1;
dcart = (l+1)*(l+2)/2;
dimc = nc*deg * ncomp * bgrids;
fac = CINTcommon_fac_sp(l);
p_exp = env + bas[bas_id*BAS_SLOTS+PTR_EXP];
pcoeff = env + bas[bas_id*BAS_SLOTS+PTR_COEFF];
atm_id = bas[bas_id*BAS_SLOTS+ATOM_OF];
ri = env + atm[PTR_COORD+atm_id*ATM_SLOTS];
ao_id = ao_loc[bas_id] - ao_loc[sh0];
if (grid2atm_atm_id != atm_id) {
_fill_grid2atm(grid2atm, min_grid2atm, coord, Ls, ri,
atm_imag_max[atm_id], bgrids, ngrids, nimgs);
grid2atm_atm_id = atm_id;
}
for (i = 0; i < nkpts2*dimc; i++) {
aobufk[i] = 0;
}
for (iL0 = 0; iL0 < nimgs; iL0+=IMGBLK) {
iLcount = MIN(IMGBLK, nimgs - iL0);
count = 0;
for (iL = iL0; iL < iL0+iLcount; iL++) {
pcoord = grid2atm + iL * 3*BLKSIZE;
if ((iL < non0table[bas_id] || non0table[bas_id] == ALL_IMAGES) &&
(min_grid2atm[iL] < rcut[bas_id]) &&
(*fexp)(eprim, pcoord, p_exp, pcoeff, l, np, nc, bgrids, fac)) {
pao = aobuf + count * dimc;
if (l <= 1) { // s, p functions
(*feval)(pao, ri, eprim, pcoord, p_exp, pcoeff, env,
l, np, nc, nc*dcart, bgrids, bgrids);
} else {
(*feval)(cart_gto, ri, eprim, pcoord, p_exp, pcoeff, env,
l, np, nc, nc*dcart, bgrids, bgrids);
pcart = cart_gto;
for (i = 0; i < ncomp * nc; i++) {
CINTc2s_ket_sph1(pao, pcart, bgrids, bgrids, l);
pao += deg * bgrids;
pcart += dcart * bgrids;
}
}
img_idx[count] = iL;
count++;
}
}
if (count > 0) {
if (img_idx[count-1] != iL0 + count-1) {
// some images are skipped
for (i = 0; i < count; i++) {
j = img_idx[i];
for (k = 0; k < nkpts; k++) {
zLk_buf[i*nkpts+k] = expLk[j*nkpts+k];
}
}
pexpLk = Lk_buf;
} else {
pexpLk = (double *)(expLk + nkpts * iL0);
}
dgemm_(&TRANS_N, &TRANS_T, &dimc, &nkpts2, &count,
&D1, aobuf, &dimc, pexpLk, &nkpts2, &D1, aobufk, &dimc);
}
}
_copy(ao+ao_id*ngrids+offao, aobufk,
ngrids, bgrids, nkpts, ncomp, nao, nc*deg);
}
}
int GTOshloc_by_atom(int *shloc, int *shls_slice, int *ao_loc, int *atm, int *bas);
/*
* blksize <= 1024 to avoid stack overflow
*
* non0table[ngrids/blksize,natm] is the T/F table for ao values to
* screen the ao evaluation for each shell
*/
void PBCeval_loop(void (*fiter)(), FPtr_eval feval, FPtr_exp fexp,
int ngrids, int param[], int *shls_slice, int *ao_loc,
double *Ls, int nimgs, double complex *expLk, int nkpts,
double complex *ao, double *coord,
double *rcut, unsigned char *non0table,
int *atm, int natm, int *bas, int nbas, double *env)
{
int shloc[shls_slice[1]-shls_slice[0]+1];
const int nshblk = GTOshloc_by_atom(shloc, shls_slice, ao_loc, atm, bas);
const int nblk = (ngrids+BLKSIZE-1) / BLKSIZE;
const size_t Ngrids = ngrids;
int i;
int di_max = 0;
for (i = shls_slice[0]; i < shls_slice[1]; i++) {
di_max = MAX(di_max, ao_loc[i+1] - ao_loc[i]);
}
#pragma omp parallel
{
const int sh0 = shls_slice[0];
const int sh1 = shls_slice[1];
const size_t nao = ao_loc[sh1] - ao_loc[sh0];
int ip, ib, k, iloc, ish;
size_t aoff, bgrids;
size_t bufsize =((nimgs*3 + NPRIMAX*2 +
nkpts *param[POS_E1]*param[TENSOR]*di_max * OF_CMPLX +
IMGBLK*param[POS_E1]*param[TENSOR]*di_max +
param[POS_E1]*param[TENSOR]*NCTR_CART) * BLKSIZE
+ nkpts * IMGBLK * OF_CMPLX + nimgs);
double *buf = malloc(sizeof(double) * bufsize);
#pragma omp for nowait schedule(dynamic, 1)
for (k = 0; k < nblk*nshblk; k++) {
iloc = k / nblk;
ish = shloc[iloc];
ib = k - iloc * nblk;
ip = ib * BLKSIZE;
aoff = (ao_loc[ish] - ao_loc[sh0]) * Ngrids + ip;
bgrids = MIN(ngrids-ip, BLKSIZE);
(*fiter)(feval, fexp, nao, Ngrids, bgrids, aoff,
param, shloc+iloc, ao_loc, buf,
Ls, expLk, nimgs, nkpts, di_max,
ao, coord+ip, rcut, non0table+ib*nbas,
atm, natm, bas, nbas, env);
}
free(buf);
}
}
void PBCeval_cart_drv(FPtr_eval feval, FPtr_exp fexp,
int ngrids, int param[], int *shls_slice, int *ao_loc,
double *Ls, int nimgs, double complex *expLk, int nkpts,
double complex *ao, double *coord,
double *rcut, unsigned char *non0table,
int *atm, int natm, int *bas, int nbas, double *env)
{
PBCeval_loop(PBCeval_cart_iter, feval, fexp,
ngrids, param, shls_slice, ao_loc, Ls, nimgs, expLk, nkpts,
ao, coord, rcut, non0table, atm, natm, bas, nbas, env);
}
void PBCeval_sph_drv(FPtr_eval feval, FPtr_exp fexp,
int ngrids, int param[], int *shls_slice, int *ao_loc,
double *Ls, int nimgs, double complex *expLk, int nkpts,
double complex *ao, double *coord,
double *rcut, unsigned char *non0table,
int *atm, int natm, int *bas, int nbas, double *env)
{
PBCeval_loop(PBCeval_sph_iter, feval, fexp,
ngrids, param, shls_slice, ao_loc, Ls, nimgs, expLk, nkpts,
ao, coord, rcut, non0table, atm, natm, bas, nbas, env);
}
void PBCGTOval_cart_deriv0(int ngrids, int *shls_slice, int *ao_loc,
double *Ls, int nimgs, double complex *expLk, int nkpts,
double complex *ao, double *coord,
double *rcut, unsigned char *non0table,
int *atm, int natm, int *bas, int nbas, double *env)
{
int param[] = {1, 1};
PBCeval_cart_drv(GTOshell_eval_grid_cart, GTOcontract_exp0,
ngrids, param, shls_slice, ao_loc, Ls, nimgs, expLk, nkpts,
ao, coord, rcut, non0table, atm, natm, bas, nbas, env);
}
void PBCGTOval_sph_deriv0(int ngrids, int *shls_slice, int *ao_loc,
double *Ls, int nimgs, double complex *expLk, int nkpts,
double complex *ao, double *coord,
double *rcut, unsigned char *non0table,
int *atm, int natm, int *bas, int nbas, double *env)
{
int param[] = {1, 1};
PBCeval_sph_drv(GTOshell_eval_grid_cart, GTOcontract_exp0,
ngrids, param, shls_slice, ao_loc, Ls, nimgs, expLk, nkpts,
ao, coord, rcut, non0table, atm, natm, bas, nbas, env);
}
void PBCGTOval_cart_deriv1(int ngrids, int *shls_slice, int *ao_loc,
double *Ls, int nimgs, double complex *expLk, int nkpts,
double complex *ao, double *coord,
double *rcut, unsigned char *non0table,
int *atm, int natm, int *bas, int nbas, double *env)
{
int param[] = {1, 4};
PBCeval_cart_drv(GTOshell_eval_grid_cart_deriv1, GTOcontract_exp1,
ngrids, param, shls_slice, ao_loc, Ls, nimgs, expLk, nkpts,
ao, coord, rcut, non0table, atm, natm, bas, nbas, env);
}
void PBCGTOval_sph_deriv1(int ngrids, int *shls_slice, int *ao_loc,
double *Ls, int nimgs, double complex *expLk, int nkpts,
double complex *ao, double *coord,
double *rcut, unsigned char *non0table,
int *atm, int natm, int *bas, int nbas, double *env)
{
int param[] = {1, 4};
PBCeval_sph_drv(GTOshell_eval_grid_cart_deriv1, GTOcontract_exp1,
ngrids, param, shls_slice, ao_loc, Ls, nimgs, expLk, nkpts,
ao, coord, rcut, non0table, atm, natm, bas, nbas, env);
}
void PBCGTOval_cart_deriv2(int ngrids, int *shls_slice, int *ao_loc,
double *Ls, int nimgs, double complex *expLk, int nkpts,
double complex *ao, double *coord,
double *rcut, unsigned char *non0table,
int *atm, int natm, int *bas, int nbas, double *env)
{
int param[] = {1, 10};
PBCeval_cart_drv(GTOshell_eval_grid_cart_deriv2, GTOprim_exp,
ngrids, param, shls_slice, ao_loc, Ls, nimgs, expLk, nkpts,
ao, coord, rcut, non0table, atm, natm, bas, nbas, env);
}
void PBCGTOval_sph_deriv2(int ngrids, int *shls_slice, int *ao_loc,
double *Ls, int nimgs, double complex *expLk, int nkpts,
double complex *ao, double *coord,
double *rcut, unsigned char *non0table,
int *atm, int natm, int *bas, int nbas, double *env)
{
int param[] = {1, 10};
PBCeval_sph_drv(GTOshell_eval_grid_cart_deriv2, GTOprim_exp,
ngrids, param, shls_slice, ao_loc, Ls, nimgs, expLk, nkpts,
ao, coord, rcut, non0table, atm, natm, bas, nbas, env);
}
void PBCGTOval_cart_deriv3(int ngrids, int *shls_slice, int *ao_loc,
double *Ls, int nimgs, double complex *expLk, int nkpts,
double complex *ao, double *coord,
double *rcut, unsigned char *non0table,
int *atm, int natm, int *bas, int nbas, double *env)
{
int param[] = {1, 20};
PBCeval_cart_drv(GTOshell_eval_grid_cart_deriv3, GTOprim_exp,
ngrids, param, shls_slice, ao_loc, Ls, nimgs, expLk, nkpts,
ao, coord, rcut, non0table, atm, natm, bas, nbas, env);
}
void PBCGTOval_sph_deriv3(int ngrids, int *shls_slice, int *ao_loc,
double *Ls, int nimgs, double complex *expLk, int nkpts,
double complex *ao, double *coord,
double *rcut, unsigned char *non0table,
int *atm, int natm, int *bas, int nbas, double *env)
{
int param[] = {1, 20};
PBCeval_sph_drv(GTOshell_eval_grid_cart_deriv3, GTOprim_exp,
ngrids, param, shls_slice, ao_loc, Ls, nimgs, expLk, nkpts,
ao, coord, rcut, non0table, atm, natm, bas, nbas, env);
}
void PBCGTOval_cart_deriv4(int ngrids, int *shls_slice, int *ao_loc,
double *Ls, int nimgs, double complex *expLk, int nkpts,
double complex *ao, double *coord,
double *rcut, unsigned char *non0table,
int *atm, int natm, int *bas, int nbas, double *env)
{
int param[] = {1, 35};
PBCeval_cart_drv(GTOshell_eval_grid_cart_deriv4, GTOprim_exp,
ngrids, param, shls_slice, ao_loc, Ls, nimgs, expLk, nkpts,
ao, coord, rcut, non0table, atm, natm, bas, nbas, env);
}
void PBCGTOval_sph_deriv4(int ngrids, int *shls_slice, int *ao_loc,
double *Ls, int nimgs, double complex *expLk, int nkpts,
double complex *ao, double *coord,
double *rcut, unsigned char *non0table,
int *atm, int natm, int *bas, int nbas, double *env)
{
int param[] = {1, 35};
PBCeval_sph_drv(GTOshell_eval_grid_cart_deriv4, GTOprim_exp,
ngrids, param, shls_slice, ao_loc, Ls, nimgs, expLk, nkpts,
ao, coord, rcut, non0table, atm, natm, bas, nbas, env);
}
void PBCGTOval_cart(int ngrids, int *shls_slice, int *ao_loc,
double *Ls, int nimgs, double complex *expLk, int nkpts,
double complex *ao, double *coord,
double *rcut, unsigned char *non0table,
int *atm, int natm, int *bas, int nbas, double *env)
{
// int param[] = {1, 1};
// PBCeval_cart_drv(GTOshell_eval_grid_cart, GTOcontract_exp0,
// ngrids, param, shls_slice, ao_loc, Ls, nimgs, expLk, nkpts,
// ao, coord, rcut, non0table, atm, natm, bas, nbas, env);
PBCGTOval_cart_deriv0(ngrids, shls_slice, ao_loc, Ls, nimgs, expLk, nkpts,
ao, coord, rcut, non0table, atm, natm, bas, nbas, env);
}
void PBCGTOval_sph(int ngrids, int *shls_slice, int *ao_loc,
double *Ls, int nimgs, double complex *expLk, int nkpts,
double complex *ao, double *coord,
double *rcut, unsigned char *non0table,
int *atm, int natm, int *bas, int nbas, double *env)
{
// int param[] = {1, 1};
// PBCeval_sph_drv(GTOshell_eval_grid_cart, GTOcontract_exp0,
// ngrids, param, shls_slice, ao_loc, Ls, nimgs, expLk, nkpts,
// ao, coord, rcut, non0table, atm, natm, bas, nbas, env);
PBCGTOval_sph_deriv0(ngrids, shls_slice, ao_loc, Ls, nimgs, expLk, nkpts,
ao, coord, rcut, non0table, atm, natm, bas, nbas, env);
}
void PBCGTOval_ip_cart(int ngrids, int *shls_slice, int *ao_loc,
double *Ls, int nimgs, double complex *expLk, int nkpts,
double complex *ao, double *coord,
double *rcut, unsigned char *non0table,
int *atm, int natm, int *bas, int nbas, double *env)
{
int param[] = {1, 3};
PBCeval_cart_drv(GTOshell_eval_grid_ip_cart, GTOcontract_exp1,
ngrids, param, shls_slice, ao_loc, Ls, nimgs, expLk, nkpts,
ao, coord, rcut, non0table, atm, natm, bas, nbas, env);
}
void PBCGTOval_ip_sph(int ngrids, int *shls_slice, int *ao_loc,
double *Ls, int nimgs, double complex *expLk, int nkpts,
double complex *ao, double *coord,
double *rcut, unsigned char *non0table,
int *atm, int natm, int *bas, int nbas, double *env)
{
int param[] = {1, 3};
PBCeval_sph_drv(GTOshell_eval_grid_ip_cart, GTOcontract_exp1,
ngrids, param, shls_slice, ao_loc, Ls, nimgs, expLk, nkpts,
ao, coord, rcut, non0table, atm, natm, bas, nbas, env);
}
| 45.987749 | 101 | 0.493007 | [
"shape"
] |
769065bd23d776dc6c96a171f87b7071fd3719a6 | 6,068 | c | C | kernels/linux-2.6.24/arch/x86/boot/cpucheck.c | liuhaozzu/linux | bdf9758cd23e34b5f53e8e6339d9b29348615e14 | [
"Apache-2.0"
] | null | null | null | kernels/linux-2.6.24/arch/x86/boot/cpucheck.c | liuhaozzu/linux | bdf9758cd23e34b5f53e8e6339d9b29348615e14 | [
"Apache-2.0"
] | 1 | 2021-04-09T09:24:44.000Z | 2021-04-09T09:24:44.000Z | arch/x86/boot/cpucheck.c | KylinskyChen/linuxCore_2.6.24 | 11e90b14386491cc80477d4015e0c8f673f6d020 | [
"MIT"
] | null | null | null | /* -*- linux-c -*- ------------------------------------------------------- *
*
* Copyright (C) 1991, 1992 Linus Torvalds
* Copyright 2007 rPath, Inc. - All Rights Reserved
*
* This file is part of the Linux kernel, and is made available under
* the terms of the GNU General Public License version 2.
*
* ----------------------------------------------------------------------- */
/*
* arch/i386/boot/cpucheck.c
*
* Check for obligatory CPU features and abort if the features are not
* present. This code should be compilable as 16-, 32- or 64-bit
* code, so be very careful with types and inline assembly.
*
* This code should not contain any messages; that requires an
* additional wrapper.
*
* As written, this code is not safe for inclusion into the kernel
* proper (after FPU initialization, in particular).
*/
#ifdef _SETUP
# include "boot.h"
# include "bitops.h"
#endif
#include <linux/types.h>
#include <asm/cpufeature.h>
#include <asm/processor-flags.h>
#include <asm/required-features.h>
#include <asm/msr-index.h>
struct cpu_features {
int level; /* Family, or 64 for x86-64 */
int model;
u32 flags[NCAPINTS];
};
static struct cpu_features cpu;
static u32 cpu_vendor[3];
static u32 err_flags[NCAPINTS];
static const int req_level = CONFIG_X86_MINIMUM_CPU_FAMILY;
static const u32 req_flags[NCAPINTS] =
{
REQUIRED_MASK0,
REQUIRED_MASK1,
REQUIRED_MASK2,
REQUIRED_MASK3,
REQUIRED_MASK4,
REQUIRED_MASK5,
REQUIRED_MASK6,
REQUIRED_MASK7,
};
#define A32(a,b,c,d) (((d) << 24)+((c) << 16)+((b) << 8)+(a))
static int is_amd(void)
{
return cpu_vendor[0] == A32('A','u','t','h') &&
cpu_vendor[1] == A32('e','n','t','i') &&
cpu_vendor[2] == A32('c','A','M','D');
}
static int is_centaur(void)
{
return cpu_vendor[0] == A32('C','e','n','t') &&
cpu_vendor[1] == A32('a','u','r','H') &&
cpu_vendor[2] == A32('a','u','l','s');
}
static int is_transmeta(void)
{
return cpu_vendor[0] == A32('G','e','n','u') &&
cpu_vendor[1] == A32('i','n','e','T') &&
cpu_vendor[2] == A32('M','x','8','6');
}
static int has_fpu(void)
{
u16 fcw = -1, fsw = -1;
u32 cr0;
asm("movl %%cr0,%0" : "=r" (cr0));
if (cr0 & (X86_CR0_EM|X86_CR0_TS)) {
cr0 &= ~(X86_CR0_EM|X86_CR0_TS);
asm volatile("movl %0,%%cr0" : : "r" (cr0));
}
asm volatile("fninit ; fnstsw %0 ; fnstcw %1"
: "+m" (fsw), "+m" (fcw));
return fsw == 0 && (fcw & 0x103f) == 0x003f;
}
static int has_eflag(u32 mask)
{
u32 f0, f1;
asm("pushfl ; "
"pushfl ; "
"popl %0 ; "
"movl %0,%1 ; "
"xorl %2,%1 ; "
"pushl %1 ; "
"popfl ; "
"pushfl ; "
"popl %1 ; "
"popfl"
: "=&r" (f0), "=&r" (f1)
: "ri" (mask));
return !!((f0^f1) & mask);
}
static void get_flags(void)
{
u32 max_intel_level, max_amd_level;
u32 tfms;
if (has_fpu())
set_bit(X86_FEATURE_FPU, cpu.flags);
if (has_eflag(X86_EFLAGS_ID)) {
asm("cpuid"
: "=a" (max_intel_level),
"=b" (cpu_vendor[0]),
"=d" (cpu_vendor[1]),
"=c" (cpu_vendor[2])
: "a" (0));
if (max_intel_level >= 0x00000001 &&
max_intel_level <= 0x0000ffff) {
asm("cpuid"
: "=a" (tfms),
"=c" (cpu.flags[4]),
"=d" (cpu.flags[0])
: "a" (0x00000001)
: "ebx");
cpu.level = (tfms >> 8) & 15;
cpu.model = (tfms >> 4) & 15;
if (cpu.level >= 6)
cpu.model += ((tfms >> 16) & 0xf) << 4;
}
asm("cpuid"
: "=a" (max_amd_level)
: "a" (0x80000000)
: "ebx", "ecx", "edx");
if (max_amd_level >= 0x80000001 &&
max_amd_level <= 0x8000ffff) {
u32 eax = 0x80000001;
asm("cpuid"
: "+a" (eax),
"=c" (cpu.flags[6]),
"=d" (cpu.flags[1])
: : "ebx");
}
}
}
/* Returns a bitmask of which words we have error bits in */
static int check_flags(void)
{
u32 err;
int i;
err = 0;
for (i = 0; i < NCAPINTS; i++) {
err_flags[i] = req_flags[i] & ~cpu.flags[i];
if (err_flags[i])
err |= 1 << i;
}
return err;
}
/*
* Returns -1 on error.
*
* *cpu_level is set to the current CPU level; *req_level to the required
* level. x86-64 is considered level 64 for this purpose.
*
* *err_flags_ptr is set to the flags error array if there are flags missing.
*/
int check_cpu(int *cpu_level_ptr, int *req_level_ptr, u32 **err_flags_ptr)
{
int err;
memset(&cpu.flags, 0, sizeof cpu.flags);
cpu.level = 3;
if (has_eflag(X86_EFLAGS_AC))
cpu.level = 4;
get_flags();
err = check_flags();
if (test_bit(X86_FEATURE_LM, cpu.flags))
cpu.level = 64;
if (err == 0x01 &&
!(err_flags[0] &
~((1 << X86_FEATURE_XMM)|(1 << X86_FEATURE_XMM2))) &&
is_amd()) {
/* If this is an AMD and we're only missing SSE+SSE2, try to
turn them on */
u32 ecx = MSR_K7_HWCR;
u32 eax, edx;
asm("rdmsr" : "=a" (eax), "=d" (edx) : "c" (ecx));
eax &= ~(1 << 15);
asm("wrmsr" : : "a" (eax), "d" (edx), "c" (ecx));
get_flags(); /* Make sure it really did something */
err = check_flags();
} else if (err == 0x01 &&
!(err_flags[0] & ~(1 << X86_FEATURE_CX8)) &&
is_centaur() && cpu.model >= 6) {
/* If this is a VIA C3, we might have to enable CX8
explicitly */
u32 ecx = MSR_VIA_FCR;
u32 eax, edx;
asm("rdmsr" : "=a" (eax), "=d" (edx) : "c" (ecx));
eax |= (1<<1)|(1<<7);
asm("wrmsr" : : "a" (eax), "d" (edx), "c" (ecx));
set_bit(X86_FEATURE_CX8, cpu.flags);
err = check_flags();
} else if (err == 0x01 && is_transmeta()) {
/* Transmeta might have masked feature bits in word 0 */
u32 ecx = 0x80860004;
u32 eax, edx;
u32 level = 1;
asm("rdmsr" : "=a" (eax), "=d" (edx) : "c" (ecx));
asm("wrmsr" : : "a" (~0), "d" (edx), "c" (ecx));
asm("cpuid"
: "+a" (level), "=d" (cpu.flags[0])
: : "ecx", "ebx");
asm("wrmsr" : : "a" (eax), "d" (edx), "c" (ecx));
err = check_flags();
}
if (err_flags_ptr)
*err_flags_ptr = err ? err_flags : NULL;
if (cpu_level_ptr)
*cpu_level_ptr = cpu.level;
if (req_level_ptr)
*req_level_ptr = req_level;
return (cpu.level < req_level || err) ? -1 : 0;
}
| 23.072243 | 77 | 0.556032 | [
"model"
] |
7690fca06a7e4626cdd7cb8a6beef735d745f0e3 | 1,711 | h | C | Accelerators/Vtkm/vtkmWarpVector.h | forestGzh/VTK | bc98327275bd5cfa95c5825f80a2755a458b6da8 | [
"BSD-3-Clause"
] | 3 | 2015-07-28T18:07:50.000Z | 2018-02-28T20:59:58.000Z | Accelerators/Vtkm/vtkmWarpVector.h | forestGzh/VTK | bc98327275bd5cfa95c5825f80a2755a458b6da8 | [
"BSD-3-Clause"
] | 4 | 2018-10-25T09:46:11.000Z | 2019-01-17T16:49:17.000Z | Accelerators/Vtkm/vtkmWarpVector.h | forestGzh/VTK | bc98327275bd5cfa95c5825f80a2755a458b6da8 | [
"BSD-3-Clause"
] | 4 | 2016-09-08T02:11:00.000Z | 2019-08-15T02:38:39.000Z | //=============================================================================
//
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
//
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//
// Copyright 2012 Sandia Corporation.
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
//=============================================================================
/**
* @class vtkmWarpVector
* @brief deform geometry with vector data
*
* vtkWarpVector is a filter that modifies point coordinates by moving
* points along vector times the scale factor. Useful for showing flow
* profiles or mechanical deformation.
*
* The filter passes both its point data and cell data to its output.
*/
#ifndef vtkmWarpVector_h
#define vtkmWarpVector_h
#include "vtkWarpVector.h"
#include "vtkAcceleratorsVTKmModule.h" // required for correct export
class VTKACCELERATORSVTKM_EXPORT vtkmWarpVector : public vtkWarpVector
{
public:
vtkTypeMacro(vtkmWarpVector, vtkWarpVector)
void PrintSelf(ostream& os, vtkIndent indent) override;
static vtkmWarpVector* New();
protected:
vtkmWarpVector();
~vtkmWarpVector();
int RequestData(vtkInformation* , vtkInformationVector**,
vtkInformationVector*) override;
private:
vtkmWarpVector(const vtkmWarpVector&) = delete;
void operator=(const vtkmWarpVector&) = delete;
};
#endif // vtkmWarpVector_h
// VTK-HeaderTest-Exclude: vtkmWarpVector.h
| 30.553571 | 79 | 0.679135 | [
"geometry",
"vector"
] |
76910c80b50e01e167527339c0935bcaff2c3e62 | 12,334 | h | C | include/xloil/AppObjects.h | cunnane/xloil | 2c66bdbe47b3de4cb97213351bf5f1099a3c11d2 | [
"Apache-2.0"
] | null | null | null | include/xloil/AppObjects.h | cunnane/xloil | 2c66bdbe47b3de4cb97213351bf5f1099a3c11d2 | [
"Apache-2.0"
] | null | null | null | include/xloil/AppObjects.h | cunnane/xloil | 2c66bdbe47b3de4cb97213351bf5f1099a3c11d2 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <xloil/ExportMacro.h>
#include <xloil/ExcelObj.h>
#include <xloil/ExcelRange.h>
#include <xloil/ExcelRef.h>
#include <string>
#include <memory>
#include <vector>
// Forward Declarations from Typelib
struct IDispatch;
namespace Excel {
struct _Application;
struct Window;
struct _Workbook;
struct _Worksheet;
struct Range;
}
namespace xloil
{
/// <summary>
/// Gets the Excel.Application object which is the root of the COM API
/// </summary>
XLOIL_EXPORT Excel::_Application& excelApp() noexcept;
/// <summary>
/// Base class for objects in the object model, not very usefuly directly.
/// </summary>
class XLOIL_EXPORT IAppObject
{
public:
virtual ~IAppObject();
/// <summary>
/// Returns an identifier for the object. This may be a workbook name,
/// window caption or range address.
/// </summary>
/// <returns></returns>
virtual std::wstring name() const = 0;
IDispatch* basePtr() const { return _ptr; }
protected:
IDispatch* _ptr;
IAppObject(IDispatch* ptr = nullptr) { init(ptr); }
void init(IDispatch* ptr);
void assign(const IAppObject& that);
};
class ExcelWindow;
class ExcelWorksheet;
/// <summary>
/// Wraps a Workbook (https://docs.microsoft.com/en-us/office/vba/api/excel.workbook) in
/// Excel's object model but with very limited functionality at present
/// </summary>
class XLOIL_EXPORT ExcelWorkbook : public IAppObject
{
public:
/// <summary>
/// Gives the ExcelWorkbook object associated with the given workbookb name, or the active workbook
/// </summary>
/// <param name="name">The name of the workbook to find, or the active workbook if null</param>
explicit ExcelWorkbook(const std::wstring_view& name = std::wstring_view());
/// <summary>
/// Constructs an ExcelWorkbook from a COM pointer
/// </summary>
/// <param name="p"></param>
ExcelWorkbook(Excel::_Workbook* p) : IAppObject((IDispatch*)p) {}
ExcelWorkbook(ExcelWorkbook&& that) noexcept { std::swap(_ptr, that._ptr); }
ExcelWorkbook(const ExcelWorkbook& that) : IAppObject(that._ptr) {}
ExcelWorkbook& operator=(const ExcelWorkbook& that) noexcept { assign(that); return *this; }
ExcelWorkbook& operator=(ExcelWorkbook&& that) noexcept { std::swap(_ptr, that._ptr); return *this; }
/// <inheritdoc />
std::wstring name() const override;
/// <summary>
/// Returns the full file path and file name for this workbook
/// </summary>
std::wstring path() const;
/// <summary>
/// Returns a list of all Windows associated with this workbook (there can be
/// multiple windows viewing a single workbook).
/// </summary>
/// <returns></returns>
std::vector<ExcelWindow> windows() const;
/// <summary>
/// Returns a list of all Worksheets in this Workbook. It does not include
/// chart sheets
/// </summary>
/// <returns></returns>
std::vector<ExcelWorksheet> worksheets() const;
ExcelWorksheet worksheet(const std::wstring_view& name) const;
/// <summary>
/// Makes this the active workbook
/// </summary>
/// <returns></returns>
void activate() const;
/// <summary>
/// The raw COM ptr to the underlying object. Be sure to correctly inc ref
/// and dec ref any use of it.
/// </summary>
Excel::_Workbook* ptr() const { return (Excel::_Workbook*)_ptr; }
};
/// <summary>
/// Wraps an COM Excel::Window object to avoid exposing the COM typelib
/// </summary>
class XLOIL_EXPORT ExcelWindow : public IAppObject
{
public:
/// <summary>
/// Constructs an ExcelWindow from a COM pointer
/// </summary>
/// <param name="p"></param>
ExcelWindow(Excel::Window* p) : IAppObject((IDispatch*)p) {}
/// <summary>
/// Gives the ExcelWindow object associated with the given window caption, or the active window
/// </summary>
/// <param name="caption">The name of the window to find, or the active window if null</param>
explicit ExcelWindow(const std::wstring_view& caption = std::wstring_view());
ExcelWindow(ExcelWindow&& that) noexcept { std::swap(_ptr, that._ptr); }
ExcelWindow(const ExcelWindow& that) : IAppObject(that._ptr) {}
ExcelWindow& operator=(const ExcelWindow& that) noexcept { assign(that); return *this; }
ExcelWindow& operator=(ExcelWindow&& that) noexcept { std::swap(_ptr, that._ptr); return *this; }
/// <summary>
/// Retuns the Win32 window handle
/// </summary>
/// <returns></returns>
size_t hwnd() const;
/// <summary>
/// Returns the window title
/// </summary>
std::wstring name() const override;
/// <summary>
/// Gives the name of the workbook displayed by this window
/// </summary>
ExcelWorkbook workbook() const;
/// <summary>
/// The raw COM ptr to the underlying object. Be sure to correctly inc ref
/// and dec ref any use of it.
/// </summary>
Excel::Window* ptr() const { return (Excel::Window*)_ptr; }
};
class XLOIL_EXPORT ExcelRange : public Range, public IAppObject
{
public:
/// <summary>
/// Constructs a Range from a address. A local address (not qualified with
/// a workbook name) will refer to the active workbook
/// </summary>
explicit ExcelRange(const std::wstring_view& address);
ExcelRange(const Range& range);
ExcelRange(Excel::Range* range) : IAppObject((IDispatch*)range) {}
ExcelRange(const ExcelRef& ref) : ExcelRange(ref.address()) {}
ExcelRange(ExcelRange&& that) noexcept { std::swap(_ptr, that._ptr); }
ExcelRange(const ExcelRange& that) : IAppObject(that._ptr) {}
ExcelRange& operator=(ExcelRange&& that) noexcept { std::swap(_ptr, that._ptr); return *this; }
ExcelRange& operator=(const ExcelRange& that) noexcept { assign(that); return *this; }
Range* range(
int fromRow, int fromCol,
int toRow = TO_END, int toCol = TO_END) const final override;
/// <summary>
/// Returns a tuple (width, height)
/// </summary>
std::tuple<row_t, col_t> shape() const final override;
/// <summary>
/// Returns the tuple (top row, top column, bottom row, bottom column)
/// which describes the extent of the range, which is assumed rectangular.
/// </summary>
std::tuple<row_t, col_t, row_t, col_t> bounds() const final override;
/// <summary>
/// Returns the address of the range in the form
/// 'SheetNm!A1:Z5'
/// </summary>
std::wstring address(bool local = false) const final override;
/// <summary>
/// Converts the referenced range to an ExcelObj.
/// References to single cells return an ExcelObj of the
/// appropriate type. Multicell refernces return an array.
/// </summary>
ExcelObj value() const final override;
/// <summary>
/// Gets the value at (i, j) as an ExcelObj (zero-based)
/// </summary>
ExcelObj value(row_t i, col_t j) const final override;
/// <summary>
/// Sets all cells in the range to the specified value
/// </summary>
void set(const ExcelObj& value) final override;
void setFormula(const std::wstring_view& formula);
std::wstring formula() final override;
/// <summary>
/// Clears / empties all cells referred to by this ExcelRange.
/// </summary>
void clear() final override;
/// <summary>
/// The range address
/// </summary>
std::wstring name() const override;
/// <summary>
/// The worksheet which contains this range
/// </summary>
ExcelWorksheet parent() const;
/// <summary>
/// The raw COM ptr to the underlying object. Be sure to correctly inc ref
/// and dec ref any use of it.
/// </summary>
Excel::Range* ptr() const { return (Excel::Range*)_ptr; }
Excel::Range* ptr() { return (Excel::Range*)_ptr; }
};
XLOIL_EXPORT ExcelRef refFromComRange(Excel::Range* range);
inline ExcelRef refFromRange(const Range& range)
{
auto excelRange = dynamic_cast<const ExcelRange*>(&range);
if (excelRange)
return refFromComRange(excelRange->ptr());
else
return static_cast<const XllRange&>(range).asRef();
}
/// <summary>
/// Wraps an COM Excel::Window object to avoid exposing the COM typelib
/// </summary>
class XLOIL_EXPORT ExcelWorksheet : public IAppObject
{
public:
/// <summary>
/// Constructs an ExcelWindow from a COM pointer
/// </summary>
/// <param name="p"></param>
ExcelWorksheet(Excel::_Worksheet* p) : IAppObject((IDispatch*)p) {}
ExcelWorksheet(ExcelWorksheet&& that) noexcept { std::swap(_ptr, that._ptr); }
ExcelWorksheet(const ExcelWorksheet& that) : IAppObject(that._ptr) {}
ExcelWorksheet& operator=(const ExcelWorksheet& that) noexcept { assign(that); return *this; }
ExcelWorksheet& operator=(ExcelWorksheet&& that) noexcept { std::swap(_ptr, that._ptr); return *this; }
/// <summary>
/// Returns the window title
/// </summary>
/// <returns></returns>
std::wstring name() const override;
/// <summary>
/// Gives the name of the workbook which owns this sheet
/// </summary>
ExcelWorkbook parent() const;
/// <summary>
/// Returns a range on this worksheet given a (local) address
/// </summary>
ExcelRange range(const std::wstring_view& address) const;
/// <summary>
/// Returns the range on this worksheet starting and ending at the specified
/// rows and columns. Includes the start row and columns and the end row and
/// column, just as Excel's Worksheet.Range behaves.
/// </summary>
ExcelRange range(int fromRow, int fromCol,
int toRow = ExcelRange::TO_END, int toCol = ExcelRange::TO_END) const;
/// <summary>
/// Returns a Range referring to the single cell (i, j) (zero-based indexing)
/// </summary>
ExcelRange cell(int i, int j) const
{
return range(i, j, i, j);
}
/// <summary>
/// Convenience wrapper for cell(i,j)->value()
/// </summary>
ExcelObj value(Range::row_t i, Range::col_t j) const;
/// <summary>
/// Returns the size of the worksheet, which is always (MaxRows, MaxCols).
/// This function exists mainly to provide some polymorphism with Range.
/// </summary>
std::tuple<Range::row_t, Range::col_t> shape() const
{
return std::make_tuple(XL_MAX_ROWS, XL_MAX_COLS);
}
/// <summary>
/// Makes this worksheet the active one in its workbook
/// </summary>
void activate();
/// <summary>
/// Calculates this worksheet
/// </summary>
void calculate();
/// <summary>
/// The raw COM ptr to the underlying object. Be sure to correctly inc ref
/// and dec ref any use of it.
/// </summary>
Excel::_Worksheet* ptr() const { return (Excel::_Worksheet*)_ptr; }
};
namespace App
{
XLOIL_EXPORT ExcelObj Run(const std::wstring& func, const size_t nArgs, const ExcelObj* args[]);
struct XLOIL_EXPORT Workbooks
{
static ExcelWorkbook active();
inline ExcelWorkbook get(const std::wstring_view& name) { return ExcelWorkbook(name); }
static std::vector<ExcelWorkbook> list();
static size_t count();
};
struct XLOIL_EXPORT Windows
{
static ExcelWindow active();
inline ExcelWindow get(const std::wstring_view& name) { return ExcelWindow(name); }
static std::vector<ExcelWindow> list();
static size_t count();
};
struct XLOIL_EXPORT Worksheets
{
static ExcelWorksheet active();
};
struct ExcelInternals
{
/// <summary>
/// The Excel major version number
/// </summary>
int version;
/// <summary>
/// The Windows API process instance handle, castable to HINSTANCE
/// </summary>
void* hInstance;
/// <summary>
/// The Windows API handle for the top level Excel window
/// castable to type HWND
/// </summary>
long long hWnd;
size_t mainThreadId;
};
/// <summary>
/// Returns Excel application state information such as the version number,
/// HINSTANCE, window handle and thread ID.
/// </summary>
XLOIL_EXPORT const ExcelInternals& internals() noexcept;
}
} | 31.870801 | 112 | 0.642209 | [
"object",
"shape",
"vector",
"model"
] |
76954af1b61b7acc3067d51b52d2a1508140bfb6 | 14,209 | h | C | src/mongo/db/s/collection_sharding_runtime.h | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/db/s/collection_sharding_runtime.h | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/db/s/collection_sharding_runtime.h | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2018-present MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* 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
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the Server Side Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#pragma once
#include "mongo/bson/bsonobj.h"
#include "mongo/db/concurrency/d_concurrency.h"
#include "mongo/db/namespace_string.h"
#include "mongo/db/s/collection_sharding_state.h"
#include "mongo/db/s/metadata_manager.h"
#include "mongo/db/s/sharding_migration_critical_section.h"
#include "mongo/db/s/sharding_state_lock.h"
#include "mongo/platform/atomic_word.h"
#include "mongo/util/cancellation.h"
#include "mongo/util/decorable.h"
namespace mongo {
/**
* See the comments for CollectionShardingState for more information on how this class fits in the
* sharding architecture.
*/
class CollectionShardingRuntime final : public CollectionShardingState,
public Decorable<CollectionShardingRuntime> {
CollectionShardingRuntime(const CollectionShardingRuntime&) = delete;
CollectionShardingRuntime& operator=(const CollectionShardingRuntime&) = delete;
public:
CollectionShardingRuntime(ServiceContext* service,
NamespaceString nss,
std::shared_ptr<executor::TaskExecutor> rangeDeleterExecutor);
using CSRLock = ShardingStateLock<CollectionShardingRuntime>;
/**
* Obtains the sharding runtime state for the specified collection. If it does not exist, it
* will be created and will remain active until the collection is dropped or unsharded.
*
* Must be called with some lock held on the specific collection being looked up and the
* returned pointer should never be stored.
*/
static CollectionShardingRuntime* get(OperationContext* opCtx, const NamespaceString& nss);
/**
* Obtains the sharding runtime state from the the specified sharding collection state. The
* returned pointer should never be stored.
*/
static CollectionShardingRuntime* get(CollectionShardingState* css);
ScopedCollectionFilter getOwnershipFilter(OperationContext* opCtx,
OrphanCleanupPolicy orphanCleanupPolicy,
bool supportNonVersionedOperations) override;
ScopedCollectionDescription getCollectionDescription(OperationContext* opCtx) override;
void checkShardVersionOrThrow(OperationContext* opCtx) override;
void appendShardVersion(BSONObjBuilder* builder) override;
size_t numberOfRangesScheduledForDeletion() const override;
/**
* Returns boost::none if the description for the collection is not known yet. Otherwise
* returns the most recently refreshed from the config server metadata.
*
* This method do not check for the shard version that the operation requires and should only
* be used for cases such as checking whether a particular config server update has taken
* effect.
*/
boost::optional<CollectionMetadata> getCurrentMetadataIfKnown();
/**
* Updates the collection's filtering metadata based on changes received from the config server
* and also resolves the pending receives map in case some of these pending receives have
* committed on the config server or have been abandoned by the donor shard.
*
* This method must be called with an exclusive collection lock and it does not acquire any
* locks itself.
*/
void setFilteringMetadata(OperationContext* opCtx, CollectionMetadata newMetadata);
void setFilteringMetadata_withLock(OperationContext* opCtx,
CollectionMetadata newMetadata,
const CSRLock& csrExclusiveLock);
/**
* Marks the collection's filtering metadata as UNKNOWN, meaning that all attempts to check for
* shard version match will fail with StaleConfig errors in order to trigger an update.
*
* It is safe to call this method with only an intent lock on the collection (as opposed to
* setFilteringMetadata which requires exclusive), however note that clearing a collection's
* filtering metadata will interrupt all in-progress orphan cleanups in which case orphaned data
* will remain behind on disk.
*/
void clearFilteringMetadata(OperationContext* opCtx);
/**
* Methods to control the collection's critical section. Methods listed below must be called
* with both the collection lock and CSRLock held in exclusive mode.
*
* In these methods, the CSRLock ensures concurrent access to the critical section.
*/
void enterCriticalSectionCatchUpPhase(const CSRLock&, const BSONObj& reason);
void enterCriticalSectionCommitPhase(const CSRLock&, const BSONObj& reason);
/**
* It transitions the critical section back to the catch up phase.
*/
void rollbackCriticalSectionCommitPhaseToCatchUpPhase(const CSRLock&, const BSONObj& reason);
/**
* Method to control the collection's critical secion. Method listed below must be called with
* the CSRLock in exclusive mode.
*
* In this method, the CSRLock ensures concurrent access to the critical section.
*/
void exitCriticalSection(const CSRLock&, const BSONObj& reason);
/**
* Same semantics than 'exitCriticalSection' but without doing error-checking. Only meant to be
* used when recovering the critical sections in the RecoverableCriticalSectionService.
*/
void exitCriticalSectionNoChecks(const CSRLock&);
/**
* If the collection is currently in a critical section, returns the critical section signal to
* be waited on. Otherwise, returns nullptr.
*
* This method internally acquires the CSRLock in MODE_IS.
*/
boost::optional<SharedSemiFuture<void>> getCriticalSectionSignal(
OperationContext* opCtx, ShardingMigrationCriticalSection::Operation op);
/**
* Schedules documents in `range` for cleanup after any running queries that may depend on them
* have terminated. Does not block. Fails if range overlaps any current local shard chunk.
* Passed kDelayed, an additional delay (configured via server parameter orphanCleanupDelaySecs)
* is added to permit (most) dependent queries on secondaries to complete, too.
*
* Returns a future that will be resolved when the deletion completes or fails. If that
* succeeds, waitForClean can be called to ensure no other deletions are pending for the range.
*/
enum CleanWhen { kNow, kDelayed };
SharedSemiFuture<void> cleanUpRange(ChunkRange const& range,
const UUID& migrationId,
CleanWhen when);
/**
* Waits for all ranges deletion tasks with UUID 'collectionUuid' overlapping range
* 'orphanRange' to be processed, even if the collection does not exist in the storage catalog.
* It will block until the minimum of the operation context's timeout deadline or 'deadline' is
* reached.
*/
static Status waitForClean(OperationContext* opCtx,
const NamespaceString& nss,
const UUID& collectionUuid,
ChunkRange orphanRange,
Date_t deadline);
std::uint64_t getNumMetadataManagerChanges_forTest() {
return _numMetadataManagerChanges;
}
/**
* Initializes the shard version recover/refresh shared semifuture for other threads to wait on
* it.
*
* In this method, the CSRLock ensures concurrent access to the shared semifuture.
*
* To invoke this method, the criticalSectionSignal must not be hold by a different thread.
*/
void setShardVersionRecoverRefreshFuture(SharedSemiFuture<void> future,
CancellationSource cancellationSource,
const CSRLock&);
/**
* If there an ongoing shard version recover/refresh, it returns the shared semifuture to be
* waited on. Otherwise, returns boost::none.
*
* This method internally acquires the CSRLock in MODE_IS.
*/
boost::optional<SharedSemiFuture<void>> getShardVersionRecoverRefreshFuture(
OperationContext* opCtx);
/**
* Resets the shard version recover/refresh shared semifuture to boost::none.
*
* In this method, the CSRLock ensures concurrent access to the shared semifuture.
*/
void resetShardVersionRecoverRefreshFuture(const CSRLock&);
private:
friend CSRLock;
struct ShardVersionRecoverOrRefresh {
public:
ShardVersionRecoverOrRefresh(SharedSemiFuture<void> future,
CancellationSource cancellationSource)
: future(std::move(future)), cancellationSource(std::move(cancellationSource)){};
// Tracks ongoing shard version recover/refresh.
SharedSemiFuture<void> future;
// Cancellation source to cancel the ongoing recover/refresh shard version.
CancellationSource cancellationSource;
};
/**
* Returns the latest version of collection metadata with filtering configured for
* atClusterTime if specified.
*/
std::shared_ptr<ScopedCollectionDescription::Impl> _getCurrentMetadataIfKnown(
const boost::optional<LogicalTime>& atClusterTime);
/**
* Returns the latest version of collection metadata with filtering configured for
* atClusterTime if specified. Throws StaleConfigInfo if the shard version attached to the
* operation context does not match the shard version on the active metadata object.
*/
std::shared_ptr<ScopedCollectionDescription::Impl> _getMetadataWithVersionCheckAt(
OperationContext* opCtx,
const boost::optional<mongo::LogicalTime>& atClusterTime,
bool supportNonVersionedOperations = false);
// The service context under which this instance runs
ServiceContext* const _serviceContext;
// Namespace this state belongs to.
const NamespaceString _nss;
// The executor used for deleting ranges of orphan chunks.
std::shared_ptr<executor::TaskExecutor> _rangeDeleterExecutor;
// Object-wide ResourceMutex to protect changes to the CollectionShardingRuntime or objects held
// within (including the MigrationSourceManager, which is a decoration on the CSR). Use only the
// CSRLock to lock this mutex.
Lock::ResourceMutex _stateChangeMutex;
// Tracks the migration critical section state for this collection.
// Must hold CSRLock while accessing.
ShardingMigrationCriticalSection _critSec;
// Protects state around the metadata manager below
mutable Mutex _metadataManagerLock =
MONGO_MAKE_LATCH("CollectionShardingRuntime::_metadataManagerLock");
// Tracks whether the filtering metadata is unknown, unsharded, or sharded
enum class MetadataType { kUnknown, kUnsharded, kSharded } _metadataType;
// If the collection is sharded, contains all the metadata associated with this collection.
//
// If the collection is unsharded, the metadata has not been set yet, or the metadata has been
// specifically reset by calling clearFilteringMetadata(), this will be nullptr;
std::shared_ptr<MetadataManager> _metadataManager;
// Used for testing to check the number of times a new MetadataManager has been installed.
std::uint64_t _numMetadataManagerChanges{0};
// Tracks ongoing shard version recover/refresh. Eventually set to the semifuture to wait on and
// a CancellationSource to cancel it
boost::optional<ShardVersionRecoverOrRefresh> _shardVersionInRecoverOrRefresh;
};
/**
* RAII-style class, which obtains a reference to the critical section for the specified collection.
*
*
* Shard version recovery/refresh procedures always wait for the critical section to be released in
* order to serialise with concurrent moveChunk/shardCollection commit operations.
*
* Entering the critical section doesn't serialise with concurrent recovery/refresh, because
* causally such refreshes would have happened *before* the critical section was entered.
*/
class CollectionCriticalSection {
CollectionCriticalSection(const CollectionCriticalSection&) = delete;
CollectionCriticalSection& operator=(const CollectionCriticalSection&) = delete;
public:
CollectionCriticalSection(OperationContext* opCtx, NamespaceString nss, BSONObj reason);
~CollectionCriticalSection();
/**
* Enters the commit phase of the critical section and blocks reads.
*/
void enterCommitPhase();
private:
OperationContext* const _opCtx;
NamespaceString _nss;
const BSONObj _reason;
};
} // namespace mongo
| 44.264798 | 100 | 0.712999 | [
"object"
] |
7698eb39f9728a4dc068cac1088ebc812de1956d | 2,390 | h | C | projects/biogears/libBiogears/include/biogears/cdm/properties/SEFunctionElectricPotentialVsTime.h | ajbaird/core | 81fa9ba41efe07c3c0dacf0cad7bb4e3016a99b5 | [
"Apache-2.0"
] | 42 | 2018-05-15T18:10:15.000Z | 2022-02-16T23:50:18.000Z | projects/biogears/libBiogears/include/biogears/cdm/properties/SEFunctionElectricPotentialVsTime.h | ajbaird/core | 81fa9ba41efe07c3c0dacf0cad7bb4e3016a99b5 | [
"Apache-2.0"
] | 57 | 2018-07-17T20:25:36.000Z | 2022-01-18T20:44:49.000Z | projects/biogears/libBiogears/include/biogears/cdm/properties/SEFunctionElectricPotentialVsTime.h | jules-bergmann/biogears-core | 92e13287cd2b878a75a47190f09e694d57c16e43 | [
"Apache-2.0"
] | 51 | 2018-07-05T16:12:45.000Z | 2022-02-14T20:53:30.000Z | /**************************************************************************************
Copyright 2015 Applied Research Associates, Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the License
at:
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under
the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
**************************************************************************************/
#pragma once
#include <biogears/cdm/properties/SEFunction.h>
#include <biogears/schema/cdm/Properties.hxx>
namespace biogears {
class TimeUnit;
class ElectricPotentialUnit;
namespace io {
class Property;
}
class BIOGEARS_API SEFunctionElectricPotentialVsTime : public SEFunction {
public:
friend io::Property;
SEFunctionElectricPotentialVsTime();
virtual ~SEFunctionElectricPotentialVsTime();
virtual void Clear();
virtual bool Load(const CDM::FunctionElectricPotentialVsTimeData& in);
virtual CDM::FunctionElectricPotentialVsTimeData* Unload() const;
protected:
virtual void Unload(CDM::FunctionElectricPotentialVsTimeData& data) const;
public:
double GetIndependentValue(unsigned int index) = delete;
virtual double GetTimeValue(unsigned int index, const TimeUnit& unit);
virtual std::vector<double>& GetTime();
virtual const TimeUnit* GetTimeUnit();
virtual void SetTimeUnit(const TimeUnit& unit);
double GetDependentValue(unsigned int index) = delete;
virtual double GetElectricPotentialValue(unsigned int index, const ElectricPotentialUnit& unit);
virtual std::vector<double>& GetElectricPotential();
virtual const ElectricPotentialUnit* GetElectricPotentialUnit();
virtual void SetElectricPotentialUnit(const ElectricPotentialUnit& unit);
virtual SEFunctionElectricPotentialVsTime* InterpolateToTime(std::vector<double>& Independent, const TimeUnit& unit);
bool operator==(const SEFunctionElectricPotentialVsTime&) const ;
bool operator!=(const SEFunctionElectricPotentialVsTime&) const;
protected:
const TimeUnit* m_TimeUnit;
const ElectricPotentialUnit* m_ElectricPotentialUnit;
};
} | 41.206897 | 119 | 0.746025 | [
"vector"
] |
769d9be2684ad2a6cca1807e9f38ccfe6b0419ed | 8,549 | c | C | fifolib/fifo_static.c | trijezdci/C-Collections | 0d5671846f59f3bba69793004648cc1c3bf78800 | [
"BSD-3-Clause"
] | 1 | 2021-08-06T02:47:18.000Z | 2021-08-06T02:47:18.000Z | fifolib/fifo_static.c | trijezdci/C-Collections | 0d5671846f59f3bba69793004648cc1c3bf78800 | [
"BSD-3-Clause"
] | null | null | null | fifolib/fifo_static.c | trijezdci/C-Collections | 0d5671846f59f3bba69793004648cc1c3bf78800 | [
"BSD-3-Clause"
] | 2 | 2021-08-06T02:47:37.000Z | 2021-12-16T12:25:48.000Z | /* FIFO Storage Library
*
* @file fifo_static.c
* Static queue implementation
*
* Universal Static Queue
*
* Author: Benjamin Kowarsch
*
* Copyright (C) 2009 Benjamin Kowarsch. All rights reserved.
*
* License:
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met
*
* 1) NO FEES may be charged for the provision of the software. The software
* may NOT be published on websites that contain advertising, unless
* specific prior written permission has been obtained.
*
* 2) Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 3) Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and other materials provided with the distribution.
*
* 4) Neither the author's name nor the names of any contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* 5) Where this list of conditions or the following disclaimer, in part or
* as a whole is overruled or nullified by applicable law, no permission
* is granted to use the software.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "../common/alloc.h"
#include "../common/common.h"
#include "fifo_static.h"
// ---------------------------------------------------------------------------
// Static queue type
// ---------------------------------------------------------------------------
typedef struct /* fifo_s */ {
cardinal size;
cardinal entry_count;
cardinal head;
cardinal tail;
fifo_data_t value[0];
} fifo_s;
// ---------------------------------------------------------------------------
// function: fifo_new_queue( size, status )
// ---------------------------------------------------------------------------
//
// Creates and returns a new queue object with a storage capacity of <size>.
// If zero is passed in for <size>, then the new queue object will be created
// with a capacity of FIFO_DEFAULT_QUEUE_SIZE. Returns NULL if the queue
// object could not be created.
//
// The status of the operation is passed back in <status>, unless NULL was
// passed in for <status>.
fifo_t fifo_new_queue(cardinal size, fifo_status_t *status) {
fifo_s *new_queue;
if (size == 0) {
size = FIFO_DEFAULT_QUEUE_SIZE;
} // end if
// allocate new queue
new_queue = ALLOCATE(sizeof(fifo_s) + size * sizeof(fifo_data_t));
// bail out if allocation failed
if (new_queue == NULL) {
ASSIGN_BY_REF(status, FIFO_ALLOCATION_FAILED);
return NULL;
} // end if
// initialise the new queue
new_queue->size = size;
new_queue->entry_count = 0;
new_queue->head = 0;
new_queue->tail = 0;
new_queue->value[0] = NULL;
// pass status and queue to caller
ASSIGN_BY_REF(status, FIFO_STATUS_SUCCESS);
return (fifo_t) new_queue;
} // end fifo_new_queue
// ---------------------------------------------------------------------------
// function: fifo_enqueue( queue, value, status )
// ---------------------------------------------------------------------------
//
// Adds a new entry <value> to the head of queue <queue> and returns <queue>.
// The new entry is added by reference, NO data is copied. If the queue is
// full, then NO new entry is added to <queue> and NULL is returned. The
// function fails if NULL is passed in for <queue> or <value>.
//
// The status of the operation is passed back in <status>, unless NULL was
// passed in for <status>.
fifo_t *fifo_enqueue(fifo_t queue, fifo_data_t value, fifo_status_t *status) {
fifo_s *this_queue = (fifo_s *) queue;
// bail out if queue is NULL
if (queue == NULL) {
ASSIGN_BY_REF(status, FIFO_STATUS_INVALID_QUEUE);
return queue;
} // end if
// bail out if value is NULL
if (value == NULL) {
ASSIGN_BY_REF(status, FIFO_STATUS_INVALID_DATA);
return queue;
} // end if
// check if queue is full
if (this_queue->entry_count == this_queue->size) {
ASSIGN_BY_REF(status, FIFO_STATUS_QUEUE_OVERFLOW);
return queue;
} // end if
this_queue->value[this_queue->head] = value;
this_queue->entry_count++;
this_queue->head++;
if (this_queue->head >= this_queue->size)
this_queue->head = 0;
ASSIGN_BY_REF(status, FIFO_STATUS_SUCCESS);
return (fifo_t) this_queue;
} // end fifo_enqueue
// ---------------------------------------------------------------------------
// function: fifo_dequeue( queue, status )
// ---------------------------------------------------------------------------
//
// Removes the oldest value from the tail of queue <queue> and returns it. If
// the queue is empty, then NULL is returned.
//
// The function fails if NULL is passed in for <queue>. The status of the op-
// eration is passed back in <status>, unless NULL was passed in for <status>.
fifo_data_t fifo_dequeue(fifo_t queue, fifo_status_t *status) {
fifo_s *this_queue = (fifo_s *) queue;
cardinal oldest;
// bail out if queue is NULL
if (queue == NULL) {
ASSIGN_BY_REF(status, FIFO_STATUS_INVALID_QUEUE);
return NULL;
} // end if
if (this_queue->entry_count == 0) {
ASSIGN_BY_REF(status, FIFO_STATUS_QUEUE_EMPTY);
return NULL;
} // end if
oldest = this_queue->tail;
this_queue->entry_count--;
this_queue->tail++;
if (this_queue->tail >= this_queue->size)
this_queue->tail = 0;
ASSIGN_BY_REF(status, FIFO_STATUS_SUCCESS);
return this_queue->value[oldest];
} // end fifo_dequeue
// ---------------------------------------------------------------------------
// function: fifo_queue_size( queue )
// ---------------------------------------------------------------------------
//
// Returns the total capacity of <queue>, returns zero if NULL is passed in
// for <queue>.
cardinal fifo_queue_size(fifo_t queue) {
fifo_s *this_queue = (fifo_s *) queue;
// bail out if queue is NULL
if (queue == NULL)
return 0;
return this_queue->size;
} // end fifo_queue_size
// ---------------------------------------------------------------------------
// function: fifo_number_of_entries( queue )
// ---------------------------------------------------------------------------
//
// Returns the number of entries stored in <queue>, returns zero if NULL is
// passed in for <queue>.
cardinal fifo_number_of_entries(fifo_t queue) {
fifo_s *this_queue = (fifo_s *) queue;
// bail out if queue is NULL
if (queue == NULL)
return 0;
return this_queue->entry_count;
} // end fifo_number_of_entries
// ---------------------------------------------------------------------------
// function: fifo_queue_is_resizable( queue )
// ---------------------------------------------------------------------------
//
// Returns false.
bool fifo_queue_is_resizable(fifo_t queue) {
return false;
} // end fifo_queue_is_resizable
// ---------------------------------------------------------------------------
// function: fifo_dispose_queue( queue )
// ---------------------------------------------------------------------------
//
// Disposes of queue object <queue>. Returns NULL.
fifo_t *fifo_dispose_queue(fifo_t queue) {
DEALLOCATE(queue);
return NULL;
} // end fifo_dispose_queue
// END OF FILE
| 33.135659 | 78 | 0.573517 | [
"object"
] |
76a2c5be5c25910a61206538bde7d68bbe7446ef | 8,099 | h | C | src/tests/vcl.math/poisson.h | bfierz/vcl | 6ef8d446b6a2f46543a5b3f9f76cad0d8f691969 | [
"MIT"
] | 15 | 2015-05-15T09:14:42.000Z | 2022-02-20T13:00:17.000Z | src/tests/vcl.math/poisson.h | bfierz/vcl | 6ef8d446b6a2f46543a5b3f9f76cad0d8f691969 | [
"MIT"
] | 54 | 2015-05-14T09:21:51.000Z | 2021-05-28T06:09:06.000Z | src/tests/vcl.math/poisson.h | bfierz/vcl | 6ef8d446b6a2f46543a5b3f9f76cad0d8f691969 | [
"MIT"
] | 4 | 2017-04-18T06:16:42.000Z | 2021-07-16T08:00:12.000Z | /*
* This file is part of the Visual Computing Library (VCL) release under the
* MIT license.
*
* Copyright (c) 2014-2016 Basil Fierz
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#pragma once
// VCL configuration
#include <vcl/config/global.h>
#include <vcl/config/eigen.h>
// VCL
#include <vcl/math/solver/jacobi.h>
#include <vcl/math/math.h>
VCL_BEGIN_EXTERNAL_HEADERS
// Google test
#include <gtest/gtest.h>
VCL_END_EXTERNAL_HEADERS
inline Eigen::MatrixXf createStencilMatrix1D(unsigned int size, std::vector<unsigned char>& boundary)
{
Eigen::MatrixXf stencil;
stencil.setZero(size, size);
for (Eigen::MatrixXf::Index i = 0; i < static_cast<Eigen::MatrixXf::Index>(size); i++)
{
if (!boundary[i])
{
if (i < (size - 1))
{
stencil(i, i) -= 1;
stencil(i, i + 1) = 1;
}
if (i > 0)
{
stencil(i, i) -= 1;
stencil(i, i - 1) = 1;
}
} else
{
stencil(i, i) = 1;
}
}
return stencil;
}
class GenericPoissonJacobiCtx : public Vcl::Mathematics::Solver::JacobiContext
{
using real_t = float;
using matrix_t = Eigen::Matrix<real_t, Eigen::Dynamic, Eigen::Dynamic>;
using vector_t = Eigen::Matrix<real_t, Eigen::Dynamic, 1>;
using map_t = Eigen::Map<vector_t>;
public:
GenericPoissonJacobiCtx(unsigned int size)
: _size(size)
, _unknowns(nullptr, size)
, _rhs(nullptr, size)
{
_next.setZero(size);
}
void setData(map_t unknowns, map_t rhs)
{
new (&_unknowns) map_t(unknowns);
new (&_rhs) map_t(rhs);
}
void updatePoissonStencil(real_t h, real_t k, real_t o, Eigen::Map<const Eigen::Matrix<unsigned char, Eigen::Dynamic, 1>> skip)
{
std::vector<unsigned char> boundary(skip.data(), skip.data() + skip.size());
const real_t s = k / (h * h);
_M = s * createStencilMatrix1D(_size, boundary);
_M += vector_t::Constant(_M.rows(), o).asDiagonal();
_D = (1.0f / (_M.diagonal()).array()).matrix().asDiagonal();
for (int i = 0; i < skip.size(); i++)
{
if (skip[i] != 0)
_D(i, i) = 0;
}
_R = _M;
_R.diagonal().setZero();
}
int size() const override
{
return static_cast<int>(_size);
}
void precompute() override
{
_error = 0;
}
// A x = b
// -> A = D + R
// -> x^{n+1} = D^-1 (b - R x^{n})
void updateSolution() override
{
auto& unknowns = _unknowns;
auto& rhs = _rhs;
// x^{n+1} = D^-1 (b - R x^{n})
_next = _D * (rhs - _R * unknowns);
for (int i = 0; i < unknowns.size(); i++)
{
if (_D(i, i) != 0)
unknowns(i) = _next(i);
}
auto e = rhs - _M * unknowns;
_error = e.squaredNorm();
}
//
double computeError() override
{
return double(sqrt(_error) / size());
}
//! Ends the solver and returns the residual
void finish(double*) override {}
private:
//! Dimensions of the grid
unsigned int _size;
//! Current error
float _error{ 0 };
//! Laplacian matrix
matrix_t _M;
matrix_t _D;
matrix_t _R;
//! Left-hand side
map_t _unknowns;
//! Right-hand side
map_t _rhs;
//! Temporary buffer for the updated solution
vector_t _next;
};
// Example with exact solution taken from
// Burkardt - Jacobi Iterative Solution of Poisson's Equation in 1D
inline unsigned int createPoisson1DProblem(float& h, Eigen::VectorXf& rhs, Eigen::VectorXf& sol, std::vector<unsigned char>& boundary)
{
// Number of points
unsigned int nr_pts = 33;
// Domain [0, 1]
h = 1.0f / static_cast<float>(nr_pts - 1);
// Right-hand side and exact solution of the poisson problem
rhs.setZero(nr_pts);
sol.setZero(nr_pts);
for (Eigen::VectorXf::Index i = 0; i < static_cast<Eigen::VectorXf::Index>(nr_pts); i++)
{
float x = i * h;
rhs(i) = -x * (x + 3) * exp(x);
sol(i) = x * (x - 1) * exp(x);
}
// Configure boundary condition
boundary.assign(nr_pts, 0);
boundary[0] = 1;
boundary[nr_pts - 1] = 1;
rhs(0) = 0;
sol(0) = 0;
rhs(nr_pts - 1) = 0;
sol(nr_pts - 1) = 0;
return nr_pts;
}
inline unsigned int createPoisson2DProblem(float& h, Eigen::VectorXf& rhs, Eigen::VectorXf& sol, std::vector<unsigned char>& boundary)
{
using Vcl::Mathematics::pi;
// Number of points
unsigned int nr_pts = 16;
// Domain [0, 1] x [0, 1]
h = 1.0f / static_cast<float>(nr_pts - 1);
// Right-hand side and exact solution of the poisson problem
rhs.setZero(nr_pts * nr_pts);
sol.setZero(nr_pts * nr_pts);
boundary.assign(nr_pts * nr_pts, 0);
for (Eigen::VectorXf::Index j = 0; j < static_cast<Eigen::VectorXf::Index>(nr_pts); j++)
{
for (Eigen::VectorXf::Index i = 0; i < static_cast<Eigen::VectorXf::Index>(nr_pts); i++)
{
float x = 0 + i * h;
float y = 0 + j * h;
sol(j * nr_pts + i) = sin(pi<float>() * x) * sin(pi<float>() * y);
rhs(j * nr_pts + i) = 2 * pi<float>() * pi<float>() * sin(pi<float>() * x) * sin(pi<float>() * y);
if (i == 0 || i == nr_pts - 1 || j == 0 || j == nr_pts - 1)
boundary[j * nr_pts + i] = 1;
}
}
return nr_pts;
}
inline unsigned int createPoisson3DProblem(float& h, Eigen::VectorXf& rhs, Eigen::VectorXf& sol, std::vector<unsigned char>& boundary)
{
using Vcl::Mathematics::pi;
// Number of points
unsigned int nr_pts = 8;
// Domain [0, 1] x [0, 1] x [0, 1]
h = 1.0f / static_cast<float>(nr_pts - 1);
// Right-hand side and exact solution of the poisson problem
rhs.setZero(nr_pts * nr_pts * nr_pts);
sol.setZero(nr_pts * nr_pts * nr_pts);
boundary.assign(nr_pts * nr_pts * nr_pts, 0);
for (Eigen::VectorXf::Index k = 0; k < static_cast<Eigen::VectorXf::Index>(nr_pts); k++)
{
for (Eigen::VectorXf::Index j = 0; j < static_cast<Eigen::VectorXf::Index>(nr_pts); j++)
{
for (Eigen::VectorXf::Index i = 0; i < static_cast<Eigen::VectorXf::Index>(nr_pts); i++)
{
float x = 0 + i * h;
float y = 0 + j * h;
float z = 0 + k * h;
sol(k * nr_pts * nr_pts + j * nr_pts + i) = sin(pi<float>() * x) * sin(pi<float>() * y) * sin(pi<float>() * z);
rhs(k * nr_pts * nr_pts + j * nr_pts + i) = 3 * pi<float>() * pi<float>() * sin(pi<float>() * x) * sin(pi<float>() * y) * sin(pi<float>() * z);
if (i == 0 || i == nr_pts - 1 || j == 0 || j == nr_pts - 1 || k == 0 || k == nr_pts - 1)
boundary[k * nr_pts * nr_pts + j * nr_pts + i] = 1;
}
}
}
return nr_pts;
}
template<typename Solver, typename Ctx, typename Dim>
void runPoissonTest(Dim dim, float h, Eigen::VectorXf& lhs, Eigen::VectorXf& rhs, const Eigen::VectorXf& sol, const std::vector<unsigned char>& skip, int max_iters, float eps)
{
Eigen::Map<Eigen::VectorXf> x(lhs.data(), lhs.size());
Eigen::Map<Eigen::VectorXf> y(rhs.data(), rhs.size());
Eigen::Map<const Eigen::Matrix<unsigned char, Eigen::Dynamic, 1>> boundary(skip.data(), (int64_t)skip.size());
Ctx ctx{ dim };
ctx.updatePoissonStencil(h, -1, 0, boundary);
ctx.setData(x, y);
// Execute the poisson solver
Solver solver;
solver.setMaxIterations(max_iters);
solver.solve(&ctx);
// Check for the solution
Eigen::VectorXf err;
err.setZero(sol.size());
for (Eigen::VectorXf::Index i = 0; i < sol.size(); i++)
{
err(i) = fabs(lhs(i) - sol(i));
}
Eigen::VectorXf::Index max_err_idx;
EXPECT_LE(err.maxCoeff(&max_err_idx), eps) << "Maximum error at index " << max_err_idx;
}
| 27.454237 | 175 | 0.644154 | [
"vector"
] |
76a4401da18487870056aba16a156e16c080816c | 2,211 | h | C | SimG4CMS/Calo/interface/HFNoseSD.h | trackerpro/cmssw | 3e05774a180a5f4cdc70b713bd711c23f9364765 | [
"Apache-2.0"
] | 1 | 2019-03-09T19:47:49.000Z | 2019-03-09T19:47:49.000Z | SimG4CMS/Calo/interface/HFNoseSD.h | trackerpro/cmssw | 3e05774a180a5f4cdc70b713bd711c23f9364765 | [
"Apache-2.0"
] | null | null | null | SimG4CMS/Calo/interface/HFNoseSD.h | trackerpro/cmssw | 3e05774a180a5f4cdc70b713bd711c23f9364765 | [
"Apache-2.0"
] | 1 | 2019-04-03T19:23:27.000Z | 2019-04-03T19:23:27.000Z | #ifndef SimG4CMS_HFNoseSD_h
#define SimG4CMS_HFNoseSD_h
///////////////////////////////////////////////////////////////////////////////
// File: HFNoseSD.h
// Description: Stores hits of the High Granularity Calorimeter (HGC) in the
// appropriate container (post TDR version)
///////////////////////////////////////////////////////////////////////////////
#include "SimG4CMS/Calo/interface/CaloSD.h"
#include "SimG4Core/Notification/interface/BeginOfJob.h"
#include "SimG4CMS/Calo/interface/HFNoseNumberingScheme.h"
#include "SimG4CMS/Calo/interface/HGCMouseBite.h"
#include <string>
class DDCompactView;
class HGCalDDDConstants;
class G4LogicalVolume;
class G4Step;
class HFNoseSD : public CaloSD, public Observer<const BeginOfJob *> {
public:
HFNoseSD(const std::string& , const DDCompactView &,
const SensitiveDetectorCatalog &,
edm::ParameterSet const &, const SimTrackManager*);
~HFNoseSD() override = default;
uint32_t setDetUnitId(const G4Step* step) override;
protected:
double getEnergyDeposit(const G4Step*) override;
using CaloSD::update;
void update(const BeginOfJob *) override;
void initRun() override;
bool filterHit(CaloG4Hit*, double) override;
private:
uint32_t setDetUnitId(int, int, int, int, G4ThreeVector &);
bool isItinFidVolume (const G4ThreeVector&);
const HGCalDDDConstants* hgcons_;
std::unique_ptr<HFNoseNumberingScheme> numberingScheme_;
std::unique_ptr<HGCMouseBite> mouseBite_;
std::string nameX_;
HGCalGeometryMode::GeometryMode geom_mode_;
double eminHit_, slopeMin_, weight_;
double mouseBiteCut_, distanceFromEdge_;
int levelT1_, levelT2_, cornerMinMask_;
bool storeAllG4Hits_;
bool fiducialCut_, rejectMB_, waferRot_;
const double tan30deg_;
std::vector<double> angles_;
};
#endif // HFNoseSD_h
| 36.85 | 79 | 0.574853 | [
"vector"
] |
76a6b799959e16baa2169c5ea8918f2120fe6a96 | 852 | h | C | satlib/inc/AcisExppcCurv.h | humkyung/app.framework | 6a709c0ccc6a78e66ad8638b2db9d560da5ee77a | [
"MIT"
] | null | null | null | satlib/inc/AcisExppcCurv.h | humkyung/app.framework | 6a709c0ccc6a78e66ad8638b2db9d560da5ee77a | [
"MIT"
] | null | null | null | satlib/inc/AcisExppcCurv.h | humkyung/app.framework | 6a709c0ccc6a78e66ad8638b2db9d560da5ee77a | [
"MIT"
] | null | null | null | #pragma once
#include <Aciscurve.h>
class ON_EXT_CLASS AcisExppcCurv : public AcisCurve
{
public:
AcisExppcCurv(const TCHAR*,const long& nIndex);
~AcisExppcCurv(void);
int degree() const;
int knots() const;
int params() const;
bool Parse(AcisDoc*,const TCHAR*);
AcisEntity* subtype();
typedef vector<AcisCurve::Knot>::const_iterator knot_iterator;
knot_iterator knot_begin() { return m_pKnots->begin(); }
knot_iterator knot_end() { return m_pKnots->end(); }
typedef vector<AcisCurve::Param>::const_iterator param_iterator;
param_iterator begin() { return m_pParams->begin(); }
param_iterator end() { return m_pParams->end(); }
ACISLIB_DECLARE_FUNC(AcisExppcCurv)
private:
int m_iDegree , m_iKnots;
vector<AcisCurve::Knot>* m_pKnots;
vector<AcisCurve::Param>* m_pParams;
AcisEntity* m_pSubType;
};
| 26.625 | 66 | 0.721831 | [
"vector"
] |
76a80901768eedeb28557aa05007e0a7208438ef | 3,497 | c | C | src/util/data_structure/list.c | inu1997/RPilot | 26e79fbe25b1ed7bc42bda57a29d4fdf6a164531 | [
"MIT"
] | 1 | 2021-11-02T03:01:25.000Z | 2021-11-02T03:01:25.000Z | src/util/data_structure/list.c | inu1997/raspi-pilot | 26e79fbe25b1ed7bc42bda57a29d4fdf6a164531 | [
"MIT"
] | null | null | null | src/util/data_structure/list.c | inu1997/raspi-pilot | 26e79fbe25b1ed7bc42bda57a29d4fdf6a164531 | [
"MIT"
] | null | null | null | #include "list.h"
#include "util/logger.h"
#include "util/debug.h"
#include <stdlib.h>
#include <stdarg.h>
struct Node {
void *object;
struct Node *next;
};
struct List {
struct Node *head;
};
/**
* @brief Initiator of list.
*
* @return Newly created list structure.
*/
struct List *list_init() {
struct List *l = malloc(sizeof(struct List));
l->head = NULL;
return l;
}
/**
* @brief Destroyer of list.
*
* @param l
* The list.
* @return Count of objects the list used to hold.
*/
int list_destroy(struct List *l) {
int cnt = 0;
struct Node *tmp;
struct Node *node = l->head;
while(node != NULL) {
tmp = node;
node = node->next;
free(tmp);
cnt++;
}
free(l);
return cnt;
}
/**
* @brief Add object to list.
*
* @param l
* The list.
* @param object
* The object.
* @return Count of objects after adding to list.
*/
int list_add(struct List *l, void *object) {
struct Node *new_node = malloc(sizeof(struct Node));
new_node->object = object;
new_node->next = NULL;
int cnt = 1;
if (l->head == NULL) {
// Handle first add.
l->head = new_node;
} else {
struct Node *prev;
struct Node *node = l->head;
while(node != NULL) {
prev = node;
node = node->next;
cnt++;
}
prev->next = new_node;
}
return cnt;
}
/**
* @brief Remove object(recognized by address) from list.
*
* @param l
* The list.
* @param object
* The object.
* @return 0 if success else -1.
*/
int list_remove(struct List *l, void *object) {
int ret = -1;
if (l->head->object == object) {
// Handle remove first object.
struct Node *orig_head = l->head;
l->head = l->head->next;
ret = 0;
free(orig_head);
} else {
struct Node *node = l->head;
struct Node *prev;
while(node != NULL) {
prev = node;
node = node->next;
if (node != NULL) {
if (node->object == object) {
// Found object.
prev->next = node->next;
free(node);
ret = 0;
break;
}
}
}
}
return ret;
}
/**
* @brief Find the first object from list.
*
* @param l
* The list.
* @param object
* The object.
* @return Index of object else -1(Not found).
*/
int list_find(struct List *l, void *object) {
struct Node *node = l->head;
int i = 0;
int ret = -1;
while(node != NULL) {
if (node->object == object) {
ret = i;
break;
}
node = node->next;
i++;
}
return ret;
}
/**
* @brief Work as iternation.
*
* @param l
* The list.
* @param i
* Index.
* @return Address of object at i index. NULL if it doesn't exist.
*/
void *list_iterate(struct List *l, int i) {
struct Node *node = l->head;
while(node != NULL && i > 0) {
node = node->next;
i--;
}
return node == NULL ? NULL : node->object;
}
/**
* @brief Get how many objects are in the list.
*
* @param l
* The list.
* @return Count of objects.
*/
int list_get_count(struct List *l) {
struct Node *node = l->head;
int cnt = 0;
while (node != NULL) {
node = node->next;
cnt++;
}
return cnt;
} | 19.869318 | 67 | 0.500715 | [
"object"
] |
76a865079e319d7824eee95a279a6663289d7013 | 3,634 | h | C | source/src/controls/interface/interface.h | boston-engineering/universal-ventilator | 3500abd4e813bb3c158f446c714fe9f596e26483 | [
"MIT"
] | null | null | null | source/src/controls/interface/interface.h | boston-engineering/universal-ventilator | 3500abd4e813bb3c158f446c714fe9f596e26483 | [
"MIT"
] | null | null | null | source/src/controls/interface/interface.h | boston-engineering/universal-ventilator | 3500abd4e813bb3c158f446c714fe9f596e26483 | [
"MIT"
] | null | null | null | #ifndef UVENT_INTERFACE_H
#define UVENT_INTERFACE_H
#include <lvgl.h>
#include <variant.h>
#include <display/main_display.h>
#define clamp(n, low, high) max(low, min(n, high))
#define CHART_IDX_FLOW 0
#define CHART_IDX_PRESSURE 1
typedef enum AdjValueType {
TIDAL_VOLUME = 0,
RESPIRATION_RATE,
PEEP,
PIP,
PLATEAU_TIME,
PLAT_PRESSURE,
IE_RATIO_LEFT,
IE_RATIO_RIGHT,
FLOW,
CUR_PRESSURE,
ADJ_VALUE_COUNT,
UNKNOWN,
} AdjValueType;
typedef struct AdjValueParams {
AdjValueParams(const char* title, const char* control_title, const char* measured_formatter,
const char* target_formatter, const char* unit, double min_val, double max_val, double default_value,
float step, lv_color_t main_color)
: title(title), control_title(control_title), measured_formatter(measured_formatter),
target_formatter(target_formatter), unit(unit),
min_value(min_val), max_value(max_val), default_value(default_value), step(step),
main_color(main_color) { }
const char* title;
const char* control_title;
const char* measured_formatter;
const char* target_formatter;
const char* unit;
double min_value;
double max_value;
double default_value;
double step;
lv_color_t main_color;
} AdjValueParams;
extern const AdjValueParams adj_value_settings[ADJ_VALUE_COUNT];
class AdjustableValue {
public:
AdjustableValue() = default;
explicit AdjustableValue(double val)
: target(val) { }
AdjValueType value_type = UNKNOWN;
void (* control_press_cb)(AdjustableValue* this_ptr, lv_event_t* evt) = nullptr;
void (* readout_update_cb)(AdjustableValue* this_ptr, lv_event_t* evt) = nullptr;
/**
* Sets up the object for use. Must be called before calling get_settings
* @param type The on-screen measured type
*/
inline void init(AdjValueType type)
{
value_type = type;
}
void refresh_readout();
void on_control_button_press(lv_event_t* evt);
void on_readout_update(lv_event_t* evt);
AdjValueParams get_settings() const;
double get_step() const;
/**
* The holder for all the content that displays the sensor-measured value
* @return The base object
*/
lv_obj_t* get_obj_measured();
/**
* The holder for all the controls to set the target value for the mechanics
* @return The base object
*/
lv_obj_t* get_obj_target();
AdjustableValue set_obj_measured(lv_obj_t* obj);
AdjustableValue set_obj_target(lv_obj_t* obj);
/**
* @return The last measured value
*/
double* get_value_measured();
/**
* @return The current set target value
*/
double* get_value_target();
AdjustableValue set_value_measured(double value);
AdjustableValue set_value_target(double value);
inline bool is_selected() const
{
return selected;
}
inline void set_selected(bool state)
{
selected = state;
}
inline void toggle_selected()
{
set_selected(!selected);
}
inline bool is_dirty()
{
return dirty;
}
inline void clear_dirty()
{
dirty = false;
};
private:
lv_obj_t* lv_obj_measured = nullptr;
lv_obj_t* lv_obj_target = nullptr;
double measured = -1;
double target = 0;
/**
* Only used if this is part of a composite value like I:E Ratio
*/
bool selected = true;
bool dirty = false;
};
extern AdjustableValue adjustable_values[AdjValueType::ADJ_VALUE_COUNT];
#endif //UVENT_INTERFACE_H
| 25.236111 | 113 | 0.673638 | [
"object"
] |
76b0b5cef85d235f5c6d4ba730b90d4e88e68a10 | 2,939 | h | C | src/sources.h | BingzhangChen/ROMS-NPZDcont | b908590aa0eddea00223889a36b8b9a3e8fa1280 | [
"MIT"
] | 1 | 2021-07-27T09:08:59.000Z | 2021-07-27T09:08:59.000Z | src/sources.h | BingzhangChen/ROMS-NPZDcont | b908590aa0eddea00223889a36b8b9a3e8fa1280 | [
"MIT"
] | null | null | null | src/sources.h | BingzhangChen/ROMS-NPZDcont | b908590aa0eddea00223889a36b8b9a3e8fa1280 | [
"MIT"
] | null | null | null | ! $Id: sources.h 1225 2013-07-11 15:33:27Z gcambon $
#if defined PSOURCE || defined PSOURCE_NCFILE
!
! Nsrc Number of point Sources/Sinks.
! Dsrc Direction of point Sources/Sinks: 0 = along XI-;
! 1 = along ETA-direction.
! Isrc,Jsrc i,j-grid location of point Sources/Sinks,
! 0 <= Isrc <= Lm+1; 0 =<- Jsrc <= Mm+1.
! Lsrc Logical switch indicating which tracer field to apply
! the point Sources/Sinks.
! Qsrc Mass transport profile (m3/s) of point Sources/Sinks.
! Qbar Vertically integrated Qsrc (m3/s) of point
! QbarG Latest two-time snapshots of vertically integrated
! mass transport (m3/s) of point Sources/Sinks.
! Tsrc Tracer (tracer units) point Sources/Sinks.
! TsrcG Latest two-time snapshots of tracer (tracer units)
! point Sources/Sinks.
! Qshape Nondimensional shape function to distribute mass
! ass point Sources/Sinks vertically.
!
real Qbar(Msrc)
common /sources_Qbar/ Qbar
real Qsrc(Msrc,N)
common /source_Qsrc/ Qsrc
real Qshape(Msrc,N)
common /source_Qshape/ Qshape
real Tsrc(Msrc,N,NT)
common /source_Tsrc/ Tsrc
real Tsrc0(Msrc,NT)
common /source_Tsrc0/ Tsrc0
real lasrc(Msrc)
common /source_lasrc/ lasrc
real losrc(Msrc)
common /source_losrc/ losrc
integer Nsrc
common /source_Nsrc/ Nsrc
integer Dsrc(Msrc)
common /source_Dsrc/ Dsrc
integer Isrc(Msrc)
common /source_Isrc/ Isrc
integer Jsrc(Msrc)
common /source_Jsrc/ Jsrc
logical Lsrc(Msrc,30)
common /source_Lsrc/ Lsrc
#ifdef PSOURCE_NCFILE
!
! qbarg | Two-time-level grided data for river runoff [m3/s].
! tqbar Time of river runoff data.
!
real qbarg(Msrc,2)
common /qbardat_qbarg/qbarg
real qbar_time(2)
real qbar_cycle
integer itqbar, qbar_ncycle, qbar_rec, qbar_tid, qbar_id
common /qbardat1/ qbar_time
common /qbardat2/ qbar_cycle
common /qbardat3/ itqbar, qbar_ncycle, qbar_rec, qbar_tid, qbar_id
real qbardir(Msrc)
common /source_qbardir/ qbardir
# ifdef PSOURCE_NCFILE_TS
real tsrcg(Msrc,2,NT)
common /tsrcdat_tsrcg/tsrcg
real tsrc_time(2,NT)
real tsrc_cycle(NT)
integer ittsrc(NT), tsrc_ncycle(NT), tsrc_rec(NT), tsrc_tid(NT),
& tsrc_id(NT)
common /tsrcdat1/ tsrc_time
common /tsrcdat2/ tsrc_cycle
common /tsrcdat3/ ittsrc, tsrc_ncycle, tsrc_rec, tsrc_tid, tsrc_id
logical got_tsrc(NT)
common /tsrc_logical/ got_tsrc
# endif
#endif /* PSOURCE_NCFILE */
# ifdef MPI
integer Isrc_mpi(Msrc,0:NNODES-1)
common /source_Isrc_mpi/ Isrc_mpi
integer Jsrc_mpi(Msrc,0:NNODES-1)
common /source_Jsrc_mpi/ Jsrc_mpi
# endif
#endif
| 29.39 | 73 | 0.633209 | [
"shape"
] |
1883f65f68d2cae10f5729a5f53986782f24ee1f | 4,957 | c | C | prebuilt-intermediates/ir3/ir3_nir_imul.c | pundiramit/external-mesa3d | c342483c57fa185ff67bd5ab7d82cb884e42684e | [
"MIT"
] | null | null | null | prebuilt-intermediates/ir3/ir3_nir_imul.c | pundiramit/external-mesa3d | c342483c57fa185ff67bd5ab7d82cb884e42684e | [
"MIT"
] | null | null | null | prebuilt-intermediates/ir3/ir3_nir_imul.c | pundiramit/external-mesa3d | c342483c57fa185ff67bd5ab7d82cb884e42684e | [
"MIT"
] | null | null | null | #include "ir3_nir.h"
#include "nir.h"
#include "nir_builder.h"
#include "nir_search.h"
#include "nir_search_helpers.h"
/* What follows is NIR algebraic transform code for the following 2
* transforms:
* ('imul', 'a@32', 'b@32') => ('imadsh_mix16', 'b', 'a', ('imadsh_mix16', 'a', 'b', ('umul_low', 'a', 'b')))
* ('iadd', ('imul24', 'a', 'b'), 'c') => ('imad24_ir3', 'a', 'b', 'c')
*/
static const nir_search_variable search0_0 = {
{ nir_search_value_variable, 32 },
0, /* a */
false,
nir_type_invalid,
NULL,
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15},
};
static const nir_search_variable search0_1 = {
{ nir_search_value_variable, 32 },
1, /* b */
false,
nir_type_invalid,
NULL,
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15},
};
static const nir_search_expression search0 = {
{ nir_search_value_expression, 32 },
false, false,
0, 1,
nir_op_imul,
{ &search0_0.value, &search0_1.value },
NULL,
};
/* replace0_0 -> search0_1 in the cache */
/* replace0_1 -> search0_0 in the cache */
/* replace0_2_0 -> search0_0 in the cache */
/* replace0_2_1 -> search0_1 in the cache */
/* replace0_2_2_0 -> search0_0 in the cache */
/* replace0_2_2_1 -> search0_1 in the cache */
static const nir_search_expression replace0_2_2 = {
{ nir_search_value_expression, 32 },
false, false,
0, 1,
nir_op_umul_low,
{ &search0_0.value, &search0_1.value },
NULL,
};
static const nir_search_expression replace0_2 = {
{ nir_search_value_expression, 32 },
false, false,
-1, 1,
nir_op_imadsh_mix16,
{ &search0_0.value, &search0_1.value, &replace0_2_2.value },
NULL,
};
static const nir_search_expression replace0 = {
{ nir_search_value_expression, 32 },
false, false,
-1, 1,
nir_op_imadsh_mix16,
{ &search0_1.value, &search0_0.value, &replace0_2.value },
NULL,
};
/* search1_0_0 -> search0_0 in the cache */
/* search1_0_1 -> search0_1 in the cache */
static const nir_search_expression search1_0 = {
{ nir_search_value_expression, 32 },
false, false,
1, 1,
nir_op_imul24,
{ &search0_0.value, &search0_1.value },
NULL,
};
static const nir_search_variable search1_1 = {
{ nir_search_value_variable, 32 },
2, /* c */
false,
nir_type_invalid,
NULL,
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15},
};
static const nir_search_expression search1 = {
{ nir_search_value_expression, 32 },
false, false,
0, 2,
nir_op_iadd,
{ &search1_0.value, &search1_1.value },
NULL,
};
/* replace1_0 -> search0_0 in the cache */
/* replace1_1 -> search0_1 in the cache */
/* replace1_2 -> search1_1 in the cache */
static const nir_search_expression replace1 = {
{ nir_search_value_expression, 32 },
false, false,
0, 1,
nir_op_imad24_ir3,
{ &search0_0.value, &search0_1.value, &search1_1.value },
NULL,
};
static const struct transform ir3_nir_lower_imul_state2_xforms[] = {
{ &search0, &replace0.value, 0 },
};
static const struct transform ir3_nir_lower_imul_state4_xforms[] = {
{ &search1, &replace1.value, 0 },
};
static const struct per_op_table ir3_nir_lower_imul_table[nir_num_search_ops] = {
[nir_op_imul] = {
.filter = (uint16_t []) {
0,
0,
0,
0,
0,
},
.num_filtered_states = 1,
.table = (uint16_t []) {
2,
},
},
[nir_op_iadd] = {
.filter = (uint16_t []) {
0,
0,
0,
1,
0,
},
.num_filtered_states = 2,
.table = (uint16_t []) {
0,
4,
4,
4,
},
},
[nir_op_imul24] = {
.filter = (uint16_t []) {
0,
0,
0,
0,
0,
},
.num_filtered_states = 1,
.table = (uint16_t []) {
3,
},
},
};
const struct transform *ir3_nir_lower_imul_transforms[] = {
NULL,
NULL,
ir3_nir_lower_imul_state2_xforms,
NULL,
ir3_nir_lower_imul_state4_xforms,
};
const uint16_t ir3_nir_lower_imul_transform_counts[] = {
0,
0,
(uint16_t)ARRAY_SIZE(ir3_nir_lower_imul_state2_xforms),
0,
(uint16_t)ARRAY_SIZE(ir3_nir_lower_imul_state4_xforms),
};
bool
ir3_nir_lower_imul(nir_shader *shader)
{
bool progress = false;
bool condition_flags[1];
const nir_shader_compiler_options *options = shader->options;
const shader_info *info = &shader->info;
(void) options;
(void) info;
condition_flags[0] = true;
nir_foreach_function(function, shader) {
if (function->impl) {
progress |= nir_algebraic_impl(function->impl, condition_flags,
ir3_nir_lower_imul_transforms,
ir3_nir_lower_imul_transform_counts,
ir3_nir_lower_imul_table);
}
}
return progress;
}
| 22.634703 | 112 | 0.595723 | [
"transform"
] |
1887d7fd3eecd83b782571e35b509e2af52a2956 | 368 | h | C | Example/Tests/clx/Models/CLX_DurationWrapper.h | vladimir-shcherbakov/azure-runtime-client-for-objectiveC | b3857cf68c73e9aa5f3ad51bab4cb79676e7c91f | [
"MIT"
] | null | null | null | Example/Tests/clx/Models/CLX_DurationWrapper.h | vladimir-shcherbakov/azure-runtime-client-for-objectiveC | b3857cf68c73e9aa5f3ad51bab4cb79676e7c91f | [
"MIT"
] | null | null | null | Example/Tests/clx/Models/CLX_DurationWrapper.h | vladimir-shcherbakov/azure-runtime-client-for-objectiveC | b3857cf68c73e9aa5f3ad51bab4cb79676e7c91f | [
"MIT"
] | null | null | null | /**
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
#import <AzureClientRuntime/AzureClientRuntime.h>
/**
* The CLX_DurationWrapper model.
*/
@interface CLX_DurationWrapper : NSObject <AZCodable>
/**
* The field property.
*/
@property AZTimeSpan *field;
@end
| 20.444444 | 71 | 0.733696 | [
"model"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.