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
cee00d736b2161c3a3e6097f660b354dbbab46fb
25,289
c
C
s32k1_st7735/SDK/platform/drivers/src/power/S32K1xx/power_manager_S32K1xx.c
migsantiago/s32k1_st7735
e202fd6e573ccb80959e48d6b0af5e28c8914438
[ "MIT" ]
null
null
null
s32k1_st7735/SDK/platform/drivers/src/power/S32K1xx/power_manager_S32K1xx.c
migsantiago/s32k1_st7735
e202fd6e573ccb80959e48d6b0af5e28c8914438
[ "MIT" ]
null
null
null
s32k1_st7735/SDK/platform/drivers/src/power/S32K1xx/power_manager_S32K1xx.c
migsantiago/s32k1_st7735
e202fd6e573ccb80959e48d6b0af5e28c8914438
[ "MIT" ]
1
2021-01-17T01:44:41.000Z
2021-01-17T01:44:41.000Z
/* * Copyright (c) 2014-2016, Freescale Semiconductor, Inc. * Copyright 2016-2018 NXP * All rights reserved. * * THIS SOFTWARE IS PROVIDED BY NXP "AS IS" AND ANY EXPRESSED 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 NXP OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ /*! * @file power_manager_S32K1xx.c * * @page misra_violations MISRA-C:2012 violations * * @section [global] * Violates MISRA 2012 Required Rule 1.3, There shall be no occurrence of * undefined or critical unspecified behaviour. * The addresses of the stack variables are only used at local scope. * * @section [global] * Violates MISRA 2012 Advisory Rule 8.7, External could be made static. * Function is defined for usage by application code. * * @section [global] * Violates MISRA 2012 Required Rule 11.6, A cast shall not be performed * between pointer to void and an arithmetic type. * The base address parameter from HAL functions is provided as integer so * it needs to be cast to pointer. * * @section [global] * Violates MISRA 2012 Advisory Rule 11.4, A conversion should not be performed * between a pointer to object and an integer type. * The base address parameter from HAL functions is provided as integer so * a conversion between a pointer and an integer has to be performed * */ #include <stddef.h> #include "power_manager.h" #include "power_smc_hw_access.h" #include "power_rcm_hw_access.h" #include "power_scg_hw_access.h" #include "clock_manager.h" /*! @brief Power manager internal structure. */ power_manager_state_t gPowerManagerState; /* Save system clock configure */ static sys_clk_config_t sysClkConfig; /* Confirm change clock when switch very low power run mode */ static bool changeClkVlp = false; #if FEATURE_HAS_SPLL_CLK /* Confirm clock source SPLL config enabled or disable */ static bool enableSPLL = false; #endif /* #if FEATURE_HAS_SPLL_CLK */ /* Confirm clock source FIRC config enabled or disable */ static bool enableFIRC = false; /* Confirm clock source SOSC config enabled or disable */ static bool enableSOSC = false; /******************************************************************************* * INTERNAL FUNCTIONS ******************************************************************************/ static status_t POWER_SYS_SwitchToSleepingPowerMode(const power_manager_user_config_t * const configPtr); static status_t POWER_SYS_SwitchToRunningPowerMode(const power_manager_user_config_t * const configPtr); static status_t POWER_DRV_SwitchVlprClk(const sys_clk_config_t * const sysClock); static status_t POWER_DRV_UpdateInitClk(const sys_clk_config_t * const sysClk); static void POWER_DRV_EnableVlpClockSrc(void); static void POWER_DRV_DisableVlpClockSrc(void); static void POWER_DRV_GetEnableClockSrc(void); #if FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE static status_t POWER_SYS_EnterHsrunMode(void); #endif /******************************************************************************* * Code ******************************************************************************/ /******************************************************************************* * * It is expected that prior to the POWER_SYS_Init() call the write-once protection * register was configured appropriately allowing entry to all required low power * modes. * The following is an example of how to set up two power modes and one * callback, and initialize the Power manager with structures containing their settings. * The example shows two possible ways the configuration structures can be stored * (ROM or RAM), although it is expected that they will be placed in the read-only * memory to save the RAM space. (Note: In the example it is assumed that the programmed chip * doesn't support any optional power options described in the power_manager_user_config_t) * : * @code * * power_manager_user_config_t vlprConfig = { vlprConfig power mode configuration * .powerMode = POWER_MANAGER_VLPR, * .sleepOnExitValue = false, * }; * * power_manager_user_config_t stopConfig = { stopConfig power mode configuration * .powerMode = POWER_MANAGER_STOP, * .sleepOnExitValue = false, * }; * * power_manager_user_config_t const * powerConfigsArr[] = { Power mode configurations array * &vlprConfig, * &stopConfig * }; * * power_manager_callback_user_config_t callbackCfg0 = { Callback configuration structure callbackCfg0 * .callbackFunction = &callback0, * .callbackType = POWER_MANAGER_CALLBACK_BEFORE_AFTER, * .callbackData = (void *)0, * }; * * power_manager_callback_user_config_t const * callbacksConfigsArr[] = { Callback configuration structures array * &callbackCfg0 * }; * * status_t callback0(power_manager_notify_struct_t * notify, Definition of power manager callback * power_manager_callback_data_t * dataPtr) * { * status_t ret = STATUS_SUCCESS; * ... * return ret; * } * * int main(void) Main function * { * status_t ret = STATUS_SUCCESS; * * Calling of init method * POWER_SYS_Init(&powerConfigsArr, 2U, &powerStaticCallbacksConfigsArr, 1U); * * Switch to VLPR mode * ret = POWER_SYS_SetMode(MODE_VLPR,POWER_MANAGER_POLICY_AGREEMENT); * * if (ret != STATUS_SUCCESS) * { * return -1; * } * return 0; * } * * @endcode * *END**************************************************************************/ status_t POWER_SYS_DoInit(void) { uint8_t k = 0U; smc_power_mode_protection_config_t powerModeProtConfig; #if FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE powerModeProtConfig.hsrunProt = false; #endif /* #if FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE */ powerModeProtConfig.vlpProt = false; for (k = 0;k < gPowerManagerState.configsNumber;k++) { const power_manager_user_config_t * const config = (*gPowerManagerState.configs)[k]; #if FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE if (config->powerMode == POWER_MANAGER_HSRUN) { powerModeProtConfig.hsrunProt = true; /* High speed mode is allowed. */ } #endif /* #if FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE */ if ((config->powerMode == POWER_MANAGER_VLPR) || (config->powerMode == POWER_MANAGER_VLPS)) { powerModeProtConfig.vlpProt = true; /* Very low power mode is allowed. */ } } /* Very low power modes and high speed mode are not protected. */ SMC_SetProtectionMode(SMC, &powerModeProtConfig); /* Get all clock source were enabled. This one was used for update initialize clock when CPU came back RUN mode from very low power mode */ POWER_DRV_GetEnableClockSrc(); return STATUS_SUCCESS; } /*FUNCTION********************************************************************** * * Function Name : POWER_SYS_DoDeinit * Description : This function performs the actual implementation-specific de-initialization. * * *END**************************************************************************/ status_t POWER_SYS_DoDeinit(void) { return STATUS_SUCCESS; } /*FUNCTION********************************************************************** * * Function Name : POWER_SYS_DoSetMode * Description : This function performs the actual implementation-specific logic to switch * to one of the defined power modes. * * *END**************************************************************************/ status_t POWER_SYS_DoSetMode(const power_manager_user_config_t * const configPtr) { status_t returnCode; /* Function return */ /* Check whether the power mode is a sleeping or a running power mode */ if (configPtr->powerMode <= POWER_MANAGER_VLPR) { /* Switch to a running power mode */ returnCode = POWER_SYS_SwitchToRunningPowerMode(configPtr); } else { /* Switch to a sleeping power mode */ returnCode = POWER_SYS_SwitchToSleepingPowerMode(configPtr); } return returnCode; } /*FUNCTION********************************************************************** * * Function Name : POWER_SYS_GetCurrentMode * Description : Returns currently running power mode. * * Implements POWER_SYS_GetCurrentMode_Activity * *END**************************************************************************/ power_manager_modes_t POWER_SYS_GetCurrentMode(void) { power_manager_modes_t retVal; switch (SMC_GetPowerModeStatus(SMC)) { #if FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE /* High speed run mode */ case STAT_HSRUN: retVal = POWER_MANAGER_HSRUN; break; #endif /* Run mode */ case STAT_RUN: retVal = POWER_MANAGER_RUN; break; /* Very low power run mode */ case STAT_VLPR: retVal = POWER_MANAGER_VLPR; break; /* This should never happen - core has to be in some run mode to execute code */ default: retVal = POWER_MANAGER_MAX; break; } return retVal; } /*FUNCTION********************************************************************** * * Function Name : POWER_SYS_SwitchToRunningPowerMode * Description :Internal function used by POWER_SYS_SetMode function to switch to a running power mode * configPtr pointer to the requested user-defined power mode configuration. * System clock source must be SIRC or SOSC in Run mode before transition very low power run mode. * Update initialization or default clock source in run mode when came back from very low power run mode. * *END**************************************************************************/ static status_t POWER_SYS_SwitchToRunningPowerMode(const power_manager_user_config_t * const configPtr) { smc_power_mode_config_t modeConfig; /* SMC hardware layer configuration structure */ power_mode_stat_t currentMode = SMC_GetPowerModeStatus(SMC); status_t returnCode = STATUS_SUCCESS; /* Configure the running mode */ switch (configPtr->powerMode) { #if FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE /* High speed run mode */ case POWER_MANAGER_HSRUN: /* High speed run mode can be entered only from Run mode */ if (currentMode != STAT_HSRUN) { if (currentMode != STAT_RUN) { modeConfig.powerModeName = POWER_MANAGER_RUN; /* Switch the mode */ returnCode = SMC_SetPowerMode(SMC, &modeConfig); } if (returnCode == STATUS_SUCCESS) { returnCode = POWER_SYS_EnterHsrunMode(); } } else { returnCode = STATUS_SUCCESS; } break; #endif /* if FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE */ /* Run mode */ case POWER_MANAGER_RUN: if (currentMode != STAT_RUN) { modeConfig.powerModeName = POWER_MANAGER_RUN; /* Switch the mode */ returnCode = SMC_SetPowerMode(SMC, &modeConfig); } if ((returnCode == STATUS_SUCCESS) && changeClkVlp) { /* Enable all clock source */ POWER_DRV_EnableVlpClockSrc(); /* Update initialize clock configuration */ returnCode = POWER_DRV_UpdateInitClk(&sysClkConfig); if (returnCode == STATUS_SUCCESS) { changeClkVlp = false; } } break; /* Very low power run mode */ case POWER_MANAGER_VLPR: if (currentMode != STAT_VLPR) { /* Very low power run mode can be entered only from Run mode */ if (SMC_GetPowerModeStatus(SMC) != STAT_RUN) { modeConfig.powerModeName = POWER_MANAGER_RUN; /* Switch the mode */ returnCode = SMC_SetPowerMode(SMC, &modeConfig); } if (STATUS_SUCCESS == returnCode) { if (!changeClkVlp) { CLOCK_DRV_GetSystemClockSource(&sysClkConfig); } returnCode = POWER_DRV_SwitchVlprClk(&sysClkConfig); if (STATUS_SUCCESS == returnCode) { changeClkVlp = true; modeConfig.powerModeName = POWER_MANAGER_VLPR; /* Disable all clock source except SIRC */ POWER_DRV_DisableVlpClockSrc(); /* Switch the mode */ returnCode = SMC_SetPowerMode(SMC, &modeConfig); } } } else { returnCode = STATUS_SUCCESS; } break; /* Wait mode */ default: /* invalid power mode */ returnCode = STATUS_UNSUPPORTED; modeConfig.powerModeName = POWER_MANAGER_MAX; break; } return returnCode; } /*FUNCTION********************************************************************** * * Function Name : POWER_SYS_SwitchToSleepingPowerMode * Description :Internal function used by POWER_SYS_SetMode function to switch to a sleeping power mode * configPtr pointer to the requested user-defined power mode configuration * *END**************************************************************************/ static status_t POWER_SYS_SwitchToSleepingPowerMode(const power_manager_user_config_t * const configPtr) { smc_power_mode_config_t modeConfig; /* SMC hardware layer configuration structure */ status_t returnCode = STATUS_SUCCESS; /* return value */ power_mode_stat_t pwrModeStat = SMC_GetPowerModeStatus(SMC); /* power mode stat */ /* Configure the hardware layer */ switch (configPtr->powerMode) { #if FEATURE_SMC_HAS_WAIT_VLPW /* Wait mode */ case POWER_MANAGER_WAIT: /* Wait mode can be entered only from Run mode */ if (pwrModeStat != STAT_RUN) { modeConfig.powerModeName = POWER_MANAGER_RUN; /* Switch the mode */ returnCode = SMC_SetPowerMode(SMC, &modeConfig); } modeConfig.powerModeName = POWER_MANAGER_WAIT; break; /* Very low power wait mode */ case POWER_MANAGER_VLPW: /* Very low power wait mode can be entered only from Very low power run mode */ if (pwrModeStat != STAT_VLPR) { modeConfig.powerModeName = POWER_MANAGER_VLPR; /* Switch the mode */ returnCode = SMC_SetPowerMode(SMC, &modeConfig); } modeConfig.powerModeName = POWER_MANAGER_VLPW; break; #endif /* if FEATURE_SMC_HAS_WAIT_VLPW */ #if FEATURE_SMC_HAS_PSTOPO /* Partial stop modes */ case POWER_MANAGER_PSTOP1: /* fall-through */ case POWER_MANAGER_PSTOP2: /* fall-through */ #endif #if FEATURE_SMC_HAS_STOPO /* Stop modes */ case POWER_MANAGER_STOP1: /* fall-through */ case POWER_MANAGER_STOP2: /* Stop1 and Stop2 mode can be entered only from Run mode */ if (pwrModeStat != STAT_RUN) { modeConfig.powerModeName = POWER_MANAGER_RUN; /* Switch the mode */ returnCode = SMC_SetPowerMode(SMC, &modeConfig); } modeConfig.powerModeName = configPtr->powerMode; #endif /* #if FEATURE_SMC_HAS_STOPO */ #if FEATURE_SMC_HAS_PSTOPO modeConfig.pstopOption = true; /* Set the partial stop option value */ if (POWER_MANAGER_PSTOP1 == configPtr->powerMode) { modeConfig.pstopOptionValue = SMC_PSTOP_STOP1; } else if (POWER_MANAGER_PSTOP2 == configPtr->powerMode) { modeConfig.pstopOptionValue = SMC_PSTOP_STOP2; } else { modeConfig.pstopOptionValue = SMC_PSTOP_STOP; } #endif /* if FEATURE_SMC_HAS_PSTOPO */ #if FEATURE_SMC_HAS_STOPO /* Set the stop option value */ if (POWER_MANAGER_STOP1 == configPtr->powerMode) { modeConfig.stopOptionValue = SMC_STOP1; } else { modeConfig.stopOptionValue = SMC_STOP2; } #endif /* if FEATURE_SMC_HAS_STOPO */ break; /* Very low power stop mode */ case POWER_MANAGER_VLPS: /* Very low power stop mode can be entered only from Run mode or Very low power run mode*/ if ((pwrModeStat != STAT_RUN) && (pwrModeStat != STAT_VLPR)) { modeConfig.powerModeName = POWER_MANAGER_RUN; returnCode = SMC_SetPowerMode(SMC, &modeConfig); } if (returnCode == STATUS_SUCCESS) { if (POWER_SYS_GetCurrentMode() == POWER_MANAGER_RUN) { /* Get current source clock */ if (!changeClkVlp) { CLOCK_DRV_GetSystemClockSource(&sysClkConfig); } returnCode = POWER_DRV_SwitchVlprClk(&sysClkConfig); if (STATUS_SUCCESS == returnCode) { changeClkVlp = true; modeConfig.powerModeName = POWER_MANAGER_VLPS; /* Disable all clock source except SIRC */ POWER_DRV_DisableVlpClockSrc(); } } } modeConfig.powerModeName = POWER_MANAGER_VLPS; break; default: /* invalid power mode */ returnCode = STATUS_UNSUPPORTED; modeConfig.powerModeName = POWER_MANAGER_MAX; break; } if (STATUS_SUCCESS == returnCode) { /* Configure ARM core what to do after interrupt invoked in (deep) sleep state */ if (configPtr->sleepOnExitValue) { /* Go back to (deep) sleep state on ISR exit */ S32_SCB->SCR |= S32_SCB_SCR_SLEEPONEXIT_MASK; } else { /* Do not re-enter (deep) sleep state on ISR exit */ S32_SCB->SCR &= ~(S32_SCB_SCR_SLEEPONEXIT_MASK); } /* Switch the mode */ if (SMC_SetPowerMode(SMC, &modeConfig) != STATUS_SUCCESS) { returnCode = STATUS_MCU_TRANSITION_FAILED; } } return returnCode; } /*FUNCTION********************************************************************** * * Function Name : POWER_DRV_SwitchVlprClk * Description : This function will change system clock in run mode before MCU enter very low power run mode. * * *END**************************************************************************/ static status_t POWER_DRV_SwitchVlprClk(const sys_clk_config_t * const sysClock) { status_t retCode = STATUS_SUCCESS; sys_clk_config_t sysClkVlprConfig; clock_names_t currentSystemClockSource = sysClock->src; if (currentSystemClockSource != SIRC_CLK) { /* Set SIRC the system clock source */ sysClkVlprConfig.src = SIRC_CLK; sysClkVlprConfig.dividers[0U] = 1U; /* Core clock divider, do not divide */ sysClkVlprConfig.dividers[1U] = 2U; /* Bus clock divider, do not divide */ sysClkVlprConfig.dividers[2U] = 2U; /* Slow clock divider, do not divide */ retCode = CLOCK_DRV_SetSystemClock(NULL,&sysClkVlprConfig); } return retCode; } /*FUNCTION********************************************************************** * * Function Name : POWER_DRV_UpdateInitClk * Description : This function will update initialization or default clock source of run mode when MCU come back run mode. * * *END**************************************************************************/ static status_t POWER_DRV_UpdateInitClk(const sys_clk_config_t * const sysClk) { status_t retCode = STATUS_SUCCESS; retCode = CLOCK_DRV_SetSystemClock(NULL,sysClk); return retCode; } /*FUNCTION********************************************************************** * * Function Name : POWER_DRV_EnableVlpClockSrc * Description : This function will enable SPLL, FIRC, SOSC * *END**************************************************************************/ static void POWER_DRV_EnableVlpClockSrc(void) { #if FEATURE_HAS_SPLL_CLK SCG_SetEnableSPLL(enableSPLL); #endif /* #if FEATURE_HAS_SPLL_CLK */ SCG_SetEnableFIRC(enableFIRC); SCG_SetEnableSOSC(enableSOSC); } /*FUNCTION********************************************************************** * * Function Name : POWER_DRV_DisableVlpClockSrc * Description : This function will disable SPLL, FIRC, SOSC * before enter the very low power mode. * * *END**************************************************************************/ static void POWER_DRV_DisableVlpClockSrc(void) { #if FEATURE_HAS_SPLL_CLK SCG_SetEnableSPLL(false); #endif /* #if FEATURE_HAS_SPLL_CLK */ SCG_SetEnableSOSC(false); SCG_SetEnableFIRC(false); } /*FUNCTION********************************************************************** * * Function Name : POWER_DRV_GetEnableClockSrc * Description : This function will get status of clock source enable or not. * *END**************************************************************************/ static void POWER_DRV_GetEnableClockSrc(void) { #if FEATURE_HAS_SPLL_CLK enableSPLL = SCG_GetEnableSPLL(); #endif /* #if FEATURE_HAS_SPLL_CLK */ enableFIRC = SCG_GetEnableFIRC(); enableSOSC = SCG_GetEnableSOSC(); } #if FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE /*FUNCTION********************************************************************** * * Function Name : POWER_SYS_EnterHsrunMode * Description :Internal function used by POWER_SYS_SwitchToRunningPowerMode function to enter configuration * to a Hsrun power mode. * configPtr pointer to the requested user-defined Hsrun mode power mode configuration. * System clock source must be FIRC or SPLL in HSRun mode before transition very low power run mode. * Update initialization when came back from very low power run mode. * *END**************************************************************************/ static status_t POWER_SYS_EnterHsrunMode(void) { status_t returnCode = STATUS_SUCCESS; smc_power_mode_config_t modeConfig; /* SMC hardware layer configuration structure */ #if FEATURE_HAS_SPLL_CLK bool checkEnableSPLL = SCG_GetHsrunSelectSPLL(); if ((!enableSPLL) && (!enableFIRC)) { returnCode = STATUS_ERROR; } else if ((checkEnableSPLL && !enableSPLL) || (!checkEnableSPLL && !enableFIRC)) { returnCode = STATUS_ERROR; } else #endif { if (changeClkVlp) { POWER_DRV_EnableVlpClockSrc(); /* Update initialize clock configuration */ returnCode = POWER_DRV_UpdateInitClk(&sysClkConfig); if (returnCode == STATUS_SUCCESS) { changeClkVlp = false; modeConfig.powerModeName = POWER_MANAGER_HSRUN; /* Switch the mode */ returnCode = SMC_SetPowerMode(SMC, &modeConfig); } } else { modeConfig.powerModeName = POWER_MANAGER_HSRUN; /* Switch the mode */ returnCode = SMC_SetPowerMode(SMC, &modeConfig); } } return returnCode; } #endif /*FUNCTION********************************************************************** * * Function Name : POWER_SYS_GetResetSrcStatusCmd * Description : This function will get the current reset source status for specified source * * Implements POWER_SYS_GetResetSrcStatusCmd_Activity * *END**************************************************************************/ bool POWER_SYS_GetResetSrcStatusCmd(const RCM_Type * const baseAddr , const rcm_source_names_t srcName) { return RCM_GetSrcStatusCmd(baseAddr , srcName); } /******************************************************************************* * EOF ******************************************************************************/
36.650725
125
0.578947
[ "object" ]
cef0e84c2ebcc43d113e6ac26ff81478c2f5b119
3,653
h
C
views/tableview/tableviewdelegate.h
DatabasesWorks/passiflora-symphytum-configurable-fields
6128d0391fe33438250efad4398d65c5982b005b
[ "BSD-2-Clause" ]
2
2017-10-01T07:59:54.000Z
2021-09-09T14:40:41.000Z
views/tableview/tableviewdelegate.h
DatabasesWorks/passiflora-symphytum-configurable-fields
6128d0391fe33438250efad4398d65c5982b005b
[ "BSD-2-Clause" ]
3
2017-11-01T15:42:46.000Z
2019-02-18T08:42:33.000Z
views/tableview/tableviewdelegate.h
DatabasesWorks/passiflora-symphytum-configurable-fields
6128d0391fe33438250efad4398d65c5982b005b
[ "BSD-2-Clause" ]
null
null
null
/** * \class TableViewDelegate * \brief This is the main delegate for the TableView. * \author Giorgio Wicklein - GIOWISYS Software * \date 09/06/2012 */ #ifndef TABLEVIEWDELEGATE_H #define TABLEVIEWDELEGATE_H //----------------------------------------------------------------------------- // Headers //----------------------------------------------------------------------------- #include <QtWidgets/QStyledItemDelegate> //----------------------------------------------------------------------------- // Forward declarations //----------------------------------------------------------------------------- class MetadataEngine; //----------------------------------------------------------------------------- // TableViewDelegate //----------------------------------------------------------------------------- class TableViewDelegate : public QStyledItemDelegate { Q_OBJECT public: explicit TableViewDelegate(QObject *parent = 0); void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const; QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const; QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const; void setEditorData(QWidget *editor, const QModelIndex &index) const; void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const; void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const; private slots: void commitAndCloseCustomEditor(); private: //custom paint methods void paintTextType(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const; void paintNumericType(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const; void paintCreateDateType(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const; void paintCheckboxType(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const; void paintComboboxType(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const; void paintProgressType(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const; void paintImageType(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const; void paintFilesType(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const; //custom set editor data methods void setTextTypeEditorData(QWidget *editor, const QModelIndex &index) const; void setNumericTypeEditorData(QWidget *editor, const QModelIndex &index) const; void setCheckboxTypeEditorData(QWidget *editor, const QModelIndex &index) const; void setComboboxTypeEditorData(QWidget *editor, const QModelIndex &index) const; void setProgressTypeEditorData(QWidget *editor, const QModelIndex &index) const; void setImageTypeEditorData(QWidget *editor, const QModelIndex &index) const; void setFilesTypeEditorData(QWidget *editor, const QModelIndex &index) const; void setDateTypeEditorData(QWidget *editor, const QModelIndex &index) const; MetadataEngine *m_metadataEngine; }; #endif // TABLEVIEWDELEGATE_H
42.976471
84
0.612647
[ "model" ]
cefe94b9b62b651eb19a5153a2327a68b57f22f4
1,301
h
C
sdk-6.5.20/libs/sdklt/bcma/include/bcma/bcmbd/bcma_bcmbdcmd_cmicx_pop.h
copslock/broadcom_cpri
8e2767676e26faae270cf485591902a4c50cf0c5
[ "Spencer-94" ]
null
null
null
sdk-6.5.20/libs/sdklt/bcma/include/bcma/bcmbd/bcma_bcmbdcmd_cmicx_pop.h
copslock/broadcom_cpri
8e2767676e26faae270cf485591902a4c50cf0c5
[ "Spencer-94" ]
null
null
null
sdk-6.5.20/libs/sdklt/bcma/include/bcma/bcmbd/bcma_bcmbdcmd_cmicx_pop.h
copslock/broadcom_cpri
8e2767676e26faae270cf485591902a4c50cf0c5
[ "Spencer-94" ]
null
null
null
/*! \file bcma_bcmbdcmd_cmicx_pop.h * * CLI 'pop' command for CMICx */ /* * This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file. * * Copyright 2007-2020 Broadcom Inc. All rights reserved. */ #ifndef BCMA_BCMBDCMD_CMICX_POP_H #define BCMA_BCMBDCMD_CMICX_POP_H #include <bcma/cli/bcma_cli.h> /*! Brief description for CLI command. */ #define BCMA_BCMBDCMD_CMICX_POP_DESC \ "Pop an entry from a FIFO." /*! Syntax for CLI command. */ #define BCMA_BCMBDCMD_CMICX_POP_SYNOP \ "[raw] [cf] <expr>" /*! Help for CLI command. */ #define BCMA_BCMBDCMD_CMICX_POP_HELP \ "Pop an entry from a device FIFO.\n" \ "The raw option suppresses the decoding of individual memory fields.\n" \ "The cf option selects a compact-field output format, which is useful\n" \ "for slow terminals and high-volume output." /*! Examples for CLI command. */ #define BCMA_BCMBDCMD_CMICX_POP_EXAMPLES \ "ING_SER_FIFOm{0}" /*! * \brief CLI 'pop' command implementation for CMICx. * * \param [in] cli CLI object. * \param [in] args Argument list. * * \return BCMA_CLI_CMD_xxx return values. */ extern int bcma_bcmbdcmd_cmicx_pop(bcma_cli_t *cli, bcma_cli_args_t *args); #endif /* BCMA_BCMBDCMD_CMICX_POP_H */
27.680851
134
0.725596
[ "object" ]
1df0caeed308ca2965aabd39bbb83203262caf3e
3,097
h
C
Pepper/include/ViewRightBR.h
sarangbaheti/Pepper
f26033711201b0c051521883ad3aad90ef4aa8a4
[ "MIT" ]
null
null
null
Pepper/include/ViewRightBR.h
sarangbaheti/Pepper
f26033711201b0c051521883ad3aad90ef4aa8a4
[ "MIT" ]
null
null
null
Pepper/include/ViewRightBR.h
sarangbaheti/Pepper
f26033711201b0c051521883ad3aad90ef4aa8a4
[ "MIT" ]
1
2021-01-11T15:10:34.000Z
2021-01-11T15:10:34.000Z
/**************************************************************************************************** * Copyright (C) 2018-2019, Jovibor: https://github.com/jovibor/ * * This software is available under the "MIT License". * * https://github.com/jovibor/Pepper/blob/master/LICENSE * * Pepper - PE (x86) and PE+ (x64) files viewer, based on libpe: https://github.com/jovibor/Pepper * * libpe - Windows library for reading PE (x86) and PE+ (x64) files inner structure information. * * https://github.com/jovibor/libpe * ****************************************************************************************************/ #pragma once #include <memory> #include "PepperDoc.h" #include "ChildFrm.h" #include "ListEx/ListEx.h" #include "constants.h" using namespace LISTEX; class CWndSampledlg : public CWnd { public: void Attach(CImageList* pImgList, CChildFrame* pChildFrame); void SetDlgVisible(bool fVisible); DECLARE_MESSAGE_MAP() private: afx_msg void OnPaint(); afx_msg void OnClose(); private: CImageList* m_pImgRes { }; CChildFrame* m_pChildFrame { }; }; class CViewRightBR : public CScrollView { DECLARE_DYNCREATE(CViewRightBR) protected: virtual void OnDraw(CDC* pDC); // overridden to draw this view virtual void OnInitialUpdate(); // first time after construct afx_msg void OnSize(UINT nType, int cx, int cy); virtual void OnUpdate(CView* /*pSender*/, LPARAM /*lHint*/, CObject* /*pHint*/); void ShowResource(const SRESHELPER*); void CreateIconCursor(const SRESHELPER* pResHelper); void CreateBitmap(const SRESHELPER* pResHelper); void CreateDlg(const SRESHELPER* pResHelper); void ParceDlgTemplate(PBYTE pDataDlgRes, size_t nSize, std::wstring& wstrData); void CreateStrings(const SRESHELPER* pResHelper); void CreateGroupIconCursor(const SRESHELPER* pResHelper); void CreateVersion(const SRESHELPER* pResHelper); void CreateManifest(const SRESHELPER* pResHelper); void CreateToolbar(const SRESHELPER* pResHelper); int CreateListTLSCallbacks(); void ResLoadError(); void CreateDebugEntry(DWORD dwEntry); DECLARE_MESSAGE_MAP() private: HWND m_hwndActive { }; libpe_ptr m_pLibpe; CChildFrame* m_pChildFrame { }; CPepperDoc* m_pMainDoc { }; CImageList m_stImgRes; CWndSampledlg m_wndSampledlg; LISTEXCREATESTRUCT m_stlcs; IListExPtr m_stListTLSCallbacks { CreateListEx() }; LOGFONTW m_lf { }, m_hdrlf { }; bool m_fDrawRes { false }; COLORREF m_clrBkIcons { RGB(230, 230, 230) }; COLORREF m_clrBkImgList { RGB(250, 250, 250) }; BITMAP m_stBmp { }; int m_iResTypeToDraw { }; int m_iImgResWidth { }, m_iImgResHeight { }; //Width and height of whole image to draw. std::vector<std::unique_ptr<CImageList>> m_vecImgRes { }; //Vector for RT_GROUP_ICON/CURSOR. std::wstring m_wstrEditBRB; //WString for m_EditBRB. CEdit m_EditBRB; //Edit control for RT_STRING, RT_VERSION, RT_MANIFEST, Debug additional info CFont m_fontEditRes; //Font for m_EditBRB. };
41.851351
106
0.660962
[ "vector" ]
1dfafd55fb722e55cc4f4bb09a2f64e649f6f5a5
7,497
h
C
src/Pegasus/ProviderManager2/SimpleResponseHandler.h
ncultra/Pegasus-2.5
4a0b9a1b37e2eae5c8105fdea631582dc2333f9a
[ "MIT" ]
null
null
null
src/Pegasus/ProviderManager2/SimpleResponseHandler.h
ncultra/Pegasus-2.5
4a0b9a1b37e2eae5c8105fdea631582dc2333f9a
[ "MIT" ]
null
null
null
src/Pegasus/ProviderManager2/SimpleResponseHandler.h
ncultra/Pegasus-2.5
4a0b9a1b37e2eae5c8105fdea631582dc2333f9a
[ "MIT" ]
1
2022-03-07T22:54:02.000Z
2022-03-07T22:54:02.000Z
//%2005//////////////////////////////////////////////////////////////////////// // // Copyright (c) 2000, 2001, 2002 BMC Software; Hewlett-Packard Development // Company, L.P.; IBM Corp.; The Open Group; Tivoli Systems. // Copyright (c) 2003 BMC Software; Hewlett-Packard Development Company, L.P.; // IBM Corp.; EMC Corporation, The Open Group. // Copyright (c) 2004 BMC Software; Hewlett-Packard Development Company, L.P.; // IBM Corp.; EMC Corporation; VERITAS Software Corporation; The Open Group. // Copyright (c) 2005 Hewlett-Packard Development Company, L.P.; IBM Corp.; // EMC Corporation; VERITAS Software Corporation; The Open Group. // // 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. // //============================================================================== // // Author: Chip Vincent (cvincent@us.ibm.com) // // Modified By: // Roger Kumpf, Hewlett-Packard Company (roger_kumpf@hp.com) // Dave Rosckes (rosckes@us.ibm.com) // Brian G. Campbell, EMC (campbell_brian@emc.com) - PEP140/phase2 // //%///////////////////////////////////////////////////////////////////////////// #ifndef Pegasus_SimpleResponseHandler_h #define Pegasus_SimpleResponseHandler_h #include <Pegasus/Common/Config.h> #include <Pegasus/Common/ResponseHandler.h> #include <Pegasus/ProviderManager2/Linkage.h> PEGASUS_NAMESPACE_BEGIN // // ValueResponseHandler (used internally to implement property operations) // class PEGASUS_PPM_LINKAGE ValueResponseHandler : virtual public ResponseHandler { public: virtual void deliver(const CIMValue & value) = 0; virtual void deliver(const Array<CIMValue> & values) = 0; }; // // SimpleResponseHandler // class PEGASUS_PPM_LINKAGE SimpleResponseHandler : virtual public ResponseHandler { public: SimpleResponseHandler(void); virtual ~SimpleResponseHandler(void); virtual void processing(void); virtual void complete(void); // return the number of objects in this handler virtual Uint32 size(void) const; // clear any objects in this handler virtual void clear(void); ContentLanguages getLanguages(void); protected: virtual void send(Boolean isComplete); }; class PEGASUS_PPM_LINKAGE SimpleInstanceResponseHandler : public SimpleResponseHandler, public InstanceResponseHandler { public: SimpleInstanceResponseHandler(void); virtual void processing(void); virtual void complete(void); virtual Uint32 size(void) const; virtual void clear(void); virtual void deliver(const CIMInstance & instance); virtual void deliver(const Array<CIMInstance> & instances); const Array<CIMInstance> getObjects(void) const; private: Array<CIMInstance> _objects; }; class PEGASUS_PPM_LINKAGE SimpleObjectPathResponseHandler : public SimpleResponseHandler, public ObjectPathResponseHandler { public: SimpleObjectPathResponseHandler(void); virtual void processing(void); virtual void complete(void); virtual Uint32 size(void) const; virtual void clear(void); virtual void deliver(const CIMObjectPath & objectPath); virtual void deliver(const Array<CIMObjectPath> & objectPaths); const Array<CIMObjectPath> getObjects(void) const; private: Array<CIMObjectPath> _objects; }; class PEGASUS_PPM_LINKAGE SimpleMethodResultResponseHandler : public SimpleResponseHandler, public MethodResultResponseHandler { public: SimpleMethodResultResponseHandler(void); virtual void processing(void); virtual void complete(void); // NOTE: this is the total size (count) of ALL parameters! virtual Uint32 size(void) const; virtual void clear(void); virtual void deliverParamValue(const CIMParamValue & outParamValue); virtual void deliverParamValue(const Array<CIMParamValue> & outParamValues); virtual void deliver(const CIMValue & returnValue); const Array<CIMParamValue> getParamValues(void) const; const CIMValue getReturnValue(void) const; private: Array<CIMParamValue> _objects; CIMValue _returnValue; }; class PEGASUS_PPM_LINKAGE SimpleIndicationResponseHandler : public SimpleResponseHandler, public IndicationResponseHandler { public: SimpleIndicationResponseHandler(void); virtual void processing(void); virtual void complete(void); virtual Uint32 size(void) const; virtual void clear(void); virtual void deliver(const CIMIndication & indication); virtual void deliver(const Array<CIMIndication> & indications); virtual void deliver( const OperationContext & context, const CIMIndication & indication); virtual void deliver( const OperationContext & context, const Array<CIMIndication> & indications); const Array<CIMIndication> getObjects(void) const; // ATTN: why is this variable public? CIMInstance _provider; private: Array<CIMIndication> _objects; }; class PEGASUS_PPM_LINKAGE SimpleObjectResponseHandler : public SimpleResponseHandler, public ObjectResponseHandler { public: SimpleObjectResponseHandler(void); virtual void processing(void); virtual void complete(void); virtual Uint32 size(void) const; virtual void clear(void); virtual void deliver(const CIMObject & object); virtual void deliver(const Array<CIMObject> & objects); const Array<CIMObject> getObjects(void) const; private: Array<CIMObject> _objects; }; class PEGASUS_PPM_LINKAGE SimpleInstance2ObjectResponseHandler : public SimpleResponseHandler, public InstanceResponseHandler { public: SimpleInstance2ObjectResponseHandler(void); virtual void processing(void); virtual void complete(void); virtual Uint32 size(void) const; virtual void clear(void); virtual void deliver(const CIMInstance & object); virtual void deliver(const Array<CIMInstance> & objects); const Array<CIMObject> getObjects(void) const; private: Array<CIMObject> _objects; }; class PEGASUS_PPM_LINKAGE SimpleValueResponseHandler : public SimpleResponseHandler, public ValueResponseHandler { public: SimpleValueResponseHandler(void); virtual void processing(void); virtual void complete(void); virtual Uint32 size(void) const; virtual void clear(void); virtual void deliver(const CIMValue & value); virtual void deliver(const Array<CIMValue> & values); const Array<CIMValue> getObjects(void) const; private: Array<CIMValue> _objects; }; PEGASUS_NAMESPACE_END #endif
27.163043
126
0.728025
[ "object" ]
380c1e640b360bc09001c39fee52fc7f83d7b254
4,179
c
C
lab-exams/I Esonero/server/src/main.c
alberto093/lab-reti
0f22ee3394e24d9e58138d18d2de227916d6b80e
[ "MIT" ]
null
null
null
lab-exams/I Esonero/server/src/main.c
alberto093/lab-reti
0f22ee3394e24d9e58138d18d2de227916d6b80e
[ "MIT" ]
null
null
null
lab-exams/I Esonero/server/src/main.c
alberto093/lab-reti
0f22ee3394e24d9e58138d18d2de227916d6b80e
[ "MIT" ]
null
null
null
/* ============================================================================ Name : calculator_server.c Author : Alberto Saltarelli Version : 0.1 Copyright : Copyright © 2021 calculator_server - Alberto Saltarelli Description : A simple calculator in C (server-side) ============================================================================ */ #include <stdio.h> #include <stdlib.h> #include "api.h" #define NO_ERROR 0 /* function declaration */ calc_result add(int op1, int op2); calc_result mult(int op1, int op2); calc_result sub(int op1, int op2); calc_result division(int op1, int op2); calc_result calculate(struct calc_operation *operation); int main(int argc, char *argv[]) { int port; if (argc > 1) { port = atoi(argv[1]); if (port < 0) { printf("bad port number %s \n", argv[1]); return -1; } } else { port = PROTOPORT; } #if defined WIN32 // Initialize Winsock WSADATA wsa_data; int result = WSAStartup(MAKEWORD(2,2), &wsa_data); if (result != NO_ERROR) { printf("Error at WSAStartup()\n"); return -1; } #endif // Create socket int welcome_socket; welcome_socket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); if (welcome_socket < 0) { printf("socket creation failed.\n"); clearwinsock(); return -1; } // Bind socket address struct sockaddr_in sad; memset(&sad, 0, sizeof(sad)); sad.sin_family = AF_INET; sad.sin_addr.s_addr = inet_addr(LOCAL_HOST); sad.sin_port = htons(port); if (bind(welcome_socket, (struct sockaddr*) &sad, sizeof(sad)) < 0) { printf("socket bind failed.\n"); closesocket(welcome_socket); clearwinsock(); return -1; } // Open listening session if (listen(welcome_socket, QLEN) < 0) { printf("socket listen failed.\n"); closesocket(welcome_socket); clearwinsock(); return -1; } // Accept new client request struct sockaddr_in cad; int client_socket; int client_open = 0; socklen_t client_len; struct calc_operation operation; int calc_operation_l = sizeof(calc_operation); calc_result result; int result_l = sizeof(calc_result); printf("\nWaiting for a client to connect...\n"); while (1) { client_len = sizeof(cad); if ((client_socket = accept(welcome_socket, (struct sockaddr *) &cad, &client_len)) < 0) { printf("socket accept failed.\n"); closesocket(welcome_socket); clearwinsock(); return -1; } printf("Connection established with %s:%i", inet_ntoa(cad.sin_addr), cad.sin_port); fflush(stdout); client_open = 1; while (client_open == 1) { if (recv(client_socket, &operation, calc_operation_l, 0) == calc_operation_l) { result = calculate(&operation); if (send(client_socket, &result, result_l, 0) != result_l) { client_open = 0; } } else { client_open = 0; } } printf("\nDisconnect client %s:%i\n", inet_ntoa(cad.sin_addr), cad.sin_port); } closesocket(welcome_socket); clearwinsock(); return NO_ERROR; } calc_result add(int op1, int op2) { return (float) op1 + op2; } calc_result mult(int op1, int op2) { return (float) op1 * op2; } calc_result sub(int op1, int op2) { return (float) op1 - op2; } calc_result division(int op1, int op2) { if (op2 == 0) { return 0; } else { return (float) op1 / op2; } } calc_result calculate(struct calc_operation *operation) { if (operation->operator == '+') { return add(operation->op1, operation->op2); } else if (operation->operator == '*') { return mult(operation->op1, operation->op2); } else if (operation->operator == '-') { return sub(operation->op1, operation->op2); } else if (operation->operator == '/') { return division(operation->op1, operation->op2); } else { return 0; } }
26.617834
98
0.567361
[ "cad" ]
380edca66ff6d0efec1a4bc906d3e1bc2b89b860
4,367
h
C
client/task/input_file_task.h
dzeromsk/goma
350f67319eb985013515b533f03f2f95570c37d3
[ "BSD-3-Clause" ]
4
2018-12-26T10:54:24.000Z
2022-03-31T21:19:47.000Z
client/task/input_file_task.h
dzeromsk/goma
350f67319eb985013515b533f03f2f95570c37d3
[ "BSD-3-Clause" ]
null
null
null
client/task/input_file_task.h
dzeromsk/goma
350f67319eb985013515b533f03f2f95570c37d3
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2019 The Goma 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 DEVTOOLS_GOMA_CLIENT_TASK_INPUT_FILE_TASK_H_ #define DEVTOOLS_GOMA_CLIENT_TASK_INPUT_FILE_TASK_H_ #include <memory> #include <unordered_map> #include "absl/memory/memory.h" #include "absl/time/time.h" #include "base/basictypes.h" #include "base/lockhelper.h" #include "compile_task.h" #include "file_hash_cache.h" #include "goma_blob.h" #include "prototmp/goma_data.pb.h" #include "simple_timer.h" #include "worker_thread_manager.h" namespace devtools_goma { class InputFileTask { public: // Gets InputFileTask for the filename. // If an InputFileTask for the same filename already exists, use the same // InputFileTask. static InputFileTask* NewInputFileTask( WorkerThreadManager* wm, std::unique_ptr<BlobClient::Uploader> blob_uploader, FileHashCache* file_hash_cache, const FileStat& file_stat, const string& filename, bool missed_content, bool linking, bool is_new_file, const string& old_hash_key, CompileTask* task, ExecReq_Input* input); void Run(CompileTask* task, OneshotClosure* closure); void Done(CompileTask* task); const string& filename() const { return filename_; } bool missed_content() const { return missed_content_; } bool need_hash_only() const { return need_hash_only_; } const absl::optional<absl::Time>& mtime() const { return file_stat_.mtime; } const SimpleTimer& timer() const { return timer_; } ssize_t file_size() const { return file_stat_.size; } const string& old_hash_key() const { return old_hash_key_; } const string& hash_key() const { return blob_uploader_->hash_key(); } bool success() const { return success_; } bool new_cache_key() const { return new_cache_key_; } size_t num_tasks() const { AUTOLOCK(lock, &mu_); return tasks_.size(); } bool UpdateInputInTask(CompileTask* task) const; ExecReq_Input* GetInputForTask(CompileTask* task) const; bool need_to_compute_key() const; bool need_to_upload_content(absl::string_view hash_key) const; const char* upload_reason(absl::string_view hash_key) const; const HttpClient::Status& http_status() const { // TODO: blob_uploader should support this API? return blob_uploader_->http_status(); } private: enum State { INIT, RUN, DONE, }; InputFileTask(WorkerThreadManager* wm, std::unique_ptr<BlobClient::Uploader> blob_uploader, FileHashCache* file_hash_cache, const FileStat& file_stat, string filename, bool missed_content, bool linking, bool is_new_file, string old_hash_key); ~InputFileTask(); void SetTaskInput(CompileTask* task, ExecReq_Input* input); static void InitializeStaticOnce(); WorkerThreadManager* wm_; std::unique_ptr<BlobClient::Uploader> blob_uploader_; FileHashCache* file_hash_cache_; const FileStat file_stat_; const string filename_; State state_; mutable Lock mu_; std::map<CompileTask*, ExecReq_Input*> tasks_ GUARDED_BY(mu_); std::vector<std::pair<WorkerThread::ThreadId, OneshotClosure*>> callbacks_ GUARDED_BY(mu_); // true if goma servers couldn't find the content, so we must upload it. const bool missed_content_; // true if we'll use hash key only in ExecReq to prevent from bloating it. // false to embed content in ExecReq. bool need_hash_only_; // true if the file is considered as new file, so the file might not be // in goma cache yet. // false means the file is old enough, so we could think someone else already // uploaded the content in goma cache. const bool is_new_file_; // hash key stored in file_hash_cache. const string old_hash_key_; SimpleTimer timer_; // true if goma file ops is succeeded. bool success_; // true if the hash_key_ is first inserted in file hash cache. bool new_cache_key_; static absl::once_flag init_once_; static Lock global_mu_; static std::unordered_map<string, InputFileTask*>* task_by_filename_ GUARDED_BY(global_mu_); DISALLOW_COPY_AND_ASSIGN(InputFileTask); }; } // namespace devtools_goma #endif // DEVTOOLS_GOMA_CLIENT_TASK_INPUT_FILE_TASK_H_
29.506757
79
0.721319
[ "vector" ]
3823834a434bb68c633dba60fd766b3d9446a369
5,096
c
C
mentos/src/descriptor_tables/idt.c
adamantinum/MentOS
d24274f1047a0df0ed925297329c61332b3dab0f
[ "MIT" ]
1
2022-01-10T15:14:10.000Z
2022-01-10T15:14:10.000Z
mentos/src/descriptor_tables/idt.c
LauraCanaia/MentOS
9af9701ddb34b7904d9379badc2ba8e19a7b7071
[ "MIT" ]
null
null
null
mentos/src/descriptor_tables/idt.c
LauraCanaia/MentOS
9af9701ddb34b7904d9379badc2ba8e19a7b7071
[ "MIT" ]
null
null
null
/// MentOS, The Mentoring Operating system project /// @file idt.c /// @brief Functions which manage the Interrupt Descriptor Table (IDT). /// @copyright (c) 2019 This file is distributed under the MIT License. /// See LICENSE.md for details. #include "idt.h" #include "gdt.h" #include "debug.h" /// @brief This function is in idt.asm. extern void idt_flush(uint32_t idt_pointer); /// The IDT itself. static idt_descriptor_t idt_table[IDT_SIZE]; /// Pointer structure to give to the CPU. idt_pointer_t idt_pointer; // 1000 0000 #define IDT_PRESENT 0x80 // 0000 0000 #define IDT_KERNEL 0x00 // 0110 0000 #define IDT_USER 0x60 // 0000 1110 #define IDT_PADDING 0x0E void init_idt() { // Prepare IDT vector. for (uint32_t it = 0; it < IDT_SIZE; ++it) { idt_table[it].offset_low = 0; idt_table[it].seg_selector = 0; idt_table[it].null_par = 0; idt_table[it].options = 0; idt_table[it].offset_high = 0; } // Just like the GDT, the IDT has a "limit" field that is set to the last // valid byte in the IDT, after adding in the start position (i.e. size-1). idt_pointer.limit = sizeof(idt_descriptor_t) * IDT_SIZE - 1; idt_pointer.base = (uint32_t)&idt_table; // Initialize ISR for CPU execptions. isrs_init(); // Initialize ISR for PIC interrupts. irqs_init(); // Register ISR [0-31] + 80, interrupts generated by CPU. // These interrupts will be initially managed by isr_handler. // The appropriate handler will be called by looking at the vector // isr_routines. idt_set_gate(0, INT_0, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(1, INT_1, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(2, INT_2, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(3, INT_3, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(4, INT_4, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(5, INT_5, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(6, INT_6, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(7, INT_7, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(8, INT_8, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(9, INT_9, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(10, INT_10, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(11, INT_11, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(12, INT_12, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(13, INT_13, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(14, INT_14, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(15, INT_15, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(16, INT_16, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(17, INT_17, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(18, INT_18, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(19, INT_19, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(20, INT_20, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(21, INT_21, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(22, INT_22, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(23, INT_23, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(24, INT_24, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(25, INT_25, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(26, INT_26, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(27, INT_27, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(28, INT_28, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(29, INT_29, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(30, INT_30, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(31, INT_31, IDT_PRESENT | IDT_KERNEL, 0x8); // Registers ISR [32-47] (irq [0-15]), interrupts generated by PIC. // These interrupts will be initially managed by irq_handler. // The appropriate handler will be called by looking at the vector // isr_routines. idt_set_gate(32, IRQ_0, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(33, IRQ_1, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(34, IRQ_2, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(35, IRQ_3, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(36, IRQ_4, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(37, IRQ_5, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(38, IRQ_6, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(39, IRQ_7, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(40, IRQ_8, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(41, IRQ_9, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(42, IRQ_10, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(43, IRQ_11, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(44, IRQ_12, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(45, IRQ_13, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(46, IRQ_14, IDT_PRESENT | IDT_KERNEL, 0x8); idt_set_gate(47, IRQ_15, IDT_PRESENT | IDT_KERNEL, 0x8); // System call! idt_set_gate(128, INT_80, IDT_PRESENT | IDT_USER, 0x8); // Points the processor's internal register to the new IDT. idt_flush((uint32_t)&idt_pointer); } void idt_set_gate(uint8_t index, interrupt_handler_t handler, uint16_t options, uint8_t seg_sel) { uint32_t base_prt = (uint32_t)handler; // Assign the base values. idt_table[index].offset_low = (base_prt & 0xFFFF); idt_table[index].offset_high = (base_prt >> 16) & 0xFFFF; // Set the other fields. idt_table[index].null_par = 0x00; idt_table[index].seg_selector = seg_sel; idt_table[index].options = options | IDT_PADDING; }
39.2
79
0.7396
[ "vector" ]
3838350bf19466d16586a67490822931fa1cedc9
959
h
C
decoders/nv_decoder.h
AkillesAILimited/Sensor-Stream-Pipe
9c8671ad5d5e5fdfd43f4d835fa89c36d4de8a6e
[ "MIT" ]
52
2019-12-05T18:00:46.000Z
2022-03-24T04:21:01.000Z
decoders/nv_decoder.h
AkillesAILimited/Sensor-Stream-Pipe
9c8671ad5d5e5fdfd43f4d835fa89c36d4de8a6e
[ "MIT" ]
7
2020-03-24T22:28:08.000Z
2022-02-25T14:28:02.000Z
decoders/nv_decoder.h
AkillesAILimited/Sensor-Stream-Pipe
9c8671ad5d5e5fdfd43f4d835fa89c36d4de8a6e
[ "MIT" ]
10
2020-04-04T00:08:33.000Z
2022-02-25T01:34:12.000Z
/** * \file nv_decoder.h @brief NvPipe decoder */ // Created by amourao on 12-09-2019 #pragma once #include <NvPipe.h> #include <iostream> #include <opencv2/core/mat.hpp> #include "../utils/nvpipe_types.h" #include "../utils/video_utils.h" #include "idecoder.h" namespace moetsi::ssp { /** * @brief NvPipe decoder */ class NvDecoder : public IDecoder { private: NvPipe* decoder_; std::vector<uint8_t> decompressed_buffer_; unsigned int width_; unsigned int height_; NvPipe_Codec codec_; NvPipe_Format format_; public: /** @brief Constructor */ NvDecoder(); /** @brief Destructor */ ~NvDecoder(); /** * @brief Initialize. * \param parameter_data parameters */ void Init(std::vector<unsigned char> parameter_data); /** * @brief Extract an opencv image from a FrameStruct * \param data FrameStruct * \return OpenCV matrix/image */ cv::Mat Decode(FrameStruct& frame); }; } // namespace moetsi::ssp
19.979167
55
0.679875
[ "vector" ]
383a8638eb16f127ca27c16e3a4c4eb0ce290770
2,613
h
C
gym-cloth/render/src/cloth.h
ernovoseller/BC_switching_criteria
44259dd17d14bc6bab05afb5df79943773508419
[ "MIT" ]
null
null
null
gym-cloth/render/src/cloth.h
ernovoseller/BC_switching_criteria
44259dd17d14bc6bab05afb5df79943773508419
[ "MIT" ]
null
null
null
gym-cloth/render/src/cloth.h
ernovoseller/BC_switching_criteria
44259dd17d14bc6bab05afb5df79943773508419
[ "MIT" ]
null
null
null
#ifndef CLOTH_H #define CLOTH_H #include <unordered_set> #include <unordered_map> #include <vector> #include <zmq.hpp> #include "CGL/CGL.h" #include "CGL/misc.h" #include "clothMesh.h" #include "collision/collisionObject.h" #include "spring.h" using namespace CGL; using namespace std; enum e_orientation { HORIZONTAL = 0, VERTICAL = 1 }; /** * Create `ClothParameters` and `Cloth` data structures. A bunch of stuff * without definitions; look at `cloth.cpp` for details. The parameters here are * useful for rendering. Don't worry too much about these, look at `Cloth`. * * Note that tilde operators are destructors. Look them up: * https://stackoverflow.com/questions/5343437/meaning-of-tilde-symbol-in-c */ struct ClothParameters { ClothParameters() {} ClothParameters(bool enable_structural_constraints, bool enable_shearing_constraints, bool enable_bending_constraints, double damping, double density, double ks) : enable_structural_constraints(enable_structural_constraints), enable_shearing_constraints(enable_shearing_constraints), enable_bending_constraints(enable_bending_constraints), damping(damping), density(density), ks(ks) {} ~ClothParameters() {} // Global simulation parameters bool enable_structural_constraints; bool enable_shearing_constraints; bool enable_bending_constraints; double damping; // Mass-spring parameters double density; double ks; }; /** * Need spatial hashing with the cloth, requires the hash position from a given * Vector3D (i.e., a 3D position in whatever space we're using). */ struct Cloth { Cloth() {} Cloth(double width, double height, int num_width_points, int num_height_points, float thickness); ~Cloth(); void buildGrid(); void simulate(double frames_per_sec, double simulation_steps, ClothParameters *cp, vector<Vector3D> external_accelerations, vector<CollisionObject *> *collision_objects); void reset(); void buildClothMesh(); void build_spatial_map(); void self_collide(PointMass &pm, double simulation_steps); float hash_position(Vector3D pos); // Cloth properties double width; double height; int num_width_points; int num_height_points; double thickness; e_orientation orientation; // Cloth components vector<PointMass> point_masses; vector<vector<int>> pinned; vector<Spring> springs; ClothMesh *clothMesh; zmq::socket_t *subscriber; // Spatial hashing unordered_map<float, vector<PointMass *> *> map; }; #endif /* CLOTH_H */
26.393939
84
0.723689
[ "vector", "3d" ]
383e385976762dc636d595ee4121ed1992471083
5,934
c
C
src/rt/viewdir.c
lf-/brlcad
f91ea585c1a930a2e97c3f5a8274db8805ebbb46
[ "BSD-4-Clause", "BSD-3-Clause" ]
83
2021-03-10T05:54:52.000Z
2022-03-31T16:33:46.000Z
src/rt/viewdir.c
lf-/brlcad
f91ea585c1a930a2e97c3f5a8274db8805ebbb46
[ "BSD-4-Clause", "BSD-3-Clause" ]
13
2021-06-24T17:07:48.000Z
2022-03-31T15:31:33.000Z
src/rt/viewdir.c
lf-/brlcad
f91ea585c1a930a2e97c3f5a8274db8805ebbb46
[ "BSD-4-Clause", "BSD-3-Clause" ]
54
2021-03-10T07:57:06.000Z
2022-03-28T23:20:37.000Z
/* V I E W D I R . C * BRL-CAD * * Copyright (c) 1993-2021 United States Government as represented by * the U.S. Army Research Laboratory. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this file; see the file named COPYING for more * information. */ /** @file rt/viewdir.c * * RT-View-Module for printing out the hit point of a ray and the ray's * direction on a user-specified grid. * */ #include "common.h" #include <stdio.h> #include <math.h> #include "vmath.h" #include "raytrace.h" #include "./rtuif.h" #include "./ext.h" extern int width; /* # of pixels in X; picture width */ extern int npsw; /* number of worker PSWs to run */ /* Viewing module specific "set" variables */ struct bu_structparse view_parse[] = { {"", 0, (char *)0, 0, BU_STRUCTPARSE_FUNC_NULL } }; char usage[] = "\ Usage: rtrange [options] model.g objects... >file.ray\n\ Options:\n\ -s # Grid size in pixels, default 512\n\ -a Az Azimuth in degrees (conflicts with -M)\n\ -e Elev Elevation in degrees (conflicts with -M)\n\ -M Read model2view matrix on stdin (conflicts with -a, -e)\n\ -o model.g Specify output file (default=stdout)\n\ -U # Set use_air boolean to # (default=0)\n\ -x # Set librt debug flags\n\ "; int rayhit(register struct application *ap, struct partition *PartHeadp), raymiss(register struct application *ap); /* * This routine is called by main(). It initializes the entire run, i.e., * it does things such as opening files, etc., which must be done before * any other computations take place. It is called only once per run. * Pointers to rayhit() and raymiss() are set up and are later called from * do_run(). * */ int view_init(register struct application *ap, char *file, char *obj, int minus_o) { ap->a_hit = rayhit; ap->a_miss = raymiss; ap->a_onehit = 1; /* only the first hit is considered */ output_is_binary = 0; /* output is not binary */ return 0; /* No framebuffer needed */ } /* * A null-function. * View_2init is called by do_frame(), which in turn is called by * main() in rt.c. This routine is called once per frame. Static * images only have one frame. Animations have MANY frames, and bounding * boxes, for example, need to be computed once per frame. * Never preclude a new and nifty animation: rule: if it's a variable, it can * change from frame to frame ( frame/picture width; angle between surface * normals triggering shading.... etc.). */ void view_2init(struct application *ap) { if ( outfp == NULL ) bu_exit(EXIT_FAILURE, "outfp is NULL\n"); /* * For now, RTVIEWDIR does not operate in parallel, while ray-tracing. * However, not dropping out of parallel mode here permits * tree walking and database prepping to still be done in parallel. */ if ( npsw >= 1 ) { bu_log("Note: changing from %d cpus to 1 cpu\n", npsw ); npsw = 1; /* Disable parallel processing */ } } /* * This function is called by rt_shootray(), which is called by * do_frame(). Records coordinates where a miss is detected. */ int raymiss(register struct application *ap) { struct cell *posp; /* store the current cell position */ /* Getting defensive.... just in case. */ if (ap->a_x > width) { bu_exit(EXIT_FAILURE, "raymiss: pixels exceed width\n"); } return 0; } /* * This routine is called from do_run(), and in this case does nothing. */ void view_pixel(void) { return; } void view_setup(void) {} void view_cleanup(void) {} /* * Rayhit() is called by rt_shootray() when a hit is detected. It * computes the hit distance, the distance traveled by the * ray, and the direction vector. * */ int rayhit(struct application *ap, register struct partition *PartHeadp) { register struct partition *pp = PartHeadp->pt_forw; if ( pp == PartHeadp ) return 0; /* nothing was actually hit?? */ /* Getting defensive.... just in case. */ if (ap->a_x > width) { bu_exit(EXIT_FAILURE, "rayhit: pixels exceed width\n"); } /* Calculate the hit distance and the direction vector. This is done * by VJOIN1(hitp->hit_point, rp->r_pt, hitp->hit_dist, rp->r_dir). */ VJOIN1(pp->pt_inhit->hit_point, ap->a_ray.r_pt, pp->pt_inhit->hit_dist, ap->a_ray.r_dir); /* Print the information onto stdout. The first three numbers are * ray impact coordinates, and the next three numbers are the ray * direction. The line must be semi-colon terminated so that * the output can be read by "miss" for use with PCAVAM. */ fprintf(stdout, "%g %g %g %g %g %g;\n", pp->pt_inhit->hit_point[0], pp->pt_inhit->hit_point[1], pp->pt_inhit->hit_point[2], ap->a_ray.r_dir[0], ap->a_ray.r_dir[1], ap->a_ray.r_dir[2]); return 0; } /* * View_eol() is called by rt_shootray() in do_run(). * This routine is called by worker.c whenever there is a full scanline. * worker.c figures out what is a full scanline. Whenever there * is a full buffer in memory, the hit distances ar plotted. */ void view_eol(struct application *ap) { } /* * View_end() is called by rt_shootray in do_run(). */ void view_end(struct application *ap) { fflush(outfp); } void application_init (void) {} /* * Local Variables: * mode: C * tab-width: 8 * indent-tabs-mode: t * c-file-style: "stroustrup" * End: * ex: shiftwidth=4 tabstop=8 */
25.912664
115
0.668689
[ "cad", "vector", "model" ]
383f06a1c5ed99a89232a5f96eebf5cc554d6463
3,058
h
C
BasicRenderEngine/include/Model/Mesh.h
chbaker0/gl-engine
7721c90d6bb552b99f01a57d30bafa772937cdb7
[ "MIT" ]
3
2015-03-19T10:58:49.000Z
2015-06-16T08:50:30.000Z
BasicRenderEngine/include/Model/Mesh.h
chbaker0/gl-engine
7721c90d6bb552b99f01a57d30bafa772937cdb7
[ "MIT" ]
null
null
null
BasicRenderEngine/include/Model/Mesh.h
chbaker0/gl-engine
7721c90d6bb552b99f01a57d30bafa772937cdb7
[ "MIT" ]
null
null
null
/* * Mesh.h * * Created on: Apr 5, 2015 * Author: Collin */ #ifndef MODEL_MESH_H_INCLUDED #define MODEL_MESH_H_INCLUDED #include <memory> #include <stdexcept> #include <utility> #include "GLContext.h" #include "GLVertexArrayObject.h" #include "BufferUtils/GLBufferView.h" class MeshVertexData { public: virtual ~MeshVertexData() {}; virtual void release(GLsizeiptr indexOffset, GLsizeiptr indexCount) = 0; virtual GLVertexArrayObject* getVAO() = 0; virtual GLBuffer* getBuffer() = 0; }; class Mesh { private: MeshVertexData *vertexData; GLenum primType; GLenum indexType; GLsizeiptr indexOffset; GLsizeiptr indexCount; public: Mesh(): vertexData(nullptr), primType(GL_INVALID_ENUM), indexType(GL_INVALID_ENUM), indexOffset(0), indexCount(0) {} Mesh(const Mesh&) = delete; Mesh(Mesh&& other) { vertexData = other.vertexData; primType = other.primType; indexType = other.indexType; indexOffset = other.indexOffset; indexCount = other.indexCount; other.vertexData = nullptr; } Mesh(MeshVertexData *vaoWrapper_in, GLenum primType_in, GLenum indexType_in, GLsizeiptr indexOffset_in, GLsizeiptr indexCount_in): vertexData(vaoWrapper_in), primType(primType_in), indexType(indexType_in), indexOffset(indexOffset_in), indexCount(indexCount_in) {} ~Mesh() { if(vertexData != nullptr) vertexData->release(indexOffset, indexCount); } Mesh& operator= (Mesh other) { swap(other); return *this; } void swap(Mesh& other) { using std::swap; swap(vertexData, other.vertexData); swap(primType, other.primType); swap(indexType, other.indexType); swap(indexOffset, other.indexOffset); swap(indexCount, other.indexCount); } GLsizeiptr getIndexCount() const { return indexCount; } GLsizeiptr getIndexOffset() const { return indexOffset; } GLenum getIndexType() const { return indexType; } GLenum getPrimType() const { return primType; } const GLVertexArrayObject* getVao() const { return vertexData->getVAO(); } GLVertexArrayObject* getVao() { return vertexData->getVAO(); } void draw(GLContext& context); }; struct MeshVertexAttribDescriptor { GLVertexArrayObject::Attribute attrib; GLint size; GLenum type; GLboolean normalize; GLsizei stride; GLsizeiptr offset; }; class MeshLoaderError : public std::runtime_error { public: MeshLoaderError(const char *errorString): runtime_error(errorString) {} }; Mesh createMeshFromExisting(GLVertexArrayObject *vao, GLenum primType, GLenum indexType, GLsizeiptr indexOffset, GLsizeiptr indexCount); Mesh loadMeshFromMem(GLContext *context, const void *vertexData, const MeshVertexAttribDescriptor *attribs, unsigned int attribCount, GLsizei vertexCount, const void *indexData, GLenum indexType, GLsizei indexCount, GLenum primType); Mesh loadMeshFromFile(GLContext *context, std::string filename); #endif /* MODEL_MESH_H_INCLUDED */
22.485294
155
0.709941
[ "mesh" ]
38408239ad015abef694d16958de71fadce48b28
8,022
h
C
Libraries/gtkmm/include/atkmm/atkmm/relation.h
utilForever/Wings
1dbf0c88cf3cc97b48788c23abc50c32447e228a
[ "MIT" ]
3
2017-01-19T09:30:50.000Z
2017-03-20T10:47:20.000Z
dependancies/include/gtkmm/atkmm/relation.h
Illation/synthesizer
da77d55c1c69829bbad76d0c14b9c56a5261b642
[ "MIT" ]
null
null
null
dependancies/include/gtkmm/atkmm/relation.h
Illation/synthesizer
da77d55c1c69829bbad76d0c14b9c56a5261b642
[ "MIT" ]
2
2017-01-19T09:32:19.000Z
2021-03-15T16:00:43.000Z
// -*- c++ -*- // Generated by gmmproc 2.47.3.1 -- DO NOT MODIFY! #ifndef _ATKMM_RELATION_H #define _ATKMM_RELATION_H #include <glibmm/ustring.h> #include <sigc++/sigc++.h> /* $Id: relation.hg,v 1.3 2005/01/05 18:21:30 murrayc Exp $ */ /* Copyright (C) 1998-2002 The gtkmm Development Team * * 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <glibmm/object.h> #include <glibmm/arrayhandle.h> #ifndef DOXYGEN_SHOULD_SKIP_THIS typedef struct _AtkRelation AtkRelation; typedef struct _AtkRelationClass AtkRelationClass; #endif /* DOXYGEN_SHOULD_SKIP_THIS */ #ifndef DOXYGEN_SHOULD_SKIP_THIS namespace Atk { class Relation_Class; } // namespace Atk #endif //DOXYGEN_SHOULD_SKIP_THIS namespace Atk { /** @addtogroup atkmmEnums atkmm Enums and Flags */ /** * @var RelationType RELATION_NULL * Not used, represens "no relationship" or an error condition. * * @var RelationType RELATION_CONTROLLED_BY * Indicates an object controlled by one or more target objects. * * @var RelationType RELATION_CONTROLLER_FOR * Indicates an object is an controller for one or more target objects. * * @var RelationType RELATION_LABEL_FOR * Indicates an object is a label for one or more target objects. * * @var RelationType RELATION_LABELLED_BY * Indicates an object is labelled by one or more target objects. * * @var RelationType RELATION_MEMBER_OF * Indicates an object is a member of a group of one or more target objects. * * @var RelationType RELATION_NODE_CHILD_OF * Indicates an object is a cell in a treetable which is displayed because a cell in the same column is expanded and identifies that cell. * * @var RelationType RELATION_FLOWS_TO * Indicates that the object has content that flows logically to another * AtkObject in a sequential way, (for instance text-flow). * * @var RelationType RELATION_FLOWS_FROM * Indicates that the object has content that flows logically from * another AtkObject in a sequential way, (for instance text-flow). * * @var RelationType RELATION_SUBWINDOW_OF * Indicates a subwindow attached to a component but otherwise has no connection in the UI heirarchy to that component. * * @var RelationType RELATION_EMBEDS * Indicates that the object visually embeds * another object's content, i.e. this object's content flows around * another's content. * * @var RelationType RELATION_EMBEDDED_BY * Inverse of Atk::RELATION_EMBEDS, indicates that * this object's content is visualy embedded in another object. * * @var RelationType RELATION_POPUP_FOR * Indicates that an object is a popup for another object. * * @var RelationType RELATION_PARENT_WINDOW_OF * Indicates that an object is a parent window of another object. * * @var RelationType RELATION_DESCRIBED_BY * Indicates that another object provides descriptive information about this object; more verbose than ATK_RELATION_LABELLED_BY. * * @var RelationType RELATION_DESCRIPTION_FOR * Indicates that an object provides descriptive information about another object; more verbose than ATK_RELATION_LABEL_FOR. * * @var RelationType RELATION_NODE_PARENT_OF * Indicates an object is a cell in a treetable and is expanded to display other cells in the same column. * * @var RelationType RELATION_LAST_DEFINED * Not used, this value indicates the end of the enumeration. * * @enum RelationType * * Describes the type of the relation * * @ingroup atkmmEnums */ enum RelationType { RELATION_NULL, RELATION_CONTROLLED_BY, RELATION_CONTROLLER_FOR, RELATION_LABEL_FOR, RELATION_LABELLED_BY, RELATION_MEMBER_OF, RELATION_NODE_CHILD_OF, RELATION_FLOWS_TO, RELATION_FLOWS_FROM, RELATION_SUBWINDOW_OF, RELATION_EMBEDS, RELATION_EMBEDDED_BY, RELATION_POPUP_FOR, RELATION_PARENT_WINDOW_OF, RELATION_DESCRIBED_BY, RELATION_DESCRIPTION_FOR, RELATION_NODE_PARENT_OF, RELATION_LAST_DEFINED }; } // namespace Atk #ifndef DOXYGEN_SHOULD_SKIP_THIS namespace Glib { template <> class Value<Atk::RelationType> : public Glib::Value_Enum<Atk::RelationType> { public: static GType value_type() G_GNUC_CONST; }; } // namespace Glib #endif /* DOXYGEN_SHOULD_SKIP_THIS */ namespace Atk { class Object; /** An Atk::Relation describes a relation between an object and one or more other objects. * The actual relations that an object has with other objects are defined as an Atk::RelationSet, * which is a set of Atk::Relations. */ class Relation : public Glib::Object { #ifndef DOXYGEN_SHOULD_SKIP_THIS public: typedef Relation CppObjectType; typedef Relation_Class CppClassType; typedef AtkRelation BaseObjectType; typedef AtkRelationClass BaseClassType; // noncopyable Relation(const Relation&) = delete; Relation& operator=(const Relation&) = delete; private: friend class Relation_Class; static CppClassType relation_class_; protected: explicit Relation(const Glib::ConstructParams& construct_params); explicit Relation(AtkRelation* castitem); #endif /* DOXYGEN_SHOULD_SKIP_THIS */ public: Relation(Relation&& src) noexcept; Relation& operator=(Relation&& src) noexcept; virtual ~Relation() noexcept; /** Get the GType for this class, for use with the underlying GObject type system. */ static GType get_type() G_GNUC_CONST; #ifndef DOXYGEN_SHOULD_SKIP_THIS static GType get_base_type() G_GNUC_CONST; #endif ///Provides access to the underlying C GObject. AtkRelation* gobj() { return reinterpret_cast<AtkRelation*>(gobject_); } ///Provides access to the underlying C GObject. const AtkRelation* gobj() const { return reinterpret_cast<AtkRelation*>(gobject_); } ///Provides access to the underlying C instance. The caller is responsible for unrefing it. Use when directly setting fields in structs. AtkRelation* gobj_copy(); private: protected: explicit Relation(const Glib::ArrayHandle< Glib::RefPtr<Atk::Object> >& targets, RelationType relationship); public: static Glib::RefPtr<Relation> create(const Glib::ArrayHandle< Glib::RefPtr<Atk::Object> >& targets, RelationType relationship = RELATION_NULL); /** Gets the type of @a relation * * @return The type of @a relation. */ RelationType get_relation_type() const; Glib::ArrayHandle< Glib::RefPtr<Atk::Object> > get_target(); Glib::ArrayHandle< Glib::RefPtr<const Atk::Object> > get_target() const; /** Adds the specified AtkObject to the target for the relation, if it is * not already present. See also Atk::Object::add_relationship(). * * * @newin{1,9} * * @param target An Atk::Object. */ void add_target(const Glib::RefPtr<Atk::Object>& target); public: public: //C++ methods used to invoke GTK+ virtual functions: protected: //GTK+ Virtual Functions (override these to change behaviour): //Default Signal Handlers:: }; } // namespace Atk namespace Glib { /** A Glib::wrap() method for this object. * * @param object The C instance. * @param take_copy False if the result should take ownership of the C instance. True if it should take a new copy or ref. * @result A C++ instance that wraps this C instance. * * @relates Atk::Relation */ Glib::RefPtr<Atk::Relation> wrap(AtkRelation* object, bool take_copy = false); } #endif /* _ATKMM_RELATION_H */
28.446809
146
0.744203
[ "object" ]
3844dde5a0bcb6501fb92cc1abbc03c5ef63c79d
788
h
C
Classes/Model/Bonus/IBonus.h
nonothing/Dyna-Blaster-cocos2dx
c128b4e982f7d984e8933196bf199423db997a6e
[ "Unlicense" ]
10
2016-09-19T21:58:37.000Z
2021-04-01T13:41:44.000Z
Classes/Model/Bonus/IBonus.h
nonothing/Dyna-Blaster
c128b4e982f7d984e8933196bf199423db997a6e
[ "Unlicense" ]
null
null
null
Classes/Model/Bonus/IBonus.h
nonothing/Dyna-Blaster
c128b4e982f7d984e8933196bf199423db997a6e
[ "Unlicense" ]
null
null
null
#ifndef __IBONUS_H__ #define __IBONUS_H__ #include "cocos2d.h" #include "Model/Data/PlayerData.h" class IBonus : public cocos2d::Node { protected: PlayerData& _data; cocos2d::Sprite* _sprite; inline std::vector<cocos2d::Node*> getBonusesByTag(int tag) { std::vector< cocos2d::Node* > result; auto parent = getParent(); if (parent) { for (auto node : parent->getChildren()) { if (node->getTag() == tag) { result.push_back(node); } } } return result; } virtual void end() { removeFromParentAndCleanup(true); } public: virtual bool init(cocos2d::Sprite* sprite) { if (!Node::init()) return false; _sprite = sprite; return true; } IBonus(PlayerData& data) : _data(data) { } virtual void active() = 0; }; #endif // __IBONUS_H__
17.511111
60
0.654822
[ "vector", "model" ]
38472ef24c38227131a1d2561cbaa22ddc6b9f10
10,802
h
C
package/lib-nntest/ck_nntest_armcl.h
G4V/ck-nntest
0c1a52cfe2c6634f0edae3f14911fa43838a17f6
[ "BSD-3-Clause" ]
9
2018-08-08T03:17:06.000Z
2021-01-03T13:24:40.000Z
package/lib-nntest/ck_nntest_armcl.h
G4V/ck-nntest
0c1a52cfe2c6634f0edae3f14911fa43838a17f6
[ "BSD-3-Clause" ]
9
2018-07-12T09:32:14.000Z
2020-06-30T13:35:01.000Z
package/lib-nntest/ck_nntest_armcl.h
G4V/ck-nntest
0c1a52cfe2c6634f0edae3f14911fa43838a17f6
[ "BSD-3-Clause" ]
4
2018-07-31T13:12:31.000Z
2020-08-09T19:25:37.000Z
/* * Copyright (c) 2017 cTuning foundation. * See CK COPYRIGHT.txt for copyright details. * * SPDX-License-Identifier: BSD-3-Clause. * See CK LICENSE.txt for licensing details. */ #ifndef CK_NNTEST_ARMCL_H #define CK_NNTEST_ARMCL_H #include <arm_compute/runtime/CL/CLScheduler.h> #include <arm_compute/runtime/CL/CLTensor.h> #include <arm_compute/runtime/CL/CLTuner.h> #if defined(ARMCL_18_05_PLUS) #include <arm_compute/runtime/CL/tuners/BifrostTuner.h> #endif #include "ck_nntest_common.h" namespace CK { namespace armcl { enum CKDataLayout { LAYOUT_NCHW, LAYOUT_NHWC, }; void printf_callback(const char *buffer, unsigned int len, size_t complete, void *user_data) { printf("%.*s", len, buffer); } inline void set_kernel_path() { const char *kernel_path = getenv("CK_ENV_LIB_ARMCL_CL_KERNELS"); if (kernel_path) { printf("Kernel path: %s\n", kernel_path); arm_compute::CLKernelLibrary::get().set_kernel_path(kernel_path); } } inline void init_armcl(arm_compute::ICLTuner *cl_tuner = nullptr) { cl_context_properties properties[] = { CL_PRINTF_CALLBACK_ARM, reinterpret_cast<cl_context_properties>(printf_callback), CL_PRINTF_BUFFERSIZE_ARM, static_cast<cl_context_properties>(0x100000), CL_CONTEXT_PLATFORM, reinterpret_cast<cl_context_properties>(cl::Platform::get()()), 0 }; cl::Context::setDefault(cl::Context(CL_DEVICE_TYPE_DEFAULT, properties)); arm_compute::CLScheduler::get().default_init(cl_tuner); // Should be called after initialization set_kernel_path(); } using TunerPtr = std::unique_ptr<arm_compute::ICLTuner>; template <typename TCustomTuner> TunerPtr get_lws_tuner() { auto tuner_type = getenv("CK_LWS_TUNER_TYPE"); if (!tuner_type || strcmp(tuner_type, "NONE") == 0) return TunerPtr(); if (strcmp(tuner_type, "CUSTOM") == 0) { printf("INFO: Custom tuner selected\n"); return TunerPtr(new TCustomTuner()); } if (strcmp(tuner_type, "DEFAULT") == 0) { printf("INFO: Tuner selected: CLTuner\n"); return TunerPtr(new arm_compute::CLTuner()); } if (strcmp(tuner_type, "BIFROST") == 0) { #if defined(ARMCL_18_05_PLUS) printf("INFO: Tuner selected: BifrostTuner\n"); auto device = cl::Device::getDefault(); auto gpu_target = arm_compute::get_target_from_device(device); auto gpu_arch = arm_compute::get_arch_from_target(gpu_target); if (gpu_arch != arm_compute::GPUTarget::BIFROST) { printf("WARNING: BifrostTuner selected for non-Bifrost architecture.\n"); } return TunerPtr(new arm_compute::tuners::BifrostTuner()); #else printf("WARNING: BifrostTuner is only available for ArmCL v18.05 and later. " "Default CLTuner will be used instead.\n"); printf("INFO: Tuner selected: CLTuner\n"); return TunerPtr(new arm_compute::CLTuner()); #endif } printf("WARNING: Unknown tuner type: %s\n", tuner_type); return TunerPtr(); } inline int get_flat_index(const Shape &shape, const arm_compute::Coordinates &id, CKDataLayout data_layout) { const int n = id[3]; const int c = data_layout == LAYOUT_NCHW ? id[2] : id[0]; const int h = data_layout == LAYOUT_NCHW ? id[1] : id[2]; const int w = data_layout == LAYOUT_NCHW ? id[0] : id[1]; return n * (shape.width * shape.height * shape.channels) + c * (shape.width * shape.height) + h * shape.width + w; } inline arm_compute::TensorShape tensor_info_to_shape(const arm_compute::TensorInfo *info) { arm_compute::TensorShape shape; for (int dim = 0; dim < info->num_dimensions(); dim++) { shape.set(dim, info->dimension(dim)); } return shape; } // ArmCL stores dimensions as // Layout NCHW: [N C H W] // Dimension index: [3 2 1 0] // Layout NHWC: [N H W C] inline arm_compute::TensorShape to_tensor_shape(const Shape &shape, CKDataLayout data_layout) { switch (data_layout) { case LAYOUT_NCHW: return arm_compute::TensorShape( static_cast<size_t>(shape.width), static_cast<size_t>(shape.height), static_cast<size_t>(shape.channels), static_cast<size_t>(shape.num)); case LAYOUT_NHWC: return arm_compute::TensorShape( static_cast<size_t>(shape.channels), static_cast<size_t>(shape.width), static_cast<size_t>(shape.height), static_cast<size_t>(shape.num)); } return arm_compute::TensorShape(); } inline Shape to_ck_shape(const arm_compute::TensorInfo *info, CKDataLayout data_layout) { Shape shape; switch (data_layout) { case LAYOUT_NCHW: shape.width = info->dimension(0); shape.height = info->dimension(1); shape.channels = info->dimension(2); shape.num = info->dimension(3); break; case LAYOUT_NHWC: shape.channels = info->dimension(0); shape.width = info->dimension(1); shape.height = info->dimension(2); shape.num = info->dimension(3); break; } return shape; } inline CKDataLayout get_data_layout(arm_compute::CLTensor *tensor) { #if defined(ARMCL_18_08_PLUS) return tensor->info()->data_layout() == arm_compute::DataLayout::NCHW ? LAYOUT_NCHW : LAYOUT_NHWC; #else return LAYOUT_NCHW; #endif } template <typename TData> inline void copy_raw_data_to_tensor(arm_compute::CLTensor *tensor, TData *data, const Shape &shape) { auto data_layout = get_data_layout(tensor); arm_compute::Window window; window.use_tensor_dimensions(tensor_info_to_shape(tensor->info())); tensor->map(); arm_compute::Iterator it(tensor, window); arm_compute::execute_window_loop(window, [&](const arm_compute::Coordinates & id) { *reinterpret_cast<TData *>(it.ptr()) = data[get_flat_index(shape, id, data_layout)]; }, it); tensor->unmap(); } template <typename TData> inline void copy_raw_data_to_tensor(arm_compute::CLTensor *tensor, TData *data, int data_count) { assert(tensor->info()->tensor_shape().total_size() == data_count); arm_compute::Window window; window.use_tensor_dimensions(tensor_info_to_shape(tensor->info())); tensor->map(); arm_compute::Iterator it(tensor, window); int index = 0; arm_compute::execute_window_loop(window, [&](const arm_compute::Coordinates & id) { *reinterpret_cast<TData *>(it.ptr()) = data[index++]; }, it); tensor->unmap(); } template <typename TData> inline void copy_raw_data_from_tensor(arm_compute::CLTensor *tensor, TData *data, const Shape &shape) { auto data_layout = get_data_layout(tensor); arm_compute::Window window; window.use_tensor_dimensions(tensor_info_to_shape(tensor->info())); tensor->map(); arm_compute::Iterator it(tensor, window); arm_compute::execute_window_loop(window, [&](const arm_compute::Coordinates & id) { data[get_flat_index(shape, id, data_layout)] = *reinterpret_cast<TData *>(it.ptr()); }, it); tensor->unmap(); } template <typename TData> inline void copy_raw_data_from_tensor(arm_compute::CLTensor *tensor, TData *data, int data_count) { assert(tensor->info()->tensor_shape().total_size() == data_count); arm_compute::Window window; window.use_tensor_dimensions(tensor_info_to_shape(tensor->info())); tensor->map(); arm_compute::Iterator it(tensor, window); int index = 0; arm_compute::execute_window_loop(window, [&](const arm_compute::Coordinates & id) { data[index++] = *reinterpret_cast<TData *>(it.ptr()); }, it); tensor->unmap(); } inline void print_tensor_shape(const char *header, const arm_compute::CLTensor *tensor) { auto info = tensor->info(); printf("%s: num_dims=%d, ", header, static_cast<int>(info->num_dimensions())); for (size_t dim = 0; dim < info->num_dimensions(); dim++) { printf("dim[%d]=%d, ", static_cast<int>(dim), static_cast<int>(info->dimension(dim))); } printf("num_channels=%d\n", static_cast<int>(info->num_channels())); } inline void print_tensor_data(const char *header, arm_compute::CLTensor *tensor) { printf("%s:\n", header); tensor->map(); tensor->print(std::cout); tensor->unmap(); } #if 0 // FIXME: 'scale' used to be of type 'float', now of type 'std::vector<float>'; // 'offset' used to be of type 'int', now of type 'std::vector<int, std:allocator<int> >'. inline void print_quantization_info(const char *header, const arm_compute::TensorInfo &info) { printf("Quantized %s: scale=%f, offset=%d\n", header, info.quantization_info().scale(), info.quantization_info().offset()); } #endif typedef ConvolutionParams PoolingParams; inline PoolingParams get_pooling_params_from_env(int default_kernel, int default_stride, int default_pad) { PoolingParams params; params.kernel = static_cast<unsigned int>(getenv_i("CK_POOL_KERNEL", default_kernel)); params.stride = static_cast<unsigned int>(getenv_i("CK_POOL_STRIDE", default_stride)); params.pad = static_cast<unsigned int>(getenv_i("CK_POOL_PAD", default_pad)); printf("Pooling params: kernel=%d, stride=%d, pad=%d\n", params.kernel, params.stride, params.pad); return params; } inline arm_compute::QuantizationInfo get_quantization_info(float min_value, float max_value) { assert(max_value > min_value); const float quant_min = 0; const float quant_max = 255; const float quant_range = quant_max - quant_min; const float scale = (max_value - min_value) / quant_range; const int offset = fmin(quant_max, fmax(quant_min, round(quant_min - min_value / scale))); return arm_compute::QuantizationInfo(scale, offset); } inline void init_quantization_info(arm_compute::TensorInfo &info, float min_value, float max_value) { info.set_quantization_info(get_quantization_info(min_value, max_value)); } inline CKDataLayout get_data_layout_from_env() { #if defined(ARMCL_18_08_PLUS) auto data_layout_str = getenv("CK_DATA_LAYOUT"); if (!data_layout_str) return LAYOUT_NCHW; if (strcmp(data_layout_str, "NCHW") == 0) return LAYOUT_NCHW; if (strcmp(data_layout_str, "NHWC") == 0) return LAYOUT_NHWC; printf("WARNING: Unknown data layout: %s\n", data_layout_str); #endif return LAYOUT_NCHW; } inline arm_compute::TensorInfo make_tensor_info(const arm_compute::TensorShape& tensor_shape, arm_compute::DataType data_type, CKDataLayout data_layout) { arm_compute::TensorInfo tensor_info(tensor_shape, 1, data_type); #if defined(ARMCL_18_08_PLUS) switch (data_layout) { case LAYOUT_NCHW: tensor_info.set_data_layout(arm_compute::DataLayout::NCHW); break; case LAYOUT_NHWC: tensor_info.set_data_layout(arm_compute::DataLayout::NHWC); break; } #endif return tensor_info; } } // namespace armcl } // namespace CK #endif // CK_NNTEST_ARMCL_H
34.401274
125
0.699222
[ "shape", "vector" ]
3857a4f5a762ccb956263331db255faefa2ee4fa
5,400
h
C
src/Managers/AnimationManager.h
Patuti/crossuo
489f69aba501fee0408c042ef6a45ea1b5cc6c34
[ "MIT" ]
null
null
null
src/Managers/AnimationManager.h
Patuti/crossuo
489f69aba501fee0408c042ef6a45ea1b5cc6c34
[ "MIT" ]
null
null
null
src/Managers/AnimationManager.h
Patuti/crossuo
489f69aba501fee0408c042ef6a45ea1b5cc6c34
[ "MIT" ]
null
null
null
// MIT License // Copyright (C) August 2016 Hotride #pragma once #include <stdint.h> #include <unordered_map> #include <deque> #include <vector> #include <xuocore/mulstruct.h> // AnimationSelector #include "../Globals.h" // ANIMATION_GROUPS class CTargetGump; class CGameCharacter; struct CTextureAnimationDirection; static const int MAX_LAYER_DIRECTIONS = 8; static const float UPPER_BODY_RATIO = 0.35f; static const float MID_BODY_RATIO = 0.60f; static const float LOWER_BODY_RATIO = 0.94f; class CEquipConvData { public: uint16_t Graphic = 0; uint16_t Gump = 0; uint16_t Color = 0; CEquipConvData(uint16_t graphic, uint16_t gump, uint16_t color) : Graphic(graphic) , Gump(gump) , Color(color) { } ~CEquipConvData() {} }; typedef std::unordered_map<uint16_t, CEquipConvData> EQUIP_CONV_DATA_MAP; typedef std::unordered_map<uint16_t, EQUIP_CONV_DATA_MAP> EQUIP_CONV_BODY_MAP; class CAnimationManager { public: uint16_t Color = 0; AnimationSelector SelectAnim; private: size_t m_AddressIdx[6]; size_t m_SizeIdx[6]; int m_CharacterFrameHeight = 0; static void PrepareTargetAttackGump( CTargetGump &gump, int drawX, int drawY, uint16_t targetColor, int per, CGameCharacter &obj); int m_CharacterFrameStartY = 0; int m_StartCharacterWaistY = 0; int m_StartCharacterKneesY = 0; int m_StartCharacterFeetY = 0; int m_Sitting = 0; bool m_UseBlending = false; EQUIP_CONV_BODY_MAP m_EquipConv; CEquipConvData *m_EquipConvItem{ nullptr }; static const int USED_LAYER_COUNT = 23; static const int m_UsedLayers[MAX_LAYER_DIRECTIONS][USED_LAYER_COUNT]; std::vector<std::pair<uint16_t, uint8_t>> m_GroupReplaces[2]; std::deque<CTextureAnimationDirection *> m_UsedAnimList; bool TestPixels( class CGameObject *obj, int x, int y, bool mirror, uint8_t &frameIndex, uint16_t id = 0x0000); void FixSittingDirection(uint8_t &layerDirection, bool &mirror, int &x, int &y); void Draw(class CGameObject *obj, int x, int y, bool mirror, uint8_t &frameIndex, int id = 0); void DrawIntoFrameBuffer(class CGameCharacter *obj, int x, int y); bool DrawEquippedLayers( bool selection, class CGameObject *obj, int drawX, int drawY, bool mirror, uint8_t layerDir, uint8_t animIndex, int lightOffset); bool IsCovered(int layer, class CGameObject *owner); bool m_Transform = false; uint16_t m_CharacterLayerGraphic[25]; uint16_t m_CharacterLayerAnimID[25]; uint8_t GetObjectNewAnimationType_0(CGameCharacter *obj, uint16_t action, uint8_t mode); uint8_t GetObjectNewAnimationType_1_2(CGameCharacter *obj, uint16_t action, uint8_t mode); uint8_t GetObjectNewAnimationType_3(CGameCharacter *obj, uint16_t action, uint8_t mode); uint8_t GetObjectNewAnimationType_4(CGameCharacter *obj, uint16_t action, uint8_t mode); uint8_t GetObjectNewAnimationType_5(CGameCharacter *obj, uint16_t action, uint8_t mode); uint8_t GetObjectNewAnimationType_6_14(CGameCharacter *obj, uint16_t action, uint8_t mode); uint8_t GetObjectNewAnimationType_7(CGameCharacter *obj, uint16_t action, uint8_t mode); uint8_t GetObjectNewAnimationType_8(CGameCharacter *obj, uint16_t action, uint8_t mode); uint8_t GetObjectNewAnimationType_9_10(CGameCharacter *obj, uint16_t action, uint8_t mode); uint8_t GetObjectNewAnimationType_11(CGameCharacter *obj, uint16_t action, uint8_t mode); public: CAnimationManager(); ~CAnimationManager(); void ClearUnusedTextures(uint32_t ticks); void Init(int graphic, size_t addressIdx, size_t sizeIdx) { m_AddressIdx[graphic] = addressIdx; m_SizeIdx[graphic] = sizeIdx; } EQUIP_CONV_BODY_MAP &GetEquipConv() { return m_EquipConv; } void InitIndexReplaces(uint32_t *verdata); void UpdateAnimationAddressTable(); void Load(uint32_t *verdata); void GetAnimDirection(uint8_t &dir, bool &mirror); void GetSittingAnimDirection(uint8_t &dir, bool &mirror, int &x, int &y); void DrawCharacter(class CGameCharacter *obj, int x, int y); bool CharacterPixelsInXY(class CGameCharacter *obj, int x, int y); void DrawCorpse(class CGameItem *obj, int x, int y); bool CorpsePixelsInXY(class CGameItem *obj, int x, int y); uint8_t GetDieGroupIndex(uint16_t id, bool second); ANIMATION_GROUPS GetGroupIndex(uint16_t id); bool AnimationExists(uint16_t graphic, uint8_t group); AnimationFrameInfo GetAnimationDimensions( uint8_t frameIndex, uint16_t id, uint8_t dir, uint8_t animGroup, bool isCorpse); AnimationFrameInfo GetAnimationDimensions( class CGameObject *obj, uint8_t frameIndex = 0xFF, uint8_t defaultDirection = 0, uint8_t defaultGroup = 0); struct DRAW_FRAME_INFORMATION CollectFrameInformation(class CGameObject *gameObject, bool checkLayers = true); uint8_t GetReplacedObjectAnimation(CGameCharacter *obj, uint16_t index); uint8_t GetObjectNewAnimation(CGameCharacter *obj, uint16_t type, uint16_t action, uint8_t mode); CTextureAnimationDirection & ExecuteAnimation(uint8_t group, uint8_t direction, uint16_t graphic); }; extern CAnimationManager g_AnimationManager;
33.128834
98
0.727222
[ "vector" ]
3857bd72f610ed9b3ff578393f08c284fba84297
2,605
h
C
src/mafScriptInterpreter/mafInterpreterConsole.h
examyes/MAF3
f9614d36591754544b23e3a670980799254dfd2c
[ "Apache-2.0" ]
1
2020-05-15T05:19:45.000Z
2020-05-15T05:19:45.000Z
src/mafScriptInterpreter/mafInterpreterConsole.h
examyes/MAF3
f9614d36591754544b23e3a670980799254dfd2c
[ "Apache-2.0" ]
null
null
null
src/mafScriptInterpreter/mafInterpreterConsole.h
examyes/MAF3
f9614d36591754544b23e3a670980799254dfd2c
[ "Apache-2.0" ]
1
2018-02-06T03:51:57.000Z
2018-02-06T03:51:57.000Z
/* * mafInterpreterConsole.h * mafGui * * Created by Paolo Quadrani - Daniele Giunchi on 10/06/11. * Copyright 2011 SCS-B3C. All rights reserved. * * See Licence at: http://tiny.cc/QXJ4D * */ #ifndef MAFINTERPRETERCONSOLE_H #define MAFINTERPRETERCONSOLE_H #include "mafScriptInterpreter_global.h" #include <mafTextEditor.h> namespace mafScriptInterpreter { class mafScriptEditor; /** Class Name: mafInterpreterConsole Represents the widget in which will be logged all the output of the script editor. */ class MAFSCRIPTINTERPRETERSHARED_EXPORT mafInterpreterConsole : public mafGUI::mafTextEditor { Q_OBJECT public Q_SLOTS: /// Key Command Event void onKeyUpPressed(void); /// Key Command Event void onKeyDownPressed(void); /// Key Command Event void onKeyLeftPressed(void); /// Key Command Event void onKeyRightPressed(void); /// Key Command Event void onKeyEnterPressed(void); /// Key Command Event void onKeyBackspacePressed(void); /// Return output void output(const QString& result, int *stat); Q_SIGNALS: /// Signal emitted when input is inserted. QString input(const QString& command, int *stat); /// Signal emitted when load an external script. void load(const QString& path); /// Signal emitted when save a script. void save(const QString& path); /// Signal emitted when request help. void help(void); /// Signal emitted when stopped. void stopped(void); public: /// Object Constructor. mafInterpreterConsole(QWidget *parent = 0); /// Object Destructor. ~mafInterpreterConsole(void); /// Read settings for the interpreter. void readSettings(void); /// Initialize signal/slot connections. void registerInterpreter(mafScriptEditor *interpreter); /// Apply a highlight filter to the text. QString filter(QString text); /// Return current script editor. mafScriptEditor *interpreter(void); protected: /// Key Command Event void keyPressEvent(QKeyEvent *event); /// Mouse Command Event void mousePressEvent(QMouseEvent *event); /// Mouse Command Event void mouseReleaseEvent(QMouseEvent *event); private: mafScriptEditor *m_Interpreter; ///< script interpreter QTextCursor m_Cursor; ///< mouse cursor. QStringList m_History; ///< history list. unsigned int m_HistoryIndex; ///< index of history list. bool m_HistoryDirty; ///< flag for invalidating history. }; } // namespace mafScriptInterpreter #endif
26.581633
94
0.686756
[ "object" ]
385b8b37e88bb914e432e7b91149fa94e3ceb8b3
9,735
c
C
linux/drivers/acpi/events/evxfregn.c
CodeAsm/PS1Linux
8c3c4d9ffccf446dd061a38186efc924da8a66be
[ "CC0-1.0" ]
4
2020-01-01T20:26:42.000Z
2021-10-17T21:51:58.000Z
linux/drivers/acpi/events/evxfregn.c
CodeAsm/PS1Linux
8c3c4d9ffccf446dd061a38186efc924da8a66be
[ "CC0-1.0" ]
4
2020-07-23T11:20:30.000Z
2020-07-24T20:09:09.000Z
linux/drivers/acpi/events/evxfregn.c
CodeAsm/PS1Linux
8c3c4d9ffccf446dd061a38186efc924da8a66be
[ "CC0-1.0" ]
null
null
null
/****************************************************************************** * * Module Name: evxfregn - External Interfaces, ACPI Operation Regions and * Address Spaces. * $Revision: 1.1.1.1 $ * *****************************************************************************/ /* * Copyright (C) 2000 R. Byron Moore * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "acpi.h" #include "achware.h" #include "acnamesp.h" #include "acevents.h" #include "amlcode.h" #include "acinterp.h" #define _COMPONENT EVENT_HANDLING MODULE_NAME ("evxfregn") /****************************************************************************** * * FUNCTION: Acpi_install_address_space_handler * * PARAMETERS: Device - Handle for the device * Space_id - The address space ID * Handler - Address of the handler * Setup - Address of the setup function * Context - Value passed to the handler on each access * * RETURN: Status * * DESCRIPTION: Install a handler for all Op_regions of a given Space_id. * ******************************************************************************/ ACPI_STATUS acpi_install_address_space_handler ( ACPI_HANDLE device, ACPI_ADDRESS_SPACE_TYPE space_id, ADDRESS_SPACE_HANDLER handler, ADDRESS_SPACE_SETUP setup, void *context) { ACPI_OPERAND_OBJECT *obj_desc; ACPI_OPERAND_OBJECT *handler_obj; ACPI_NAMESPACE_NODE *node; ACPI_STATUS status = AE_OK; OBJECT_TYPE_INTERNAL type; u16 flags = 0; /* Parameter validation */ if ((!device) || ((!handler) && (handler != ACPI_DEFAULT_HANDLER)) || (space_id > ACPI_MAX_ADDRESS_SPACE)) { return (AE_BAD_PARAMETER); } acpi_cm_acquire_mutex (ACPI_MTX_NAMESPACE); /* Convert and validate the device handle */ node = acpi_ns_convert_handle_to_entry (device); if (!node) { status = AE_BAD_PARAMETER; goto unlock_and_exit; } /* * This registration is valid for only the types below * and the root. This is where the default handlers * get placed. */ if ((node->type != ACPI_TYPE_DEVICE) && (node->type != ACPI_TYPE_PROCESSOR) && (node->type != ACPI_TYPE_THERMAL) && (node != acpi_gbl_root_node)) { status = AE_BAD_PARAMETER; goto unlock_and_exit; } if (handler == ACPI_DEFAULT_HANDLER) { flags = ADDR_HANDLER_DEFAULT_INSTALLED; switch (space_id) { case ADDRESS_SPACE_SYSTEM_MEMORY: handler = acpi_aml_system_memory_space_handler; setup = acpi_ev_system_memory_region_setup; break; case ADDRESS_SPACE_SYSTEM_IO: handler = acpi_aml_system_io_space_handler; setup = acpi_ev_io_space_region_setup; break; case ADDRESS_SPACE_PCI_CONFIG: handler = acpi_aml_pci_config_space_handler; setup = acpi_ev_pci_config_region_setup; break; default: status = AE_NOT_EXIST; goto unlock_and_exit; break; } } /* * If the caller hasn't specified a setup routine, use the default */ if (!setup) { setup = acpi_ev_default_region_setup; } /* * Check for an existing internal object */ obj_desc = acpi_ns_get_attached_object ((ACPI_HANDLE) node); if (obj_desc) { /* * The object exists. * Make sure the handler is not already installed. */ /* check the address handler the user requested */ handler_obj = obj_desc->device.addr_handler; while (handler_obj) { /* * We have an Address handler, see if user requested this * address space. */ if(handler_obj->addr_handler.space_id == space_id) { status = AE_EXIST; goto unlock_and_exit; } /* * Move through the linked list of handlers */ handler_obj = handler_obj->addr_handler.next; } } else { /* Obj_desc does not exist, create one */ if (node->type == ACPI_TYPE_ANY) { type = ACPI_TYPE_DEVICE; } else { type = node->type; } obj_desc = acpi_cm_create_internal_object (type); if (!obj_desc) { status = AE_NO_MEMORY; goto unlock_and_exit; } /* Init new descriptor */ obj_desc->common.type = (u8) type; /* Attach the new object to the Node */ status = acpi_ns_attach_object (node, obj_desc, (u8) type); if (ACPI_FAILURE (status)) { acpi_cm_remove_reference (obj_desc); goto unlock_and_exit; } } /* * Now we can install the handler * * At this point we know that there is no existing handler. * So, we just allocate the object for the handler and link it * into the list. */ handler_obj = acpi_cm_create_internal_object (INTERNAL_TYPE_ADDRESS_HANDLER); if (!handler_obj) { status = AE_NO_MEMORY; goto unlock_and_exit; } handler_obj->addr_handler.space_id = (u8) space_id; handler_obj->addr_handler.hflags = flags; handler_obj->addr_handler.next = obj_desc->device.addr_handler; handler_obj->addr_handler.region_list = NULL; handler_obj->addr_handler.node = node; handler_obj->addr_handler.handler = handler; handler_obj->addr_handler.context = context; handler_obj->addr_handler.setup = setup; /* * Now walk the namespace finding all of the regions this * handler will manage. * * We start at the device and search the branch toward * the leaf nodes until either the leaf is encountered or * a device is detected that has an address handler of the * same type. * * In either case we back up and search down the remainder * of the branch */ status = acpi_ns_walk_namespace (ACPI_TYPE_ANY, device, ACPI_UINT32_MAX, NS_WALK_UNLOCK, acpi_ev_addr_handler_helper, handler_obj, NULL); /* * Place this handler 1st on the list */ handler_obj->common.reference_count = (u16) (handler_obj->common.reference_count + obj_desc->common.reference_count - 1); obj_desc->device.addr_handler = handler_obj; unlock_and_exit: acpi_cm_release_mutex (ACPI_MTX_NAMESPACE); return (status); } /****************************************************************************** * * FUNCTION: Acpi_remove_address_space_handler * * PARAMETERS: Space_id - The address space ID * Handler - Address of the handler * * RETURN: Status * * DESCRIPTION: Install a handler for accesses on an Operation Region * ******************************************************************************/ ACPI_STATUS acpi_remove_address_space_handler ( ACPI_HANDLE device, ACPI_ADDRESS_SPACE_TYPE space_id, ADDRESS_SPACE_HANDLER handler) { ACPI_OPERAND_OBJECT *obj_desc; ACPI_OPERAND_OBJECT *handler_obj; ACPI_OPERAND_OBJECT *region_obj; ACPI_OPERAND_OBJECT **last_obj_ptr; ACPI_NAMESPACE_NODE *node; ACPI_STATUS status = AE_OK; /* Parameter validation */ if ((!device) || ((!handler) && (handler != ACPI_DEFAULT_HANDLER)) || (space_id > ACPI_MAX_ADDRESS_SPACE)) { return (AE_BAD_PARAMETER); } acpi_cm_acquire_mutex (ACPI_MTX_NAMESPACE); /* Convert and validate the device handle */ node = acpi_ns_convert_handle_to_entry (device); if (!node) { status = AE_BAD_PARAMETER; goto unlock_and_exit; } /* Make sure the internal object exists */ obj_desc = acpi_ns_get_attached_object ((ACPI_HANDLE) node); if (!obj_desc) { /* * The object DNE. */ status = AE_NOT_EXIST; goto unlock_and_exit; } /* * find the address handler the user requested */ handler_obj = obj_desc->device.addr_handler; last_obj_ptr = &obj_desc->device.addr_handler; while (handler_obj) { /* * We have a handler, see if user requested this one */ if(handler_obj->addr_handler.space_id == space_id) { /* * Got it, first dereference this in the Regions */ region_obj = handler_obj->addr_handler.region_list; /* Walk the handler's region list */ while (region_obj) { /* * First disassociate the handler from the region. * * NOTE: this doesn't mean that the region goes away * The region is just inaccessible as indicated to * the _REG method */ acpi_ev_disassociate_region_from_handler(region_obj, FALSE); /* * Walk the list, since we took the first region and it * was removed from the list by the dissassociate call * we just get the first item on the list again */ region_obj = handler_obj->addr_handler.region_list; } /* * Remove this Handler object from the list */ *last_obj_ptr = handler_obj->addr_handler.next; /* * Now we can delete the handler object */ acpi_cm_remove_reference (handler_obj); acpi_cm_remove_reference (handler_obj); goto unlock_and_exit; } /* * Move through the linked list of handlers */ last_obj_ptr = &handler_obj->addr_handler.next; handler_obj = handler_obj->addr_handler.next; } /* * The handler does not exist */ status = AE_NOT_EXIST; unlock_and_exit: acpi_cm_release_mutex (ACPI_MTX_NAMESPACE); return (status); }
25.285714
80
0.648588
[ "object" ]
386218df7a983fa592c8a77c0b47c5b7e063f464
699
h
C
OpenTESArena/src/Interface/ChooseClassCreationPanel.h
AnotherFoxGuy/OpenTESArena
38d2fe72b0ef7e0e838e525bf135f7ef4a7858d7
[ "MIT" ]
742
2016-03-09T17:18:55.000Z
2022-03-21T07:23:47.000Z
OpenTESArena/src/Interface/ChooseClassCreationPanel.h
AnotherFoxGuy/OpenTESArena
38d2fe72b0ef7e0e838e525bf135f7ef4a7858d7
[ "MIT" ]
196
2016-06-07T15:19:21.000Z
2021-12-12T16:50:58.000Z
OpenTESArena/src/Interface/ChooseClassCreationPanel.h
AnotherFoxGuy/OpenTESArena
38d2fe72b0ef7e0e838e525bf135f7ef4a7858d7
[ "MIT" ]
85
2016-04-17T13:25:16.000Z
2022-03-25T06:45:15.000Z
#ifndef CHOOSE_CLASS_CREATION_PANEL_H #define CHOOSE_CLASS_CREATION_PANEL_H #include <string> #include "Panel.h" #include "../UI/Button.h" #include "../UI/TextBox.h" #include "../UI/Texture.h" class Renderer; class ChooseClassCreationPanel : public Panel { private: Texture parchment; TextBox titleTextBox, generateTextBox, selectTextBox; Button<Game&> generateButton, selectButton; void drawTooltip(const std::string &text, Renderer &renderer); public: ChooseClassCreationPanel(Game &game); ~ChooseClassCreationPanel() override = default; bool init(); virtual std::optional<CursorData> getCurrentCursor() const override; virtual void render(Renderer &renderer) override; }; #endif
21.84375
69
0.775393
[ "render" ]
386bacd3bca1541d47d669d8cfa5632a3bfdf4e9
14,707
h
C
testing/volume/RawFileStructuredVolume.h
NicolasHo/openvkl
d48ee28c3b824c39ab7db3013b05eb25678e719e
[ "Apache-2.0" ]
null
null
null
testing/volume/RawFileStructuredVolume.h
NicolasHo/openvkl
d48ee28c3b824c39ab7db3013b05eb25678e719e
[ "Apache-2.0" ]
null
null
null
testing/volume/RawFileStructuredVolume.h
NicolasHo/openvkl
d48ee28c3b824c39ab7db3013b05eb25678e719e
[ "Apache-2.0" ]
null
null
null
// ======================================================================== // // Copyright 2019 Intel Corporation // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // ======================================================================== // #pragma once #include "TestingStructuredVolume.h" // std #include <algorithm> #include <fstream> #include <CImg.h> #include <imebra/imebra.h> #include "./dcm/data_element.h" #include "./dcm/data_sequence.h" #include "./dcm/data_set.h" #include "./dcm/dicom_file.h" #include "./dcm/logger.h" #include "./dcm/visitor.h" #include <dirent.h> #include <algorithm> #include <experimental/filesystem> using namespace ospcommon; namespace openvkl { namespace testing { struct RawFileStructuredVolume : public TestingStructuredVolume { RawFileStructuredVolume(const std::string &filename, std::string &gridType, vec3i &dimensions, vec3f &gridOrigin, vec3f &gridSpacing, VKLDataType voxelType); void initDicomFormat( std::string &gridType, vec3i &dimensions, vec3f &gridOrigin, vec3f &gridSpacing, VKLDataType voxelType); std::vector<unsigned char> generateVoxels() override; std::vector<unsigned char> generateVoxelsDicom(); private: std::string filename; }; // Inlined definitions //////////////////////////////////////////////////// inline RawFileStructuredVolume::RawFileStructuredVolume( const std::string &filename, std::string &gridType, vec3i &dimensions, vec3f &gridOrigin, vec3f &gridSpacing, VKLDataType voxelType) : filename(filename), TestingStructuredVolume( gridType, dimensions, gridOrigin, gridSpacing, voxelType) { if(std::experimental::filesystem::is_directory(std::experimental::filesystem::status(filename))) initDicomFormat(gridType, dimensions, gridOrigin, gridSpacing, voxelType); } inline void RawFileStructuredVolume::initDicomFormat( std::string &_gridType, vec3i &_dimensions, vec3f &_gridOrigin, vec3f &_gridSpacing, VKLDataType _voxelType) { // filename = directory path std::vector<std::string> files; DIR *dirp; struct dirent *directory; int width; int height; dirp = opendir(filename.c_str()); if (dirp) { while ((directory = readdir(dirp)) != NULL) { std::string file = filename + directory->d_name; if(file.substr(file.find_last_of(".") + 1) == "dcm") files.push_back(file); } closedir(dirp); } if(files.size() == 0) { dirp = opendir((filename + "/CTScanData/").c_str()); if (dirp) { while ((directory = readdir(dirp)) != NULL) { std::string file = filename + "/CTScanData/" + directory->d_name; if(file.substr(file.find_last_of(".") + 1) == "jpg") files.push_back(file); } closedir(dirp); } if(files.size() == 0) throw std::runtime_error("error no dicom files (or images) found"); cimg_library::CImg<unsigned char> image(files[0].c_str()); width = image.width(); height = image.height(); std::cout << "JPG | width=" << width << " height="<< height << std::endl; } else { imebra::DataSet loadedDataSet(imebra::CodecFactory::load(files[1], 2048)); // Retrieve the first image (index = 0) imebra::Image image(loadedDataSet.getImageApplyModalityTransform(0)); // Get the size in pixels width = image.getWidth(); height = image.getHeight(); std::cout << "Dicom | width=" << width << " height="<< height << std::endl; } ///////////////////////////////////////////////////////////////////////////////////////////// // imebra::DataSet loadedDataSet(imebra::CodecFactory::load(files[1], 2048)); // // Retrieve the first image (index = 0) // imebra::Image image(loadedDataSet.getImageApplyModalityTransform(0)); // // Get the color space // std::string colorSpace = image.getColorSpace(); // // Get the size in pixels // std::uint32_t width = image.getWidth(); // std::uint32_t height = image.getHeight(); // std::cout << colorSpace << " | width=" << width << " height="<< height << std::endl; ///////////////////////////////////////////////////////////////////////////////////////////// // loading of a random slice // dcm::DicomFile dicom_file(files[0]); // if (!dicom_file.Load()) { // throw std::runtime_error("error opening dicom file"); // } // std::string tmp; // if (dicom_file.GetString(0x00200013, &tmp)) // std::cout << "InstanceNumber:" << tmp << std::endl; // if (dicom_file.GetString(0x00200012, &tmp)) // std::cout << "Acquisition Number:" << tmp << std::endl; // if (dicom_file.GetString(0x00201002, &tmp)) // std::cout << "InstanceNumber:" << tmp << std::endl; // setting the TestingStructuredVolume attributes // std::uint16_t rows; // std::uint16_t columns; // if (!dicom_file.GetUint16(dcm::tags::kRows, &rows)) // throw std::runtime_error("error reading rows volume file"); // if (!dicom_file.GetUint16(dcm::tags::kColumns, &columns)) // throw std::runtime_error("error reading columns volume file"); dimensions = vec3i(width,height,files.size()); // Pixel Aspect Ratio (0028,0034) // Pixel Padding Range Limit (0028,0121) // Slice Thickness (0018,0050) // std::string ratio; // std::string thickness; // if (!dicom_file.GetString(dcm::tags::kPixelSpacing, &ratio)) // throw std::runtime_error("error reading columns volume file"); // if (!dicom_file.GetString(0x00180050, &thickness)) // throw std::runtime_error("error reading columns volume file"); // std::cout << "ratio=" << ratio << " thickness="<< thickness << std::endl; gridSpacing = vec3f(1,1,1); // Slice Location ? gridOrigin = vec3f(0,0,0); // TO-DO gridType = "structured_regular"; // Pixel Representation (0028,0103) voxelType = VKL_USHORT; _gridType = gridType; _dimensions = dimensions; _gridOrigin = gridOrigin; _gridSpacing = gridSpacing; _voxelType = voxelType; } inline std::vector<unsigned char> RawFileStructuredVolume::generateVoxelsDicom() { // generation of the files list std::vector<std::string> files; std::vector<std::string> segm; DIR *dirp; struct dirent *directory; bool areImages = false; dirp = opendir(filename.c_str()); if (dirp) { while ((directory = readdir(dirp)) != NULL) { std::string file = filename + directory->d_name; if(file.substr(file.find_last_of(".") + 1) == "dcm") files.push_back(file); } closedir(dirp); } if(files.size() == 0) { dirp = opendir((filename + "/CTScanData").c_str()); if (dirp) { while ((directory = readdir(dirp)) != NULL) { std::string file = filename + "/CTScanData/" + directory->d_name; if(file.substr(file.find_last_of(".") + 1) == "jpg") files.push_back(file); std::string file_seg = filename + "/LabelledData/" + directory->d_name; if(file_seg.substr(file_seg.find_last_of(".") + 1) == "jpg") segm.push_back(file_seg); } closedir(dirp); } areImages = true; } // sorting slices std::sort(files.begin(), files.end()); if(segm.size() != 0) std::sort(segm.begin(), segm.end()); // creation of the voxels list auto numValues = this->dimensions.long_product(); int voxel_size = sizeOfVKLDataType(voxelType) + sizeof(uint8_t); std::vector<unsigned char> voxels(numValues *voxel_size); // loading voxels int imageSize = this->dimensions.x*this->dimensions.y; std::uint32_t width = this->dimensions.x; std::uint32_t height = this->dimensions.y; uint i, k = voxel_size * height * width; int imageNumber; for (i=0; i<files.size(); i++) { // dcm::DicomFile dicom_file(files[i]); // if (!dicom_file.Load()) { // throw std::runtime_error("error opening raw volume file"); // } // const dcm::DataElement* element = dicom_file.Get(dcm::tags::kPixelData); // k = 0; // for (std::vector<char>::const_iterator j = element->buffer().begin(); j != element->buffer().end(); ++(++j)) // { // voxels[i*imageSize+k] = (unsigned char)i; // k += 1; // } // imebra::DataSet loadedDataSet(imebra::CodecFactory::load(files[i], 2048)); // // Retrieve the first image (index = 0) // imebra::Image image(loadedDataSet.getImageApplyModalityTransform(0)); // // Retrieve the data handler // imebra::ReadingDataHandlerNumeric dataHandler(image.getReadingDataHandler()); // for(std::uint32_t scanY(0); scanY != height; ++scanY) // { // for(std::uint32_t scanX(0); scanX != width; ++scanX) // { // // For monochrome images // std::int32_t luminance = dataHandler.getSignedLong(scanY * width + scanX); // //voxels[4*(scanY * width + scanX) + k] = luminance; // voxels[4*(scanY * width + scanX) + k] = (luminance >> 24) & 0xFF; // voxels[4*(scanY * width + scanX) + k +1] = (luminance >> 16) & 0xFF; // voxels[4*(scanY * width + scanX) + k +2] = (luminance >> 8) & 0xFF; // voxels[4*(scanY * width + scanX) + k +3] = luminance & 0xFF; // } // } // k += 4 * height * width; if(areImages) { cimg_library::CImg<unsigned char> image(files[i].c_str()); cimg_library::CImg<unsigned char> image_seg; if(segm.size() != 0) image_seg = cimg_library::CImg<unsigned char>(segm[i].c_str()); for(int scanY(0); scanY != height; ++scanY) { for(int scanX(0); scanX != width; ++scanX) { uint16_t luminance = static_cast<uint16_t>((int)image(scanX,scanY,0,0)); memcpy(&voxels[voxel_size*(scanY * width + scanX) + (i * k)], &luminance, sizeof(uint16_t)); if(segm.size() != 0) { uint8_t segmentation = static_cast<uint8_t>((int)image_seg(scanX,scanY,0,0)); memcpy(&voxels[sizeOfVKLDataType(voxelType) + voxel_size*(scanY * width + scanX) + (i * k)], &segmentation, sizeof(uint8_t)); } } } } else { { dcm::DicomFile dicom_file(files[i]); if (!dicom_file.Load()) { throw std::runtime_error("error opening dicom file"); } std::string tmp; if (dicom_file.GetString(0x00200013, &tmp)) imageNumber = std::stoi(tmp); // std::cout << "InstanceNumber:" << tmp << std::endl; } imebra::DataSet loadedDataSet(imebra::CodecFactory::load(files[i], 2048)); // Retrieve the first image (index = 0) imebra::Image image(loadedDataSet.getImageApplyModalityTransform(0)); // Retrieve the data handler imebra::ReadingDataHandlerNumeric dataHandler(image.getReadingDataHandler()); for(std::uint32_t scanY(0); scanY != height; ++scanY) { for(std::uint32_t scanX(0); scanX != width; ++scanX) { // For monochrome images float luminance = static_cast<float>(dataHandler.getSignedLong(scanY * width + scanX)); memcpy(&voxels[4*(scanY * width + scanX) + ((imageNumber-1) * k)], &luminance, sizeof(float)); } } } // throw std::runtime_error("error reading raw volume file"); //std::cout << (i-1)*imageSize+k << std::endl; } std::cout << (i * k) << "/" << numValues * voxel_size << " bytes loaded" << std::endl; return voxels; } inline std::vector<unsigned char> RawFileStructuredVolume::generateVoxels() { if(std::experimental::filesystem::is_directory(std::experimental::filesystem::status(filename))) { return generateVoxelsDicom(); } auto numValues = this->dimensions.long_product(); std::vector<unsigned char> voxels(numValues * sizeOfVKLDataType(voxelType)); std::ifstream input(filename, std::ios::binary); if (!input) { throw std::runtime_error("error opening raw volume file"); } input.read( (char *)voxels.data(), this->dimensions.long_product() * sizeOfVKLDataType(voxelType)); if (!input.good()) { throw std::runtime_error("error reading raw volume file"); } return voxels; } } // namespace testing } // namespace openvkl
34.442623
141
0.527028
[ "vector" ]
3874d0f7ea839e7c298dea089c2c992ded7e3c15
9,658
h
C
source/abcc_abp/abp_pnio.h
HMSAB/AbccSpiAnalyzer
59b533ed1e90a925695604007f281d0a50eb86df
[ "MIT" ]
2
2020-12-04T15:12:43.000Z
2022-01-07T19:03:24.000Z
source/abcc_abp/abp_pnio.h
hms-networks/AbccSpiAnalyzer
59b533ed1e90a925695604007f281d0a50eb86df
[ "MIT" ]
11
2019-07-17T20:39:51.000Z
2022-03-30T18:42:52.000Z
source/abcc_abp/abp_pnio.h
HMSAB/AbccSpiAnalyzer
59b533ed1e90a925695604007f281d0a50eb86df
[ "MIT" ]
null
null
null
/******************************************************************************* ******************************************************************************** ** ** File Name ** --------- ** ** abp_pnio.h ** ******************************************************************************** ******************************************************************************** ** ** Description ** ----------- ** ** abp_pnio.h - Anybus-CC Protocol Definitions for PROFINET Object. ** ** This file contains network specific definitions used by the Anybus-CC ** PROFINET module as well as applications designed to use such module. ** ******************************************************************************** ******************************************************************************** ** ** ** COPYRIGHT NOTIFICATION (c) 2008 HMS Industrial Networks AB ** ** ** ** This code is the property of HMS Industrial Networks AB. ** ** The source code may not be reproduced, distributed, or used without ** ** permission. When used together with a product from HMS, this code can be ** ** modified, reproduced and distributed in binary form without any ** ** restrictions. ** ** ** ** THE CODE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. HMS DOES NOT ** ** WARRANT THAT THE FUNCTIONS OF THE CODE WILL MEET YOUR REQUIREMENTS, OR ** ** THAT THE OPERATION OF THE CODE WILL BE UNINTERRUPTED OR ERROR-FREE, OR ** ** THAT DEFECTS IN IT CAN BE CORRECTED. ** ** ** ******************************************************************************** ******************************************************************************** */ #ifndef ABP_PNIO_H #define ABP_PNIO_H /******************************************************************************* ** ** Anybus-CC PROFINET object constants. ** ** Object revision: 1. ** ******************************************************************************** */ /*------------------------------------------------------------------------------ ** ** The Anybus-CC PROFINET Object instance attributes. ** **------------------------------------------------------------------------------ */ #define ABP_PNIO_IA_DEVICE_ID 1 #define ABP_PNIO_IA_VENDOR_ID 2 #define ABP_PNIO_IA_STATION_TYPE 3 #define ABP_PNIO_IA_MAX_AR 4 /* ** Instance attributes 5-6 are reserved */ #define ABP_PNIO_IA_RTM 7 #define ABP_PNIO_IA_IM_ORDER_ID 8 #define ABP_PNIO_IA_IM_SERIAL_NBR 9 #define ABP_PNIO_IA_IM_HW_REV 10 #define ABP_PNIO_IA_IM_SW_REV 11 #define ABP_PNIO_IA_IM_REV_CNT 12 #define ABP_PNIO_IA_IM_PROFILE_ID 13 #define ABP_PNIO_IA_IM_PROFILE_SPEC_TYPE 14 #define ABP_PNIO_IA_IM_VER 15 #define ABP_PNIO_IA_IM_SUPPORTED 16 #define ABP_PNIO_IA_PORT1_MAC_ADDRESS 17 #define ABP_PNIO_IA_PORT2_MAC_ADDRESS 18 #define ABP_PNIO_IA_SYSTEM_DESCRIPTION 19 #define ABP_PNIO_IA_INTERFACE_DESCRIPTION 20 #define ABP_PNIO_IA_MOD_ID_ASSIGN_MODE 21 #define ABP_PNIO_IA_SYSTEM_CONTACT 22 #define ABP_PNIO_IA_PROFIENERGY_FUNC 23 #define ABP_PNIO_IA_CUSTOM_STATION_NAME 24 #define ABP_PNIO_IA_IM_MODULE_ORDER_ID 25 #define ABP_PNIO_IA_IM_ANNOTATION 26 #define ABP_PNIO_IA_IM5_ENABLED 27 #define ABP_PNIO_IA_S2_ENABLED 28 #define ABP_PNIO_IA_S2_PRIMARY_AR_HANDLE 29 /*------------------------------------------------------------------------------ ** ** The data size of the Anybus-CC PROFINET Object instance attributes (in ** bytes). ** **------------------------------------------------------------------------------ */ #define ABP_PNIO_IA_DEVICE_ID_DS ABP_UINT16_SIZEOF #define ABP_PNIO_IA_VENDOR_ID_DS ABP_UINT16_SIZEOF #define ABP_PNIO_IA_STATION_TYPE_DS ( 25 * ABP_UINT8_SIZEOF ) #define ABP_PNIO_IA_MAX_AR_DS ABP_UINT32_SIZEOF #define ABP_PNIO_IA_RTM_DS ABP_UINT8_SIZEOF #define ABP_PNIO_IA_IM_ORDER_ID_DS ( 20 * ABP_UINT8_SIZEOF ) #define ABP_PNIO_IA_IM_SERIAL_NBR_DS ( 16 * ABP_UINT8_SIZEOF ) #define ABP_PNIO_IA_IM_HW_REV_DS ABP_UINT16_SIZEOF #define ABP_PNIO_IA_IM_SW_REV_DS ( 4 * ABP_UINT8_SIZEOF ) #define ABP_PNIO_IA_IM_REV_CNT_DS ABP_UINT16_SIZEOF #define ABP_PNIO_IA_IM_PROFILE_ID_DS ABP_UINT16_SIZEOF #define ABP_PNIO_IA_IM_PROFILE_SPEC_TYPE_DS ABP_UINT16_SIZEOF #define ABP_PNIO_IA_IM_VER_DS ( 2 * ABP_UINT8_SIZEOF ) #define ABP_PNIO_IA_IM_SUPPORTED_DS ABP_UINT16_SIZEOF #define ABP_PNIO_IA_PORT1_MAC_ADDRESS_DS ( 6 * ABP_UINT8_SIZEOF ) #define ABP_PNIO_IA_PORT2_MAC_ADDRESS_DS ( 6 * ABP_UINT8_SIZEOF ) #define ABP_PNIO_IA_SYSTEM_DESCRIPTION_DS ( 255 * ABP_UINT8_SIZEOF ) #define ABP_PNIO_IA_INTERFACE_DESCRIPTION_DS ( 255 * ABP_UINT8_SIZEOF ) #define ABP_PNIO_IA_MOD_ID_ASSIGN_MODE_DS ( ABP_UINT8_SIZEOF ) #define ABP_PNIO_IA_SYSTEM_CONTACT_DS ( 255 * ABP_UINT8_SIZEOF ) #define ABP_PNIO_IA_PROFIENERGY_FUNC_DS ( ABP_UINT8_SIZEOF ) #define ABP_PNIO_IA_CUSTOM_STATION_NAME_DS ( 58 * ABP_UINT8_SIZEOF ) #define ABP_PNIO_IA_IM_MODULE_ORDER_ID_DS ( 64 * ABP_UINT8_SIZEOF ) #define ABP_PNIO_IA_IM_ANNOTATION_ID_DS ( 64 * ABP_UINT8_SIZEOF ) #define ABP_PNIO_IA_IM5_ENABLE_DS ABP_BOOL_SIZEOF #define ABP_PNIO_IA_S2_ENABLE_DS ABP_BOOL_SIZEOF #define ABP_PNIO_IA_S2_PRIMARY_AR_HANDLE_DS ABP_UINT16_SIZEOF /*------------------------------------------------------------------------------ ** ** The PROFINET IO object specific message commands. ** **------------------------------------------------------------------------------ */ #define ABP_PNIO_CMD_GET_RECORD 0x10 #define ABP_PNIO_CMD_SET_RECORD 0x11 #define ABP_PNIO_CMD_GET_IM_RECORD 0x12 #define ABP_PNIO_CMD_SET_IM_RECORD 0x13 #define ABP_PNIO_CMD_AR_CHECK_IND 0x14 #define ABP_PNIO_CMD_CFG_MISMATCH_IND 0x15 #define ABP_PNIO_CMD_AR_INFO_IND 0x16 #define ABP_PNIO_CMD_END_OF_PRM_IND 0x17 #define ABP_PNIO_CMD_AR_ABORT_IND 0x19 #define ABP_PNIO_CMD_PLUG_SUB_FAILED 0x1A #define ABP_PNIO_CMD_EXPECTED_IDENT_IND 0x1B #define ABP_PNIO_CMD_SAVE_IP_SUITE 0x1C #define ABP_PNIO_CMD_SAVE_STATION_NAME 0x1D #define ABP_PNIO_CMD_INDICATE_DEVICE 0x1E #define ABP_PNIO_CMD_PRM_BEGIN_IND 0x1F /*------------------------------------------------------------------------------ ** ** The data size of the PROFINET Object specific message commands. ** **------------------------------------------------------------------------------ */ #define ABP_PNIO_CMD_GET_RECORD_DS 11 #define ABP_PNIO_CMD_SET_RECORD_DS 255 #define ABP_PNIO_CMD_GET_IM_RECORD_DS 4 #define ABP_PNIO_CMD_SET_IM_RECORD_DS 255 #define ABP_PNIO_CMD_AR_CHECK_IND_DS 255 #define ABP_PNIO_CMD_CFG_MISMATCH_IND_DS 16 #define ABP_PNIO_CMD_AR_INFO_IND_DS 255 #define ABP_PNIO_CMD_END_OF_PRM_IND_DS 8 #define ABP_PNIO_CMD_AR_ABORT_IND_DS 2 #define ABP_PNIO_CMD_PLUG_SUB_FAILED_DS 8 #define ABP_PNIO_CMD_EXPECTED_IDENT_IND_DS 255 #define ABP_PNIO_CMD_INDICATE_DEVICE_DS 0 #define ABP_PNIO_CMD_PRM_BEGIN_IND_DS 8 /*------------------------------------------------------------------------------ ** ** Response codes for Expected_Ident_Ind ** **------------------------------------------------------------------------------ */ #define ABP_PNIO_RSP_EXPECTED_IDENT_IND_CONT 0 #define ABP_PNIO_RSP_EXPECTED_IDENT_IND_BLOCK 1 /*------------------------------------------------------------------------------ ** ** PROFINET IO specific exception information codes. ** **------------------------------------------------------------------------------ */ #define ABP_PNIO_NW_EXCPT_ILLEGAL_VALUE 1 #define ABP_PNIO_NW_EXCPT_WRONG_DATA_SIZE 2 #define ABP_PNIO_NW_EXCPT_ILLEGAL_RSP 3 #define ABP_PNIO_NW_EXCPT_MISSING_MAC_ADDRESS 4 #define ABP_PNIO_NW_EXCPT_CMD_TIMEOUT 5 #define ABP_PNIO_NW_EXCPT_MDD_ERR 6 #define ABP_PNIO_NW_EXCPT_PE_WRONG_VERSION 7 #define ABP_PNIO_NW_EXCPT_PE_INST_OUT_OF_RANGE 8 #define ABP_PNIO_NW_EXCPT_INVALID_MAX_AR 9 #endif /* inclusion lock */ /******************************************************************************* ** ** end of abp_pnio.h ** ******************************************************************************** */
46.883495
81
0.500104
[ "object" ]
387c7f33d355c09135925e1441e3a671551f19a1
5,279
h
C
cpp/src/main/models/combination/ToplistCombinationModel.h
fbobee/Alpenglow
5f956511017c1bee72390aaecd964c04d8ad4b45
[ "Apache-2.0" ]
null
null
null
cpp/src/main/models/combination/ToplistCombinationModel.h
fbobee/Alpenglow
5f956511017c1bee72390aaecd964c04d8ad4b45
[ "Apache-2.0" ]
null
null
null
cpp/src/main/models/combination/ToplistCombinationModel.h
fbobee/Alpenglow
5f956511017c1bee72390aaecd964c04d8ad4b45
[ "Apache-2.0" ]
null
null
null
#ifndef TOPLIST_COMBINATION_MODEL_RANKING_SCORE_ITERATOR_H #define TOPLIST_COMBINATION_MODEL_RANKING_SCORE_ITERATOR_H //SIP_AUTOCONVERT #include <vector> #include <set> #include <stdexcept> #include <gtest/gtest_prod.h> #include "WeightedModelStructure.h" #include "../Model.h" #include "../RankingScoreIterator.h" #include "../../general_interfaces/Initializable.h" #include "../../general_interfaces/NeedsExperimentEnvironment.h" #include "../../utils/RankComputer.h" #include "../../utils/ToplistCreator.h" #include "../../filters/DummyModelFilter.h" using namespace std; class ToplistCombinationModelRankingScoreIterator : public RankingScoreIterator{ public: bool has_next(double bound) override; pair<int, double> get_next() override; void set_up(vector<pair<int,double>> toplist){ counter_ = 0; current_scores_ = toplist; } void reinit(){counter_=0;} int unique_items_num(){ throw runtime_error("Not implemented. Should not be called by RankComputer as all scores are nonnegative."); } private: void clear(){counter_=0;current_scores_.clear();} vector<pair<int,double>> current_scores_; int counter_; }; struct ToplistCombinationModelParameters{ int seed = 745578; int top_k = -1; }; class ToplistCombinationModel : public Model, virtual public RankingScoreIteratorProvider, public Initializable, public NeedsExperimentEnvironment { public: ToplistCombinationModel(ToplistCombinationModelParameters* params){ random_.set(params->seed); seed_ = params->seed; } void add_model(Model* model){ wms_.models_.push_back(model); } bool self_test(){ bool ok = Model::self_test() && random_.self_test(); if(wms_.models_.size()==0) ok=false; for(auto rank_computer : rank_computers_) ok &= rank_computer->self_test(); for(auto toplist_creator : toplist_creators_) ok &= toplist_creator->self_test(); return ok; } void add(RecDat* rec_dat) override; double prediction(RecDat* rec_dat) override; void write(ostream& file) override; void read(istream& file) override; RankingScoreIterator* get_ranking_score_iterator(int user) override; ~ToplistCombinationModel(){ for(auto rank_computer: rank_computers_){ delete rank_computer; } for(auto toplist_creator: toplist_creators_){ delete toplist_creator; } rank_computers_.clear(); } void inject_wms_into(WMSUpdater* object){ object->set_wms(&wms_); } protected: bool autocalled_initialize() override { if(top_k_==-1){ if(experiment_environment_==NULL) return false; top_k_=experiment_environment_->get_top_k(); } wms_.distribution_.clear(); //should not be called twice, but... wms_.distribution_.resize(wms_.models_.size(),1.0/wms_.models_.size()); dummy_model_filter_.set_experiment_environment(experiment_environment_); bool ok = true; ok &= dummy_model_filter_.initialize(); for(auto model : wms_.models_){ RankComputerParameters rank_computer_params; rank_computer_params.top_k=top_k_; rank_computer_params.random_seed=seed_+1; RankComputer* rank_computer = new RankComputer(&rank_computer_params); rank_computers_.push_back(rank_computer); rank_computer->set_experiment_environment(experiment_environment_); rank_computer->set_model(model); ok &= rank_computer->initialize(); ToplistCreatorPersonalizedParameters toplist_computer_params; ToplistCreatorPersonalized* toplist_creator = new ToplistCreatorPersonalized(&toplist_computer_params); toplist_creators_.push_back(toplist_creator); toplist_creator->set_experiment_environment(experiment_environment_); toplist_creator->set_model(model); toplist_creator->set_filter(&dummy_model_filter_); ok &= toplist_creator->initialize(); } wms_.initialized_=true; return ok; } private: WeightedModelStructure wms_; ToplistCombinationModelRankingScoreIterator rsi_; void recompute_predictions(RecDat* rec_dat); bool random_values_generated_ = false; void generate_random_values_for_toplists(); vector<int> random_model_indices_; void compute_score_map(); map<int,double> scores_; void compute_last_occ_of_models(); vector<int> last_occ_of_models_; bool test_top_k(RecDat*); void compute_toplists(RecDat* rec_dat); vector<vector<pair<int,double>>> toplists_; //models->toplist->(item,score) void merge_toplists(); vector<pair<int,double>> toplist_; //vector<Model*> models_; vector<RankComputer*> rank_computers_; vector<ToplistCreatorPersonalized*> toplist_creators_; DummyModelFilter dummy_model_filter_; //vector<double> distribution_; //cache double last_timestamp_ = -1; int last_user_ = -1; int last_id_ = -1; Random random_; int seed_ = -1; int top_k_ = -1; FRIEND_TEST(TestToplistCombinationModel, generate_random_values_for_toplists); FRIEND_TEST(TestToplistCombinationModel, compute_last_occ_of_models); FRIEND_TEST(TestToplistCombinationModel, test_top_k); FRIEND_TEST(TestToplistCombinationModel, compute_toplists); FRIEND_TEST(TestToplistCombinationModel, merge_toplists); FRIEND_TEST(TestToplistCombinationModel, prediction); //friend class RandomChoosingCombinedModelExpertUpdater; }; #endif /* TOPLIST_COMBINATION_MODEL_RANKING_SCORE_ITERATOR_H */
37.707143
136
0.766054
[ "object", "vector", "model" ]
387cbe61c7cccc65ce587531ecc300535f4e1a32
3,120
h
C
Include/Graphics/GtePickRecord.h
vehsakul/gtl
498bb20947e9ff21c08dd5a884ac3dc6f8313bb9
[ "BSL-1.0" ]
null
null
null
Include/Graphics/GtePickRecord.h
vehsakul/gtl
498bb20947e9ff21c08dd5a884ac3dc6f8313bb9
[ "BSL-1.0" ]
null
null
null
Include/Graphics/GtePickRecord.h
vehsakul/gtl
498bb20947e9ff21c08dd5a884ac3dc6f8313bb9
[ "BSL-1.0" ]
null
null
null
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2016 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // File Version: 3.0.1 (2016/06/26) #pragma once #include <Mathematics/GteVector4.h> #include <Graphics/GteIndexFormat.h> #include <memory> namespace gte { class Visual; class GTE_IMPEXP PickRecord { public: // Construction and destruction. The default constructor does not // initialize any members. It exists to support the construction // of the const static PickRecord in the Picker class. ~PickRecord(); PickRecord(); // The object for which some primitive satisfies the picking criteria. // The vertexIndex[] are relative to the vertex buffer array of the // 'visual'. If the primitive is a triangle, then all three indices are // valid. If the primitive is a segment, then the first two indices are // valid. If the primitive is a point, then the first index is valid. // The invalid indices are set to -1. std::shared_ptr<Visual> visual; IPType primitiveType; int primitiveIndex; int vertexIndex[3]; // The linear component is parameterized by P + t*D. The t-value // corresponds to the point of intersection when the primitive is a // triangle. For point and segment primitives, the t-value corresponds // to the closest point to the primitive. NOTE: Picking occurs in the // model space of the objects. If the model-to-world transform is not // rigid (i.e. the world transform has non-unit scaling), the t-values // cannot be compared between objects. Therefore, the sorting of // PickRecords must use the linePoint, which is computed in world // coordinates. float t; Vector4<float> linePoint; // The barycentric coordinates of the point of intersection when the // primitive is a triangle or of the closest primitive point when the // primitive is a segment or a point. The coordinates have the // properties 0 <= bary[i] <= 1 and bary[0] + bary[1] + bary[2] = 1. // For a triangle, all three bary[] values are potentially positive. // For a segment, bary[2] = 0. For a point, bary[0] = 1 and bary[1] // = bary[2] = 0. The order of the bary[] values is consistent with // the ordering of the vertices of the primitive. The primitivePoint // is the same as the linePoint when the primitive is a triangle. // However, it is the closest primitive point to the line when the // primitive is a segment or a point. float bary[3]; Vector4<float> primitivePoint; // The distances are all measured in world coordinates. The distanceTo* // values are measured from the world origin of the pick line. // when the primitives are triangles. The distanceBetweenLinePrimitive // is the distance between the primitive and the pick object (line, ray, // or segment). float distanceToLinePoint; float distanceToPrimitivePoint; float distanceBetweenLinePrimitive; }; }
41.052632
76
0.705128
[ "object", "model", "transform" ]
387e9e55395cd7063d4f39b2eaf1532f118b9d0e
320
h
C
src/compiler/tar.h
sdizdarevic/tmbasic
fac8edd931eb1a457b93a783bd43134fc76debc5
[ "MIT" ]
49
2020-11-26T10:50:04.000Z
2022-03-29T13:54:51.000Z
src/compiler/tar.h
sdizdarevic/tmbasic
fac8edd931eb1a457b93a783bd43134fc76debc5
[ "MIT" ]
5
2020-11-20T23:17:46.000Z
2022-03-31T04:50:03.000Z
src/compiler/tar.h
sdizdarevic/tmbasic
fac8edd931eb1a457b93a783bd43134fc76debc5
[ "MIT" ]
5
2021-06-29T13:48:29.000Z
2022-03-10T23:22:18.000Z
#pragma once #include "../common.h" namespace compiler { class TarEntry { public: std::string name; std::vector<uint8_t> data; uint mode; TarEntry(std::string name, std::vector<uint8_t> data, uint mode); }; std::vector<uint8_t> tar(const std::vector<TarEntry>& entries); } // namespace compiler
17.777778
69
0.671875
[ "vector" ]
a80add37259424922b76df0e15ac0ebd536d9c7f
1,048
h
C
lib/variable/include/scipp/variable/creation.h
nvaytet/scipp
f14f56ed19cccb4162d55b1123df7225eeedb395
[ "BSD-3-Clause" ]
43
2019-04-08T14:13:11.000Z
2022-02-08T06:09:35.000Z
lib/variable/include/scipp/variable/creation.h
nvaytet/scipp
f14f56ed19cccb4162d55b1123df7225eeedb395
[ "BSD-3-Clause" ]
1,342
2019-03-30T07:06:08.000Z
2022-03-28T13:12:47.000Z
lib/variable/include/scipp/variable/creation.h
nvaytet/scipp
f14f56ed19cccb4162d55b1123df7225eeedb395
[ "BSD-3-Clause" ]
12
2019-06-13T08:56:12.000Z
2021-11-04T08:24:18.000Z
// SPDX-License-Identifier: BSD-3-Clause // Copyright (c) 2021 Scipp contributors (https://github.com/scipp) /// @file /// @author Simon Heybrock #pragma once #include <optional> #include "scipp/core/flags.h" #include "scipp-variable_export.h" #include "scipp/variable/variable.h" namespace scipp::variable { [[nodiscard]] SCIPP_VARIABLE_EXPORT Variable empty(const Dimensions &dims, const units::Unit &unit, const DType type, const bool with_variances = false); [[nodiscard]] SCIPP_VARIABLE_EXPORT Variable ones(const Dimensions &dims, const units::Unit &unit, const DType type, const bool with_variances = false); [[nodiscard]] SCIPP_VARIABLE_EXPORT Variable empty_like(const Variable &prototype, const std::optional<Dimensions> &shape = std::nullopt, const Variable &sizes = {}); [[nodiscard]] SCIPP_VARIABLE_EXPORT Variable special_like(const Variable &prototype, const FillValue &fill); [[nodiscard]] SCIPP_VARIABLE_EXPORT Variable zero_like(const Variable &prototype); } // namespace scipp::variable
29.942857
72
0.747137
[ "shape" ]
a80cb8e830e7b65be81281db8cae445db2ec3224
552
h
C
EventFilter/L1TRawToDigi/plugins/implementations_stage2/RegionalMuonGMTPacker.h
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
EventFilter/L1TRawToDigi/plugins/implementations_stage2/RegionalMuonGMTPacker.h
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
EventFilter/L1TRawToDigi/plugins/implementations_stage2/RegionalMuonGMTPacker.h
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
#ifndef L1T_PACKER_STAGE2_REGIONALMUONGMTPACKER_H #define L1T_PACKER_STAGE2_REGIONALMUONGMTPACKER_H namespace l1t { namespace stage2 { class RegionalMuonGMTPacker : public Packer { public: virtual Blocks pack(const edm::Event&, const PackerTokens*) override; private: typedef std::map<unsigned int, std::vector<uint32_t>> PayloadMap; void packTF(const edm::Event&, const edm::EDGetTokenT<RegionalMuonCandBxCollection>&, Blocks&, const std::vector<unsigned int>&); }; } } #endif
32.470588
141
0.695652
[ "vector" ]
a8116e8ceec705553e4f36dbe87551c00cf756b1
3,309
h
C
remus/worker/ServerConnection.h
robertmaynard/Remus
090a14c9a4b0e628a86590dcfa7e46ba728e9c04
[ "BSD-3-Clause-Clear" ]
9
2015-08-11T03:42:58.000Z
2021-01-19T11:36:16.000Z
remus/worker/ServerConnection.h
robertmaynard/Remus
090a14c9a4b0e628a86590dcfa7e46ba728e9c04
[ "BSD-3-Clause-Clear" ]
25
2015-01-22T18:35:50.000Z
2016-02-23T16:42:56.000Z
remus/worker/ServerConnection.h
Kitware/Remus
090a14c9a4b0e628a86590dcfa7e46ba728e9c04
[ "BSD-3-Clause-Clear" ]
9
2015-03-23T20:41:19.000Z
2022-01-14T09:09:05.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. // //============================================================================= #ifndef remus_worker_ServerConnection_h #define remus_worker_ServerConnection_h #include <remus/proto/zmqSocketInfo.h> REMUS_THIRDPARTY_PRE_INCLUDE #include <boost/shared_ptr.hpp> REMUS_THIRDPARTY_POST_INCLUDE //included for export symbols #include <remus/worker/WorkerExports.h> #ifdef REMUS_MSVC #pragma warning(push) #pragma warning(disable:4251) /*dll-interface missing on stl type*/ #endif //forward declare the context namespace zmq { class context_t; } namespace remus{ namespace worker{ //Class is Not Thread Safe. Construct of the zmq::context is delayed //until requested. So if you are sharing a ServerConnection between threads //you need to manage when and how the zmq context is created. class REMUSWORKER_EXPORT ServerConnection { public: //create a connection object that represents connecting to //the default local host remus server. ServerConnection(); //create a connection object that connects to the server specified by the //zmq::socketInfo. This is best way to connect to a non default server //with a custom protocol template<typename T> explicit ServerConnection(zmq::socketInfo<T> const& socket); //create a connection object that represent connection to a //standard tcp-ip remus server on a custom port ServerConnection(std::string const& hostName, int port); //Not Thread Safe. std::string const& endpoint() const; inline bool isLocalEndpoint() const{ return IsLocalEndpoint; } //we have to leak some details to support inproc communication //Not Thread Safe boost::shared_ptr<zmq::context_t> context() const; //don't overwrite the context of a server connection once the server //connection is passed to the worker, as that will cause undefined behavior //and most likely will crash the program //Not Thread Safe void context(boost::shared_ptr<zmq::context_t> c) { this->Context = c; } private: mutable boost::shared_ptr<zmq::context_t> Context; std::string Endpoint; bool IsLocalEndpoint; }; //convert a string in the form of proto://hostname:port where :port //is optional into a server connection class //if we fail to parse the string we will return an instance of //the default server connection REMUSWORKER_EXPORT remus::worker::ServerConnection make_ServerConnection(const std::string& dest); //construct a server context that can be shared between many server connections REMUSWORKER_EXPORT boost::shared_ptr<zmq::context_t> make_ServerContext(std::size_t num_threads=1); //------------------------------------------------------------------------------ template<typename T> ServerConnection::ServerConnection(zmq::socketInfo<T> const& socket): Context( ), Endpoint(socket.endpoint()), IsLocalEndpoint( zmq::isLocalEndpoint(socket) ) { } } } #ifdef REMUS_MSVC #pragma warning(pop) #endif #endif // remus_ServerConnection_h
31.514286
80
0.712602
[ "object" ]
a8127cbf44c32b75b5836c95490abd115aefdda0
468
h
C
src/pragma/graphics/import/Parsers.h
vicutrinu/pragma-studios
181fd14d072ccbb169fa786648dd942a3195d65a
[ "MIT" ]
null
null
null
src/pragma/graphics/import/Parsers.h
vicutrinu/pragma-studios
181fd14d072ccbb169fa786648dd942a3195d65a
[ "MIT" ]
null
null
null
src/pragma/graphics/import/Parsers.h
vicutrinu/pragma-studios
181fd14d072ccbb169fa786648dd942a3195d65a
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <vector> namespace pragma { class Mesh; class MaterialLibrary; // Parseo de elementos base (enteros, flotantes, strings...) template<typename T> T Parse(const std::string& aString); void Tokenize(const char* aTextBuffer, std::vector<std::string>& aTokens); bool ParseASE(const char* aFilename, Mesh& aMesh); bool ParseOBJ(const char* aFilename, Mesh& aMesh, MaterialLibrary& aMaterialLibrary); }
23.4
87
0.713675
[ "mesh", "vector" ]
a816bee06adb699336993ee39400a34954f4b9e0
2,940
h
C
StRoot/StarGenerator/FILT/StarFilterMaker.h
xiaohaijin/RHIC-STAR
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
[ "MIT" ]
2
2018-12-24T19:37:00.000Z
2022-02-28T06:57:20.000Z
StRoot/StarGenerator/FILT/StarFilterMaker.h
xiaohaijin/RHIC-STAR
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
[ "MIT" ]
null
null
null
StRoot/StarGenerator/FILT/StarFilterMaker.h
xiaohaijin/RHIC-STAR
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
[ "MIT" ]
null
null
null
#ifndef __StarFilterMaker_h__ #define __StarFilterMaker_h__ #include "StMaker.h" #include "TLorentzVector.h" #include "TVector3.h" #include "TClonesArray.h" #include "TDatabasePDG.h" //#include "StarParticleStack.h" #include "StarGenerator/UTIL/StarParticleData.h" #include "StarGenerator/BASE/StarPrimaryMaker.h" class StarGenEvent; class StarPrimaryMaker; class TTree; class TFile; /** \class StarFilterMaker \author John F. Novak \brief Main filter class. Goes anywhere in the chain, filters StarGenEvent objects */ /* To Do's: JFN 4/22/13 Should the filter make it's own tree? Probably not, it should probably make a branch of the 'main' tree 4/23- make a branch on the PrimaryMakers tree How do things get passed along the chain? StarGenEvents? or a collection of them? What gets handed to the next link? 4/23- StMaker has a TDataSet object and functions to access it, but StarPrimaryMaker is also writing things to the tree */ /* To Do's: JFN 4/23/13 For each pass of BFC is only one event generated? Is it named mPrimaryEvent, or are their multiple events? 4/24- Just one, and it is named "PrimaryMaker". It can be retreived from StMaker I think for each event I should use some "Event()" function defined on the event generator class, haven't found it yet... And how will we handle looping over generators? 4/24- There is a one primary event per BFC loop and it is StarPrimaryMaker->mPrimaryEvent retreivable via primary->event() */ /* To Do's: JFN 4/24/13 Have filter return a kStatus, and then decide what to do with the event (reject, flag, etc) in Make() Decide what has to be stored in the TTree: just the event num and status, every track and status, etc... */ class StarFilterMaker : public StMaker { public: StarFilterMaker( const Char_t *name="" ); ~StarFilterMaker() { /* nothing to see here */ }; Int_t Init(); Int_t Make(); void Clear( const Option_t *opts="" ); Int_t Finish(); /// The function Filter( StarGenEvent* ) is not defined here in the base class. /// Users who write filters (which will inherit from this class) will overwrite it. /// @param event Is the event to be filtered. If no event is provided, then the event /// which was registered by SetEvent will be used. virtual Int_t Filter( StarGenEvent *event=0 ) = 0; void SetEvent( StarGenEvent *event ){ mEvent = event; } Int_t numberOfEvents(){ return NumberofEvents; } Int_t acceptedEvents(){ return AcceptedEvents; } Int_t rejectedEvents(){ return RejectedEvents; } Int_t rejectedSinceLast(){ return RejectedSinceLast; } private: Int_t NumberofEvents; Int_t AcceptedEvents; Int_t RejectedEvents; Int_t RejectedSinceLast; private: protected: ClassDef(StarFilterMaker,1); StarGenEvent *mEvent; //Options: Bool_t bFlag; // If false, failed tracks will be flaged but not rejected. Default:false }; #endif
31.276596
128
0.72517
[ "object" ]
a81b2df75fc55d658197a06022bcaf79057ab162
12,098
h
C
BRAINSABC/brainseg/BRAINSABCUtilities.h
pnlbwh/BRAINSTools
a2fe63ab5b795f03da140a4081d1fef6314dab95
[ "Apache-2.0" ]
null
null
null
BRAINSABC/brainseg/BRAINSABCUtilities.h
pnlbwh/BRAINSTools
a2fe63ab5b795f03da140a4081d1fef6314dab95
[ "Apache-2.0" ]
null
null
null
BRAINSABC/brainseg/BRAINSABCUtilities.h
pnlbwh/BRAINSTools
a2fe63ab5b795f03da140a4081d1fef6314dab95
[ "Apache-2.0" ]
1
2022-02-08T05:39:46.000Z
2022-02-08T05:39:46.000Z
/*========================================================================= * * Copyright SINAPSE: Scalable Informatics for Neuroscience, Processing and Software Engineering * The University of Iowa * * 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.txt * * 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. * *=========================================================================*/ /** * This file is to make some smaller compilation units to help improve compilation performance. */ #ifndef __BRAINSABCUtilities__h__ #define __BRAINSABCUtilities__h__ #include "Log.h" #include <AtlasDefinition.h> #include <BRAINSFitHelper.h> #include <itkImage.h> #include <itkArray.h> #include <vnl/vnl_matrix.h> #include <vnl/vnl_vector.h> #include <vnl/algo/vnl_matrix_inverse.h> #include <vector> #include <map> #include <csignal> #include <algorithm> using LOOPITERTYPE = unsigned int; // std::isnan(value) || std::isinf(value) ) #if 1 // Runtime performance penalty that can be used to find faulty code // during debugging. # define CHECK_NAN(XXXTESTXXX, srcfile, srcline, extra_print) \ { \ if (!std::isfinite(XXXTESTXXX)) \ { \ std::cout << "Found " << XXXTESTXXX << " at " << srcfile << " " << srcline << extra_print << std::endl; \ raise(SIGSEGV); \ } \ } #else # define CHECK_NAN(XXXTESTXXX, srcfile, srcline, extra_print) \ {} #endif /** A utility class for holding ordered maps */ /** * Make ordered map by choosing less than operator based on order of inputs * This comparitor function will order the maps based on a first in * priority. Elements that are not already in the list of keys * are added at the end. Elements that show up in the list first are considered * less than elements that show up in the list second. **/ class firstInOrderingOfStrings { public: firstInOrderingOfStrings() { // HACK: This is hard coding that should not be here. // A better insertion ordered map is needed. this->m_firstInOrdering.push_back("T1"); this->m_firstInOrdering.push_back("T2"); this->m_firstInOrdering.push_back("PD"); this->m_firstInOrdering.push_back("FLAIR"); this->m_firstInOrdering.push_back("OTHER"); } bool operator()(const std::string & lhs, const std::string & rhs) const { add_keys_internally(lhs); // For new items, add lhs first add_keys_internally(rhs); // Also need to add rhs if it is not in list yet for (auto & elem : m_firstInOrdering) { if (elem == lhs && (lhs != rhs)) { return true; } else if (elem == rhs) { return false; } } throw std::invalid_argument("Values need to be added before comparisions"); return false; } private: /* * Need to ensure that items are in list before comparisons. */ void add_keys_internally(const std::string & testValue) const { const bool found = (std::find(m_firstInOrdering.begin(), m_firstInOrdering.end(), testValue) != m_firstInOrdering.end()); if (!found) { this->m_firstInOrdering.push_back(testValue); } } /* This needs to be mutable. The function signature needs to be * const, but this internal list needs to be mutable for the case * of new elements being added*/ mutable std::list<std::string> m_firstInOrdering; }; template <typename Key, typename T> class orderedmap : public std::map<Key, T, firstInOrderingOfStrings> { public: orderedmap() : std::map<Key, T, firstInOrderingOfStrings>(){}; using std::map<Key, T, firstInOrderingOfStrings>::operator[]; }; using FloatingPrecision = double; using ByteImageType = itk::Image<unsigned char, 3>; using ByteImagePointerType = ByteImageType::Pointer; using FloatImageType = itk::Image<float, 3>; using FloatImagePointerType = FloatImageType::Pointer; using ShortImageType = itk::Image<signed short int, 3>; using CorrectIntensityImageType = itk::Image<float, 3>; using ImageByTypeMap = orderedmap<std::string, std::string>; using FloatImageVector = std::vector<FloatImagePointerType>; using MapOfFloatImageVectors = orderedmap<std::string, FloatImageVector>; using MaskImageVector = std::vector<ByteImagePointerType>; using MapOfMaskImageVectors = orderedmap<std::string, MaskImageVector>; using GenericTransformType = itk::Transform<double, 3, 3>; using TransformList = std::vector<GenericTransformType::Pointer>; using MapOfTransformLists = orderedmap<std::string, TransformList>; /** A utiliy class for holding statistical information * for all image channels for a given tissue class type */ class RegionStats { public: using MatrixType = vnl_matrix<FloatingPrecision>; using MatrixInverseType = vnl_matrix_inverse<FloatingPrecision>; using MeanMapType = orderedmap<std::string, double>; RegionStats() : m_Means() , m_Covariance() , m_Weighting(0.0) {} void resize(const unsigned int numModalities) { this->m_Covariance = MatrixType(numModalities, numModalities); this->m_Means.clear(); } MeanMapType m_Means; // One measure per image channel type; MatrixType m_Covariance; // Matrix of covariances of class by image // channel FloatingPrecision m_Weighting; // The strength of this class. }; #include "BRAINSABCUtilities.hxx" // External Templates to improve compilation times. /* * This function gets a map of input images, finds its first key image, * and resamples all images to the first key image lattice using identity * transform and passed interpolation type. * Note that it is assumed that all input intensity images are already aligned * in physical space. */ extern MapOfFloatImageVectors ResampleImageListToFirstKeyImage(const std::string & resamplerInterpolatorType, const MapOfFloatImageVectors & inputImageMap); /* * This function, first, transforms all inputImageMap to the space of the first image of the map * using rigid transforms (intraSubjectTransforms) and Resampling InPlace interoplation. * Then, it resamples all images within one modality to the voxel lattice of the fist image of that modality channel * using resamplerInterpolatorType and Identity transform. */ extern ByteImageType::Pointer ResampleToFirstImageList(const std::string & resamplerInterpolatorType, const MapOfFloatImageVectors & inputImageMap, const MapOfTransformLists & intraSubjectTransforms, MapOfFloatImageVectors & outputImageMap); extern template std::vector<FloatImagePointerType> DuplicateImageList<FloatImageType>(const std::vector<FloatImagePointerType> &); extern template std::vector<ShortImageType::Pointer> DuplicateImageList<ShortImageType>(const std::vector<ShortImageType::Pointer> &); extern template void NormalizeProbListInPlace<FloatImageType>(std::vector<FloatImageType::Pointer> &); extern template void ZeroNegativeValuesInPlace<FloatImageType>(std::vector<FloatImageType::Pointer> &); template <typename ImageType> typename ImageType::Pointer NormalizeInputIntensityImage(const typename ImageType::Pointer inputImage) { muLogMacro(<< "\nNormalize input intensity images..." << std::endl); using HistogramFilterType = typename itk::Statistics::ImageToHistogramFilter<ImageType>; using InputBooleanObjectType = typename HistogramFilterType::InputBooleanObjectType; using HistogramSizeType = typename HistogramFilterType::HistogramSizeType; HistogramSizeType histogramSize(1); histogramSize[0] = 256; typename InputBooleanObjectType::Pointer autoMinMaxInputObject = InputBooleanObjectType::New(); autoMinMaxInputObject->Set(true); typename HistogramFilterType::Pointer histogramFilter = HistogramFilterType::New(); histogramFilter->SetInput(inputImage); histogramFilter->SetAutoMinimumMaximumInput(autoMinMaxInputObject); histogramFilter->SetHistogramSize(histogramSize); histogramFilter->SetMarginalScale(10.0); histogramFilter->Update(); float lowerValue = histogramFilter->GetOutput()->Quantile(0, 0); float upperValue = histogramFilter->GetOutput()->Quantile(0, 1); using IntensityWindowingImageFilterType = typename itk::IntensityWindowingImageFilter<ImageType, ImageType>; typename IntensityWindowingImageFilterType::Pointer windowingFilter = IntensityWindowingImageFilterType::New(); windowingFilter->SetInput(inputImage); windowingFilter->SetWindowMinimum(lowerValue); windowingFilter->SetWindowMaximum(upperValue); windowingFilter->SetOutputMinimum(0); windowingFilter->SetOutputMaximum(1); windowingFilter->Update(); typename ImageType::Pointer outputImage = nullptr; outputImage = windowingFilter->GetOutput(); outputImage->Update(); outputImage->DisconnectPipeline(); return outputImage; } // debug output for map of vector structure template <typename TMap> void PrintMapOfImageVectors(const TMap & map) { muLogMacro(<< "Map size: " << map.size() << std::endl); for (typename TMap::const_iterator mapIt = map.begin(); mapIt != map.end(); ++mapIt) { muLogMacro(<< " " << mapIt->first << "(" << mapIt->second.size() << "):" << std::endl); for (unsigned i = 0; i < mapIt->second.size(); ++i) { muLogMacro(<< " " << mapIt->second[i].GetPointer() << mapIt->second[i]->GetLargestPossibleRegion() << " " << mapIt->second[i]->GetBufferedRegion() << std::endl); } } } template <typename TMap> unsigned int TotalMapSize(const TMap & map) { unsigned int rval = 0; for (typename TMap::const_iterator mapIt = map.begin(); mapIt != map.end(); ++mapIt) { for (typename TMap::mapped_type::const_iterator listIt = mapIt->second.begin(); listIt != mapIt->second.end(); ++listIt) { ++rval; } } return rval; } template <typename TMap> typename TMap::mapped_type::value_type & GetMapVectorNthElement(TMap & map, int n) { typename TMap::mapped_type::value_type returnElement; if (map.size() < n) { returnElement = NULL; } else { typename TMap::iterator it = map.begin(); for (int i = 0; i < n, it != map.end(); i++, ++it) { if (i == n - 1) { returnElement = *(map.begin()->second.begin()); } } } return returnElement; } template <typename TMap> typename TMap::mapped_type::value_type & GetMapVectorFirstElement(TMap & map) { return *(map.begin()->second.begin()); } template <typename TMap> const typename TMap::mapped_type::value_type & GetMapVectorFirstElement(const TMap & map) { return *(map.begin()->second.begin()); } template <typename ImageType> typename ImageType::Pointer CopyImage(const typename ImageType::Pointer & input) { using ImageDupeType = itk::ImageDuplicator<ImageType>; typename ImageDupeType::Pointer MyDuplicator = ImageDupeType::New(); MyDuplicator->SetInputImage(input); MyDuplicator->Update(); return MyDuplicator->GetOutput(); } #endif // __BRAINSABCUtilities__h__
34.965318
120
0.669532
[ "vector", "transform" ]
a81c2665eda23651e47a8fd9fee40ae2d7d784c8
1,956
h
C
MEIClient/AMTHIClient/Include/GetSystemDefenseStateCommand.h
rgl/lms
cda6a25e0f39b2a18f10415560ee6a2cfc5fbbcb
[ "Apache-2.0" ]
18
2019-04-17T10:43:35.000Z
2022-03-22T22:30:39.000Z
MEIClient/AMTHIClient/Include/GetSystemDefenseStateCommand.h
rgl/lms
cda6a25e0f39b2a18f10415560ee6a2cfc5fbbcb
[ "Apache-2.0" ]
9
2019-10-03T15:29:51.000Z
2021-12-27T14:03:33.000Z
MEIClient/AMTHIClient/Include/GetSystemDefenseStateCommand.h
rgl/lms
cda6a25e0f39b2a18f10415560ee6a2cfc5fbbcb
[ "Apache-2.0" ]
8
2019-06-13T23:30:50.000Z
2021-06-25T15:51:59.000Z
/* SPDX-License-Identifier: Apache-2.0 */ /* * Copyright (C) 2010-2021 Intel Corporation */ /*++ @file: GetSystemDefenseStateCommand.h --*/ #ifndef __GET_SYSTEM_DEFENSE_STATE_COMMAND_H__ #define __GET_SYSTEM_DEFENSE_STATE_COMMAND_H__ #include "AMTHICommand.h" #include "MEIparser.h" namespace Intel { namespace MEI_Client { namespace AMTHI_Client { typedef struct GET_SYSTEM_DEFENSE_STATE_RESPONSE_t { uint32_t RequestId; AMT_BOOLEAN SystemDefenseActivated; void parse (std::vector<uint8_t>::const_iterator &itr, const std::vector<uint8_t>::const_iterator &end) { parseData(RequestId, itr, end); parseData(SystemDefenseActivated, itr, end); } } GET_SYSTEM_DEFENSE_STATE_RESPONSE; class GetSystemDefenseStateRequest; class GetSystemDefenseStateCommand : public AMTHICommand { public: GetSystemDefenseStateCommand(); virtual ~GetSystemDefenseStateCommand() {} GET_SYSTEM_DEFENSE_STATE_RESPONSE getResponse(); private: virtual void parseResponse(const std::vector<uint8_t>& buffer); std::shared_ptr<AMTHICommandResponse<GET_SYSTEM_DEFENSE_STATE_RESPONSE>> m_response; static const uint32_t RESPONSE_COMMAND_NUMBER = 0x04800049; }; class GetSystemDefenseStateRequest : public AMTHICommandRequest { public: GetSystemDefenseStateRequest() {} virtual ~GetSystemDefenseStateRequest() {} private: static const uint32_t SYSTEM_DEFENSE_ID = 1; static const uint32_t REQUEST_COMMAND_NUMBER = 0x04000049; virtual unsigned int requestHeaderCommandNumber() { //this is the command number (taken from the AMTHI document) return REQUEST_COMMAND_NUMBER; } virtual uint32_t requestDataSize() { return sizeof(uint32_t); } virtual std::vector<uint8_t> SerializeData(); }; } // namespace AMTHI_Client } // namespace MEI_Client } // namespace Intel #endif //__GET_SYSTEM_DEFENSE_STATE_COMMAND_H__
25.076923
107
0.743354
[ "vector" ]
a81cb2104fe2d2c965228f0d3efbe2b712dee8b8
21,178
h
C
src/dmlc-core/include/dmlc/lua.h
joao-pedro-serenini/customxgboost
1fe85d028c0866c812dedcd6a53f92ebcb2cbb19
[ "Apache-2.0" ]
5
2018-07-03T21:30:58.000Z
2021-07-31T15:12:03.000Z
src/dmlc-core/include/dmlc/lua.h
joao-pedro-serenini/customxgboost
1fe85d028c0866c812dedcd6a53f92ebcb2cbb19
[ "Apache-2.0" ]
1
2020-01-26T19:53:49.000Z
2020-01-26T19:53:49.000Z
src/dmlc-core/include/dmlc/lua.h
joao-pedro-serenini/customxgboost
1fe85d028c0866c812dedcd6a53f92ebcb2cbb19
[ "Apache-2.0" ]
8
2019-02-19T23:53:23.000Z
2021-07-31T15:12:04.000Z
/*! * Copyright (c) 2016 by Contributors * \file lua.h * \brief C++11 header only interface to easily interact with Lua and Torch. * This code is evolved from torch plugin code for MXNet. * * This header will require Torch and Lua to be presented, do not include. * * \author Junyuan Xie, Min Lin, Tianqi Chen * * \code * * // Example code to use the lua module. * dmlc::LuaState* lua = dmlc::LuaState::ThreadLocalState(); * // vectors converts automatically to lua table. * auto tbl = lua->Convert(std::vector<int>{1,2,3}); * // use eval to get lua reference, this is a function * auto print = lua->Eval("return function(x) print(x) end"); * // lua function can be directly called from c++, arguments are converted. * print(100); * * // set field in the table. * tbl.SetField("square", lua->Eval("return function(x) x*x end")); * // call the function, covert back to C++ values. * int x = tbl["square"](100).Get<int>(); * * \endcode */ #ifndef DMLC_LUA_H_ #define DMLC_LUA_H_ extern "C" { #include <lua.h> #include <luaT.h> #include <lualib.h> } #include <string> #include <stdexcept> #include <tuple> #include <mutex> #include <memory> #include <vector> #include <utility> #include <unordered_map> #include <type_traits> #include "./base.h" #include "./logging.h" #include "./thread_local.h" namespace dmlc { // forward declare torch state class LuaState; namespace lua_stack { template<typename T> struct Handler; }; /*! \brief an reference to lua object */ class LuaRef { public: /*! \brief construct an nil ref */ LuaRef() = default; /*! * \brief move constructor from another LuaRef * \param other The other LuaRef to be moved */ inline LuaRef(LuaRef&& other); // NOLINT(*) /*! * \brief copy constructor * \param other The other LuaRef to be copied */ inline LuaRef(const LuaRef& other); // NOLINT(*) /*! * \brief assign operator from other * \param other The other LuaRef to be copy or moved. * \return self */ inline LuaRef& operator=(LuaRef&& other); /*! * \brief assign operator from other * \param other The other LuaRef to be copy or moved. * \return self */ inline LuaRef& operator=(const LuaRef& other); /*! \brief destructor */ inline ~LuaRef(); /*! * \brief swap content with another ref * \param other another LuaRef to be swaped. */ inline void swap(LuaRef& other); // NOLINT(*) /*! * \brief Get content out as type T. * * \tparam T the type to be fetched. * \return the corresponding c type. */ template<typename T> inline T Get() const; /*! * \brief Get user data pointer from LuaRef * * CAREFUL when getting userdata(e.g. pointer to Tensor's storage) from LuaRef. * Remember they are managed by Lua, and can get deleted when all the * LuaRef to the userdata destructs. A good practice is always use a LuaRef to keep * the userdata alive when you need them from C++ side. * * \tparam T the type of pointer to be fetched. * \return the corresponding c type. */ template<typename T> inline T* GetUDataPtr() const; /*! \return whether the value is nil */ inline bool is_nil() const; /*! * \brief invoke the LuaRef as function * \param args Arguments to be passed. * \tparam Args arguments to be passed. * \return The first return value. */ template<typename... Args> inline LuaRef operator()(Args&& ...args) const; /*! * \brief Get field from the lua table. * The reference must be a table * \param key The key to the table * \return a new ref to the corresponding field. */ inline LuaRef operator[](const std::string& key) const; /*! * \brief Get field from the lua array * The reference must be a array * \param index The index to the array, * Note: the index convention follows lua table, starts from 1 * \return a new ref to the corresponding field. */ inline LuaRef operator[](size_t index) const; /*! * \brief Set field of lua table. * The reference must be a table * \param key The key to the table * \param value Lua convertable value to be setted. * \return self. */ template<typename T> inline LuaRef& SetField(const std::string& key, const T& value); // NOLINT(*) /*! * \brief Set LuaRef to the value on top of the stack. * This state must be nil. * This is API used by developer. * * \param s the corresponding lua state. */ inline void SetByPopStack_(LuaState* s); private: // friend with luastate friend struct lua_stack::Handler<LuaRef>; friend class LuaState; friend std::ostream &operator<<(std::ostream &os, const LuaRef &r); /*! \brief pointer to the state */ LuaState* state_{nullptr}; /*! \brief reference index */ int ref_; }; /*! \brief A Lua state */ class LuaState { public: /*! \brief options to be provided in lua state */ enum Option { kNoThreadProtect, kThreadLocal, kLocking, }; /*! \brief destructor */ inline ~LuaState(); /*! * \brief evaluate a piece of lua code, return the first result. * \param lua_code Lua code * \return A LuaRef object of the first returned result, * Can be nil if the code did not return LuaRefthing. */ inline LuaRef Eval(const char* lua_code); /*! * \brief evaluate a piece of lua code, return the first result. * \param lua_code Lua code * \return A LuaRef object of the first returned result, * Can be nil if the code did not return anything. */ inline LuaRef Eval(const std::string& lua_code) { return this->Eval(lua_code.c_str()); } /*! * \brief convert a C++ type to lua type * \param value The data to be converted. * vector, map will be converted to table. * \return a converted value. * \tparam T the type to be converted. */ template<typename T> inline LuaRef Convert(const T& value); /*! * \brief get global field from the state * \param key The key to the global field. * \return The global field value. */ inline LuaRef operator[](const std::string& key); /*! * \brief Set the value to the global table. * \param key The key of the global field. * \param value The value to the set. */ inline void SetGlobalField(const std::string& key, const LuaRef& value); /*! * Get a thread local version of lua state. * The LuaState runs in thread local mode, * all the LuaRef can only be run on the current thread. * This is the recommended behavior when invoking Lua. * * \return a threadlocal version of lua state. */ static inline LuaState* ThreadLocalState(); /*! * Create a new lua state. * \note It is highly recommended to use ThreadLocalState instead. * * Most Lua program assumes it only runs from the same thread. * Some Lua code that wraps C library(e.g. Torch) could rely * on thread_local storage to store global state such as random number generator. * This means if the code is invoked by another thread, the thread_local * might become inavailable, depending on the implementation. * * If the global state is stored only in Lua's global table, then * it is safe to use kLocking mode and call the code from multiple thread. * Never-the-less, using ThreadLocalState removes the need to lock, * and is the desirable usecase in most times. * * \sa ThreadLocalState * \param option The option to use the state. * \return a newly created lua state */ static inline LuaState* Create_(Option option); /*! * \brief protected run f, this is used by API developers. * always call this to access lua state * f must not destruct LuaRef, or access the mutex * * \param f the function to be called. * \tparam F the function to be called, signiture (lua_State *L) */ template<typename F> inline void PRun_(F f); /*! * \param L the other lua state. * \return if the internal lua state is same as L */ inline bool SameLuaState(lua_State *L) const { return L_ == L; } protected: struct StackReset; friend class LuaRef; friend struct ThreadLocalStore<LuaState>; /*! * \brief constructor */ inline LuaState(); /*! \brief internal option, default to thread local */ Option option_{kThreadLocal}; /*! \brief internal lua state */ lua_State* L_; /*! \brief internal lock about the state */ std::mutex mutex_; }; // implementations after this line //! \cond Doxygen_Suppress /*! \brief macro to check error during lua call */ #define LUA_CALL(x) \ if ((x)) { \ LOG(FATAL) << "Lua Call Error:" << lua_tostring(L, -1); \ } /*! * \brief namespace to handle conversions between lua and c++ * User can provide an specialization of dmlc::lua_stack::Handler * to allow customized c++ data types to interact with Lua. * * By default basic data types, composition of vector, and unordered_map is supported. * The conversion rules * - basic types(string, int, float) to corresponding lua types. * - unordered_map to Lua table. * - vector to lua indexed table. */ namespace lua_stack { inline int lua_abs_index(lua_State* L, int index) { if (index > 0 || index <= LUA_REGISTRYINDEX) return index; return lua_gettop(L) + index + 1; } template<typename T> struct Handler; template<typename T> struct NumberHandler { static inline T Get(lua_State* L, int index, LuaState* s) { CHECK_EQ(lua_type(L, index), LUA_TNUMBER) << "Attempt to get number but type is \'" << lua_typename(L, lua_type(L, index)) << '\''; if (std::is_integral<T>::value) { return static_cast<T>(lua_tointeger(L, index)); } else { return static_cast<T>(lua_tonumber(L, index)); } } static inline void Push(lua_State* L, const T& v) { if (std::is_integral<T>::value) { lua_pushinteger(L, static_cast<lua_Integer>(v)); } else { lua_pushnumber(L, static_cast<lua_Number>(v)); } } }; template<typename ContainerType> struct MapHandler { using K = typename ContainerType::key_type; using V = typename ContainerType::mapped_type; static inline ContainerType Get(lua_State* L, int index, LuaState* s) { ContainerType ret; CHECK(lua_istable(L, index)) << "Expected a table but get " << lua_typename(L, lua_type(L, index)) << '\''; int tid = lua_abs_index(L, index); lua_pushnil(L); while (lua_next(L, -2)) { ret[Handler<K>::Get(L, -2, s)] = Handler<V>::Pop(L, -1, s); lua_pop(L, 1); } lua_settop(L, tid); return ret; } static inline void Push(lua_State* L, const ContainerType& v) { lua_createtable(L, v.size(), 0); for (const auto& kv : v) { Handler<K>::Push(L, kv.first); Handler<V>::Push(L, kv.second); lua_settable(L, -3); } } }; struct UndefinedHandler { }; template<typename T> struct Handler : public std::conditional<std::is_arithmetic<T>::value, NumberHandler<T>, UndefinedHandler>::type { }; template<> struct Handler<std::string> { static inline std::string Get(lua_State* L, int index, LuaState* s) { CHECK_EQ(lua_type(L, index), LUA_TSTRING); return std::string(lua_tostring(L, index)); } static inline void Push(lua_State* L, const std::string& v) { lua_pushstring(L, v.c_str()); } }; template<typename T> struct Handler<std::vector<T> > { static inline std::vector<T> Get(lua_State* L, int index, LuaState* s) { std::vector<T> ret; CHECK(lua_istable(L, index)) << "Expected a table but get " << lua_typename(L, lua_type(L, index)) << '\''; int tid = lua_abs_index(L, index); lua_pushnil(L); while (lua_next(L, tid)) { CHECK_EQ(Handler<size_t>::Get(L, -2, s), ret.size() + 1) << "Target table is not an array"; ret.push_back(Handler<T>::Get(L, -1, s)); lua_pop(L, 1); } lua_settop(L, tid); return ret; } static inline void Push(lua_State* L, const std::vector<T>& v) { lua_createtable(L, v.size(), 0); for (size_t i = 0; i < v.size(); ++i) { Handler<T>::Push(L, v[i]); lua_rawseti(L, -2, i + 1); } } }; template<typename K, typename V> struct Handler<std::unordered_map<K, V> > : public MapHandler<std::unordered_map<K, V> > { }; template<> struct Handler<LuaRef> { static inline LuaRef Get(lua_State* L, int index, LuaState* s) { LuaRef ret; lua_pushvalue(L, index); ret.SetByPopStack_(s); return ret; } static inline void Push(lua_State* L, const LuaRef& v) { if (v.is_nil()) { lua_pushnil(L); } else { CHECK(v.state_->SameLuaState(L)) << "Cannot pass LuaRef on a different LuaState's function"; lua_rawgeti(L, LUA_REGISTRYINDEX, v.ref_); } } }; template<> struct Handler<std::nullptr_t> { static inline LuaRef Get(lua_State* L, int index, LuaState* s) { LOG(FATAL) << "not supported"; return LuaRef(); } static inline void Push(lua_State* L, const std::nullptr_t& v) { lua_pushnil(L); } }; // generic functor to call push the arguments. struct PushArg { lua_State* L; template<typename T> inline void operator()(const T& v) const { Handler<T>::Push(L, v); } }; } // namespace lua_stack inline LuaState::LuaState() { L_ = luaL_newstate(); CHECK(L_ != nullptr) << "Failed to create new lua state"; luaL_openlibs(L_); } inline LuaState::~LuaState() { if (option_ != kThreadLocal && L_ != nullptr) { // never close threadlocal, for save destruction. lua_close(L_); } } inline LuaState* LuaState::Create_(Option opt) { LuaState* s = new LuaState(); s->option_ = opt; CHECK_NE(opt, kThreadLocal) << "use LuaState::ThreadLocalState() to get the thread local state"; return s; } inline void LuaRef::SetByPopStack_(LuaState* s) { CHECK(state_ == nullptr); lua_State* L = s->L_; if (!lua_isnil(L, -1)) { ref_ = lua_ref(L, LUA_REGISTRYINDEX); state_ = s; } else { lua_pop(L, 1); } } // RAII guard to reset stack struct LuaState::StackReset { lua_State* L; int top; ~StackReset() { lua_settop(L, top); } }; template<typename F> inline void LuaState::PRun_(F f) { if (option_ != kLocking) { StackReset reset{L_, lua_gettop(L_)}; if (option_ == kThreadLocal) { CHECK_EQ(ThreadLocalState(), this) << "Invoke lua from a different thread in ThreadLocal mode."; } f(L_); CHECK_EQ(reset.top, lua_gettop(L_)); } else { std::lock_guard<std::mutex> lock(mutex_); StackReset reset{L_, lua_gettop(L_)}; f(L_); CHECK_EQ(reset.top, lua_gettop(L_)); } } inline LuaState* LuaState::ThreadLocalState() { return ThreadLocalStore<LuaState>::Get(); } inline LuaRef LuaState::Eval(const char* lua_code) { LuaRef ret; this->PRun_([this, lua_code, &ret](lua_State* L) { luaL_loadstring(L, lua_code); CHECK_EQ(lua_pcall(L, 0, 1, 0), 0) << "Lua call error: " << lua_tostring(L, -1) << '\n' << "---------\n" << lua_code << "\n----------"; ret.SetByPopStack_(this); }); return ret; } template<typename T> inline LuaRef LuaState::Convert(const T& value) { LuaRef ret; this->PRun_([this, &value, &ret](lua_State* L) { lua_stack::Handler<T>::Push(L, value); ret.SetByPopStack_(this); }); return ret; } inline LuaRef LuaState::operator[](const std::string& key) { LuaRef ret; this->PRun_([this, &key, &ret](lua_State* L) { lua_getglobal(L, key.c_str()); ret.SetByPopStack_(this); }); return ret; } inline void LuaState::SetGlobalField( const std::string& key, const LuaRef& value) { this->PRun_([this, &key, &value](lua_State* L) { lua_rawgeti(L, LUA_REGISTRYINDEX, value.ref_); lua_setglobal(L, key.c_str()); }); } inline LuaRef::LuaRef(const LuaRef& other) { if (other.state_ != nullptr) { state_ = other.state_; state_->PRun_([this, &other](lua_State* L) { lua_rawgeti(L, LUA_REGISTRYINDEX, other.ref_); ref_ = luaL_ref(L, LUA_REGISTRYINDEX); }); } } inline LuaRef::LuaRef(LuaRef&& other) { ref_ = other.ref_; state_ = other.state_; other.state_ = nullptr; } inline LuaRef& LuaRef::operator=(LuaRef&& other) { LuaRef(std::move(other)).swap(*this); return *this; } inline LuaRef& LuaRef::operator=(const LuaRef& other) { LuaRef(other).swap(*this); return *this; } inline void LuaRef::swap(LuaRef& other) { // NOLINT(*) std::swap(state_, other.state_); std::swap(ref_, other.ref_); } inline LuaRef::~LuaRef() { if (state_ != nullptr) { state_->PRun_([this](lua_State* L) { luaL_unref(L, LUA_REGISTRYINDEX, ref_); }); } } inline bool LuaRef::is_nil() const { return state_ == nullptr; } std::ostream &operator<<(std::ostream &os, const LuaRef &r) { if (!r.is_nil()) { r.state_->PRun_([&os, &r](lua_State* L) { lua_rawgeti(L, LUA_REGISTRYINDEX, r.ref_); int type = lua_type(L, -1); switch (type) { case LUA_TSTRING: os << "lua_string:'" << lua_tostring(L, -1) << "'"; break; case LUA_TBOOLEAN: os << "lua_bool:" << (lua_toboolean(L, -1) ? "true" : "false"); break; case LUA_TNUMBER: os << "lua_number:" << lua_tonumber(L, -1); break; default: os << "lua[ref=" << r.ref_ << ']' << lua_typename(L, type); break; } lua_pop(L, 1); }); } else { os << "lua_nil"; } return os; } template<typename T> inline T LuaRef::Get() const { CHECK(state_ != nullptr) << "Get:: LuaRef is nil"; T ret; state_->PRun_([&ret, this](lua_State* L) { lua_rawgeti(L, LUA_REGISTRYINDEX, ref_); ret = lua_stack::Handler<T>::Get(L, -1, state_); lua_pop(L, 1); }); return ret; } template<typename T> inline T* LuaRef::GetUDataPtr() const { CHECK(state_ != nullptr) << "Get:: LuaRef is nil"; T* ret; state_->PRun_([&ret, this](lua_State* L) { lua_rawgeti(L, LUA_REGISTRYINDEX, ref_); ret = reinterpret_cast<T*>(lua_touserdata(L, -1)); lua_pop(L, 1); }); return ret; } // helper function to dispatch varg foreach template<bool stop, std::size_t I, typename F, typename ...Args> struct for_each_dispatcher_ { static inline void run(const std::tuple<Args...>& args, F f) { f(std::get<I>(args)); for_each_dispatcher_<(I + 1) == sizeof...(Args), (I+1), F, Args...>::run(args, f); } }; // helper function to run foreach template<std::size_t I, typename F, typename ...Args> struct for_each_dispatcher_<true, I, F, Args...> { static inline void run(const std::tuple<Args...>& args, F f) { } }; // template function to iterate over tuples template<typename F, typename ...Args> inline void for_each(const std::tuple<Args...>& args, F f) { for_each_dispatcher_<sizeof...(Args) == 0, 0, F, Args...>::run(args, f); } template<typename... Args> inline LuaRef LuaRef::operator()(Args&& ...args) const { CHECK(state_ != nullptr) << "LuaRef is nil"; auto targ = std::make_tuple(std::forward<Args>(args)...); size_t nargs = sizeof...(Args); LuaRef ret; state_->PRun_([this, nargs, &targ, &ret](lua_State* L) { lua_rawgeti(L, LUA_REGISTRYINDEX, this->ref_); CHECK(lua_isfunction(L, -1)) << "Expect to invoke a function but type='" << lua_typename(L, lua_type(L, -1)) << '\''; for_each(targ, lua_stack::PushArg{L}); LUA_CALL(lua_pcall(L, nargs, 1, 0)); ret.SetByPopStack_(state_); }); return ret; } template<typename T> inline LuaRef& LuaRef::SetField(const std::string& key, const T& value) { // NOLINT(*) CHECK(state_ != nullptr) << "LuaRef is nil"; state_->PRun_([this, &key, &value](lua_State* L) { lua_rawgeti(L, LUA_REGISTRYINDEX, this->ref_); CHECK(lua_istable(L, -1)) << "Expect a table but type='" << lua_typename(L, lua_type(L, -1)) << '\''; lua_stack::Handler<T>::Push(L, value); lua_setfield(L, -2, key.c_str()); lua_pop(L, 1); }); return *this; } inline LuaRef LuaRef::operator[](const std::string& key) const { CHECK(state_ != nullptr) << "LuaRef is nil"; LuaRef ret; state_->PRun_([this, &key, &ret](lua_State* L) { lua_rawgeti(L, LUA_REGISTRYINDEX, this->ref_); CHECK(lua_istable(L, -1)) << "Expect a table but type='" << lua_typename(L, lua_type(L, -1)) << '\''; lua_getfield(L, -1, key.c_str()); ret.SetByPopStack_(state_); lua_pop(L, 1); }); return ret; } inline LuaRef LuaRef::operator[](size_t index) const { CHECK(state_ != nullptr) << "LuaRef is nil"; LuaRef ret; state_->PRun_([this, index, &ret](lua_State* L) { lua_rawgeti(L, LUA_REGISTRYINDEX, this->ref_); CHECK(lua_istable(L, -1)) << "Expect a table but type='" << lua_typename(L, lua_type(L, -1)) << '\''; lua_rawgeti(L, -1, index); ret.SetByPopStack_(state_); lua_pop(L, 1); }); return ret; } //! \endcond } // namespace dmlc #endif // DMLC_LUA_H_
28.657645
87
0.629096
[ "object", "vector" ]
a82025398526495c861373bf01eed39a25e22c81
20,107
c
C
src/ssv/pyramid.c
glshort/MapReady
c9065400a64c87be46418ab32e3a251ca2f55fd5
[ "BSD-3-Clause" ]
3
2017-12-31T05:33:28.000Z
2021-07-28T01:51:22.000Z
src/ssv/pyramid.c
glshort/MapReady
c9065400a64c87be46418ab32e3a251ca2f55fd5
[ "BSD-3-Clause" ]
null
null
null
src/ssv/pyramid.c
glshort/MapReady
c9065400a64c87be46418ab32e3a251ca2f55fd5
[ "BSD-3-Clause" ]
7
2017-04-26T18:18:33.000Z
2020-05-15T08:01:09.000Z
// Implementation of interface described in pyramid.h. #include <ctype.h> #include <math.h> #include <glib.h> #include <glib/gstdio.h> #include <asf_meta.h> #include "meta_read_wrapper.h" #include "pyramid.h" #include "float_blob.h" #include "utilities.h" #ifdef G_LOG_DOMAIN # undef G_LOG_DOMAIN #endif #define G_LOG_DOMAIN "Pyramid" pyramid_layer * form_base_layer (const char *base) { pyramid_layer *result = g_new (pyramid_layer, 1); GString *meta = my_g_string_new_printf ("%s.meta", base); GString *data = my_g_string_new_printf ("%s.img", base); meta_parameters *mp = meta_read_wrapper (meta->str); // Dimensions of base. result->size_x = mp->general->sample_count; result->size_y = mp->general->line_count; // Convenience aliases. size_t sx = result->size_x; size_t sy = result->size_y; FloatBlob *base_blob = float_blob_new_using (sx, sy, data->str, G_BYTE_ORDER != G_BIG_ENDIAN); size_t layer_size = sx * sy; // Size of current layer in pixels. if ( layer_size * sizeof (float) <= PYRAMID_BIGGEST_LAYER_IN_MEMORY ) { result->is_float_blob = FALSE; result->data = g_new (float, layer_size); float_blob_get_region (base_blob, 0, 0, sx, sy, result->data); } else { result->is_float_blob = TRUE; result->data = base_blob; } return result; } // Form pyramid layers above base by creating FloatBlob or memory area // instances using PixMapsSpec pixmaps in directory path. If // base_name is NULL, unique file names for any individual FloatBlob // instances used are automagicly generated, otherwise names of the // form "base_name_layer_number" are used (where the first // layer_number is "1"). static GPtrArray * form_upper_layers (pyramid_layer *base, PixMapsSpec *pixmaps, GString *path, const char *base_name) { GPtrArray *result = g_ptr_array_new (); // When the smaller dimesion of the topmost layer of the pyramid is // this size or smaller we consider the pyramid fully formed. const size_t min_dimension = 1; // Layer currently being worked on. size_t layer = 0; // Dimensions of current layer. size_t cw = base->size_x, ch = base->size_y; while ( cw > min_dimension && ch > min_dimension ) { // Previous layer (with respect to layer this iteration will add). pyramid_layer *pl; if ( layer == 0 ) { pl = base; } else { pl = g_ptr_array_index (result, layer - 1); } // If the previous layer has one or two odd dimensions, we will // need to generate the rightmost and/or bottommost edges of the // new layer without having four input pixels to use. gboolean extra_column = FALSE, extra_row = FALSE; if ( cw % 2 == 1 ) { extra_column = TRUE; } if ( ch % 2 == 1 ) { extra_row = TRUE; } cw = ceil (cw / 2.0); ch = ceil (ch / 2.0); layer++; // Curent layer. pyramid_layer *cl = g_new (pyramid_layer, 1); cl->size_x = cw; cl->size_y = ch; size_t layer_size = cw * ch; // Size of current layer in pixels. if ( layer_size * sizeof (float) <= PYRAMID_BIGGEST_LAYER_IN_MEMORY ) { cl->is_float_blob = FALSE; cl->data = g_new (float, layer_size); } else { cl->is_float_blob = TRUE; if ( base_name == NULL ) { cl->data = float_blob_new (cw, ch, path->str, base_name); } else { GString *name = my_g_string_new_printf ("%s_%llu", base_name, (long long unsigned) layer); cl->data = float_blob_new (cw, ch, path->str, name->str); my_g_string_free (name); } } size_t ii, jj; // Index variables. float *cr = g_new (float, cw); // Current row being formed. if ( pl->is_float_blob ) { float *ra = g_new (float, pl->size_x); // Row above. float *rb = g_new (float, pl->size_x); // Row below. // First we do all the rows of the new layer which are truly // averages of four other pixels. We'll come back and fill in // the extra row that we have to deal with if the previous layer // had an odd number of rows later. for ( jj = 0 ; jj < ch - (extra_row ? 1 : 0) ; jj++ ) { float_blob_get_region (pl->data, 0, jj * 2, pl->size_x, 1, ra); float_blob_get_region (pl->data, 0, jj * 2 + 1, pl->size_x, 1, rb); // If this is the first layer above the base layer, we need to // apply the maps to the inputs as advertised. if ( layer == 1 ) { guint kk; for ( kk = 0 ; kk < pl->size_x ; kk++ ) { ra[kk] = pix_maps_spec_map (pixmaps, ra[kk]); rb[kk] = pix_maps_spec_map (pixmaps, rb[kk]); } } if ( cl->is_float_blob ) { // We will deal with the extra column, if any, later (see // above comment). for ( ii = 0 ; ii < cw - (extra_column ? 1 : 0) ; ii++ ) { cr[ii] = ra[ii * 2] + ra[ii * 2 + 1] + rb[ii * 2] + rb[ii * 2 + 1]; cr[ii] /= 4.0; } // Deal with the extra column (except possibly for the // bottom rightmost pixel, which is dealt with when the // bottom row is done if there is an extra row). if ( extra_column ) { size_t cind = cw - 1; // Column index. cr[cind] = (ra[cind * 2] + rb[cind * 2]) / 2.0; } float_blob_set_region (cl->data, 0, jj, cw, 1, cr); } else { // Current row pointer. float *crp = ((float *) cl->data) + jj * cw; for ( ii = 0 ; ii < cw - (extra_column ? 1 : 0) ; ii++ ) { crp[ii] = ((ra[ii * 2] + ra[ii * 2 + 1] + rb[ii * 2] + rb[ii * 2 + 1]) / 4.0); } // Deal with potential extra column (see comment above). if ( extra_column ) { size_t cind = cw - 1; // Column index. crp[cind] = (ra[cind * 2] + rb[cind * 2]) / 2.0; } } } g_free (ra); g_free (rb); } else { // Previous layer is not a FloatBlob for ( jj = 0 ; jj < ch - (extra_row ? 1 : 0) ; jj++ ) { // Interpreted previous layer data pointer. float *pld = ((float *) pl->data); for ( ii = 0 ; ii < cw - (extra_column ? 1 : 0) ; ii++ ) { // Pixel values from which we will form the next pixel. float ul, ur, ll, lr; ul = pld[jj * 2 * pl->size_x + ii * 2]; ur = pld[jj * 2 * pl->size_x + ii * 2 + 1]; ll = pld[(jj * 2 + 1) * pl->size_x + ii * 2]; lr = pld[(jj * 2 + 1) * pl->size_x + ii * 2 + 1]; // If this is the first layer above the base layer, we need // to apply the maps to the inputs as advertised. if ( layer == 1 ) { guint kk; for ( kk = 0 ; kk < pl->size_x ; kk++ ) { ul = pix_maps_spec_map (pixmaps, ul); ur = pix_maps_spec_map (pixmaps, ul); ll = pix_maps_spec_map (pixmaps, ul); lr = pix_maps_spec_map (pixmaps, ul); } } ((float *) cl->data)[jj * cw + ii] = (ul + ur + ll + lr) / 4.0; } if ( extra_column ) { size_t cind = cw - 1; // Column index. float up, lp; // Upper pixel, lower pixel. up = pld[jj * 2 * pl->size_x + cind * 2]; lp = pld[(jj * 2 + 1) * pl->size_x + cind * 2]; // Here (and other such places) is where propagation should // be implemented: if we are "infecting" upper layers, we // need to do it every layer, not just the first, and the // calculation of the new value needs to be conditionalized // as well. if ( layer == 1 ) { up = pix_maps_spec_map (pixmaps, up); lp = pix_maps_spec_map (pixmaps, lp); } ((float *) cl->data)[jj * cw + cind] = (up + lp) / 2.0; } } } // Now take care of the extra row, if any. if ( extra_row ) { float *mr = g_new (float, pl->size_x); // Model row in layer below. if ( pl->is_float_blob ) { float_blob_get_region ((FloatBlob *) pl->data, 0, (ch - 1) * 2, pl->size_x, 1, mr); } else { for ( ii = 0 ; ii < pl->size_x ; ii++ ) { mr[ii] = ((float *) pl->data)[(ch - 1) * 2 + ii]; } } if ( layer == 1 ) { for ( ii = 0 ; ii < pl->size_x ; ii++ ) { mr[ii] = pix_maps_spec_map (pixmaps, mr[ii]); } } for ( ii = 0 ; ii < cl->size_x - (extra_column ? 1 : 0) ; ii++ ) { cr[ii] = (mr[ii * 2] + mr[ii * 2 + 1]) / 2.0; } if ( extra_column ) { cr[cl->size_x - 1] = mr[pl->size_x - 1]; } if ( cl->is_float_blob ) { float_blob_set_region ((FloatBlob *) cl->data, 0, ch - 1, cw, 1, cr); } else { for ( ii = 0 ; ii < cl->size_x ; ii++ ) { ((float *) cl->data)[ii] = cr[ii]; } } g_free (mr); } // Old functional (but weird in that it cloned a row above instead // of using the bottom row of the model) extra_row code. /* if ( extra_row ) { if ( cl->is_float_blob ) { float_blob_get_region ((FloatBlob *) cl->data, 0, ch - 2, cw, 1, cr); float_blob_set_region ((FloatBlob *) cl->data, 0, ch - 1, cw, 1, cr); } else { float *cld = ((float *) cl->data); // Interpreted current layer data. for ( ii = 0 ; ii < cw ; ii++ ) { cld[cw * (ch - 1) + ii] = cld[cw * (ch - 2) + ii]; } } } */ g_free (cr); // Whew! g_ptr_array_add (result, cl); } return result; } Pyramid * pyramid_new (const char *base_name, PixMapsSpec *pixmaps, const char *scratch_dir) { // This path has worked fine in the past and seen decent testing, // and I haven't done anything that seems likely to beak it, but I // haven't run it in a while either, so this break is here. g_assert_not_reached (); Pyramid *self = g_new (Pyramid, 1); self->base_name = g_string_new (base_name); self->layers = g_ptr_array_new (); pyramid_layer *base_layer = form_base_layer (base_name); g_ptr_array_add (self->layers, base_layer); GString *path = g_string_new (scratch_dir); GPtrArray *upper_layers = form_upper_layers (base_layer, pixmaps, path, NULL); my_g_ptr_array_add_entries (self->layers, upper_layers); g_ptr_array_free (upper_layers, TRUE); self->pixmaps = pix_maps_spec_ref (pixmaps); self->cache = NULL; self->scratch_dir = path; // Take ownership of path GString. self->reference_count = 1; return self; } // Get a new string containing the md5 sum of "base_name.meta", // followed by "_", followed by the md5 sum of "base_name.img". static GString * get_md5_sums (const char *base_name) { // Create a temporary file to hold the output of the system command. // IMPROVEME: there should be some way to read our own output other // than this goofy method of writing it to a temporary file, after // all perl does it. Its not obvious to me how to do it though. GString *tmp_file_name = make_unique_tmp_file_name ("/tmp", "pyramid_"); GString *meta_name = my_g_string_new_printf ("%s.meta", base_name); GString *img_name = my_g_string_new_printf ("%s.img", base_name); // Write md5 sum information for metadata file into temporary file. GString *system_command = my_g_string_new_printf ("md5sum %s >%s", meta_name->str, tmp_file_name->str); int exit_code = system (system_command->str); g_assert (exit_code == 0); // Append md5 sum information for data file to temporary file. g_string_printf (system_command, "md5sum %s >>%s", img_name->str, tmp_file_name->str); exit_code = system (system_command->str); g_assert (exit_code == 0); my_g_string_free (system_command); // Now we read the text back out of the temporary file and pick out // just the strings. GError *tmp_error = NULL; gchar *contents = NULL; g_file_get_contents (tmp_file_name->str, &contents, NULL, &tmp_error); if ( tmp_error != NULL ) { g_error ("g_file_get_contents on %s failed: %s\n", tmp_file_name->str, tmp_error->message); } int return_code = g_unlink (tmp_file_name->str); g_assert (return_code == 0); my_g_string_free (tmp_file_name); // Everything up to the first space is the metadata md5 sum. GString *meta_md5sum = g_string_new (""); size_t ii; for ( ii = 0 ; !isspace (contents[ii]) ; ii++ ) { g_string_append_c (meta_md5sum, contents[ii]); } // Now skip everything up to the newline. for ( ; contents[ii] != '\n' ; ii++ ) { ; } // Skip newline itself. ii++; // Everything up until the next space is the data md5 sum. GString *data_md5sum = g_string_new (""); for ( ; ! isspace (contents[ii]) ; ii++ ) { g_string_append_c (data_md5sum, contents[ii]); } g_free (contents); GString *both_md5sums = my_g_string_new_printf ("%s_%s", meta_md5sum->str, data_md5sum->str); my_g_string_free (data_md5sum); my_g_string_free (meta_md5sum); return both_md5sums; } // Get a new signature string derived from the md5 sums of the data // file and its associated metadata file, and the unique serialization // of pixmaps. static GString * get_signature (const char *base_name, PixMapsSpec *pixmaps) { GString *result = get_md5_sums (base_name); GString *pix_maps_spec = pix_maps_spec_freeze_as_gstring (pixmaps); g_string_append_printf (result, "_%s", pix_maps_spec->str); my_g_string_free (pix_maps_spec); return result; } Pyramid * pyramid_new_using_cache (const char *base_name, PixMapsSpec *pixmaps, PyramidCache *cache) { Pyramid *self = g_new0 (Pyramid, 1); self->base_name = g_string_new (base_name); self->layers = g_ptr_array_new (); pyramid_layer *base_layer = form_base_layer (base_name); g_ptr_array_add (self->layers, base_layer); self->signature = get_signature (base_name, pixmaps); GPtrArray *upper_layers = pyramid_cache_try_lease (cache, self->signature); if ( upper_layers == NULL ) { GString *cache_path = g_string_new (cache->dir->str); GString *spaceless_signature = spaces_to_underscores (self->signature); upper_layers = form_upper_layers (base_layer, pixmaps, cache_path, spaceless_signature->str); my_g_string_free (spaceless_signature); my_g_string_free (cache_path); pyramid_cache_add_entry (cache, self->signature, upper_layers); } my_g_ptr_array_add_entries (self->layers, upper_layers); my_g_ptr_array_really_free (upper_layers, NULL); self->pixmaps = pix_maps_spec_ref (pixmaps); self->cache = pyramid_cache_ref (cache); self->scratch_dir = NULL; self->reference_count = 1; return self; } void pyramid_get_region (Pyramid *self, ssize_t start_x, ssize_t start_y, ssize_t w, ssize_t h, ssize_t zoom, float **region, size_t *rstart_x, size_t *rstart_y, size_t *rw, size_t *rh, gboolean *unowned_memory) { pyramid_layer *layer_0 = (pyramid_layer *) g_ptr_array_index (self->layers, 0); g_assert (start_x >= 0 && start_x < layer_0->size_x); g_assert (start_y >= 0 && start_y < layer_0->size_y); g_assert (w > 0 && start_x + w <= layer_0->size_x); g_assert (h > 0 && start_y + h <= layer_0->size_y); // I believe this is a safe use of floating point comparison, // assuming log2 is implemented decently and the interface // requirement that zoom be a power of two is honored. g_assert (log2 (zoom) - floor (log2 (zoom)) == 0.0); int loin = log2 (zoom); // Layer of interest number. pyramid_layer *loi = g_ptr_array_index (self->layers, loin); if ( loi->is_float_blob ) { // Load the region of interest from the FloatBlob for the loi. *rstart_x = (start_x / zoom) * zoom; *rstart_y = (start_y / zoom) * zoom; *rw = ceil ((double) (start_x + w) / zoom) - start_x / zoom; g_assert (*rw * zoom >= w); *rh = ceil ((double) (start_y + h) / zoom) - start_y / zoom; g_assert (*rh * zoom >= h); *unowned_memory = TRUE; *region = g_new (float, *rw * *rh); float_blob_get_region ((FloatBlob *) loi->data, start_x / zoom, start_y / zoom, *rw, *rh, *region); } else { // The loi is already in memory, just return the pointer to the data. *rstart_x = 0; *rstart_y = 0; *rw = loi->size_x; *rh = loi->size_y; *unowned_memory = FALSE; *region = loi->data; } // If this was the base layer, we have to apply pixmaps. if ( loin == 0 && pix_maps_spec_map_count (self->pixmaps) != 0 ) { guint ii, jj; for ( jj = 0 ; jj < *rh ; jj++ ) { for ( ii = 0 ; ii < *rw ; ii++ ) { // Current pixel pointer. float *cpp = *region + jj * *rw + ii; *cpp = pix_maps_spec_map (self->pixmaps, *cpp); } } } } void pyramid_export_as_jpeg_files (Pyramid *self, const char *base) { guint ii; for ( ii = 0 ; ii < self->layers->len ; ii++ ) { pyramid_layer *cl = g_ptr_array_index (self->layers, ii); FloatImage *clafi = float_image_new (cl->size_x, cl->size_y); float *cr = g_new (float, cl->size_x); guint kk; for ( kk = 0 ; kk < cl->size_y ; kk++ ) { if ( cl->is_float_blob ) { float_blob_get_region ((FloatBlob *) cl->data, 0, kk, cl->size_x, 1, cr); } else { guint jj; for ( jj = 0 ; jj < cl->size_x ; jj++ ) { cr[jj] = ((float *) cl->data)[kk * cl->size_x + jj]; } } guint jj; for ( jj = 0 ; jj < cl->size_x ; jj++ ) { float_image_set_pixel (clafi, jj, kk, cr[jj]); } } g_free (cr); // If we are working on the bottom layer, we have to apply the maps. if ( ii == 0 ) { for ( kk = 0 ; kk < clafi->size_y ; kk++ ) { guint jj; for ( jj = 0 ; jj < clafi->size_x ; jj++ ) { float cp = float_image_get_pixel (clafi, jj, kk); float npv = pix_maps_spec_map (self->pixmaps, cp); float_image_set_pixel (clafi, jj, kk, npv); } } } GString *layer_jpeg_name = my_g_string_new_printf ("%s_%u.jpeg", base, ii); size_t larger_dimension = (cl->size_x > cl->size_y ? cl->size_x : cl->size_y); float_image_export_as_jpeg (clafi, layer_jpeg_name->str, larger_dimension, NAN); my_g_string_free (layer_jpeg_name); float_image_free (clafi); } } void pyramid_export_as_float_blobs (Pyramid *self, const char *base) { guint ii; for ( ii = 0 ; ii < self->layers->len ; ii++ ) { pyramid_layer *cl = g_ptr_array_index (self->layers, ii); GString *layer_file_name = my_g_string_new_printf ("%s_%u.raw", base, ii); FILE *lfp = fopen (layer_file_name->str, "w"); // Layer file pointer. g_assert (lfp != NULL); my_g_string_free (layer_file_name); float *cr = g_new (float, cl->size_x); // Buffer for current row. guint kk; for ( kk = 0 ; kk < cl->size_y ; kk++ ) { if ( cl->is_float_blob ) { float_blob_get_region ((FloatBlob *) cl->data, 0, kk, cl->size_x, 1, cr); } else { guint jj; for ( jj = 0 ; jj < cl->size_x ; jj++ ) { cr[jj] = ((float *) cl->data)[kk * cl->size_x + jj]; } } // If we are working on the bottom layer, apply the maps. if ( ii == 0 ) { guint jj; for ( jj = 0 ; jj < cl->size_x ; jj++ ) { cr[jj] = pix_maps_spec_map (self->pixmaps, cr[jj]); } } size_t floats_written = fwrite (cr, sizeof (float), cl->size_x, lfp); g_assert (floats_written == cl->size_x); } g_free (cr); int return_code = fclose (lfp); g_assert (return_code == 0); } } Pyramid * pyramid_ref (Pyramid *self) { self->reference_count++; return self; } void pyramid_unref (Pyramid *self) { self->reference_count--; if ( self->reference_count == 0 ) { // Free or unref the layer data. gint ii; for ( ii = 0 ; ii < self->layers->len ; ii++ ) { pyramid_layer *cl = g_ptr_array_index (self->layers, ii); if ( cl->is_float_blob ) { // If we are using a cache, then the layers that are FloatBlob // instances should either have come from the cache // originally, or we have gifted them to the cache after // creating them. if ( self->cache != NULL ) { g_assert (!((FloatBlob *) cl->data)->is_file_owner); } float_blob_unref ((FloatBlob *) cl->data); } else { g_free (cl->data); } g_free (cl); } g_ptr_array_free (self->layers, TRUE); if ( self->cache != NULL ) { pyramid_cache_release (self->cache, self->signature); pyramid_cache_unref (self->cache); } else { g_assert (self->scratch_dir != NULL); g_string_free (self->scratch_dir, TRUE); } g_string_free (self->base_name, TRUE); g_string_free (self->signature, TRUE); pix_maps_spec_unref (self->pixmaps); g_free (self); } }
28.765379
78
0.618242
[ "model" ]
a821920b6628487e9130881a5866327cdbecfc04
12,274
h
C
components/zucchini/disassembler_elf.h
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
components/zucchini/disassembler_elf.h
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
components/zucchini/disassembler_elf.h
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2018 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 COMPONENTS_ZUCCHINI_DISASSEMBLER_ELF_H_ #define COMPONENTS_ZUCCHINI_DISASSEMBLER_ELF_H_ #include <stdint.h> #include <algorithm> #include <deque> #include <memory> #include <string> #include <vector> #include "base/memory/raw_ptr.h" #include "components/zucchini/address_translator.h" #include "components/zucchini/buffer_view.h" #include "components/zucchini/disassembler.h" #include "components/zucchini/image_utils.h" #include "components/zucchini/rel32_finder.h" #include "components/zucchini/rel32_utils.h" #include "components/zucchini/reloc_elf.h" #include "components/zucchini/type_elf.h" namespace zucchini { struct ArmReferencePool { enum : uint8_t { kPoolReloc, kPoolAbs32, kPoolRel32, }; }; struct AArch32ReferenceType { enum : uint8_t { kReloc, // kPoolReloc kAbs32, // kPoolAbs32 kRel32_A24, // kPoolRel32 kRel32_T8, kRel32_T11, kRel32_T20, kRel32_T24, kTypeCount }; }; struct AArch64ReferenceType { enum : uint8_t { kReloc, // kPoolReloc kAbs32, // kPoolAbs32 kRel32_Immd14, // kPoolRel32 kRel32_Immd19, kRel32_Immd26, kTypeCount }; }; struct Elf32Traits { static constexpr uint16_t kVersion = 1; static constexpr Bitness kBitness = kBit32; static constexpr elf::FileClass kIdentificationClass = elf::ELFCLASS32; using Elf_Shdr = elf::Elf32_Shdr; using Elf_Phdr = elf::Elf32_Phdr; using Elf_Ehdr = elf::Elf32_Ehdr; using Elf_Rel = elf::Elf32_Rel; using Elf_Rela = elf::Elf32_Rela; }; // Architecture-specific definitions. struct Elf32IntelTraits : public Elf32Traits { static constexpr ExecutableType kExeType = kExeTypeElfX86; static const char kExeTypeString[]; static constexpr elf::MachineArchitecture kMachineValue = elf::EM_386; static constexpr uint32_t kRelType = elf::R_386_RELATIVE; enum : uint32_t { kVAWidth = 4 }; using Rel32FinderUse = Rel32FinderX86; }; struct ElfAArch32Traits : public Elf32Traits { static constexpr ExecutableType kExeType = kExeTypeElfAArch32; static const char kExeTypeString[]; static constexpr elf::MachineArchitecture kMachineValue = elf::EM_ARM; static constexpr uint32_t kRelType = elf::R_ARM_RELATIVE; enum : uint32_t { kVAWidth = 4 }; using ArmReferenceType = AArch32ReferenceType; using Rel32FinderUse = Rel32FinderAArch32; }; struct Elf64Traits { static constexpr uint16_t kVersion = 1; static constexpr Bitness kBitness = kBit64; static constexpr elf::FileClass kIdentificationClass = elf::ELFCLASS64; using Elf_Shdr = elf::Elf64_Shdr; using Elf_Phdr = elf::Elf64_Phdr; using Elf_Ehdr = elf::Elf64_Ehdr; using Elf_Rel = elf::Elf64_Rel; using Elf_Rela = elf::Elf64_Rela; }; // Architecture-specific definitions. struct Elf64IntelTraits : public Elf64Traits { static constexpr ExecutableType kExeType = kExeTypeElfX64; static const char kExeTypeString[]; static constexpr elf::MachineArchitecture kMachineValue = elf::EM_X86_64; static constexpr uint32_t kRelType = elf::R_X86_64_RELATIVE; enum : uint32_t { kVAWidth = 8 }; using Rel32FinderUse = Rel32FinderX64; }; struct ElfAArch64Traits : public Elf64Traits { static constexpr ExecutableType kExeType = kExeTypeElfAArch64; static const char kExeTypeString[]; static constexpr elf::MachineArchitecture kMachineValue = elf::EM_AARCH64; // TODO(huangs): See if R_AARCH64_GLOB_DAT and R_AARCH64_JUMP_SLOT should be // used. static constexpr uint32_t kRelType = elf::R_AARCH64_RELATIVE; enum : uint32_t { kVAWidth = 8 }; using ArmReferenceType = AArch64ReferenceType; using Rel32FinderUse = Rel32FinderAArch64; }; // Decides whether target |offset| is covered by a section in |sorted_headers|. template <class ELF_SHDR> bool IsTargetOffsetInElfSectionList( const std::vector<const ELF_SHDR*>& sorted_headers, offset_t offset) { // Use binary search to search in a list of intervals, in a fashion similar to // AddressTranslator::OffsetToUnit(). auto comp = [](offset_t offset, const ELF_SHDR* header) -> bool { return offset < header->sh_offset; }; auto it = std::upper_bound(sorted_headers.begin(), sorted_headers.end(), offset, comp); if (it == sorted_headers.begin()) return false; --it; // Just check offset without worrying about width, since this is a target. // Not using RangeCovers() because |sh_offset| and |sh_size| can be 64-bit. return offset >= (*it)->sh_offset && offset - (*it)->sh_offset < (*it)->sh_size; } // Disassembler for ELF. template <class TRAITS> class DisassemblerElf : public Disassembler { public: using Traits = TRAITS; static constexpr uint16_t kVersion = Traits::kVersion; // Applies quick checks to determine whether |image| *may* point to the start // of an executable. Returns true iff the check passes. static bool QuickDetect(ConstBufferView image); DisassemblerElf(const DisassemblerElf&) = delete; const DisassemblerElf& operator=(const DisassemblerElf&) = delete; ~DisassemblerElf() override; // Disassembler: ExecutableType GetExeType() const override; std::string GetExeTypeString() const override; std::vector<ReferenceGroup> MakeReferenceGroups() const override = 0; // Read/Write functions that are common among different architectures. std::unique_ptr<ReferenceReader> MakeReadRelocs(offset_t lo, offset_t hi); std::unique_ptr<ReferenceWriter> MakeWriteRelocs(MutableBufferView image); const AddressTranslator& translator() const { return translator_; } protected: friend Disassembler; DisassemblerElf(); bool Parse(ConstBufferView image) override; // Returns the supported Elf_Ehdr::e_machine enum. static constexpr elf::MachineArchitecture supported_architecture() { return Traits::kMachineValue; } // Returns the type to look for in the reloc section. static constexpr uint32_t supported_relocation_type() { return Traits::kRelType; } // Performs architecture-specific parsing of an executable section, to extract // rel32 references. virtual void ParseExecSection(const typename Traits::Elf_Shdr& section) = 0; // Processes rel32 data after they are extracted from executable sections. virtual void PostProcessRel32() = 0; // Parses ELF header and section headers, and performs basic validation. // Returns whether parsing was successful. bool ParseHeader(); // Extracts and stores section headers that we need. void ExtractInterestingSectionHeaders(); // Parsing functions that extract references from various sections. void GetAbs32FromRelocSections(); void GetRel32FromCodeSections(); void ParseSections(); // Main ELF header. raw_ptr<const typename Traits::Elf_Ehdr> header_ = nullptr; // Section header table, ordered by section id. elf::Elf32_Half sections_count_ = 0; raw_ptr<const typename Traits::Elf_Shdr> sections_ = nullptr; // Program header table. elf::Elf32_Half segments_count_ = 0; raw_ptr<const typename Traits::Elf_Phdr> segments_ = nullptr; // Bit fields to store the role each section may play. std::vector<int> section_judgements_; // Translator between offsets and RVAs. AddressTranslator translator_; // Identity translator for abs32 translation. AddressTranslator identity_translator_; // Extracted relocation section dimensions data, sorted by file offsets. std::vector<SectionDimensionsElf> reloc_section_dims_; // Headers of executable sections, sorted by file offsets of the data each // header points to. std::vector<const typename Traits::Elf_Shdr*> exec_headers_; // Sorted file offsets of abs32 locations. std::vector<offset_t> abs32_locations_; }; // Disassembler for ELF with Intel architectures. template <class TRAITS> class DisassemblerElfIntel : public DisassemblerElf<TRAITS> { public: using Traits = TRAITS; enum ReferenceType : uint8_t { kReloc, kAbs32, kRel32, kTypeCount }; DisassemblerElfIntel(); DisassemblerElfIntel(const DisassemblerElfIntel&) = delete; const DisassemblerElfIntel& operator=(const DisassemblerElfIntel&) = delete; ~DisassemblerElfIntel() override; // Disassembler: std::vector<ReferenceGroup> MakeReferenceGroups() const override; // DisassemblerElf: void ParseExecSection(const typename Traits::Elf_Shdr& section) override; void PostProcessRel32() override; // Specialized Read/Write functions. std::unique_ptr<ReferenceReader> MakeReadAbs32(offset_t lo, offset_t hi); std::unique_ptr<ReferenceWriter> MakeWriteAbs32(MutableBufferView image); std::unique_ptr<ReferenceReader> MakeReadRel32(offset_t lo, offset_t hi); std::unique_ptr<ReferenceWriter> MakeWriteRel32(MutableBufferView image); private: // Sorted file offsets of rel32 locations. // Using std::deque to reduce peak memory footprint. std::deque<offset_t> rel32_locations_; }; using DisassemblerElfX86 = DisassemblerElfIntel<Elf32IntelTraits>; using DisassemblerElfX64 = DisassemblerElfIntel<Elf64IntelTraits>; // Disassembler for ELF with ARM architectures. template <class TRAITS> class DisassemblerElfArm : public DisassemblerElf<TRAITS> { public: using Traits = TRAITS; DisassemblerElfArm(); DisassemblerElfArm(const DisassemblerElfArm&) = delete; const DisassemblerElfArm& operator=(const DisassemblerElfArm&) = delete; ~DisassemblerElfArm() override; // Determines whether target |offset| is in an executable section. bool IsTargetOffsetInExecSection(offset_t offset) const; // Creates an architecture-specific Rel32Finder for ParseExecSection. virtual std::unique_ptr<typename Traits::Rel32FinderUse> MakeRel32Finder( const typename Traits::Elf_Shdr& section) = 0; // DisassemblerElf: void ParseExecSection(const typename Traits::Elf_Shdr& section) override; void PostProcessRel32() override; // Specialized Read/Write functions. std::unique_ptr<ReferenceReader> MakeReadAbs32(offset_t lo, offset_t hi); std::unique_ptr<ReferenceWriter> MakeWriteAbs32(MutableBufferView image); // Specialized Read/Write functions for different rel32 address types. template <class ADDR_TRAITS> std::unique_ptr<ReferenceReader> MakeReadRel32(offset_t lower, offset_t upper); template <class ADDR_TRAITS> std::unique_ptr<ReferenceWriter> MakeWriteRel32(MutableBufferView image); protected: // Sorted file offsets of rel32 locations for each rel32 address type. std::deque<offset_t> rel32_locations_table_[Traits::ArmReferenceType::kTypeCount]; }; // Disassembler for ELF with AArch32 (AKA ARM32). class DisassemblerElfAArch32 : public DisassemblerElfArm<ElfAArch32Traits> { public: DisassemblerElfAArch32(); DisassemblerElfAArch32(const DisassemblerElfAArch32&) = delete; const DisassemblerElfAArch32& operator=(const DisassemblerElfAArch32&) = delete; ~DisassemblerElfAArch32() override; // Disassembler: std::vector<ReferenceGroup> MakeReferenceGroups() const override; // DisassemblerElfArm: std::unique_ptr<typename Traits::Rel32FinderUse> MakeRel32Finder( const typename Traits::Elf_Shdr& section) override; // Under the naive assumption that an executable section is entirely ARM mode // or THUMB2 mode, this function implements heuristics to distinguish between // the two. Returns true if section is THUMB2 mode; otherwise return false. bool IsExecSectionThumb2(const typename Traits::Elf_Shdr& section) const; }; // Disassembler for ELF with AArch64 (AKA ARM64). class DisassemblerElfAArch64 : public DisassemblerElfArm<ElfAArch64Traits> { public: DisassemblerElfAArch64(); DisassemblerElfAArch64(const DisassemblerElfAArch64&) = delete; const DisassemblerElfAArch64& operator=(const DisassemblerElfAArch64&) = delete; ~DisassemblerElfAArch64() override; // Disassembler: std::vector<ReferenceGroup> MakeReferenceGroups() const override; // DisassemblerElfArm: std::unique_ptr<typename Traits::Rel32FinderUse> MakeRel32Finder( const typename Traits::Elf_Shdr& section) override; }; } // namespace zucchini #endif // COMPONENTS_ZUCCHINI_DISASSEMBLER_ELF_H_
34.284916
80
0.760062
[ "vector" ]
a8273fcaed30af33107bc5ea3151e83efa6c0856
1,644
h
C
Source/BuildingEscape/Grabber.h
Mike430/BuildingEscape
025e79c1e27865085b236a33e74cbe4178fe764a
[ "MIT" ]
null
null
null
Source/BuildingEscape/Grabber.h
Mike430/BuildingEscape
025e79c1e27865085b236a33e74cbe4178fe764a
[ "MIT" ]
null
null
null
Source/BuildingEscape/Grabber.h
Mike430/BuildingEscape
025e79c1e27865085b236a33e74cbe4178fe764a
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "Components/ActorComponent.h" #include "PhysicsEngine/PhysicsHandleComponent.h" #include "Components/InputComponent.h" #include "Grabber.generated.h" UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) ) class BUILDINGESCAPE_API UGrabber : public UActorComponent { GENERATED_BODY() public: // Sets default values for this component's properties UGrabber(); protected: // Called when the game starts virtual void BeginPlay() override; UPhysicsHandleComponent* _mPhysicsHandle = nullptr; UInputComponent* _mInputComponent = nullptr; FVector _mPlayerPosition; FRotator _mPlayerViewAngle; UPROPERTY( EditAnywhere ) float _mReach; // rayCast and possess object void Grab(); // Drop possessed object void Release(); private: // Getting the physics handle on the Owner and binding it to a member level variable. void FindPhysicsHandleComponent(); // Gets the input component that appears at runtime and handles bindings. void SetupInputComponent(); // Ray cast and return the first object hit. FHitResult GetFirstPhysicsBodyInReach(); // Returns a point in front of the player and centred in view. FVector GetReachLineEnd(); // Utility function for drawing a red line between two points. const void DrawRay( FVector start, FVector end ); const bool IsPhysicsHandleNullptr(); public: // Called every frame virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override; };
27.4
123
0.752433
[ "object" ]
a8307680d041340a73ad22b0eeb0adcf91ee073c
3,042
h
C
MaterialLib/MPL/Properties/CapillaryPressureSaturation/CapillaryPressureVanGenuchten.h
ufz/ogs
97d0249e0c578c3055730f4e9d994b9970885098
[ "BSD-3-Clause" ]
111
2015-03-20T22:54:17.000Z
2022-03-30T04:37:21.000Z
MaterialLib/MPL/Properties/CapillaryPressureSaturation/CapillaryPressureVanGenuchten.h
ufz/ogs
97d0249e0c578c3055730f4e9d994b9970885098
[ "BSD-3-Clause" ]
3,015
2015-01-05T21:55:16.000Z
2021-02-15T01:09:17.000Z
MaterialLib/MPL/Properties/CapillaryPressureSaturation/CapillaryPressureVanGenuchten.h
ufz/ogs
97d0249e0c578c3055730f4e9d994b9970885098
[ "BSD-3-Clause" ]
250
2015-02-10T15:43:57.000Z
2022-03-30T04:37:20.000Z
/** * \file * \copyright * Copyright (c) 2012-2021, OpenGeoSys Community (http://www.opengeosys.org) * Distributed under a Modified BSD License. * See accompanying file LICENSE.txt or * http://www.opengeosys.org/project/license * * Created on March 20, 2020, 9:59 AM */ #pragma once #include "MaterialLib/MPL/Property.h" namespace MaterialPropertyLib { class Medium; class Phase; class Component; /** * \brief The van Genuchten capillary pressure model. * * The van Genuchten capillary pressure model (\cite Genuchten1980) is: * \f[p_c(S)=p_b (S_\text{eff}^{-1/m}-1)^{1-m}\f] * with effective saturation defined as * \f[S_\text{eff}=\frac{S-S_r}{S_{\text{max}}-S_r}.\f] * Above, \f$S_r\f$ and \f$S_{\text{max}}\f$ are the residual and the maximum * saturations. * The exponent \f$m \in (0,1)\f$ and the pressure scaling parameter \f$p_b\f$ * (it is equal to \f$\rho g/\alpha\f$ in original publication) are given by the * user. * The scaling parameter \f$p_b\f$ is given in same units as pressure. * * In the original work another exponent \f$n\f$ is used, but usually set to * \f$n = 1 / (1 - m)\f$, and also in this implementation. * * The the capillary pressure is computed from saturation as above but is cut * off at maximum capillary pressure given by user. */ class CapillaryPressureVanGenuchten : public Property { public: CapillaryPressureVanGenuchten(std::string name, double const residual_liquid_saturation, double const residual_gas_saturation, double const exponent, double const p_b, double const maximum_capillary_pressure); void checkScale() const override { if (!std::holds_alternative<Medium*>(scale_)) { OGS_FATAL( "The property 'CapillaryPressureVanGenuchten' is implemented " "on the 'media' scale only."); } } /// \returns \f$ p_c(S) \f$. PropertyDataType value(VariableArray const& variable_array, ParameterLib::SpatialPosition const& pos, double const t, double const dt) const override; /// \returns \f$ \frac{\partial p_c(S)}{\partial S} \f$ PropertyDataType dValue(VariableArray const& variable_array, Variable const variable, ParameterLib::SpatialPosition const& pos, double const t, double const dt) const override; private: double const S_L_res_; ///< Residual saturation of liquid phase. double const S_L_max_; ///< Maximum saturation of liquid phase. double const m_; ///< Exponent. double const p_b_; ///< Pressure scaling factor. double const p_cap_max_; ///< Maximum capillary pressure. }; } // namespace MaterialPropertyLib
36.650602
80
0.602893
[ "model" ]
a836f9cd13da2cae6c29f5463904fef1d3e41f6f
9,203
h
C
src/translator/hypothesis.h
cepin19/marian-constraints
61f200c7ef0b29e0339a1823c97fab63fc61108a
[ "MIT" ]
null
null
null
src/translator/hypothesis.h
cepin19/marian-constraints
61f200c7ef0b29e0339a1823c97fab63fc61108a
[ "MIT" ]
null
null
null
src/translator/hypothesis.h
cepin19/marian-constraints
61f200c7ef0b29e0339a1823c97fab63fc61108a
[ "MIT" ]
null
null
null
#pragma once #include <memory> #include "common/definitions.h" #include "data/alignment.h" #include <algorithm> #include <unordered_set> #include <unordered_map> namespace marian { // A Trie node struct Trie { // true when node is a leaf node bool isLeaf; //list of words that would complete the constraint from current node std::vector<Word> finalIds; // each node stores a map to its child nodes std::unordered_map<Word, marian::Trie*> map; }; // Function that returns a new Trie node inline Trie* getNewTrieNode() { Trie* node = new Trie; node->isLeaf = false; return node; } // Iterative function to insert a string in Trie. inline void insert(Trie*& head, std::vector<Word> tokenSequence) { if (head == nullptr) head = getNewTrieNode(); // start from root node Trie* curr = head; int i=0; for (auto token:tokenSequence) { // create a new node if path doesn't exists if (curr->map.find(token) == curr->map.end()) curr->map[token] = getNewTrieNode(); //penultimate word in a sequence if (i==tokenSequence.size()-1){ curr->finalIds.push_back(tokenSequence.back()); } // go to next node curr = curr->map[token]; i++; } // mark current node as leaf curr->isLeaf = true; } // returns true if given node has any children inline bool haveChildren(Trie const* curr) { // don't use (curr->map).size() to check for children for (auto it : curr->map) if (it.second != nullptr) return true; return false; } // Recursive function to delete a string in Trie. inline bool deletion(Trie*& curr, std::vector<Word> tokenSequence) { // return if Trie is empty if (curr == nullptr) return false; // if we have not reached the end of the string int i=0; for (auto token:tokenSequence) { // recur for the node corresponding to next character in // the string and if it returns true, delete current node // (if it is non-leaf) if (curr != nullptr && curr->map.find(token) != curr->map.end() && deletion(curr->map[token], tokenSequence) && curr->isLeaf == false) { if (!haveChildren(curr)) { delete curr;; curr = nullptr; return true; } else { return false; } } i++; } // if we have reached the end of the string if (curr->isLeaf) { // if current node is a leaf node and don't have any children if (!haveChildren(curr)) { delete curr;; // delete current node curr = nullptr; return true; // delete non-leaf parent nodes } // if current node is a leaf node and have children else { // mark current node as non-leaf node (DON'T DELETE IT) curr->isLeaf = false; return false; // don't delete its parent nodes } } return false; } // Iterative function to search a string in Trie. It returns true // if the string is found in the Trie, else it returns false inline bool search(Trie* head, std::vector<Word> tokenSequence) { // return false if Trie is empty if (head == nullptr) return false; Trie* curr = head; for (auto token:tokenSequence) { // go to next node curr = curr->map[token]; // if string is invalid (reached end of path in Trie) if (curr == nullptr) return false; } // if current node is a leaf and we have reached the // end of the string, return true return curr->isLeaf; } inline Trie* copy(Trie* orig){ ; Trie *newTrie=getNewTrieNode(); return newTrie; } /* // Memory efficient Trie Implementation in C++ using Map int main() { Trie* head = nullptr; insert(head, "hello"); cout << search(head, "hello") << " "; // print 1 insert(head, "helloworld"); cout << search(head, "helloworld") << " "; // print 1 cout << search(head, "helll") << " "; // print 0 (Not present) insert(head, "hell"); cout << search(head, "hell") << " "; // print 1 insert(head, "h"); cout << search(head, "h") << endl; // print 1 + newline deletion(head, "hello"); cout << search(head, "hello") << " "; // print 0 (hello deleted) cout << search(head, "helloworld") << " "; // print 1 cout << search(head, "hell") << endl; // print 1 + newline deletion(head, "h"); cout << search(head, "h") << " "; // print 0 (h deleted) cout << search(head, "hell") << " "; // print 1 cout << search(head, "helloworld") << endl; // print 1 + newline deletion(head, "helloworld"); cout << search(head, "helloworld") << " "; // print 0 cout << search(head, "hell") << " "; // print 1 deletion(head, "hell"); cout << search(head, "hell") << endl; // print 0 + newline if (head == nullptr) cout << "Trie empty!!\n"; // Trie is empty now cout << search(head, "hell"); // print 0 return 0; }*/ // one single (partial or full) hypothesis in beam search // key elements: // - the word that this hyp ends with // - the aggregate score up to and including the word // - back pointer to previous hypothesis for traceback class Hypothesis { public: typedef IPtr<Hypothesis> PtrType; private: // Constructors are private, use Hypothesis::New(...) Hypothesis() : prevHyp_(nullptr), prevBeamHypIdx_(0), word_(Word::ZERO), pathScore_(0.0) {} Hypothesis(const PtrType prevHyp, Word word, size_t prevBeamHypIdx, // beam-hyp index that this hypothesis originated from float pathScore) : prevHyp_(prevHyp), prevBeamHypIdx_(prevBeamHypIdx), word_(word), pathScore_(pathScore) {} public: std::vector<Trie *> constraintTrieStates; Trie * constraintTrieRoot; std::vector<int> multiTokenIdsTracker; std::vector<float> multiTokenScoreTracker; // Use this whenever creating a pointer to MemoryPiece template <class ...Args> static PtrType New(Args&& ...args) { return PtrType(new Hypothesis(std::forward<Args>(args)...)); } const PtrType getPrevHyp() const { return prevHyp_; } Word getWord() const { return word_; } size_t getPrevStateIndex() const { return prevBeamHypIdx_; } float getPathScore() const { return pathScore_; } const std::vector<float>& getScoreBreakdown() { return scoreBreakdown_; } void setScoreBreakdown(const std::vector<float>& scoreBreakdown) { scoreBreakdown_ = scoreBreakdown; } float getLastWordScore() { if (prevHyp_) { return pathScore_ - prevHyp_->getPathScore(); } else { return pathScore_; } } const std::vector<float>& getAlignment() { return alignment_; } void setAlignment(const std::vector<float>& align) { alignment_ = align; }; // trace back paths referenced from this hypothesis Words tracebackWords() { Words targetWords; for(auto hyp = this; hyp->getPrevHyp(); hyp = hyp->getPrevHyp().get()) { targetWords.push_back(hyp->getWord()); } std::reverse(targetWords.begin(), targetWords.end()); return targetWords; } // calculate word-level scores for each target word by de-aggregating the path score std::vector<float> tracebackWordScores() { std::vector<float> scores; // traverse hypotheses backward for(auto hyp = this; hyp->getPrevHyp(); hyp = hyp->getPrevHyp().get()) { // a path score is a cumulative score including scores from all preceding hypotheses (words), // so calculate a word-level score by subtracting the previous path score from the current path score auto prevPathScore = hyp->getPrevHyp() ? hyp->getPrevHyp().get()->pathScore_ : 0.f; scores.push_back(hyp->pathScore_ - prevPathScore); } std::reverse(scores.begin(), scores.end()); return scores; } // get soft alignments [t][s] -> P(s|t) for each target word starting from the hyp one typedef data::SoftAlignment SoftAlignment; SoftAlignment tracebackAlignment() { SoftAlignment align; for(auto hyp = this; hyp->getPrevHyp(); hyp = hyp->getPrevHyp().get()) { align.push_back(hyp->getAlignment()); } std::reverse(align.begin(), align.end()); return align; // [t][s] -> P(s|t) } private: const PtrType prevHyp_; const size_t prevBeamHypIdx_; const Word word_; const float pathScore_; std::vector<float> scoreBreakdown_; // [num scorers] std::vector<float> alignment_; ENABLE_INTRUSIVE_PTR(Hypothesis) }; typedef std::vector<IPtr<Hypothesis>> Beam; // Beam = vector [beamSize] of hypotheses typedef std::vector<Beam> Beams; // Beams = vector [batchDim] of vector [beamSize] of hypotheses typedef std::tuple<Words, IPtr<Hypothesis>, float> Result; // (word ids for hyp, hyp, normalized sentence score for hyp) typedef std::vector<Result> NBestList; // sorted vector of (word ids, hyp, sent score) tuples } // namespace marian
29.496795
121
0.613604
[ "vector" ]
a83ba2aa0ed67420a6fef2cbbef5238866642839
3,914
h
C
kubernetes/api/NodeV1beta1API.h
zouxiaoliang/nerv-kubernetes-client-c
07528948c643270fd757d38edc68da8c9628ee7a
[ "Apache-2.0" ]
null
null
null
kubernetes/api/NodeV1beta1API.h
zouxiaoliang/nerv-kubernetes-client-c
07528948c643270fd757d38edc68da8c9628ee7a
[ "Apache-2.0" ]
null
null
null
kubernetes/api/NodeV1beta1API.h
zouxiaoliang/nerv-kubernetes-client-c
07528948c643270fd757d38edc68da8c9628ee7a
[ "Apache-2.0" ]
null
null
null
#include <stdlib.h> #include <stdio.h> #include "../include/apiClient.h" #include "../include/list.h" #include "../external/cJSON.h" #include "../include/keyValuePair.h" #include "../include/binary.h" #include "../model/io_k8s_api_node_v1beta1_runtime_class.h" #include "../model/io_k8s_api_node_v1beta1_runtime_class_list.h" #include "../model/io_k8s_apimachinery_pkg_apis_meta_v1_api_resource_list.h" #include "../model/io_k8s_apimachinery_pkg_apis_meta_v1_delete_options.h" #include "../model/io_k8s_apimachinery_pkg_apis_meta_v1_status.h" #include "../model/io_k8s_apimachinery_pkg_apis_meta_v1_watch_event.h" // create a RuntimeClass // io_k8s_api_node_v1beta1_runtime_class_t* NodeV1beta1API_createNodeV1beta1RuntimeClass(apiClient_t *apiClient, io_k8s_api_node_v1beta1_runtime_class_t * body , char * pretty , char * dryRun , char * fieldManager ); // delete collection of RuntimeClass // io_k8s_apimachinery_pkg_apis_meta_v1_status_t* NodeV1beta1API_deleteNodeV1beta1CollectionRuntimeClass(apiClient_t *apiClient, char * pretty , char * _continue , char * dryRun , char * fieldSelector , int gracePeriodSeconds , char * labelSelector , int limit , int orphanDependents , char * propagationPolicy , char * resourceVersion , char * resourceVersionMatch , int timeoutSeconds , io_k8s_apimachinery_pkg_apis_meta_v1_delete_options_t * body ); // delete a RuntimeClass // io_k8s_apimachinery_pkg_apis_meta_v1_status_t* NodeV1beta1API_deleteNodeV1beta1RuntimeClass(apiClient_t *apiClient, char * name , char * pretty , char * dryRun , int gracePeriodSeconds , int orphanDependents , char * propagationPolicy , io_k8s_apimachinery_pkg_apis_meta_v1_delete_options_t * body ); // get available resources // io_k8s_apimachinery_pkg_apis_meta_v1_api_resource_list_t* NodeV1beta1API_getNodeV1beta1APIResources(apiClient_t *apiClient); // list or watch objects of kind RuntimeClass // io_k8s_api_node_v1beta1_runtime_class_list_t* NodeV1beta1API_listNodeV1beta1RuntimeClass(apiClient_t *apiClient, char * pretty , int allowWatchBookmarks , char * _continue , char * fieldSelector , char * labelSelector , int limit , char * resourceVersion , char * resourceVersionMatch , int timeoutSeconds , int watch ); // partially update the specified RuntimeClass // io_k8s_api_node_v1beta1_runtime_class_t* NodeV1beta1API_patchNodeV1beta1RuntimeClass(apiClient_t *apiClient, char * name , object_t * body , char * pretty , char * dryRun , char * fieldManager , int force ); // read the specified RuntimeClass // io_k8s_api_node_v1beta1_runtime_class_t* NodeV1beta1API_readNodeV1beta1RuntimeClass(apiClient_t *apiClient, char * name , char * pretty ); // replace the specified RuntimeClass // io_k8s_api_node_v1beta1_runtime_class_t* NodeV1beta1API_replaceNodeV1beta1RuntimeClass(apiClient_t *apiClient, char * name , io_k8s_api_node_v1beta1_runtime_class_t * body , char * pretty , char * dryRun , char * fieldManager ); // watch changes to an object of kind RuntimeClass. deprecated: use the 'watch' parameter with a list operation instead, filtered to a single item with the 'fieldSelector' parameter. // io_k8s_apimachinery_pkg_apis_meta_v1_watch_event_t* NodeV1beta1API_watchNodeV1beta1RuntimeClass(apiClient_t *apiClient, char * name , int allowWatchBookmarks , char * _continue , char * fieldSelector , char * labelSelector , int limit , char * pretty , char * resourceVersion , char * resourceVersionMatch , int timeoutSeconds , int watch ); // watch individual changes to a list of RuntimeClass. deprecated: use the 'watch' parameter with a list operation instead. // io_k8s_apimachinery_pkg_apis_meta_v1_watch_event_t* NodeV1beta1API_watchNodeV1beta1RuntimeClassList(apiClient_t *apiClient, int allowWatchBookmarks , char * _continue , char * fieldSelector , char * labelSelector , int limit , char * pretty , char * resourceVersion , char * resourceVersionMatch , int timeoutSeconds , int watch );
51.5
402
0.809658
[ "object", "model" ]
a83cd5808e87b794f272601a49822d1024994b6d
11,040
c
C
src/gl/wrap/remote.c
CrossStream/glshim
615dbe9ca2be8053cfa48f2c42bb96c64cf6512d
[ "MIT" ]
131
2015-01-12T17:49:41.000Z
2022-01-17T05:09:41.000Z
src/gl/wrap/remote.c
CrossStream/glshim
615dbe9ca2be8053cfa48f2c42bb96c64cf6512d
[ "MIT" ]
117
2015-01-05T13:26:27.000Z
2020-12-13T06:02:23.000Z
src/gl/wrap/remote.c
CrossStream/glshim
615dbe9ca2be8053cfa48f2c42bb96c64cf6512d
[ "MIT" ]
36
2015-01-16T10:50:21.000Z
2022-01-17T05:09:44.000Z
#include <X11/Xlib.h> #include "../get.h" #include "../list.h" #include "../remote.h" #include "./glpack.h" #include "./remote.h" #include "gl_helpers.h" void remote_local_pre(ring_t *ring, packed_call_t *call) { switch (call->index) { // glX functions case glXChooseVisual_INDEX: { glXChooseVisual_PACKED *n = (glXChooseVisual_PACKED *)call; int *attribList = n->args.attribList; int size = 0; while (attribList[size++]) {} ring_write(ring, attribList, size); break; } case glXCreateContext_INDEX: { glXCreateContext_PACKED *n = (glXCreateContext_PACKED *)call; if (n->args.vis) { ring_write(ring, n->args.vis, sizeof(XVisualInfo)); } if (n->args.shareList) { ring_write(ring, n->args.shareList, sizeof(GLXContext)); } break; } case glXMakeCurrent_INDEX: { Display *dpy = ((glXMakeCurrent_PACKED *)call)->args.dpy; // if the window create hasn't flushed yet, we can't init on the remote if (dpy) { XFlush(dpy); } break; } // GL functions case glBitmap_INDEX: { glBitmap_PACKED *n = (glBitmap_PACKED *)call; size_t size = ((n->args.width + 7) / 8) * n->args.height; ring_write(ring, n->args.bitmap, size); break; } case glDeleteTextures_INDEX: { glDeleteTextures_PACKED *n = (glDeleteTextures_PACKED *)call; ring_write(ring, n->args.textures, n->args.n * sizeof(GLuint)); break; } case glDrawPixels_INDEX: { glDrawPixels_PACKED *n = (glDrawPixels_PACKED *)call; size_t size = n->args.width * n->args.height * gl_pixel_sizeof(n->args.format, n->args.type); ring_write(ring, n->args.pixels, size); break; } case glFogiv_INDEX: { glFogiv_PACKED *n = (glFogiv_PACKED *)call; ring_write(ring, n->args.params, gl_fogv_length(n->args.pname) * sizeof(GLint)); break; } case glFogfv_INDEX: { glFogfv_PACKED *n = (glFogfv_PACKED *)call; ring_write(ring, n->args.params, gl_fogv_length(n->args.pname) * sizeof(GLint)); break; } case glLightfv_INDEX: { glLightfv_PACKED *n = (glLightfv_PACKED *)call; int count = 1; switch (n->args.pname) { case GL_AMBIENT: case GL_DIFFUSE: case GL_SPECULAR: case GL_POSITION: count = 4; break; case GL_SPOT_DIRECTION: count = 3; break; } ring_write(ring, n->args.params, count * sizeof(GLfloat)); break; } case glLoadMatrixf_INDEX: case glLoadTransposeMatrixf_INDEX: case glMultMatrixf_INDEX: case glMultTransposeMatrixf_INDEX: { glLoadMatrixf_PACKED *n = (glLoadMatrixf_PACKED *)call; ring_write(ring, n->args.m, 16 * sizeof(GLfloat)); break; } case glMaterialfv_INDEX: { glMaterialfv_PACKED *n = (glMaterialfv_PACKED *)call; int count = 4; switch (n->args.pname) { case GL_SHININESS: count = 1; break; case GL_COLOR_INDEXES: count = 3; break; } ring_write(ring, n->args.params, count * sizeof(GLfloat)); break; } case glTexImage2D_INDEX: { glTexImage2D_PACKED *n = (glTexImage2D_PACKED *)call; if (n->args.pixels) { size_t size = n->args.width * n->args.height * gl_pixel_sizeof(n->args.format, n->args.type); ring_write(ring, n->args.pixels, size); } break; } case glTexSubImage2D_INDEX: { glTexSubImage2D_PACKED *n = (glTexSubImage2D_PACKED *)call; if (n->args.pixels) { size_t size = n->args.width * n->args.height * gl_pixel_sizeof(n->args.format, n->args.type); ring_write(ring, n->args.pixels, size); } break; } } } void remote_local_post(ring_t *ring, packed_call_t *call, void *ret_v, size_t ret_size) { switch (call->index) { case glGenTextures_INDEX: ring_read_into(ring, ((glGenTextures_PACKED *)call)->args.textures); break; case glXGetConfig_INDEX: ring_read_into(ring, ((glXGetConfig_PACKED *)call)->args.value); break; case glGetString_INDEX: { char *str = ring_read(ring, NULL); // TODO: somehow free this, or use a klist to preserve char *ret = malloc(strlen(str)); strcpy(ret, str); *(char **)ret_v = ret; break; } case glXSwapBuffers_INDEX: // prevent too many frames from clogging up the ring buffer ring_read(ring, NULL); break; case glXChooseVisual_INDEX: { glXChooseVisual_PACKED *n = (glXChooseVisual_PACKED *)call; XVisualInfo **ret_vis = (XVisualInfo **)ret_v; if (*ret_vis) { XVisualInfo *visual = malloc(sizeof(XVisualInfo)); ring_read_into(ring, visual); // need to use XMatchVisualInfo because the visual passed from the remote is associated with a different Display * XVisualInfo tmp; XMatchVisualInfo(n->args.dpy, visual->screen, visual->depth, visual->class, &tmp); memcpy(visual, &tmp, sizeof(XVisualInfo)); *ret_vis = visual; } break; } } } void remote_target_pre(ring_t *ring, packed_call_t *call, size_t size, void *ret) { static Display *target_display = NULL; if (! target_display) target_display = XOpenDisplay(NULL); switch (call->index) { // glshim functions case REMOTE_BLOCK_DRAW: { if (state.list.active) { void *tmp = malloc(size); memcpy(tmp, call, size); block_t *block = remote_read_block(ring, tmp); dl_append_block(state.list.active, block); block->solid = tmp; } else { block_t *block = remote_read_block(ring, (void *)call); bl_draw(block); } return; } case REMOTE_GL_GET: { uint32_t *buf = (uint32_t *)call; gl_get(buf[1], buf[2], ret); return; } // glX functions // can't pass a Display * through the proxy case glXChooseVisual_INDEX: { glXChooseVisual_PACKED *n = (glXChooseVisual_PACKED *)call; n->args.dpy = target_display; n->args.attribList = ring_read(ring, NULL); glIndexedCall(call, ret); return; } case glXCreateContext_INDEX: { glXCreateContext_PACKED *n = (glXCreateContext_PACKED *)call; n->args.dpy = target_display; if (n->args.vis) { n->args.vis = ring_read(ring, NULL); } if (n->args.shareList) { n->args.shareList = ring_read(ring, NULL); } break; } case glXDestroyContext_INDEX: ((glXDestroyContext_PACKED *)call)->args.dpy = target_display; break; case glXGetConfig_INDEX: ((glXGetConfig_PACKED *)call)->args.value = ring_dma(ring, sizeof(int)); glIndexedCall(call, ret); ring_dma_done(ring); return; case glXMakeCurrent_INDEX: ((glXCreateContext_PACKED *)call)->args.dpy = target_display; break; case glXSwapBuffers_INDEX: ring_write(ring, NULL, 0); ((glXSwapBuffers_PACKED *)call)->args.dpy = target_display; break; // GL functions case glBitmap_INDEX: ((glBitmap_PACKED *)call)->args.bitmap = ring_read(ring, NULL); break; case glDeleteTextures_INDEX: ((glDeleteTextures_PACKED *)call)->args.textures = ring_read(ring, NULL); break; case glDrawPixels_INDEX: ((glDrawPixels_PACKED *)call)->args.pixels = ring_read(ring, NULL); break; case glFogiv_INDEX: ((glFogiv_PACKED *)call)->args.params = ring_read(ring, NULL); break; case glFogfv_INDEX: ((glFogfv_PACKED *)call)->args.params = ring_read(ring, NULL); break; case glGenTextures_INDEX: { glGenTextures_PACKED *n = (glGenTextures_PACKED *)call; size_t size = n->args.n * sizeof(GLuint); GLuint *textures = ring_dma(ring, size); glGenTextures_PACKED tmp = {glGenTextures_INDEX, {n->args.n, textures}}; glIndexedCall((packed_call_t *)&tmp, NULL); ring_dma_done(ring); return; } case glLightfv_INDEX: ((glLightfv_PACKED *)call)->args.params = ring_read(ring, NULL); break; case glLoadMatrixf_INDEX: case glLoadTransposeMatrixf_INDEX: case glMultMatrixf_INDEX: case glMultTransposeMatrixf_INDEX: ((glLoadMatrixf_PACKED *)call)->args.m = ring_read(ring, NULL); break; case glMaterialfv_INDEX: ((glMaterialfv_PACKED *)call)->args.params = ring_read(ring, NULL); break; case glTexImage2D_INDEX: { glTexImage2D_PACKED *n = (glTexImage2D_PACKED *)call; if (n->args.pixels) { n->args.pixels = ring_read(ring, NULL); } break; } case glTexSubImage2D_INDEX: { glTexSubImage2D_PACKED *n = (glTexSubImage2D_PACKED *)call; if (n->args.pixels) { n->args.pixels = ring_read(ring, NULL); } break; } } glIndexedCall(call, ret); } void remote_target_post(ring_t *ring, packed_call_t *call, void *ret) { switch (call->index) { case glGetString_INDEX: { char *str = *(char **)ret; ring_write(ring, str, strlen(str) + 1); return; } case glXChooseVisual_INDEX: { XVisualInfo **info = (XVisualInfo **)ret; if (*info) { ring_write(ring, *info, sizeof(XVisualInfo)); free(*info); } } } }
34.936709
130
0.525362
[ "solid" ]
a83dc26d28236be85af738126e78c3ba44133ce4
7,750
c
C
oski-1.0.1h/tests/bcsr.c
peterahrens/FillEstimationIPDPS2017
857b6ee8866a2950aa5721d575d2d7d0797c4302
[ "BSD-3-Clause" ]
null
null
null
oski-1.0.1h/tests/bcsr.c
peterahrens/FillEstimationIPDPS2017
857b6ee8866a2950aa5721d575d2d7d0797c4302
[ "BSD-3-Clause" ]
null
null
null
oski-1.0.1h/tests/bcsr.c
peterahrens/FillEstimationIPDPS2017
857b6ee8866a2950aa5721d575d2d7d0797c4302
[ "BSD-3-Clause" ]
null
null
null
/** * \file tests/bcsr.c * \brief Test basic kernel operations for a matrix in BCSR format. * Also implicitly tests oski_ApplyMatTransforms(). */ #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <oski/common.h> #include <oski/matrix.h> #include <oski/matcreate.h> #include <oski/tune.h> #include "abort_prog.h" #include "array_util.h" #include "readhbpat.h" /** * \brief Verify that the input and tuned matrix return approximately * the same answers for \f$A\cdot x\f$. */ void check_MatMult (const oski_matrix_t A0, const oski_matrix_t A1, oski_index_t m, oski_index_t n) { oski_value_t *x_val; oski_vecview_t x; oski_value_t *y0_val; oski_vecview_t y0; oski_value_t *y1_val; oski_vecview_t y1; oski_value_t alpha = MAKE_VAL_COMPLEX (1.0, 0.0); /* oski_value_t beta = MAKE_VAL_COMPLEX( -1.0, 0.0 ); */ oski_value_t beta = MAKE_VAL_COMPLEX (0.0, 0.0); int err; x_val = array_CreateRandom (n); y0_val = array_CreateRandom (m); y1_val = array_Duplicate (y0_val, m); ABORT (x_val == NULL, check_MatMult, ERR_OUT_OF_MEMORY); ABORT (y0_val == NULL, check_MatMult, ERR_OUT_OF_MEMORY); ABORT (y1_val == NULL, check_MatMult, ERR_OUT_OF_MEMORY); x = oski_CreateVecView (x_val, n, STRIDE_UNIT); y0 = oski_CreateVecView (y0_val, m, STRIDE_UNIT); y1 = oski_CreateVecView (y1_val, m, STRIDE_UNIT); ABORT (x == INVALID_VEC, check_MatMult, ERR_BAD_VECVIEW); ABORT (y0 == INVALID_VEC, check_MatMult, ERR_BAD_VECVIEW); ABORT (y1 == INVALID_VEC, check_MatMult, ERR_BAD_VECVIEW); err = oski_MatMult (A0, OP_NORMAL, alpha, x, beta, y0); ABORT (err != 0, check_MatMult, err); err = oski_MatMult (A1, OP_NORMAL, alpha, x, beta, y1); ABORT (err != 0, check_MatMult, err); array_CompareElems ("check_MatMult", y0_val, y1_val, m); oski_DestroyVecView (x); oski_DestroyVecView (y0); oski_DestroyVecView (y1); oski_FreeAll (3, x_val, y0_val, y1_val); } /** * \brief Verify that the input and tuned matrix return approximately * the same answers for \f$A^T\cdot x\f$. */ void check_MatTransMult (const oski_matrix_t A0, const oski_matrix_t A1, oski_index_t m, oski_index_t n) { oski_value_t *x_val; oski_vecview_t x; oski_value_t *y0_val; oski_vecview_t y0; oski_value_t *y1_val; oski_vecview_t y1; oski_value_t alpha = MAKE_VAL_COMPLEX (1.0, 0.0); oski_value_t beta = MAKE_VAL_COMPLEX (-1.0, 0.0); int err; x_val = array_CreateRandom (m); y0_val = array_CreateRandom (n); y1_val = array_Duplicate (y0_val, n); ABORT (x_val == NULL, check_MatTransMult, ERR_OUT_OF_MEMORY); ABORT (y0_val == NULL, check_MatTransMult, ERR_OUT_OF_MEMORY); ABORT (y1_val == NULL, check_MatTransMult, ERR_OUT_OF_MEMORY); x = oski_CreateVecView (x_val, m, STRIDE_UNIT); y0 = oski_CreateVecView (y0_val, n, STRIDE_UNIT); y1 = oski_CreateVecView (y1_val, n, STRIDE_UNIT); ABORT (x == INVALID_VEC, check_MatTransMult, ERR_BAD_VECVIEW); ABORT (y0 == INVALID_VEC, check_MatTransMult, ERR_BAD_VECVIEW); ABORT (y1 == INVALID_VEC, check_MatTransMult, ERR_BAD_VECVIEW); err = oski_MatMult (A0, OP_TRANS, alpha, x, beta, y0); ABORT (err != 0, check_MatTransMult, err); err = oski_MatMult (A1, OP_TRANS, alpha, x, beta, y1); ABORT (err != 0, check_MatTransMult, err); array_CompareElems ("check_MatTransMult", y0_val, y1_val, n); oski_DestroyVecView (x); oski_DestroyVecView (y0); oski_DestroyVecView (y1); oski_FreeAll (3, x_val, y0_val, y1_val); } /** * \brief Verify that the input and tuned matrix return approximately * the same answers for \f$\bar{A}^T\cdot x\f$. */ void check_MatConjTransMult (const oski_matrix_t A0, const oski_matrix_t A1, oski_index_t m, oski_index_t n) { oski_value_t *x_val; oski_vecview_t x; oski_value_t *y0_val; oski_vecview_t y0; oski_value_t *y1_val; oski_vecview_t y1; oski_value_t alpha = MAKE_VAL_COMPLEX (1.0, 0.0); oski_value_t beta = MAKE_VAL_COMPLEX (-1.0, 0.0); int err; x_val = array_CreateRandom (m); y0_val = array_CreateRandom (n); y1_val = array_Duplicate (y0_val, n); ABORT (x_val == NULL, check_MatConjTransMult, ERR_OUT_OF_MEMORY); ABORT (y0_val == NULL, check_MatConjTransMult, ERR_OUT_OF_MEMORY); ABORT (y1_val == NULL, check_MatConjTransMult, ERR_OUT_OF_MEMORY); x = oski_CreateVecView (x_val, m, STRIDE_UNIT); y0 = oski_CreateVecView (y0_val, n, STRIDE_UNIT); y1 = oski_CreateVecView (y1_val, n, STRIDE_UNIT); ABORT (x == INVALID_VEC, check_MatConjTransMult, ERR_BAD_VECVIEW); ABORT (y0 == INVALID_VEC, check_MatConjTransMult, ERR_BAD_VECVIEW); ABORT (y1 == INVALID_VEC, check_MatConjTransMult, ERR_BAD_VECVIEW); err = oski_MatMult (A0, OP_CONJ_TRANS, alpha, x, beta, y0); ABORT (err != 0, check_MatConjTransMult, err); err = oski_MatMult (A1, OP_CONJ_TRANS, alpha, x, beta, y1); ABORT (err != 0, check_MatConjTransMult, err); array_CompareElems ("check_MatConjTransMult", y0_val, y1_val, n); oski_DestroyVecView (x); oski_DestroyVecView (y0); oski_DestroyVecView (y1); oski_FreeAll (3, x_val, y0_val, y1_val); } int main (int argc, char *argv[]) { char *matfile; int r, c; char xform[256]; oski_index_t m, n; /* matrix dimensions */ oski_matrix_t A_input; /* matrix read from file */ oski_matrix_t A_tunable; /* a transformed copy */ oski_timer_t timer; int err; if (argc != 4) { fprintf (stderr, "usage: %s <matfile> <r> <c>\n", argv[0]); fprintf (stderr, "\n"); fprintf (stderr, "This test program reads a matrix pattern from\n"); fprintf (stderr, "a Harwell-Boeing file, converts it to <r> x <c>\n"); fprintf (stderr, "BCSR format, and then tests several kernels\n"); fprintf (stderr, "using it.\n"); return 1; } oski_Init (); timer = oski_CreateTimer (); matfile = argv[1]; r = atoi (argv[2]); c = atoi (argv[3]); oski_PrintDebugMessage (1, "... Reading the input file, '%s' ...", matfile); oski_RestartTimer (timer); A_input = readhb_pattern_matrix (matfile, &m, &n, NULL, 0); assert (A_input != NULL); oski_StopTimer (timer); oski_PrintDebugMessage (1, "(Took %g seconds)", oski_ReadElapsedTime (timer)); oski_PrintDebugMessage (1, "... Making a tunable copy ..."); oski_RestartTimer (timer); A_tunable = oski_CopyMat (A_input); oski_StopTimer (timer); ABORT (A_tunable == NULL, main, ERR_BAD_MAT); oski_PrintDebugMessage (1, "(Took %g seconds)", oski_ReadElapsedTime (timer)); #define CONV_TEMPLATE \ "A_new = BCSR( InputMat, %d, %d )\n" \ "return A_new" snprintf (xform, 255, CONV_TEMPLATE, r, c); xform[255] = (char) 0; /* Just in case */ oski_PrintDebugMessage (1, "... Converting using this BeBOP-Lua program:"); oski_PrintDebugMessage (1, "-- begin\n%s\n-- end\n", xform); oski_RestartTimer (timer); err = oski_ApplyMatTransforms (A_tunable, xform); oski_StopTimer (timer); ABORT (err != 0, main, err); oski_PrintDebugMessage (1, "(Took %g seconds)", oski_ReadElapsedTime (timer)); oski_PrintDebugMessage (1, "... Checking matrix-vector multiply ..."); check_MatMult (A_input, A_tunable, m, n); oski_PrintDebugMessage (1, "... Checking matrix-transpose-vector multiply ..."); check_MatTransMult (A_input, A_tunable, m, n); oski_PrintDebugMessage (1, "... Checking matrix-conjugate-transpose-vector multiply ..."); check_MatConjTransMult (A_input, A_tunable, m, n); oski_PrintDebugMessage (1, "... Cleaning up ..."); oski_RestartTimer (timer); oski_DestroyMat (A_tunable); oski_DestroyMat (A_input); oski_StopTimer (timer); oski_PrintDebugMessage (1, "(Took %g seconds)", oski_ReadElapsedTime (timer)); oski_DestroyTimer (timer); oski_Close (); return 0; } /* eof */
29.356061
78
0.698065
[ "vector" ]
a84b94759096411fa7122f386aba4124c6d5ea0d
3,060
h
C
Code/Tools/AssetProcessor/native/connection/connectionworker.h
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
11
2021-07-08T09:58:26.000Z
2022-03-17T17:59:26.000Z
Code/Tools/AssetProcessor/native/connection/connectionworker.h
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
29
2021-07-06T19:33:52.000Z
2022-03-22T10:27:49.000Z
Code/Tools/AssetProcessor/native/connection/connectionworker.h
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
4
2021-07-06T19:24:43.000Z
2022-03-31T12:42:27.000Z
/* * 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 #if !defined(Q_MOC_RUN) #include <QTcpSocket> #include <QHostAddress> #include "native/connection/connectionMessages.h" #include <AzCore/Memory/Memory.h> #include <AzCore/Memory/SystemAllocator.h> #endif /** This Class is responsible for connecting to the client */ #undef SendMessage namespace AssetProcessor { class ConnectionWorker : public QObject { Q_OBJECT public: explicit ConnectionWorker(qintptr socketDescriptor = -1, QObject* parent = 0); virtual ~ConnectionWorker(); QTcpSocket& GetSocket(); void Reset(); bool Terminate(); bool ReadMessage(QTcpSocket& socket, AssetProcessor::Message& message); bool ReadData(QTcpSocket& socket, char* buffer, qint64 size); bool WriteMessage(QTcpSocket& socket, const AssetProcessor::Message& message); bool WriteData(QTcpSocket& socket, const char* buffer, qint64 size); //! True if we initiated the connection, false if someone connected to us. bool InitiatedConnection() const; Q_SIGNALS: void ReceiveMessage(unsigned int type, unsigned int serial, QByteArray payload); void SocketIPAddress(QString ipAddress); void SocketPort(int port); void Identifier(QString identifier); void AssetPlatformsString(QString platform); void ConnectionDisconnected(); void ConnectionEstablished(QString ipAddress, quint16 port); void ErrorMessage(QString msg); // the token identifies the unique connection instance, since multiple may have the same address void IsAddressInAllowedList(QHostAddress hostAddress, void* token); public Q_SLOTS: void ConnectSocket(qintptr socketDescriptor); void ConnectToEngine(QString ipAddress, quint16 port); void EngineSocketHasData(); void EngineSocketStateChanged(QAbstractSocket::SocketState socketState); void SendMessage(unsigned int type, unsigned int serial, QByteArray payload); void DisconnectSockets(); void RequestTerminate(); bool NegotiateDirect(bool initiate); // the token will be the same token sent in the allowedlisting request. void AddressIsInAllowedList(void* token, bool result); private Q_SLOTS: void TerminateConnection(); private: QTcpSocket m_engineSocket; volatile bool m_terminate; volatile bool m_alreadySentTermination = false; bool m_initiatedConnection = false; bool m_engineSocketIsConnected = false; int m_waitDelay = 10000; //increased to 10000 as 5000 milliseconds was enough in the unloaded general case but when the computer is loaded we need more time to negotiate a connection or we only get connection failures }; } // namespace AssetProcessor
36
226
0.707843
[ "3d" ]
a853772b5f15758fa26d0750d203e4527d762a9d
2,915
h
C
dali-extension/internal/evas-plugin/evas-wrapper.h
dalihub/dali-extension
9bd20cbbf588828621acc1467c61c5168d7e1772
[ "Apache-2.0" ]
null
null
null
dali-extension/internal/evas-plugin/evas-wrapper.h
dalihub/dali-extension
9bd20cbbf588828621acc1467c61c5168d7e1772
[ "Apache-2.0" ]
null
null
null
dali-extension/internal/evas-plugin/evas-wrapper.h
dalihub/dali-extension
9bd20cbbf588828621acc1467c61c5168d7e1772
[ "Apache-2.0" ]
2
2020-08-29T01:26:29.000Z
2021-05-24T07:35:51.000Z
#ifndef DALI_EXTENSION_INTERNAL_EVAS_WRAPPER #define DALI_EXTENSION_INTERNAL_EVAS_WRAPPER /* * Copyright ( c ) 2019 Samsung Electronics 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. * */ // EXTERNAL INCLUDES #include <Ecore.h> #include <Ecore_Evas.h> #include <Ecore_Wl2.h> #include <tbm_surface.h> #include <dali/public-api/math/rect.h> // INTERNAL INCLUDES namespace Dali { typedef Rect<int> PositionSize; namespace Extension { namespace Internal { /** * EvasWrapper is a class which holds a parent evas object for the EvasPlugin. * This creates essential evas ebjects (RenderTarget, AccessibiltyTarget, FocusTarget) to connect evas to Dali properly, * and also provides evas rendering interfaces. */ class EvasWrapper { public: /** * @brief Constructor * @param[in] pluginParent An parent evas object of a evas plugin * @param[in] width The initial width of the Dali view port * @param[in] height The initial height of the Dali view port * @param[in] transparent Whether the Evas object is transparent or not */ EvasWrapper( Evas_Object* pluginParent, uint16_t width, uint16_t height, bool transparent ); /** * @brief Destructor */ ~EvasWrapper(); /** * @brief Gets current native window object * @return The ecore window object */ Ecore_Wl2_Window* GetNativeWindow() const; /** * @brief Gets the geometry information * @return The geometry information */ PositionSize GetGeometry() const; /** * @brief Gets the rendering target evas object * @return The rendering target object */ Evas_Object* GetRenderTarget() const; /** * @brief Gets the accessibility target evas object * @return The accessibility target object */ Evas_Object* GetAccessibilityTarget() const; /** * @brief Gets the focus target evas object * @return The focus target object */ Evas_Object* GetFocusTarget() const; /** * @brief Sets focus */ void SetFocus(); /** * @brief Bind a tbm surface */ void BindTBMSurface( tbm_surface_h surface ); /** * @brief Request rendering */ void RequestRender(); private: Ecore_Evas* mEcoreEvas; Evas_Object* mImageEvasObject; Evas_Object* mAccessibilityEvasObject; Evas_Object* mFocusEvasObject; }; } // namespace Internal } // namespace Extension } // namespace Dali #endif // DALI_EXTENSION_INTERNAL_EVAS_WRAPPER
23.134921
120
0.714923
[ "geometry", "object" ]
a85f726691f01fcd194c9233787b847f002b0698
11,393
h
C
base/inc/SimAPI.h
Imperas/force-riscv
c15bc18e4d70e6c2f50bad1e9176e13575de6081
[ "Apache-2.0" ]
null
null
null
base/inc/SimAPI.h
Imperas/force-riscv
c15bc18e4d70e6c2f50bad1e9176e13575de6081
[ "Apache-2.0" ]
null
null
null
base/inc/SimAPI.h
Imperas/force-riscv
c15bc18e4d70e6c2f50bad1e9176e13575de6081
[ "Apache-2.0" ]
null
null
null
// // Copyright (C) [2020] Futurewei Technologies, Inc. // // FORCE-RISCV is licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR // FIT FOR A PARTICULAR PURPOSE. // See the License for the specific language governing permissions and // limitations under the License. // #ifndef Force_SimAPI_H #define Force_SimAPI_H #pragma GCC visibility push(default) #include <vector> #include <map> #include <string> #include <fstream> #include <Defines.h> #include <VectorElementUpdates.h> struct SimException; namespace Force { /*! \class SimAPI \brief A C++ wrapper class for the Force/Handcar C API. */ typedef enum _INTERRUPT { SError=1, VSError=2, IR4=4, VIRQ=8, FIQ=16, VFIQ=32 } INTERRUPT; typedef enum _Memtype { Strong,Device,Normal } Memtype; typedef unsigned int CacheType; typedef unsigned int CacheAttrs; //TODO I recommend adding a struct for instruction updates that includes things like instruction number, pc, text, operands, and adding callback to make use of it. //!< MemUpdate - struct used to record memory updates from simulator... struct MemUpdate { MemUpdate(uint32 _CpuID, uint64 _virtual_address, unsigned int _mem_bank, uint64 _physical_address, unsigned int _size, const char *_bytes, const char *_access_type) : mem_bank(_mem_bank), virtual_address(_virtual_address), physical_address(_physical_address), size(_size), bytes(), access_type(), CpuID(_CpuID) { for (unsigned int i = 0; i < _size; i++) { bytes.push_back(_bytes[i]); } access_type.assign(_access_type); } uint32 mem_bank; uint64 virtual_address; uint64 physical_address; uint32 size; std::vector<unsigned char> bytes; std::string access_type; uint32 CpuID; }; //!< RegUpdate - struct used to record register updates from simulator... struct RegUpdate { RegUpdate(uint32 _CpuID, const char *_regname, uint64 _rval, uint64 _mask, const char *_access_type) : CpuID(_CpuID), regname(), rval(_rval), mask(_mask), access_type() { regname.assign(_regname); access_type.assign(_access_type); } uint32 CpuID; std::string regname; uint64 rval; uint64 mask; std::string access_type; }; //!< MmuEvent - struct used to record memory events from simulator... struct MmuEvent { MmuEvent(uint64 _va, uint64 _pa, Memtype _type, bool _has_stage_two, CacheType _outer_type, CacheAttrs _outer_attrs, CacheType _inner_type, CacheAttrs _inner_attrs) : va(_va), pa(_pa), type(_type), has_stage_two(_has_stage_two), outer_type(_outer_type), outer_attrs(_outer_attrs), inner_type(_inner_type), inner_attrs(_inner_attrs) { } uint64 va; uint64 pa; Memtype type; bool has_stage_two; CacheType outer_type; CacheAttrs outer_attrs; CacheType inner_type; CacheAttrs inner_attrs; }; struct ExceptionUpdate { ExceptionUpdate(uint32 exceptionID, uint32 exceptionAttributes, const char* comments) : mExceptionID(exceptionID), mExceptionAttributes(exceptionAttributes), mComments() { mComments.assign(comments); } uint32 mExceptionID; //!< Exception ID uint32 mExceptionAttributes; //!< Exception attributes std::string mComments; //!< exception description }; struct ThreadSummary { uint32 mInstructionCount; //!< Instruction count for a thread. uint32 mExitCode; //!< Exit code for a thread. std::string mSummary; //!< Summary information for the thread. ThreadSummary() : mInstructionCount(0), mExitCode(0), mSummary() { } //!< Constructor. }; class ApiSimConfig { public: ApiSimConfig() : mChipNum(1), mCoreNum(1), mThreadNum(1), mPhysicalAddressSize(48u), mVectorRegLen(128), mMaxVectorElemWidth(32), mpTraceFile(NULL), mUseTraceFile(false) { } //!< default constructor ApiSimConfig(uint32 chipNum, uint32 coreNum, uint32 threadNum, uint32 physicalAddressSize, uint32 vectorRegLen, uint32 maxVectorElemWidth, const char* pTraceFile, bool outputTraceFile) //!< Constructor. : mChipNum(chipNum), mCoreNum(coreNum), mThreadNum(threadNum), mPhysicalAddressSize(physicalAddressSize), mVectorRegLen(vectorRegLen), mMaxVectorElemWidth(maxVectorElemWidth), mpTraceFile(pTraceFile), mUseTraceFile(outputTraceFile) { } ~ApiSimConfig() {} //!< Destructor ASSIGNMENT_OPERATOR_ABSENT(ApiSimConfig); COPY_CONSTRUCTOR_ABSENT(ApiSimConfig); uint32 mChipNum; //!< Chip number. uint32 mCoreNum; //!< Core number per chip. uint32 mThreadNum; //!< Thread number per core. uint32 mPhysicalAddressSize; //!< Supported physical address size. uint32 mVectorRegLen; //!< Vector register length in bits. uint32 mMaxVectorElemWidth; //!< Maximum vector element width in bits. const char* mpTraceFile; //!< trace file. not output trace if it is NULL bool mUseTraceFile; }; /*! \class SimAPI \brief Access interface class for simulator C APIs. */ class SimAPI { public: SimAPI(); //!< Constructor. virtual ~SimAPI(); //!< Destructor. //!< Initialize simulator shared object using standard Force parameters... virtual void InitializeIss(const ApiSimConfig& rConfig, const std::string &rSimSoFile, const std::string& rApiTraceFile) = 0; //!< write out simulation trace file (if any), send 'terminate' directive to simulator... virtual void Terminate() = 0; //!< return simulator version info as String... virtual void GetSimulatorVersion(std::string &sim_version) = 0; //!< read simulator physical memory. Return 0 if no errors... virtual void ReadPhysicalMemory(uint32 mem_bank, uint64 address, uint32 size, unsigned char *pBytes) = 0; //!< write simulator physical memory. Return 0 if no errors... virtual void WritePhysicalMemory(uint32 mem_bank, uint64 address, uint32 size, const unsigned char *pBytes) = 0; //!< read register value... virtual void ReadRegister(uint32 CpuID, const char *regname, uint64 *rval, uint64 *rmask) = 0; //!< read the bytes corresponding to a physical register from a large logical register without forcing the simulator to used Force's naming convention. virtual void PartialReadLargeRegister(uint32 CpuID, const char* pRegname, uint8_t* pBytes, uint32 length, uint32 offset) = 0; //!< write the bytes corresponding to a physical register from a large logical register without forcing the simulator to used Force's naming convention. virtual void PartialWriteLargeRegister(uint32 CpuID, const char* pRegname, const uint8_t* pBytes, uint32 length, uint32 offset) = 0; //!< write simulator register. mask indicates which bits to write... virtual void WriteRegister(uint32 CpuID,const char *regname,uint64 rval,uint64 rmask) = 0; //!< request simulator to 'inject event(s)... virtual void InjectEvents(uint32 CpuID, uint32 interrupt_sets) = 0; //!< step instruction for specified cpu; returns after simulator step complete, with all updates. virtual void Step(uint32 cpuid,std::vector<RegUpdate> &rRegUpdates,std::vector<MemUpdate> &rMemUpdates, std::vector<MmuEvent> &rMmuEvents, std::vector<ExceptionUpdate> &rExceptions) = 0; virtual void WakeUp(uint32 cpuId) = 0; //!< Wake up from lower power state. virtual void TurnOn(uint32 cpuId) = 0; //!< Turn the Iss thread on. virtual void EnterSpeculativeMode(uint32 cpuId) = 0; //!< The CPU thread enters speculative mode. virtual void LeaveSpeculativeMode(uint32 cpuId) = 0; //!< The CPU thread leaves speculative mode. virtual void RecordExceptionUpdate(const SimException *pException) = 0; //!< Record exceptions. //!< form 'cpuID' from cluster,core,thread... uint32 CpuID(uint32 socket, uint32 cluster, uint32 core, uint32 thread); //!< 'record' methods used by extern C 'update' methods; not protected or private since the extern C functions need //!< to be able to access... void RecordRegisterUpdate(uint32 CpuID,const char *regname,uint64 rval,uint64 mask, const char *pAccessType); void RecordMemoryUpdate(uint32 CpuID, uint64 virtualAddress, unsigned int memBank, uint64 physicalAddress, unsigned int size, const char* pBytes, const char* pAccessType); void RecordMmuEvent(MmuEvent *event); void RecordVectorRegisterUpdate(uint32 CpuID, const char* pRegname, uint32 vecRegIndex, uint32 eltIndex, uint32 eltByteWidth, const uint8_t* pValue, uint32 byteLength, const char* pAccessType); void RecordTermination(uint32 CpuId, uint32 exitCode, const char* pMsg); //!< Return termination state of the CPU with the specified ID. protected: void SetVectorRegisterWidth(cuint64 vecRegWidthBits); //!< Set the vector register width in bits. //!< used by Step: bool GetRegisterUpdates(std::vector<RegUpdate> &rRegUpdates); bool GetMemoryUpdates(std::vector<MemUpdate> &rMemUpdates); bool GetMmuEvents(std::vector<MmuEvent> &rMmuEvents); bool GetExceptionUpdates(std::vector<ExceptionUpdate> &rExceptUpdates); bool GetVectorRegisterUpdates(std::vector<RegUpdate> &rRegUpdates); //!< for logging a 'trace session': void OpenApiTrace(const std::string& rApiTraceFile); void CloseApiTrace(); void ApiTraceCheckRcode(const std::string& function); void OpenOfs(const std::string& rTraceFileName, std::ofstream& rStreamToOpen); void CloseOfs(std::ofstream& rStreamToClose); void PrintRegisterUpdates(); void PrintMemoryUpdates(); void PrintMmuEvents(); void PrintExceptionUpdates(); void PrintInstructionStep(uint64 pc, uint32 CpuID, uint32 iCount, const std::string& rOpcode, const std::string& rDisassembly); uint32 UpdateCurrentInstructionCount(uint32 CpuId); //!< Set the current Instruction count for instruction stream printing. void PrintSummary() const; //!< Print summary information before terminating the ISS. protected: //!< at end of step these vectors have recorded any updates from running step on the simulator: std::vector<RegUpdate> mRegisterUpdates; std::vector<MemUpdate> mMemoryUpdates; std::vector<MmuEvent> mMmuEvents; std::vector<ExceptionUpdate> mExceptionUpdates; std::map<uint32, VectorElementUpdates> mVectorElementUpdates; std::map<uint32, ThreadSummary> mThreadSummaries; //!< Summary information for each CPU. //!< Use to get simulator API trace file, for debugging the API itself... mutable std::ofstream mOfsApiTrace; mutable std::ofstream mOfsSimTrace; //!< Implementation specific characteristics of vector registers uint32 mVecRegWidth; std::vector<std::string> mVecPhysRegNames; uint32 mNumPhysRegs; cuint32 mPhysRegSize; //!< Speculative mode output modification std::map<uint32, uint32> mInSpeculativeMode; const std::vector<std::string> mSpecModeStrings; //const std::string mSpecModeOn; //const std::string mSpecModeOff; }; } extern "C" { Force::SimAPI * instantiate_api(); } #pragma GCC visibility pop #endif
42.196296
237
0.724919
[ "object", "vector" ]
a86dcbe54b1f226bb2527ed8e9c9e3ce41a6be94
35,921
h
C
libnd4j/include/loops/special_kernels.h
rexwong/deeplearning4j
96a12b3b0ee7282f245c8a0af1c90b0ce2c2ed38
[ "Apache-2.0" ]
97
2016-02-15T07:08:45.000Z
2021-05-09T17:36:38.000Z
libnd4j/include/loops/special_kernels.h
rexwong/deeplearning4j
96a12b3b0ee7282f245c8a0af1c90b0ce2c2ed38
[ "Apache-2.0" ]
331
2016-03-07T21:26:26.000Z
2018-06-08T07:16:15.000Z
libnd4j/include/loops/special_kernels.h
rexwong/deeplearning4j
96a12b3b0ee7282f245c8a0af1c90b0ce2c2ed38
[ "Apache-2.0" ]
108
2016-01-19T15:11:03.000Z
2021-03-29T05:25:51.000Z
// // @author raver119@gmail.com // #ifndef LIBND4J_SPECIAL_KERNELS_H #define LIBND4J_SPECIAL_KERNELS_H #include <helpers/shape.h> #include <cuda.h> #include <cuda_runtime_api.h> #include <cuda_runtime.h> #include <cuda_device_runtime_api.h> #include <device_launch_parameters.h> /** * This is utility kernel, that updates given special buffer with proper values in device memory */ extern "C" __global__ void prepareShapeBuffer(int *dimension, int *maxDimension, Nd4jLong *specialPointer, int rows) { Nd4jLong tid = blockIdx.x * blockDim.x + threadIdx.x; if (tid > 0) return; dimension[0] = 0; maxDimension[0] = 1; specialPointer[0] = 2; specialPointer[1] = rows; specialPointer[2] = 1; specialPointer[3] = 1; specialPointer[4] = 1; specialPointer[5] = 0; specialPointer[6] = 1; specialPointer[7] = 99; //printf("special[0]: [%lld]\n", (long long) specialPointer[0]); //shape::printShapeInfoLinear("prepareShapeBuffer", specialPointer); } extern "C" __global__ void prepareDimensionalShapeBuffer(Nd4jLong *xShapeInfoBuffer, float *extraParams, Nd4jLong *zShapeInfo) { // extraParams[0] - number of dimensions // extraParams[1] - dimension int tid = blockIdx.x * blockDim.x + threadIdx.x; if (tid > 0) return; int targetDimension = (int) extraParams[1]; //printf("Target dimension: [%i]\n", targetDimension); int targetWidth = shape::shapeOf(xShapeInfoBuffer)[targetDimension]; //printf("Target rank: [%i]\n", targetWidth); } template <typename T> __device__ void fillIsMaxGeneric(T *dx, long length, long idx) { int tid = blockIdx.x * blockDim.x + threadIdx.x; for (long i = tid; i < length; i+= blockDim.x * gridDim.x) { dx[i] = (i == idx? 1.0 : 0.0); } } extern "C" __global__ void fillIsMaxFloat(float *dx, long length, long idx) { fillIsMaxGeneric<float>(dx, length, idx); } extern "C" __global__ void fillIsMaxDouble(double *dx, long length, long idx) { fillIsMaxGeneric<double>(dx, length, idx); } extern "C" __global__ void fillIsMaxHalf(float16 *dx, long length, long idx) { fillIsMaxGeneric<float16>(dx, length, idx); } template <typename T> __device__ void fillDimensionalIsMaxGeneric(T *dX, Nd4jLong *xShapeInfo, T *dZ, Nd4jLong *zShapeInfo, Nd4jLong *tadOnlyShapeInfo, int *dimension, int dimensionLength, Nd4jLong *tadOffsets) { __shared__ int tadLength; __shared__ int tadEWS; __shared__ int numTads; __shared__ Nd4jLong *tadShape; __shared__ Nd4jLong *tadStride; __shared__ int tadRank; __shared__ char tadOrder; if (threadIdx.x == 0) { tadLength = shape::tadLength(zShapeInfo, dimension, dimensionLength); tadEWS = shape::elementWiseStride(tadOnlyShapeInfo); numTads = shape::length(zShapeInfo) / tadLength; tadShape = shape::shapeOf(tadOnlyShapeInfo); tadStride = shape::stride(tadOnlyShapeInfo); tadRank = shape::rank(tadOnlyShapeInfo); tadOrder = shape::order(tadOnlyShapeInfo); } __syncthreads(); for (int r = blockIdx.x; r < numTads; r+= gridDim.x) { auto tadOffsetForBlock = tadOffsets[r]; int highestElement = (int) dX[r]; if (dimensionLength > 1 || tadEWS < 1) { Nd4jLong xCoord[MAX_RANK]; for (int e = threadIdx.x; e < tadLength; e += blockDim.x) { shape::ind2subC(tadRank,tadShape, e, xCoord); auto xOffset = shape::getOffset(tadOffsetForBlock, tadShape, tadStride, xCoord, tadRank); dZ[xOffset] = (e == highestElement? (T) 1.0f : (T) 0.0f); } } else { for (int e = threadIdx.x; e < tadLength; e += blockDim.x) { // so, we just set dZ[e] for each TAD. Sure, e should be replaced with auto idx = tadOffsetForBlock + (e * tadEWS); dZ[idx] = (e == highestElement? (T) 1.0f : (T) 0.0f); } } } } extern "C" __global__ void fillDimensionalIsMaxFloat(float *dx, Nd4jLong *xShapeInfo, float *dz, Nd4jLong *zShapeInfo, Nd4jLong *tadOnlyShapeInfo, int *dimension, int dimensionLength, Nd4jLong *tadOffsets) { fillDimensionalIsMaxGeneric<float>(dx, xShapeInfo, dz, zShapeInfo, tadOnlyShapeInfo, dimension, dimensionLength, tadOffsets); } extern "C" __global__ void fillDimensionalIsMaxDouble(double *dx, Nd4jLong *xShapeInfo, double *dz, Nd4jLong *zShapeInfo, Nd4jLong *tadOnlyShapeInfo, int *dimension, int dimensionLength, Nd4jLong *tadOffsets) { fillDimensionalIsMaxGeneric<double>(dx, xShapeInfo, dz, zShapeInfo, tadOnlyShapeInfo, dimension, dimensionLength, tadOffsets); } extern "C" __global__ void fillDimensionalIsMaxHalf(float16 *dx, Nd4jLong *xShapeInfo, float16 *dz, Nd4jLong *zShapeInfo, Nd4jLong *tadOnlyShapeInfo, int *dimension, int dimensionLength, Nd4jLong *tadOffsets) { fillDimensionalIsMaxGeneric<float16>(dx, xShapeInfo, dz, zShapeInfo, tadOnlyShapeInfo, dimension, dimensionLength, tadOffsets); } template <typename T> __device__ void concatKernelGeneric(int dimension, int numArrays, Nd4jPointer *data, Nd4jPointer *inputShapeInfos, T *result, Nd4jLong *resultShapeInfo, Nd4jPointer *tadPointers, Nd4jPointer *offsetPointers, Nd4jLong *zTadShape, Nd4jLong *zOffsets) { int tid = threadIdx.x + blockIdx.x * blockDim.x; int zRank = shape::rank(resultShapeInfo); T **dataT = (T **) data; Nd4jLong **shapeInfoPointers = (Nd4jLong **) inputShapeInfos; Nd4jLong **tadShapes = (Nd4jLong **) tadPointers; Nd4jLong **tadOffsets = (Nd4jLong **) offsetPointers; //if (threadIdx.x == 0 && blockIdx.x == 0) { // shape::printShapeInfoLinear("zTadShape", zTadShape); //} //__shared__ int tDim[1]; __shared__ int baseIdx; __shared__ int yLength; __shared__ char yOrder; __shared__ int yEWS; char zOrder = shape::order(resultShapeInfo); int zEWS = shape::elementWiseStride(resultShapeInfo); int tadEWS = shape::elementWiseStride(zTadShape); int zLength = shape::length(resultShapeInfo); __shared__ int arrOffset; __shared__ int numTads; if (shape::isVector(resultShapeInfo)) { //if (threadIdx.x == 0 && blockIdx.x == 0) // printf("Vector here\n"); if (zEWS >= 1) { for (int r = blockIdx.x; r < numArrays; r += gridDim.x) { if(shape::isVector(shapeInfoPointers[r]) || shape::order(shapeInfoPointers[r]) == shape::order(resultShapeInfo)) { yLength = shape::length(shapeInfoPointers[r]); yEWS = shape::elementWiseStride(shapeInfoPointers[r]); // FIXME: this is bad __shared__ int baseIdx; if (threadIdx.x == 0) { baseIdx = 0; for (int f = 0; f < r; f++) { baseIdx += shape::length(shapeInfoPointers[f]); } } __syncthreads(); for (int i = threadIdx.x; i < yLength && baseIdx + i < zLength; i += blockDim.x) { result[baseIdx + i * zEWS] = dataT[r][i * yEWS]; } __syncthreads(); } else { if (tid == 0) printf("Non-matched order for vector\n"); } } } else { if (tid == 0) printf("Vector Non-1 zEWS\n"); } return; } bool _vec = shape::isVector(resultShapeInfo); // TODO: to be pulled into separate kernel. matrix concatenation for (int r = 0; r < numArrays; r ++) { auto currentShape = shapeInfoPointers[r]; auto currentData = dataT[r]; auto currentTad = tadShapes[r]; auto currentOffsets = tadOffsets[r]; if (threadIdx.x == 0) { yLength = shape::length(currentTad); yOrder = shape::order(currentTad); yEWS = shape::elementWiseStride(currentTad); numTads = shape::length(currentShape) / yLength; arrOffset = 0; for (int f = 0; f < r; f++) { arrOffset += shape::length(tadShapes[f]); } //if (threadIdx.x == 0 && blockIdx.x == 0) { // shape::printShapeInfoLinear("currentTad", currentTad); //} } __syncthreads(); if (yLength == 1 && _vec) { //if (threadIdx.x == 0 && blockIdx.x == 0) // printf("Branch 0\n"); // edge case, each thread will handle it's own tad then for (int j = tid; j < numTads; j += blockDim.x * gridDim.x) { Nd4jLong inputOffset = currentOffsets[j]; Nd4jLong resultOffset = zOffsets[j]; T *dataTAD = currentData + inputOffset; T *resultTAD = result + resultOffset; Nd4jLong sub[MAX_RANK]; if (shape::order(zTadShape) == 'f') { shape::ind2sub(shape::rank(zTadShape),shape::shapeOf(zTadShape),arrOffset, sub); } else { shape::ind2subC(shape::rank(zTadShape),shape::shapeOf(zTadShape),arrOffset, sub); } Nd4jLong baseOffset = shape::getOffset(0,shape::shapeOf(zTadShape),shape::stride(zTadShape), sub, shape::rank(zTadShape)); resultTAD += baseOffset; auto yRank = shape::rank(currentTad); auto tadRank = shape::rank(zTadShape); shape::ind2subC(yRank, shape::shapeOf(currentTad), 0,sub); auto yOffset = shape::getOffset(0, shape::shapeOf(currentTad), shape::stride(currentTad), sub, yRank); resultOffset = shape::getOffset(0, shape::shapeOf(zTadShape), shape::stride(zTadShape), sub, tadRank); resultTAD[resultOffset] = dataTAD[yOffset]; } } else { //if (threadIdx.x == 0 && blockIdx.x == 0) // printf("Branch 1\n"); for (int j = blockIdx.x; j < numTads; j += gridDim.x) { auto inputOffset = currentOffsets[j]; auto resultOffset = zOffsets[j]; auto dataTAD = currentData + inputOffset; auto resultTAD = result + resultOffset; Nd4jLong sub[MAX_RANK]; shape::ind2subC(shape::rank(zTadShape),shape::shapeOf(zTadShape),arrOffset, sub); Nd4jLong baseOffset = shape::getOffset(0,shape::shapeOf(zTadShape),shape::stride(zTadShape), sub, shape::rank(zTadShape)); resultTAD += baseOffset; if (zOrder == yOrder && yEWS > 0 && tadEWS > 0) { //if (threadIdx.x == 0 && blockIdx.x == 0) // printf("Branch A\n"); for (int i = threadIdx.x; i < yLength; i += blockDim.x) { resultTAD[i * tadEWS] = dataTAD[i * yEWS]; } } else { if(tadEWS > 0 && shape::order(resultShapeInfo) == shape::order(currentTad)) { //if (threadIdx.x == 0 && blockIdx.x == 0) // printf("Branch B\n"); if (threadIdx.x == 0) { baseIdx = 0; for (int f = 0; f < r; f++) { baseIdx += shape::length(shapeInfoPointers[f]); } //printf("R: %i; baseIdx: %i;\n", baseIdx); } __syncthreads(); if (numTads == 1) { for(int k = threadIdx.x; k < yLength; k+= blockDim.x) { resultTAD[baseIdx + k * tadEWS] = dataTAD[k]; } } else { Nd4jLong yIdx[MAX_RANK]; auto yRank = shape::rank(currentTad); for (int i = threadIdx.x; i < yLength; i+= blockDim.x) { shape::ind2subC(yRank, shape::shapeOf(currentTad), i, yIdx); auto yOffset = shape::getOffset(0, shape::shapeOf(currentTad), shape::stride(currentTad), yIdx, yRank); resultTAD[baseIdx + i * tadEWS] = dataTAD[yOffset]; } } __syncthreads(); } else { //if (threadIdx.x == 0 && blockIdx.x == 0) // printf("Branch C; yLength: %i;\n", yLength); Nd4jLong zIdx[MAX_RANK]; Nd4jLong yIdx[MAX_RANK]; auto yRank = shape::rank(currentTad); auto tadRank = shape::rank(zTadShape); for (int i = threadIdx.x; i < yLength; i+= blockDim.x) { shape::ind2subC(yRank, shape::shapeOf(currentTad), i,yIdx); shape::ind2subC(tadRank, shape::shapeOf(zTadShape), i,zIdx); auto yOffset = shape::getOffset(0, shape::shapeOf(currentTad), shape::stride(currentTad), yIdx, yRank); auto resultOffset = shape::getOffset(0, shape::shapeOf(zTadShape), shape::stride(zTadShape), zIdx, tadRank); resultTAD[resultOffset] = dataTAD[yOffset]; } } } __syncthreads(); } } __syncthreads(); } } template <typename T> __device__ void concatKernelScalarGeneric(int dimension, int numArrays, Nd4jPointer *data, Nd4jPointer *inputShapeInfos, T *result, Nd4jLong *resultShapeInfo, Nd4jPointer *tadPointers, Nd4jPointer *offsetPointers) { Nd4jLong tid = blockIdx.x * blockDim.x + threadIdx.x; T **input = (T **) data; for (int i = tid; i < numArrays; i += blockDim.x * gridDim.x) { result[i] = input[i][0]; } } extern "C" __global__ void concatKernelScalarFloat(int dimension, int numArrays, Nd4jPointer *data, Nd4jPointer *inputShapeInfo, float *result, Nd4jLong *resultShapeInfo, Nd4jPointer *tadPointers, Nd4jPointer *offsetPointers) { concatKernelScalarGeneric<float>(dimension, numArrays, data, inputShapeInfo, result, resultShapeInfo, tadPointers, offsetPointers); } extern "C" __global__ void concatKernelScalarHalf(int dimension, int numArrays, Nd4jPointer *data, Nd4jPointer *inputShapeInfo, float16 *result, Nd4jLong *resultShapeInfo, Nd4jPointer *tadPointers, Nd4jPointer *offsetPointers) { concatKernelScalarGeneric<float16>(dimension, numArrays, data, inputShapeInfo, result, resultShapeInfo, tadPointers, offsetPointers); } extern "C" __global__ void concatKernelScalarDouble(int dimension, int numArrays, Nd4jPointer *data, Nd4jPointer *inputShapeInfo, double *result, Nd4jLong *resultShapeInfo, Nd4jPointer *tadPointers, Nd4jPointer *offsetPointers) { concatKernelScalarGeneric<double>(dimension, numArrays, data, inputShapeInfo, result, resultShapeInfo, tadPointers, offsetPointers); } template <typename T> __device__ void concatKernelHStackGeneric(int dimension, int numArrays, Nd4jPointer *data, Nd4jPointer *inputShapeInfos, T *result, Nd4jLong *resultShapeInfo, Nd4jPointer *tadPointers, Nd4jPointer *offsetPointers) { // we expect all data coming in as vectors, and result as 2D matrix // the only significant difference here is the fact that input lengths might be different auto inputShapes = (Nd4jLong**) inputShapeInfos; T **input = (T **) data; __shared__ int inputEWS; __shared__ int resultEWS; __shared__ int inputLength; if (threadIdx.x == 0) { resultEWS = shape::elementWiseStride(resultShapeInfo); } __syncthreads(); for (int r = blockIdx.x; r < numArrays; r+= gridDim.x) { __shared__ int baseIdx; if (threadIdx.x == 0) { baseIdx = 0; for (int f = 0; f < r; f++) { baseIdx += shape::length(inputShapes[f]); } } __syncthreads(); T *inputData = (T *) input[r]; if (threadIdx.x == 0) { inputEWS = shape::elementWiseStride(inputShapes[r]); inputLength = shape::length(inputShapes[r]); } __syncthreads(); for(int i = threadIdx.x; i < inputLength; i += blockDim.x) { result[baseIdx + i * resultEWS] = inputData[i * inputEWS]; } __syncthreads(); } } extern "C" __global__ void concatKernelHStackFloat(int dimension, int numArrays, Nd4jPointer *data, Nd4jPointer *inputShapeInfo, float *result, Nd4jLong *resultShapeInfo, Nd4jPointer *tadPointers, Nd4jPointer *offsetPointers) { concatKernelHStackGeneric<float>(dimension, numArrays, data, inputShapeInfo, result, resultShapeInfo, tadPointers, offsetPointers); } extern "C" __global__ void concatKernelHStackDouble(int dimension, int numArrays, Nd4jPointer *data, Nd4jPointer *inputShapeInfo, double *result, Nd4jLong *resultShapeInfo, Nd4jPointer *tadPointers, Nd4jPointer *offsetPointers) { concatKernelHStackGeneric<double>(dimension, numArrays, data, inputShapeInfo, result, resultShapeInfo, tadPointers, offsetPointers); } extern "C" __global__ void concatKernelHStackHalf(int dimension, int numArrays, Nd4jPointer *data, Nd4jPointer *inputShapeInfo, float16 *result, Nd4jLong *resultShapeInfo, Nd4jPointer *tadPointers, Nd4jPointer *offsetPointers) { concatKernelHStackGeneric<float16>(dimension, numArrays, data, inputShapeInfo, result, resultShapeInfo, tadPointers, offsetPointers); } template <typename T> __device__ void concatKernelVStackGeneric(int dimension, int numArrays, Nd4jPointer *data, Nd4jPointer *inputShapeInfos, T *result, Nd4jLong *resultShapeInfo, Nd4jPointer *tadPointers, Nd4jPointer *offsetPointers) { /* this is special case for concat: we group bunch of vectors into 2D matrix also: we expect each inputShapeInfo to have EWS, be a vector, and have equal size */ auto inputShapes = (Nd4jLong**) inputShapeInfos; T **input = (T **) data; __shared__ int inputEWS; __shared__ int resultEWS; __shared__ int inputLength; if (threadIdx.x == 0) { inputLength = shape::length(inputShapes[0]); inputEWS = shape::elementWiseStride(inputShapes[0]); resultEWS = shape::elementWiseStride(resultShapeInfo); } __syncthreads(); for (int r = blockIdx.x; r < numArrays; r+= gridDim.x) { int resultOffset = r * inputLength * resultEWS; T *inputData = (T *) input[r]; for(int i = threadIdx.x; i < inputLength; i += blockDim.x) { result[resultOffset + i * resultEWS] = inputData[i * inputEWS]; } } } extern "C" __global__ void concatKernelVStackFloat(int dimension, int numArrays, Nd4jPointer *data, Nd4jPointer *inputShapeInfo, float *result, Nd4jLong *resultShapeInfo, Nd4jPointer *tadPointers, Nd4jPointer *offsetPointers) { concatKernelVStackGeneric<float>(dimension, numArrays, data, inputShapeInfo, result, resultShapeInfo, tadPointers, offsetPointers); } extern "C" __global__ void concatKernelVStackDouble(int dimension, int numArrays, Nd4jPointer *data, Nd4jPointer *inputShapeInfo, double *result, Nd4jLong *resultShapeInfo, Nd4jPointer *tadPointers, Nd4jPointer *offsetPointers) { concatKernelVStackGeneric<double>(dimension, numArrays, data, inputShapeInfo, result, resultShapeInfo, tadPointers, offsetPointers); } extern "C" __global__ void concatKernelVStackHalf(int dimension, int numArrays, Nd4jPointer *data, Nd4jPointer *inputShapeInfo, float16 *result, Nd4jLong *resultShapeInfo, Nd4jPointer *tadPointers, Nd4jPointer *offsetPointers) { concatKernelVStackGeneric<float16>(dimension, numArrays, data, inputShapeInfo, result, resultShapeInfo, tadPointers, offsetPointers); } extern "C" __global__ void concatKernelDouble(int dimension, int numArrays, Nd4jPointer *data, Nd4jPointer *inputShapeInfo, double *result, Nd4jLong *resultShapeInfo, Nd4jPointer *tadPointers, Nd4jPointer *offsetPointers, Nd4jLong *zTadShape, Nd4jLong *zOffsets) { concatKernelGeneric<double>(dimension, numArrays, data, inputShapeInfo, result, resultShapeInfo, tadPointers, offsetPointers, zTadShape, zOffsets); } extern "C" __global__ void concatKernelFloat(int dimension, int numArrays, Nd4jPointer *data, Nd4jPointer *inputShapeInfo, float *result, Nd4jLong *resultShapeInfo, Nd4jPointer *tadPointers, Nd4jPointer *offsetPointers, Nd4jLong *zTadShape, Nd4jLong *zOffsets) { concatKernelGeneric<float>(dimension, numArrays, data, inputShapeInfo, result, resultShapeInfo, tadPointers, offsetPointers, zTadShape, zOffsets); } extern "C" __global__ void concatKernelHalf(int dimension, int numArrays, Nd4jPointer *data, Nd4jPointer *inputShapeInfo, float16 *result, Nd4jLong *resultShapeInfo, Nd4jPointer *tadPointers, Nd4jPointer *offsetPointers, Nd4jLong *zTadShape, Nd4jLong *zOffsets) { concatKernelGeneric<float16>(dimension, numArrays, data, inputShapeInfo, result, resultShapeInfo, tadPointers, offsetPointers, zTadShape, zOffsets); } template <typename T> __device__ void pullRowsKernelGeneric(T *x, Nd4jLong *xShapeInfo, T *z, Nd4jLong *zShapeInfo, Nd4jLong n, Nd4jLong *indexes, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets, Nd4jLong *zTadShapeInfo, Nd4jLong *zTadOffsets) { auto xEWS = shape::elementWiseStride(tadShapeInfo); auto zEWS = shape::elementWiseStride(zTadShapeInfo); auto tadLength = shape::length(tadShapeInfo); if (xEWS >= 1 && zEWS >= 1) { for (int idx = blockIdx.x; idx < n; idx += gridDim.x) { T *rX = x + tadOffsets[indexes[idx]]; T *rZ = z + zTadOffsets[idx]; for (int i = threadIdx.x; i < tadLength; i += blockDim.x) { rZ[i * zEWS] = rX[i * xEWS]; } } } else { Nd4jLong xCoord[MAX_RANK]; Nd4jLong zCoord[MAX_RANK]; for (int idx = blockIdx.x; idx < n; idx += gridDim.x) { T *rX = x + tadOffsets[indexes[idx]]; T *rZ = z + zTadOffsets[idx]; for (int i = threadIdx.x; i < tadLength; i += blockDim.x) { shape::ind2subC(shape::rank(tadShapeInfo),shape::shapeOf(tadShapeInfo), i, xCoord); shape::ind2subC(shape::rank(zTadShapeInfo),shape::shapeOf(zTadShapeInfo), i, zCoord); auto xOffset = shape::getOffset(0, shape::shapeOf(tadShapeInfo), shape::stride(tadShapeInfo), xCoord, shape::rank(tadShapeInfo)); auto zOffset = shape::getOffset(0, shape::shapeOf(zTadShapeInfo), shape::stride(zTadShapeInfo), zCoord, shape::rank(zTadShapeInfo)); rZ[zOffset] = rX[xOffset]; } } } } extern "C" __global__ void pullRowsKernelHalf( float16 *x, Nd4jLong *xShapeInfo, float16 *z, Nd4jLong *zShapeInfo, Nd4jLong n, Nd4jLong *indexes, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets, Nd4jLong *zTadShapeInfo, Nd4jLong *zTadOffsets) { pullRowsKernelGeneric<float16>(x, xShapeInfo, z, zShapeInfo, n, indexes, tadShapeInfo, tadOffsets, zTadShapeInfo, zTadOffsets); } extern "C" __global__ void pullRowsKernelFloat(float *x, Nd4jLong *xShapeInfo, float *z, Nd4jLong *zShapeInfo, Nd4jLong n, Nd4jLong *indexes, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets, Nd4jLong *zTadShapeInfo, Nd4jLong *zTadOffsets) { pullRowsKernelGeneric<float>(x, xShapeInfo, z, zShapeInfo, n, indexes, tadShapeInfo, tadOffsets, zTadShapeInfo, zTadOffsets); } extern "C" __global__ void pullRowsKernelDouble(double *x, Nd4jLong *xShapeInfo, double *z, Nd4jLong *zShapeInfo, Nd4jLong n, Nd4jLong *indexes, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets, Nd4jLong *zTadShapeInfo, Nd4jLong *zTadOffsets) { pullRowsKernelGeneric<double>(x, xShapeInfo, z, zShapeInfo, n, indexes, tadShapeInfo, tadOffsets, zTadShapeInfo, zTadOffsets); } template <typename T> __device__ void convertToHalfGeneric(T *dx, Nd4jLong n, half *dz) { int tid = threadIdx.x + blockIdx.x * gridDim.x; for (Nd4jLong i = tid; i < n; i += blockDim.x * gridDim.x ) { dz[i] = __float2half((float) dx[i]); } } extern "C" __global__ void kernelFloatsToHalfs(float *dx, Nd4jLong n, half *dz) { convertToHalfGeneric<float>(dx, n, dz); } extern "C" __global__ void kernelDoublesToHalfs(double *dx, Nd4jLong n, half *dz) { convertToHalfGeneric<double>(dx, n, dz); } template <typename T> __device__ void convertHalfsToGeneric(half *dx, Nd4jLong n, T *dz) { int tid = threadIdx.x + blockIdx.x * gridDim.x; for (Nd4jLong i = tid; i < n; i += blockDim.x * gridDim.x ) { dz[i] = (T) __half2float(dx[i]); } } extern "C" __global__ void kernelHalfsToDoubles(half *dx, Nd4jLong n, double *dz) { convertHalfsToGeneric<double>(dx, n, dz); } extern "C" __global__ void kernelHalfsToFloats(half *dx, Nd4jLong n, float *dz) { convertHalfsToGeneric<float>(dx, n, dz); } /** * This kernel accumulates X arrays, and stores result into Z * * @tparam T * @param x * @param z * @param n * @param length */ template<typename T> __device__ void accumulateKernelGeneric(T **x, T *z, int n, const Nd4jLong length) { __shared__ T *shmem; if (threadIdx.x == 0) { extern __shared__ unsigned char sharedmem[]; shmem = (T *) sharedmem; } __syncthreads(); for (int r = blockDim.x * blockIdx.x; r < length; r += blockDim.x * gridDim.x) { shmem[threadIdx.x] = 0.0f; Nd4jLong baseIdx = r; // aggregation step, we roll over all arrays for (int ar = 0; ar < n; ar++) { T *cdata = (T *) x[ar]; cdata += baseIdx; if (baseIdx + threadIdx.x < length) shmem[threadIdx.x] += cdata[threadIdx.x]; } T *wdata = z + baseIdx; // saving accumulated values if (baseIdx + threadIdx.x < length) { wdata[threadIdx.x] = shmem[threadIdx.x]; } } } extern "C" __global__ void accumulateKernelHalf(float16 **dx, float16 *dz, int n, Nd4jLong length) { accumulateKernelGeneric<float16>(dx, dz, n, length); } extern "C" __global__ void accumulateKernelFloat(float **dx, float *dz, int n, Nd4jLong length) { accumulateKernelGeneric<float>(dx, dz, n, length); } extern "C" __global__ void accumulateKernelDouble(double **dx, double *dz, int n, Nd4jLong length) { accumulateKernelGeneric<double>(dx, dz, n, length); } template <typename T> __device__ void averagingKernelGeneric(T **dx, T *dz, int n, Nd4jLong length, bool propagate) { __shared__ T *shmem; if (threadIdx.x == 0) { extern __shared__ unsigned char sharedmem[]; shmem = (T *) sharedmem; } __syncthreads(); // each block cycles over it's own part of arrays for (int r = blockDim.x * blockIdx.x; r < length; r += blockDim.x * gridDim.x) { shmem[threadIdx.x] = (T) 0.0f; Nd4jLong baseIdx = r; // aggregation step, we roll over all arrays for (int ar = 0; ar < n; ar++) { T *cdata = (T *) dx[ar]; cdata += baseIdx; if (baseIdx + threadIdx.x < length) shmem[threadIdx.x] += cdata[threadIdx.x]; } // average data in shared memory if (baseIdx + threadIdx.x < length) shmem[threadIdx.x] /= n; // div step & write out step if (dz != nullptr) { T *wdata = dz + baseIdx; if (baseIdx + threadIdx.x < length) { wdata[threadIdx.x] = shmem[threadIdx.x]; } } // propagate averaged data to all arrays if (propagate) for (int ar = 0; ar < n; ar++) { T *cdata = (T *) dx[ar]; cdata += baseIdx; if (baseIdx + threadIdx.x < length) cdata[threadIdx.x] = shmem[threadIdx.x]; } } } extern "C" __global__ void averagingKernelHalf(float16 **dx, float16 *dz, int n, Nd4jLong length, bool propagate) { averagingKernelGeneric<float16>(dx, dz, n, length, propagate); } extern "C" __global__ void averagingKernelFloat(float **dx, float *dz, int n, Nd4jLong length, bool propagate) { averagingKernelGeneric<float>(dx, dz, n, length, propagate); } extern "C" __global__ void averagingKernelDouble(double **dx, double *dz, int n, Nd4jLong length, bool propagate) { averagingKernelGeneric<double>(dx, dz, n, length, propagate); } template<typename T> __device__ void tearKernelGeneric(T *x, Nd4jLong *xShapeInfo, Nd4jPointer *targets, Nd4jLong *zShapeInfo, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) { __shared__ Nd4jLong tadLength; __shared__ int tadEWS; __shared__ int zEWS; __shared__ int tadRank; __shared__ Nd4jLong numTads; __shared__ int zRank; __shared__ Nd4jLong *tadShape; __shared__ Nd4jLong *tadStride; __shared__ Nd4jLong *zShape; __shared__ Nd4jLong *zStride; if (threadIdx.x == 0) { tadLength = shape::length(tadShapeInfo); tadEWS = shape::elementWiseStride(tadShapeInfo); zEWS = shape::elementWiseStride(zShapeInfo); tadRank = shape::rank(tadShapeInfo); numTads = shape::length(xShapeInfo) / tadLength; zRank = shape::rank(zShapeInfo); tadShape = shape::shapeOf(tadShapeInfo); tadStride = shape::stride(tadShapeInfo); zShape = shape::shapeOf(zShapeInfo); zStride = shape::stride(zShapeInfo); } __syncthreads(); for (Nd4jLong r = blockIdx.x; r < numTads; r += gridDim.x) { T *z = (T *) targets[r]; T *s = x + tadOffsets[r]; if (zEWS > 0 && tadEWS > 0) { for (Nd4jLong i = threadIdx.x; i < tadLength; i += blockDim.x) { z[i * zEWS] = s[i * tadEWS]; } } else { Nd4jLong xCoord[MAX_RANK]; Nd4jLong zCoord[MAX_RANK]; for (Nd4jLong j = 0; j < tadLength; j++) { shape::ind2sub(tadRank,tadShape, j, xCoord); shape::ind2sub(zRank, zShape, j, zCoord); auto xOffset = shape::getOffset(0, tadShape, tadStride, xCoord, tadRank); auto zOffset = shape::getOffset(0, zShape, zStride, zCoord, zRank); z[zOffset] = s[xOffset]; } } } } extern "C" __global__ void tearKernelDouble(double *x, Nd4jLong *xShapeInfo, Nd4jPointer *targets, Nd4jLong *zShapeInfo, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) { tearKernelGeneric<double>(x, xShapeInfo, targets, zShapeInfo, tadShapeInfo, tadOffsets); } extern "C" __global__ void tearKernelFloat(float *x, Nd4jLong *xShapeInfo, Nd4jPointer *targets, Nd4jLong *zShapeInfo, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) { tearKernelGeneric<float>(x, xShapeInfo, targets, zShapeInfo, tadShapeInfo, tadOffsets); } extern "C" __global__ void tearKernelHalf(float16 *x, Nd4jLong *xShapeInfo, Nd4jPointer *targets, Nd4jLong *zShapeInfo, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) { tearKernelGeneric<float16>(x, xShapeInfo, targets, zShapeInfo, tadShapeInfo, tadOffsets); } template<typename T> __device__ void shuffleKernelGeneric(T **dX, Nd4jLong **xShapeInfo, T **dZ, Nd4jLong **zShapeInfo, int N, int *shuffleMap, Nd4jLong **tadOnlyShapeInfo, Nd4jLong **tadOffsets) { // we assume that shuffle map for each X contains pair TAD Y __shared__ int tadLength; __shared__ int tadEWS; __shared__ int tadRank; __shared__ int numTads; __shared__ Nd4jLong *tadShape; __shared__ Nd4jLong *tadStride; __shared__ int yStride; for (int f = 0; f < N; f++) { T *x = (T *) dX[f]; T *z = (T *) dZ[f]; __syncthreads(); if (threadIdx.x == 0) { tadLength = shape::length(tadOnlyShapeInfo[f]); tadEWS = shape::elementWiseStride(tadOnlyShapeInfo[f]); tadRank = shape::rank(tadOnlyShapeInfo[f]); numTads = shape::length(xShapeInfo[f]) / tadLength; tadShape = shape::shapeOf(tadOnlyShapeInfo[f]); tadStride = shape::stride(tadOnlyShapeInfo[f]); } __syncthreads(); // we roll over the pairs of TADs, thus limit is numTads / 2 for (Nd4jLong r = blockIdx.x; r < numTads; r += blockDim.x) { if (shuffleMap[r] < 0) continue; Nd4jLong oldOffset = tadOffsets[f][r]; Nd4jLong newOffset = tadOffsets[f][shuffleMap[r]]; T *rX = x + oldOffset; T *rY = x + newOffset; T *zX = z + oldOffset; T *zY = z + newOffset; // so we're going to change TAD[oldOffset] with TAD[newOffset] if (tadEWS == 1) { for (Nd4jLong i = threadIdx.x; i < tadLength; i += blockDim.x) { T oldX = rX[i]; rX[i] = rY[i]; zY[i] = oldX; } } else { // well have to iterate using ind2sub Nd4jLong xCoord[MAX_RANK]; Nd4jLong yCoord[MAX_RANK]; for (Nd4jLong i = threadIdx.x; i < tadLength; i+= blockDim.x) { shape::ind2subC(tadRank,tadShape, i, xCoord); shape::ind2subC(tadRank,tadShape, i, yCoord); auto xOffset = shape::getOffset(oldOffset, tadShape, tadStride, xCoord, tadRank); auto yOffset = shape::getOffset(newOffset, tadShape, tadStride, yCoord, tadRank); T oldX = x[xOffset]; z[xOffset] = x[yOffset]; z[yOffset] = oldX; } } } } } extern "C" __global__ void shuffleKernelDouble(double **x, Nd4jLong **xShapeInfo, double **z, Nd4jLong **zShapeInfo, int N, int *shuffleMap, Nd4jLong **tadOnlyShapeInfo, Nd4jLong **tadOffsets) { shuffleKernelGeneric<double>(x, xShapeInfo, z, zShapeInfo, N, shuffleMap, tadOnlyShapeInfo, tadOffsets); } extern "C" __global__ void shuffleKernelFloat(float **x, Nd4jLong **xShapeInfo, float **z, Nd4jLong **zShapeInfo, int N, int *shuffleMap, Nd4jLong **tadOnlyShapeInfo, Nd4jLong **tadOffsets) { shuffleKernelGeneric<float>(x, xShapeInfo, z, zShapeInfo, N, shuffleMap, tadOnlyShapeInfo, tadOffsets); } extern "C" __global__ void shuffleKernelHalf(float16 **x, Nd4jLong **xShapeInfo, float16 **z, Nd4jLong **zShapeInfo, int N, int *shuffleMap, Nd4jLong **tadOnlyShapeInfo, Nd4jLong **tadOffsets) { shuffleKernelGeneric<float16>(x, xShapeInfo, z, zShapeInfo, N, shuffleMap, tadOnlyShapeInfo, tadOffsets); } #endif
36.57943
210
0.602739
[ "shape", "vector" ]
e1a02b65bb2f1f023c8a5d634849202bd6749a60
5,375
h
C
microdaq/etc/dsplib/DSPF_sp_fir_cplx.h
microdaq/Scilab
ce0baa6e6a1b56347c2fda5583fb1ccdb120afaf
[ "BSD-3-Clause" ]
6
2016-10-06T03:35:54.000Z
2021-08-03T07:06:19.000Z
microdaq/etc/dsplib/DSPF_sp_fir_cplx.h
microdaq/Scilab
ce0baa6e6a1b56347c2fda5583fb1ccdb120afaf
[ "BSD-3-Clause" ]
21
2015-10-06T17:21:07.000Z
2018-11-07T21:07:52.000Z
microdaq/etc/dsplib/DSPF_sp_fir_cplx.h
microdaq/Scilab
ce0baa6e6a1b56347c2fda5583fb1ccdb120afaf
[ "BSD-3-Clause" ]
3
2015-09-03T14:00:56.000Z
2019-09-09T08:49:29.000Z
/* ======================================================================= */ /* DSPF_sp_fir_cplx.h -- Complex FIR Filter */ /* Optimized C Implementation (w/ Intrinsics) */ /* */ /* Rev 0.0.1 */ /* */ /* Copyright (C) 2011 Texas Instruments Incorporated - http://www.ti.com/ */ /* */ /* */ /* 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 Texas Instruments Incorporated 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. */ /* */ /* ======================================================================= */ #ifndef DSPF_SP_FIR_CPLX_H_ #define DSPF_SP_FIR_CPLX_H_ /** @ingroup FILTCONV */ /* @{ */ /** @defgroup DSPF_sp_fir_cplx */ /** @ingroup DSPF_sp_fir_cplx */ /* @{ */ /** * This function implements the FIR filter for complex input data. * The filter has nr output samples and nh coefficients. Each array * consists of an even and odd term with even terms representing the * real part and the odd terms the imaginary part of the element. * The coefficients are expected in normal order. * * @param x[2*(nr+nh-1)] Pointer to complex input array. * The input data pointer x must point to * the (nh)th complex element. * @param h[2*nh] Pointer to complex coefficient array. * @param r[2*nr] Pointer to complex output array. * @param nh Number of complex coefficients in vector h. * @param nr Number of complex output samples to calculate. * * @par Algorithm: * DSPF_sp_fir_cplx_cn.c is the natural C equivalent of the optimized * linear assembly code without restrictions. Note that the linear * assembly code is optimized and restrictions may apply. * * @par Assumptions: * nr is a multiple of 2 and greater than or equal to 2. <BR> * nh is a multiple of 2 and greater than or equal to 5. <BR> * x, h and r are double-word aligned. <BR> * x points to 2*(nh-1)th input element. <BR> * * @par Implementation Notes: * @b Interruptibility: The code is interruptible. <BR> * @b Endian Support: The code supports both big and little endian modes. <BR> * */ void DSPF_sp_fir_cplx(const float * x, const float * h, float * restrict y, int nh, int nr); void DSPF_sp_fir_cplx_opt(const float * x, const float * h, float * restrict y, int nh, int ny); #endif /* DSPF_SP_FIR_CPLX_H_ */ /* ======================================================================= */ /* End of file: DSPF_sp_fir_cplx.h */ /* ----------------------------------------------------------------------- */ /* Copyright (c) 2011 Texas Instruments, Incorporated. */ /* All Rights Reserved. */ /* ======================================================================= */
55.412371
79
0.485767
[ "vector" ]
e1a4b6b3a6680f7535d9c66af01f8692127667f2
7,239
h
C
sample/exafmm-dev-13274dd4ac68/include/vtk.h
naoyam/tapas-reduce
90ebf7eb6a2db232fc5ae0b4bff6b7ac3cf9b7d3
[ "MIT" ]
null
null
null
sample/exafmm-dev-13274dd4ac68/include/vtk.h
naoyam/tapas-reduce
90ebf7eb6a2db232fc5ae0b4bff6b7ac3cf9b7d3
[ "MIT" ]
null
null
null
sample/exafmm-dev-13274dd4ac68/include/vtk.h
naoyam/tapas-reduce
90ebf7eb6a2db232fc5ae0b4bff6b7ac3cf9b7d3
[ "MIT" ]
null
null
null
#ifndef vtk_h #define vtk_h #define VTK_EXCLUDE_STRSTREAM_HEADERS #include <string> #include "types.h" #include <vector> #include <vtkAxis.h> #include <vtkChartXY.h> #include <vtkCommand.h> #include <vtkContextScene.h> #include <vtkContextView.h> #include <vtkDataSetMapper.h> #include <vtkFloatArray.h> #include <vtkHexahedron.h> #include <vtkInteractorStyleTrackballCamera.h> #include <vtkPlot.h> #include <vtkPolyDataMapper.h> #include <vtkProperty.h> #include <vtkRenderer.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkSliderRepresentation2D.h> #include <vtkSliderWidget.h> #include <vtkTable.h> #include <vtkUnstructuredGrid.h> #include <vtkVertexGlyphFilter.h> //! 2D plot VTK class class vtk2DPlot { private: int numColumns; public: vtkTable * table; public: vtk2DPlot() : numColumns(0) { table = vtkTable::New(); } void setNumRows(int numRows) { table->SetNumberOfRows(numRows); } void setName(std::string name) { vtkFloatArray * array = vtkFloatArray::New(); array->SetName(name.c_str()); table->AddColumn(array); } template<typename T> void setData(int begin, int end, T * data) { for (int i=begin; i<end; i++) { table->SetValue(i-begin,numColumns,data[i]); } numColumns++; } void plot() { //Set xlabel, ylabel, title vtkChartXY * chart = vtkChartXY::New(); chart->GetAxis(vtkAxis::LEFT)->SetTitle("y"); chart->GetAxis(vtkAxis::BOTTOM)->SetTitle("x"); chart->SetShowLegend(true); // Add multiple line plots, setting the colors etc for (int i=1; i<numColumns; i++) { vtkPlot * line = chart->AddPlot(vtkChart::LINE); line->SetInput(table, 0, i); } // Set up the view vtkContextView * view = vtkContextView::New(); view->GetScene()->AddItem(chart); view->GetInteractor()->Initialize(); view->GetInteractor()->Start(); } }; //! 3D plot VTK class class vtk3DPlot { private: std::vector<vtkPoints*> groups; vtkPoints * hexPoints; struct vtkSliderCallback : public vtkCommand { std::vector<vtkPoints*> groups; vtkPolyData * polydata; vtkVertexGlyphFilter * filter; vtkSliderCallback() {} static vtkSliderCallback * New() { return new vtkSliderCallback(); } virtual void Execute(vtkObject * caller, unsigned long, void*) { vtkSliderWidget * widget = reinterpret_cast<vtkSliderWidget*>(caller); int igroup = static_cast<int>(static_cast<vtkSliderRepresentation*>(widget->GetRepresentation())->GetValue()); polydata->SetPoints(groups[igroup]); filter->SetInputConnection(polydata->GetProducerPort()); filter->Update(); } }; public: void setBounds(const real_t r0, const vec3 x0) { hexPoints = vtkPoints::New(); hexPoints->SetNumberOfPoints(8); hexPoints->SetPoint(0, x0[0]-r0, x0[1]-r0, x0[2]-r0); hexPoints->SetPoint(1, x0[0]+r0, x0[1]-r0, x0[2]-r0); hexPoints->SetPoint(2, x0[0]+r0, x0[1]+r0, x0[2]-r0); hexPoints->SetPoint(3, x0[0]-r0, x0[1]+r0, x0[2]-r0); hexPoints->SetPoint(4, x0[0]-r0, x0[1]-r0, x0[2]+r0); hexPoints->SetPoint(5, x0[0]+r0, x0[1]-r0, x0[2]+r0); hexPoints->SetPoint(6, x0[0]+r0, x0[1]+r0, x0[2]+r0); hexPoints->SetPoint(7, x0[0]-r0, x0[1]+r0, x0[2]+r0); } void setPoints(B_iter B0, B_iter BN) { vtkPoints * group = vtkPoints::New(); group->SetNumberOfPoints(BN-B0); for (B_iter B=B0; B!=BN; B++) { group->SetPoint(B-B0, B->X[0], B->X[1], B->X[2]); } groups.push_back(group); } void setGroupOfPoints(Bodies & bodies) { B_iter B0 = bodies.begin(); B_iter BN = B0; int index = B0->IBODY; for (B_iter B=bodies.begin(); B!=bodies.end(); B++, BN++) { if (B->IBODY != index) { setPoints(B0, BN); B0 = BN = B; index = B->IBODY; } } setPoints(B0, BN); } void plot() { //Create a polygon object for points vtkPolyData * polydata = vtkPolyData::New(); polydata->SetPoints(groups[0]); //Create a filter object for points vtkVertexGlyphFilter * filter = vtkVertexGlyphFilter::New(); filter->SetInputConnection(polydata->GetProducerPort()); filter->Update(); //Create a mapper object for points vtkPolyDataMapper * pointMapper = vtkPolyDataMapper::New(); pointMapper->SetInputConnection(filter->GetOutputPort()); //Associate the mapper to an actor object for points vtkActor * pointActor = vtkActor::New(); pointActor->SetMapper(pointMapper); pointActor->GetProperty()->SetColor(1, 0, 0); //Create a hexahedron for cells vtkHexahedron * hex = vtkHexahedron::New(); hex->GetPointIds()->SetId(0, 0); hex->GetPointIds()->SetId(1, 1); hex->GetPointIds()->SetId(2, 2); hex->GetPointIds()->SetId(3, 3); hex->GetPointIds()->SetId(4, 4); hex->GetPointIds()->SetId(5, 5); hex->GetPointIds()->SetId(6, 6); hex->GetPointIds()->SetId(7, 7); //Create a grid for cells vtkUnstructuredGrid * grid = vtkUnstructuredGrid::New(); grid->Allocate(1, 1); grid->InsertNextCell(hex->GetCellType(), hex->GetPointIds()); grid->SetPoints(hexPoints); //Create a mapper object for cells vtkDataSetMapper * hexMapper = vtkDataSetMapper::New(); hexMapper->SetInput(grid); //Associate the mapper to an actor object for cells vtkActor * hexActor = vtkActor::New(); hexActor->SetMapper(hexMapper); hexActor->GetProperty()->SetOpacity(.1); //Add that actor to the renderer vtkRenderer * renderer = vtkRenderer::New(); renderer->AddActor(pointActor); renderer->AddActor(hexActor); renderer->SetBackground(0, 0, 0); //Create a render window vtkRenderWindow * window = vtkRenderWindow::New(); window->AddRenderer(renderer); window->SetSize(700, 700); //Create an interactor and associate it to the render window vtkRenderWindowInteractor * interactor = vtkRenderWindowInteractor::New(); interactor->SetRenderWindow(window); //Create a slider representation vtkSliderRepresentation2D * representation = vtkSliderRepresentation2D::New(); representation->SetMinimumValue(0); representation->SetMaximumValue(groups.size()-1); representation->GetPoint1Coordinate()->SetCoordinateSystemToDisplay(); representation->GetPoint1Coordinate()->SetValue(50, 50); representation->GetPoint2Coordinate()->SetCoordinateSystemToDisplay(); representation->GetPoint2Coordinate()->SetValue(650, 50); //Create a slider widget vtkSliderWidget * widget = vtkSliderWidget::New(); widget->SetInteractor(interactor); widget->SetRepresentation(representation); widget->SetAnimationModeToAnimate(); widget->EnabledOn(); //Create a slider callback vtkSliderCallback * callback = vtkSliderCallback::New(); callback->groups = groups; callback->polydata = polydata; callback->filter = filter; widget->AddObserver(vtkCommand::InteractionEvent, callback); //Define the interacting style vtkInteractorStyleTrackballCamera * style = vtkInteractorStyleTrackballCamera::New(); interactor->SetInteractorStyle(style); //Start to interact interactor->Initialize(); interactor->Start(); } }; #endif
31.06867
116
0.672469
[ "render", "object", "vector", "3d" ]
e1a687ad0761e46f6ec95659bb585b9014d4abf4
20,789
c
C
source/git-1.7.6.4/builtin/receive-pack.c
racker/omnibus
7f619cee98d551acaef3aed28c85f1c150d0ed8a
[ "Apache-2.0" ]
2
2015-07-30T09:28:19.000Z
2016-08-30T12:40:34.000Z
source/git-1.7.6.4/builtin/receive-pack.c
racker/omnibus
7f619cee98d551acaef3aed28c85f1c150d0ed8a
[ "Apache-2.0" ]
1
2015-07-31T18:11:11.000Z
2015-07-31T18:11:11.000Z
source/git-1.7.6.4/builtin/receive-pack.c
racker/omnibus
7f619cee98d551acaef3aed28c85f1c150d0ed8a
[ "Apache-2.0" ]
null
null
null
#include "builtin.h" #include "pack.h" #include "refs.h" #include "pkt-line.h" #include "sideband.h" #include "run-command.h" #include "exec_cmd.h" #include "commit.h" #include "object.h" #include "remote.h" #include "transport.h" #include "string-list.h" #include "sha1-array.h" static const char receive_pack_usage[] = "git receive-pack <git-dir>"; enum deny_action { DENY_UNCONFIGURED, DENY_IGNORE, DENY_WARN, DENY_REFUSE }; static int deny_deletes; static int deny_non_fast_forwards; static enum deny_action deny_current_branch = DENY_UNCONFIGURED; static enum deny_action deny_delete_current = DENY_UNCONFIGURED; static int receive_fsck_objects; static int receive_unpack_limit = -1; static int transfer_unpack_limit = -1; static int unpack_limit = 100; static int report_status; static int use_sideband; static int prefer_ofs_delta = 1; static int auto_update_server_info; static int auto_gc = 1; static const char *head_name; static int sent_capabilities; static enum deny_action parse_deny_action(const char *var, const char *value) { if (value) { if (!strcasecmp(value, "ignore")) return DENY_IGNORE; if (!strcasecmp(value, "warn")) return DENY_WARN; if (!strcasecmp(value, "refuse")) return DENY_REFUSE; } if (git_config_bool(var, value)) return DENY_REFUSE; return DENY_IGNORE; } static int receive_pack_config(const char *var, const char *value, void *cb) { if (strcmp(var, "receive.denydeletes") == 0) { deny_deletes = git_config_bool(var, value); return 0; } if (strcmp(var, "receive.denynonfastforwards") == 0) { deny_non_fast_forwards = git_config_bool(var, value); return 0; } if (strcmp(var, "receive.unpacklimit") == 0) { receive_unpack_limit = git_config_int(var, value); return 0; } if (strcmp(var, "transfer.unpacklimit") == 0) { transfer_unpack_limit = git_config_int(var, value); return 0; } if (strcmp(var, "receive.fsckobjects") == 0) { receive_fsck_objects = git_config_bool(var, value); return 0; } if (!strcmp(var, "receive.denycurrentbranch")) { deny_current_branch = parse_deny_action(var, value); return 0; } if (strcmp(var, "receive.denydeletecurrent") == 0) { deny_delete_current = parse_deny_action(var, value); return 0; } if (strcmp(var, "repack.usedeltabaseoffset") == 0) { prefer_ofs_delta = git_config_bool(var, value); return 0; } if (strcmp(var, "receive.updateserverinfo") == 0) { auto_update_server_info = git_config_bool(var, value); return 0; } if (strcmp(var, "receive.autogc") == 0) { auto_gc = git_config_bool(var, value); return 0; } return git_default_config(var, value, cb); } static int show_ref(const char *path, const unsigned char *sha1, int flag, void *cb_data) { if (sent_capabilities) packet_write(1, "%s %s\n", sha1_to_hex(sha1), path); else packet_write(1, "%s %s%c%s%s\n", sha1_to_hex(sha1), path, 0, " report-status delete-refs side-band-64k", prefer_ofs_delta ? " ofs-delta" : ""); sent_capabilities = 1; return 0; } static void write_head_info(void) { for_each_ref(show_ref, NULL); if (!sent_capabilities) show_ref("capabilities^{}", null_sha1, 0, NULL); } struct command { struct command *next; const char *error_string; unsigned int skip_update; unsigned char old_sha1[20]; unsigned char new_sha1[20]; char ref_name[FLEX_ARRAY]; /* more */ }; static const char pre_receive_hook[] = "hooks/pre-receive"; static const char post_receive_hook[] = "hooks/post-receive"; static void rp_error(const char *err, ...) __attribute__((format (printf, 1, 2))); static void rp_warning(const char *err, ...) __attribute__((format (printf, 1, 2))); static void report_message(const char *prefix, const char *err, va_list params) { int sz = strlen(prefix); char msg[4096]; strncpy(msg, prefix, sz); sz += vsnprintf(msg + sz, sizeof(msg) - sz, err, params); if (sz > (sizeof(msg) - 1)) sz = sizeof(msg) - 1; msg[sz++] = '\n'; if (use_sideband) send_sideband(1, 2, msg, sz, use_sideband); else xwrite(2, msg, sz); } static void rp_warning(const char *err, ...) { va_list params; va_start(params, err); report_message("warning: ", err, params); va_end(params); } static void rp_error(const char *err, ...) { va_list params; va_start(params, err); report_message("error: ", err, params); va_end(params); } static int copy_to_sideband(int in, int out, void *arg) { char data[128]; while (1) { ssize_t sz = xread(in, data, sizeof(data)); if (sz <= 0) break; send_sideband(1, 2, data, sz, use_sideband); } close(in); return 0; } static int run_receive_hook(struct command *commands, const char *hook_name) { static char buf[sizeof(commands->old_sha1) * 2 + PATH_MAX + 4]; struct command *cmd; struct child_process proc; struct async muxer; const char *argv[2]; int have_input = 0, code; for (cmd = commands; !have_input && cmd; cmd = cmd->next) { if (!cmd->error_string) have_input = 1; } if (!have_input || access(hook_name, X_OK) < 0) return 0; argv[0] = hook_name; argv[1] = NULL; memset(&proc, 0, sizeof(proc)); proc.argv = argv; proc.in = -1; proc.stdout_to_stderr = 1; if (use_sideband) { memset(&muxer, 0, sizeof(muxer)); muxer.proc = copy_to_sideband; muxer.in = -1; code = start_async(&muxer); if (code) return code; proc.err = muxer.in; } code = start_command(&proc); if (code) { if (use_sideband) finish_async(&muxer); return code; } for (cmd = commands; cmd; cmd = cmd->next) { if (!cmd->error_string) { size_t n = snprintf(buf, sizeof(buf), "%s %s %s\n", sha1_to_hex(cmd->old_sha1), sha1_to_hex(cmd->new_sha1), cmd->ref_name); if (write_in_full(proc.in, buf, n) != n) break; } } close(proc.in); if (use_sideband) finish_async(&muxer); return finish_command(&proc); } static int run_update_hook(struct command *cmd) { static const char update_hook[] = "hooks/update"; const char *argv[5]; struct child_process proc; int code; if (access(update_hook, X_OK) < 0) return 0; argv[0] = update_hook; argv[1] = cmd->ref_name; argv[2] = sha1_to_hex(cmd->old_sha1); argv[3] = sha1_to_hex(cmd->new_sha1); argv[4] = NULL; memset(&proc, 0, sizeof(proc)); proc.no_stdin = 1; proc.stdout_to_stderr = 1; proc.err = use_sideband ? -1 : 0; proc.argv = argv; code = start_command(&proc); if (code) return code; if (use_sideband) copy_to_sideband(proc.err, -1, NULL); return finish_command(&proc); } static int is_ref_checked_out(const char *ref) { if (is_bare_repository()) return 0; if (!head_name) return 0; return !strcmp(head_name, ref); } static char *refuse_unconfigured_deny_msg[] = { "By default, updating the current branch in a non-bare repository", "is denied, because it will make the index and work tree inconsistent", "with what you pushed, and will require 'git reset --hard' to match", "the work tree to HEAD.", "", "You can set 'receive.denyCurrentBranch' configuration variable to", "'ignore' or 'warn' in the remote repository to allow pushing into", "its current branch; however, this is not recommended unless you", "arranged to update its work tree to match what you pushed in some", "other way.", "", "To squelch this message and still keep the default behaviour, set", "'receive.denyCurrentBranch' configuration variable to 'refuse'." }; static void refuse_unconfigured_deny(void) { int i; for (i = 0; i < ARRAY_SIZE(refuse_unconfigured_deny_msg); i++) rp_error("%s", refuse_unconfigured_deny_msg[i]); } static char *refuse_unconfigured_deny_delete_current_msg[] = { "By default, deleting the current branch is denied, because the next", "'git clone' won't result in any file checked out, causing confusion.", "", "You can set 'receive.denyDeleteCurrent' configuration variable to", "'warn' or 'ignore' in the remote repository to allow deleting the", "current branch, with or without a warning message.", "", "To squelch this message, you can set it to 'refuse'." }; static void refuse_unconfigured_deny_delete_current(void) { int i; for (i = 0; i < ARRAY_SIZE(refuse_unconfigured_deny_delete_current_msg); i++) rp_error("%s", refuse_unconfigured_deny_delete_current_msg[i]); } static const char *update(struct command *cmd) { const char *name = cmd->ref_name; unsigned char *old_sha1 = cmd->old_sha1; unsigned char *new_sha1 = cmd->new_sha1; struct ref_lock *lock; /* only refs/... are allowed */ if (prefixcmp(name, "refs/") || check_ref_format(name + 5)) { rp_error("refusing to create funny ref '%s' remotely", name); return "funny refname"; } if (is_ref_checked_out(name)) { switch (deny_current_branch) { case DENY_IGNORE: break; case DENY_WARN: rp_warning("updating the current branch"); break; case DENY_REFUSE: case DENY_UNCONFIGURED: rp_error("refusing to update checked out branch: %s", name); if (deny_current_branch == DENY_UNCONFIGURED) refuse_unconfigured_deny(); return "branch is currently checked out"; } } if (!is_null_sha1(new_sha1) && !has_sha1_file(new_sha1)) { error("unpack should have generated %s, " "but I can't find it!", sha1_to_hex(new_sha1)); return "bad pack"; } if (!is_null_sha1(old_sha1) && is_null_sha1(new_sha1)) { if (deny_deletes && !prefixcmp(name, "refs/heads/")) { rp_error("denying ref deletion for %s", name); return "deletion prohibited"; } if (!strcmp(name, head_name)) { switch (deny_delete_current) { case DENY_IGNORE: break; case DENY_WARN: rp_warning("deleting the current branch"); break; case DENY_REFUSE: case DENY_UNCONFIGURED: if (deny_delete_current == DENY_UNCONFIGURED) refuse_unconfigured_deny_delete_current(); rp_error("refusing to delete the current branch: %s", name); return "deletion of the current branch prohibited"; } } } if (deny_non_fast_forwards && !is_null_sha1(new_sha1) && !is_null_sha1(old_sha1) && !prefixcmp(name, "refs/heads/")) { struct object *old_object, *new_object; struct commit *old_commit, *new_commit; struct commit_list *bases, *ent; old_object = parse_object(old_sha1); new_object = parse_object(new_sha1); if (!old_object || !new_object || old_object->type != OBJ_COMMIT || new_object->type != OBJ_COMMIT) { error("bad sha1 objects for %s", name); return "bad ref"; } old_commit = (struct commit *)old_object; new_commit = (struct commit *)new_object; bases = get_merge_bases(old_commit, new_commit, 1); for (ent = bases; ent; ent = ent->next) if (!hashcmp(old_sha1, ent->item->object.sha1)) break; free_commit_list(bases); if (!ent) { rp_error("denying non-fast-forward %s" " (you should pull first)", name); return "non-fast-forward"; } } if (run_update_hook(cmd)) { rp_error("hook declined to update %s", name); return "hook declined"; } if (is_null_sha1(new_sha1)) { if (!parse_object(old_sha1)) { rp_warning("Allowing deletion of corrupt ref."); old_sha1 = NULL; } if (delete_ref(name, old_sha1, 0)) { rp_error("failed to delete %s", name); return "failed to delete"; } return NULL; /* good */ } else { lock = lock_any_ref_for_update(name, old_sha1, 0); if (!lock) { rp_error("failed to lock %s", name); return "failed to lock"; } if (write_ref_sha1(lock, new_sha1, "push")) { return "failed to write"; /* error() already called */ } return NULL; /* good */ } } static char update_post_hook[] = "hooks/post-update"; static void run_update_post_hook(struct command *commands) { struct command *cmd; int argc; const char **argv; struct child_process proc; for (argc = 0, cmd = commands; cmd; cmd = cmd->next) { if (cmd->error_string) continue; argc++; } if (!argc || access(update_post_hook, X_OK) < 0) return; argv = xmalloc(sizeof(*argv) * (2 + argc)); argv[0] = update_post_hook; for (argc = 1, cmd = commands; cmd; cmd = cmd->next) { char *p; if (cmd->error_string) continue; p = xmalloc(strlen(cmd->ref_name) + 1); strcpy(p, cmd->ref_name); argv[argc] = p; argc++; } argv[argc] = NULL; memset(&proc, 0, sizeof(proc)); proc.no_stdin = 1; proc.stdout_to_stderr = 1; proc.err = use_sideband ? -1 : 0; proc.argv = argv; if (!start_command(&proc)) { if (use_sideband) copy_to_sideband(proc.err, -1, NULL); finish_command(&proc); } } static void check_aliased_update(struct command *cmd, struct string_list *list) { struct string_list_item *item; struct command *dst_cmd; unsigned char sha1[20]; char cmd_oldh[41], cmd_newh[41], dst_oldh[41], dst_newh[41]; int flag; const char *dst_name = resolve_ref(cmd->ref_name, sha1, 0, &flag); if (!(flag & REF_ISSYMREF)) return; if ((item = string_list_lookup(list, dst_name)) == NULL) return; cmd->skip_update = 1; dst_cmd = (struct command *) item->util; if (!hashcmp(cmd->old_sha1, dst_cmd->old_sha1) && !hashcmp(cmd->new_sha1, dst_cmd->new_sha1)) return; dst_cmd->skip_update = 1; strcpy(cmd_oldh, find_unique_abbrev(cmd->old_sha1, DEFAULT_ABBREV)); strcpy(cmd_newh, find_unique_abbrev(cmd->new_sha1, DEFAULT_ABBREV)); strcpy(dst_oldh, find_unique_abbrev(dst_cmd->old_sha1, DEFAULT_ABBREV)); strcpy(dst_newh, find_unique_abbrev(dst_cmd->new_sha1, DEFAULT_ABBREV)); rp_error("refusing inconsistent update between symref '%s' (%s..%s) and" " its target '%s' (%s..%s)", cmd->ref_name, cmd_oldh, cmd_newh, dst_cmd->ref_name, dst_oldh, dst_newh); cmd->error_string = dst_cmd->error_string = "inconsistent aliased update"; } static void check_aliased_updates(struct command *commands) { struct command *cmd; struct string_list ref_list = STRING_LIST_INIT_NODUP; for (cmd = commands; cmd; cmd = cmd->next) { struct string_list_item *item = string_list_append(&ref_list, cmd->ref_name); item->util = (void *)cmd; } sort_string_list(&ref_list); for (cmd = commands; cmd; cmd = cmd->next) check_aliased_update(cmd, &ref_list); string_list_clear(&ref_list, 0); } static void execute_commands(struct command *commands, const char *unpacker_error) { struct command *cmd; unsigned char sha1[20]; if (unpacker_error) { for (cmd = commands; cmd; cmd = cmd->next) cmd->error_string = "n/a (unpacker error)"; return; } if (run_receive_hook(commands, pre_receive_hook)) { for (cmd = commands; cmd; cmd = cmd->next) cmd->error_string = "pre-receive hook declined"; return; } check_aliased_updates(commands); head_name = resolve_ref("HEAD", sha1, 0, NULL); for (cmd = commands; cmd; cmd = cmd->next) if (!cmd->skip_update) cmd->error_string = update(cmd); } static struct command *read_head_info(void) { struct command *commands = NULL; struct command **p = &commands; for (;;) { static char line[1000]; unsigned char old_sha1[20], new_sha1[20]; struct command *cmd; char *refname; int len, reflen; len = packet_read_line(0, line, sizeof(line)); if (!len) break; if (line[len-1] == '\n') line[--len] = 0; if (len < 83 || line[40] != ' ' || line[81] != ' ' || get_sha1_hex(line, old_sha1) || get_sha1_hex(line + 41, new_sha1)) die("protocol error: expected old/new/ref, got '%s'", line); refname = line + 82; reflen = strlen(refname); if (reflen + 82 < len) { if (strstr(refname + reflen + 1, "report-status")) report_status = 1; if (strstr(refname + reflen + 1, "side-band-64k")) use_sideband = LARGE_PACKET_MAX; } cmd = xcalloc(1, sizeof(struct command) + len - 80); hashcpy(cmd->old_sha1, old_sha1); hashcpy(cmd->new_sha1, new_sha1); memcpy(cmd->ref_name, line + 82, len - 81); *p = cmd; p = &cmd->next; } return commands; } static const char *parse_pack_header(struct pack_header *hdr) { switch (read_pack_header(0, hdr)) { case PH_ERROR_EOF: return "eof before pack header was fully read"; case PH_ERROR_PACK_SIGNATURE: return "protocol error (pack signature mismatch detected)"; case PH_ERROR_PROTOCOL: return "protocol error (pack version unsupported)"; default: return "unknown error in parse_pack_header"; case 0: return NULL; } } static const char *pack_lockfile; static const char *unpack(void) { struct pack_header hdr; const char *hdr_err; char hdr_arg[38]; hdr_err = parse_pack_header(&hdr); if (hdr_err) return hdr_err; snprintf(hdr_arg, sizeof(hdr_arg), "--pack_header=%"PRIu32",%"PRIu32, ntohl(hdr.hdr_version), ntohl(hdr.hdr_entries)); if (ntohl(hdr.hdr_entries) < unpack_limit) { int code, i = 0; const char *unpacker[4]; unpacker[i++] = "unpack-objects"; if (receive_fsck_objects) unpacker[i++] = "--strict"; unpacker[i++] = hdr_arg; unpacker[i++] = NULL; code = run_command_v_opt(unpacker, RUN_GIT_CMD); if (!code) return NULL; return "unpack-objects abnormal exit"; } else { const char *keeper[7]; int s, status, i = 0; char keep_arg[256]; struct child_process ip; s = sprintf(keep_arg, "--keep=receive-pack %"PRIuMAX" on ", (uintmax_t) getpid()); if (gethostname(keep_arg + s, sizeof(keep_arg) - s)) strcpy(keep_arg + s, "localhost"); keeper[i++] = "index-pack"; keeper[i++] = "--stdin"; if (receive_fsck_objects) keeper[i++] = "--strict"; keeper[i++] = "--fix-thin"; keeper[i++] = hdr_arg; keeper[i++] = keep_arg; keeper[i++] = NULL; memset(&ip, 0, sizeof(ip)); ip.argv = keeper; ip.out = -1; ip.git_cmd = 1; status = start_command(&ip); if (status) { return "index-pack fork failed"; } pack_lockfile = index_pack_lockfile(ip.out); close(ip.out); status = finish_command(&ip); if (!status) { reprepare_packed_git(); return NULL; } return "index-pack abnormal exit"; } } static void report(struct command *commands, const char *unpack_status) { struct command *cmd; struct strbuf buf = STRBUF_INIT; packet_buf_write(&buf, "unpack %s\n", unpack_status ? unpack_status : "ok"); for (cmd = commands; cmd; cmd = cmd->next) { if (!cmd->error_string) packet_buf_write(&buf, "ok %s\n", cmd->ref_name); else packet_buf_write(&buf, "ng %s %s\n", cmd->ref_name, cmd->error_string); } packet_buf_flush(&buf); if (use_sideband) send_sideband(1, 1, buf.buf, buf.len, use_sideband); else safe_write(1, buf.buf, buf.len); strbuf_release(&buf); } static int delete_only(struct command *commands) { struct command *cmd; for (cmd = commands; cmd; cmd = cmd->next) { if (!is_null_sha1(cmd->new_sha1)) return 0; } return 1; } static void add_one_alternate_sha1(const unsigned char sha1[20], void *unused) { add_extra_ref(".have", sha1, 0); } static void collect_one_alternate_ref(const struct ref *ref, void *data) { struct sha1_array *sa = data; sha1_array_append(sa, ref->old_sha1); } static void add_alternate_refs(void) { struct sha1_array sa = SHA1_ARRAY_INIT; for_each_alternate_ref(collect_one_alternate_ref, &sa); sha1_array_for_each_unique(&sa, add_one_alternate_sha1, NULL); sha1_array_clear(&sa); } int cmd_receive_pack(int argc, const char **argv, const char *prefix) { int advertise_refs = 0; int stateless_rpc = 0; int i; char *dir = NULL; struct command *commands; packet_trace_identity("receive-pack"); argv++; for (i = 1; i < argc; i++) { const char *arg = *argv++; if (*arg == '-') { if (!strcmp(arg, "--advertise-refs")) { advertise_refs = 1; continue; } if (!strcmp(arg, "--stateless-rpc")) { stateless_rpc = 1; continue; } usage(receive_pack_usage); } if (dir) usage(receive_pack_usage); dir = xstrdup(arg); } if (!dir) usage(receive_pack_usage); setup_path(); if (!enter_repo(dir, 0)) die("'%s' does not appear to be a git repository", dir); if (is_repository_shallow()) die("attempt to push into a shallow repository"); git_config(receive_pack_config, NULL); if (0 <= transfer_unpack_limit) unpack_limit = transfer_unpack_limit; else if (0 <= receive_unpack_limit) unpack_limit = receive_unpack_limit; if (advertise_refs || !stateless_rpc) { add_alternate_refs(); write_head_info(); clear_extra_refs(); /* EOF */ packet_flush(1); } if (advertise_refs) return 0; if ((commands = read_head_info()) != NULL) { const char *unpack_status = NULL; if (!delete_only(commands)) unpack_status = unpack(); execute_commands(commands, unpack_status); if (pack_lockfile) unlink_or_warn(pack_lockfile); if (report_status) report(commands, unpack_status); run_receive_hook(commands, post_receive_hook); run_update_post_hook(commands); if (auto_gc) { const char *argv_gc_auto[] = { "gc", "--auto", "--quiet", NULL, }; run_command_v_opt(argv_gc_auto, RUN_GIT_CMD); } if (auto_update_server_info) update_server_info(0); } if (use_sideband) packet_flush(1); return 0; }
24.807876
89
0.683775
[ "object" ]
e1aa0775c5d41cdad5ad00592d11eaf71b5cc551
2,552
h
C
SerialHMD/headers/SerialHMDDriver.h
Seneral/SerialHMD
d01fa216fd9290c4d2ee5e664bbd54edf8a9e747
[ "MIT" ]
4
2019-03-14T11:51:57.000Z
2020-09-21T15:47:12.000Z
SerialHMD/headers/SerialHMDDriver.h
Seneral/SerialHMD
d01fa216fd9290c4d2ee5e664bbd54edf8a9e747
[ "MIT" ]
null
null
null
SerialHMD/headers/SerialHMDDriver.h
Seneral/SerialHMD
d01fa216fd9290c4d2ee5e664bbd54edf8a9e747
[ "MIT" ]
1
2021-04-12T21:14:09.000Z
2021-04-12T21:14:09.000Z
#ifndef HMDDRIVER_H #define HMDDRIVER_H #if defined(_WIN32) #include <Windows.h> #endif #include <SerialHMDShared.h> #include <SerialHMDComm.h> #include <math.h> #include <string.h> // ******************************************************* // Tracked SerialHMD Device // ******************************************************* class SerialHMDDriver : public vr::ITrackedDeviceServerDriver, public vr::IVRDisplayComponent, public ICommStreamReceiver { public: bool m_HMDConnected = false; SerialHMDDriver(); virtual ~SerialHMDDriver(); // HMD Lifetime virtual EVRInitError Activate(vr::TrackedDeviceIndex_t unObjectId); virtual void Deactivate(); virtual void EnterStandby(); virtual void PowerOff(); // Pose and Tracking void SetRestPose(bool pos, bool rot); void StreamPacket(std::vector<unsigned char> packet); void UpdatePose(); DriverPose_t CreatePose(_HMDData poseData); virtual DriverPose_t GetPose(); // Other void *GetComponent(const char *pchComponentNameAndVersion); virtual void DebugRequest(const char *pchRequest, char *pchResponseBuffer, uint32_t unResponseBufferSize); std::string GetSerialNumber() const { return m_sSerialNumber; } std::string GetModelNumber() const { return m_sModelNumber; } // Display Methods virtual void GetWindowBounds(int32_t *pnX, int32_t *pnY, uint32_t *pnWidth, uint32_t *pnHeight); virtual bool IsDisplayOnDesktop(); virtual bool IsDisplayRealDisplay(); virtual void GetRecommendedRenderTargetSize(uint32_t *pnWidth, uint32_t *pnHeight); virtual void GetEyeOutputViewport(EVREye eEye, uint32_t *pnX, uint32_t *pnY, uint32_t *pnWidth, uint32_t *pnHeight); virtual void GetProjectionRaw(EVREye eEye, float *pfLeft, float *pfRight, float *pfTop, float *pfBottom); virtual DistortionCoordinates_t ComputeDistortion(EVREye eEye, float fU, float fV); private: vr::TrackedDeviceIndex_t m_unObjectId; vr::PropertyContainerHandle_t m_ulPropertyContainer; _HMDData m_HMDPose; _HMDData m_restPose; std::string m_sSerialNumber; std::string m_sModelNumber; float m_flSecondsFromVsyncToPhotons; float m_flDisplayFrequency; float m_flIPD; bool m_bDebugMode; int32_t m_nWindowX; int32_t m_nWindowY; int32_t m_nWindowWidth; int32_t m_nWindowHeight; int32_t m_nRenderWidth; int32_t m_nRenderHeight; float m_fDistortionK1; float m_fDistortionK2; float m_fZoomWidth; float m_fZoomHeight; bool m_bRealDisplay; bool m_bOnDesktop; }; #endif // HMDDRIVER_H
27.148936
122
0.724922
[ "vector" ]
e1aad4c5208d0c6f86a620807df2b68985245eb9
919
h
C
include/Bibim/MPQStream.h
halak/bibim
ad01efa8aac4f074f64bf033ac0f1ed382060334
[ "curl" ]
3
2016-08-28T06:48:11.000Z
2019-12-04T13:04:34.000Z
include/Bibim/MPQStream.h
Darkttd/Bibim
9dec24529ef89536f7686abc1245ea5fc7fa9474
[ "curl" ]
8
2016-04-24T13:07:28.000Z
2016-06-01T10:04:42.000Z
include/Bibim/MPQStream.h
Darkttd/Bibim
9dec24529ef89536f7686abc1245ea5fc7fa9474
[ "curl" ]
1
2016-08-28T06:47:43.000Z
2016-08-28T06:47:43.000Z
#pragma once #ifndef __BIBIM_MPQSTREAM_H__ #define __BIBIM_MPQSTREAM_H__ #include <Bibim/FWD.h> #if (defined(BIBIM_PLATFORM_WINDOWS)) #include <Bibim/Stream.h> #include <Bibim/String.h> #include <vector> namespace Bibim { class MPQStream : public Stream { public: MPQStream(MPQ* mpq, const String& path); virtual ~MPQStream(); void Close(); virtual int Read(void* buffer, int size); virtual int Write(const void* buffer, int size); virtual void Flush(); virtual int Seek(int offset, SeekOrigin origin); virtual int GetPosition(); virtual int GetLength(); virtual bool CanRead() const; virtual bool CanWrite() const; virtual bool CanSeek() const; private: void* handle; }; } #endif #endif
22.975
61
0.569097
[ "vector" ]
e1b0b53132c8cced1d5ac7dfb0710ae049d5326e
6,954
h
C
tests/Address_tests_suite.h
wenshen/bitcon-ansi-c
24ea993b2f068c7e63772d82793f2a84d545a807
[ "MIT" ]
null
null
null
tests/Address_tests_suite.h
wenshen/bitcon-ansi-c
24ea993b2f068c7e63772d82793f2a84d545a807
[ "MIT" ]
null
null
null
tests/Address_tests_suite.h
wenshen/bitcon-ansi-c
24ea993b2f068c7e63772d82793f2a84d545a807
[ "MIT" ]
null
null
null
/******----------------------- File Name: Address_tests_suite.h ---------------------------****** Created by: Fadwa Alseiari on 05/12/2012. Tested by: Full Name on DD/MM/YYYY. Modified by: Full Name on 21/11/2012. Version: 1.0 Copyright (c) 2012, MIBitcoinc Brief Description: ------------------ This file includes all the test cases related to Address. It inlcudes functions: test_case_createNewAddressFromString, test_case_createNewAddressFromRIPEMD160Hash, test_case_getAddress, test_case_destroyAddress ******--------------------------------------------------------------------******/ #include <stdio.h> #include <stdlib.h> #include <time.h> #include "CUnit/CUnit.h" #include "CUnit/Basic.h" /*#include "CUnit/TBTest.h"*/ /*#include "CUnit/Automated.h" #include "CUnit/Console.h"*/ #include "../src/Object/Network/Address.h" #include "../src/Constants.h" /* Test Suite setup and cleanup functions: */ int init_address_suite(void) { return 0; } int clean_address_suite(void) { return 0; } /* void onErrorReceived(Error a, char * format, ...); void onErrorReceived(Error a, char * format, ...) { va_list argptr; va_start(argptr, format); vfprintf(stderr, format, argptr); va_end(argptr); printf("\n"); }*/ /************* Test case functions ****************/ void test_case_createNewAddressFromString(void) { /* creating Address of Bitcoin pubkey hash type(starting with 1) */ ByteArray * addressString = createNewByteArrayFromString("1D5A1q5d192j5gYuWiP3CSE5fcaaZxe6E9", TRUE, onErrorReceived); /*int index; printf("\nFirst Address String consists of the following %i bytes:\n",addressString->length); for(index=0;index<addressString->length;index++) printf("%u ",addressString->sharedData->data[index]);*/ Address * address = createNewAddressFromString(addressString, FALSE, onErrorReceived); CU_ASSERT_PTR_NOT_NULL(address); CU_ASSERT_PTR_NULL(getVersionChecksumBytes(address)->cachedString); /*printf("\nFirst Address consists of the following %i bytes:\n",address->base.base.length); for(index=0;index<address->base.base.length;index++) printf("%u ",address->base.base.sharedData->data[index]);*/ Address * address2 = createNewAddressFromString(addressString, FALSE, onErrorReceived); decrementReferenceCount(addressString); /*printf("\nSecond Address consists of the following %i bytes:\n",address2->base.base.length); for(index=0;index<address2->base.base.length;index++) printf("%u ",address2->base.base.sharedData->data[index]);*/ uint8_t netVersionByte = getNetVersionByteForVersionChecksumBytes(getVersionChecksumBytes(address)); /*printf("\n\nVersion Byte is the first byte %u",netVersionByte);*/ CU_ASSERT_EQUAL(netVersionByte, ADDRESS_PUBKEYHASH); ByteArray * addressStringFromVersionChecksum = getStringForVersionChecksumBytes(getVersionChecksumBytes(address)); CU_ASSERT_STRING_EQUAL((char *) getByteArrayData(addressStringFromVersionChecksum), "1D5A1q5d192j5gYuWiP3CSE5fcaaZxe6E9"); decrementReferenceCount(addressStringFromVersionChecksum); decrementReferenceCount(address); /*printf("\n\nAddress as a String is: %s",(char *) getByteArrayData(addressStringFromVersionChecksum)); if (strcmp((char *) getByteArrayData(addressStringFromVersionChecksum), "1D5A1q5d192j5gYuWiP3CSE5fcaaZxe6E9")) { printf( "\nNOT CACHED STRING WRONG %s != 1D5A1q5d192j5gYuWiP3CSE5fcaaZxe6E9\n", (char *) getByteArrayData(addressStringFromVersionChecksum)); return 1; } decrementReferenceCount(addressStringFromVersionChecksum); decrementReferenceCount(address);*/ /* creating Address of Bitcoin testnet pubkey hash type(starting with 111) */ ByteArray* addressString3 = createNewByteArrayFromString("mzCk9JXXF9we7MB2Gdt59tcfj6Lr2rSzpu", TRUE, onErrorReceived); /*printf("\nThird Address String consists of the following %i bytes:\n",addressString3->length); for(index=0;index<addressString3->length;index++) printf("%u ",addressString3->sharedData->data[index]);*/ Address* address3 = createNewAddressFromString(addressString3, FALSE, onErrorReceived); decrementReferenceCount(addressString3); /*printf("\nThird Address consists of the following %i bytes:\n",address3->base.base.length); for(index=0;index<address3->base.base.length;index++) printf("%u ",address3->base.base.sharedData->data[index]);*/ netVersionByte = getNetVersionByteForVersionChecksumBytes(getVersionChecksumBytes(address3)); CU_ASSERT_EQUAL(netVersionByte, ADDRESS_TESTNETPUBKEYHASH); } void test_case_createNewAddressFromRIPEMD160Hash(void) { uint8_t * hash = malloc(20); int x; for (x = 0; x < 20; x++) hash[x] = rand(); Address *address = createNewAddressFromRIPEMD160Hash(hash, ADDRESS_PUBKEYHASH, false ,onErrorReceived); free(hash); uint8_t netVersionByte = getNetVersionByteForVersionChecksumBytes(getVersionChecksumBytes(address)); CU_ASSERT_EQUAL(netVersionByte, ADDRESS_PUBKEYHASH ); decrementReferenceCount(address); hash = malloc(20); for (x = 0; x < 20; x++) hash[x] = rand(); address = createNewAddressFromRIPEMD160Hash(hash, ADDRESS_TESTNETPUBKEYHASH, false, onErrorReceived); free(hash); netVersionByte = getNetVersionByteForVersionChecksumBytes(getVersionChecksumBytes(address)); CU_ASSERT_EQUAL(netVersionByte, ADDRESS_TESTNETPUBKEYHASH); decrementReferenceCount(address); /* Test createNewAddressFromRIPEMD160Hash for pre-known address*/ hash = malloc(20); for (x = 0; x < 20; x++) hash[x] = x; address = createNewAddressFromRIPEMD160Hash(hash, ADDRESS_PUBKEYHASH, false, onErrorReceived); free(hash); ByteArray *addressString = getStringForVersionChecksumBytes(getVersionChecksumBytes(address)); CU_ASSERT_STRING_EQUAL(((char *)getByteArrayData(addressString)), "112D2adLM3UKy4Z4giRbReR6gjWuvHUqB"); decrementReferenceCount(addressString); decrementReferenceCount(address); } void test_case_getAddress(void) { ByteArray * addressString = createNewByteArrayFromString("1D5A1q5d192j5gYuWiP3CSE5fcaaZxe6E9", TRUE, onErrorReceived); Address * address = createNewAddressFromString(addressString, FALSE, onErrorReceived); CU_ASSERT_EQUAL(getAddress(address), address); } void test_case_destroyAddress(void) { ByteArray * addressString = createNewByteArrayFromString("1D5A1q5d192j5gYuWiP3CSE5fcaaZxe6E9", TRUE, onErrorReceived); Address * address = createNewAddressFromString(addressString, FALSE, onErrorReceived); CU_ASSERT_PTR_NOT_NULL(address->base.base.sharedData->data); destroyAddress(address); CU_ASSERT_PTR_NULL(address->base.base.sharedData->data); } /* Grouping all test cases into an array that will be registered later with a single test suite. */ CU_TestInfo address_test_array[] = { { "test_case_createNewAddressFromString", test_case_createNewAddressFromString }, { "test_case_createNewAddressFromRIPEMD160Hash", test_case_createNewAddressFromRIPEMD160Hash }, {"test_case_getAddress", test_case_getAddress}, {"test_case_destroyAddress", test_case_destroyAddress}, CU_TEST_INFO_NULL, };
37.187166
123
0.764596
[ "object" ]
e1cfc9a2279a05f9c0682283e8e257699be8a768
6,013
h
C
flashlight/common/Serialization-inl.h
wesbz/flashlight
e692a941e902f9e207a1a4ee226c0ad0f8dbdc5e
[ "BSD-3-Clause" ]
null
null
null
flashlight/common/Serialization-inl.h
wesbz/flashlight
e692a941e902f9e207a1a4ee226c0ad0f8dbdc5e
[ "BSD-3-Clause" ]
null
null
null
flashlight/common/Serialization-inl.h
wesbz/flashlight
e692a941e902f9e207a1a4ee226c0ad0f8dbdc5e
[ "BSD-3-Clause" ]
null
null
null
/** * Copyright (c) Facebook, Inc. and its affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ /** * @file common/Serialization-inl.h * * Implementation details, only to be included from Serialization.h */ #include <stdexcept> #include <utility> #include "flashlight/flashlight/common/CppBackports.h" #pragma once namespace fl { namespace detail { template <typename T> using IsOutputArchive = std::is_base_of<cereal::detail::OutputArchiveBase, T>; template <typename T> using IsInputArchive = std::is_base_of<cereal::detail::InputArchiveBase, T>; /** * Wrapper indicating that an expression should be serialized only if the * version is in a certain range. */ template <typename T> struct Versioned { T&& ref; uint32_t minVersion; uint32_t maxVersion; }; template <typename S, typename T> struct SerializeAs { using T0 = cpp::decay_t<T>; T&& ref; std::function<S(const T0&)> saveConverter; std::function<T0(S)> loadConverter; }; // 0 arguments (no-op). template <typename Archive> void applyArchive(Archive& ar, const uint32_t version) {} // 1 argument, general case. template <typename Archive, typename Arg> void applyArchive(Archive& ar, const uint32_t version, Arg&& arg) { ar(std::forward<Arg>(arg)); } // 1 argument, version-restricted. template <typename Archive, typename T> void applyArchive(Archive& ar, const uint32_t version, Versioned<T> varg) { if (version >= varg.minVersion && version <= varg.maxVersion) { applyArchive(ar, version, std::forward<T>(varg.ref)); } } // 1 argument, with conversion, saving. template < typename Archive, typename S, typename T, cpp::enable_if_t<IsOutputArchive<Archive>::value, int> = 0> void applyArchive(Archive& ar, const uint32_t version, SerializeAs<S, T> arg) { if (arg.saveConverter) { applyArchive(ar, version, arg.saveConverter(arg.ref)); } else { applyArchive(ar, version, static_cast<const S&>(arg.ref)); } } // 1 argument, with conversion, loading. template < typename Archive, typename S, typename T, cpp::enable_if_t<IsInputArchive<Archive>::value, int> = 0> void applyArchive(Archive& ar, const uint32_t version, SerializeAs<S, T> arg) { using T0 = cpp::remove_reference_t<T>; S s; applyArchive(ar, version, s); if (arg.loadConverter) { arg.ref = arg.loadConverter(std::move(s)); } else { arg.ref = static_cast<T0>(std::move(s)); } } // 2+ arguments (recurse). template <typename Archive, typename Arg, typename... Args> void applyArchive( Archive& ar, const uint32_t version, Arg&& arg, Args&&... args) { applyArchive(ar, version, std::forward<Arg>(arg)); applyArchive(ar, version, std::forward<Args>(args)...); } } // namespace detail template <typename T> detail::Versioned<T> versioned(T&& t, uint32_t minVersion, uint32_t maxVersion) { return detail::Versioned<T>{std::forward<T>(t), minVersion, maxVersion}; } template <typename S, typename T> detail::SerializeAs<S, T> serializeAs(T&& t) { return detail::SerializeAs<S, T>{std::forward<T>(t), nullptr, nullptr}; } template <typename S, typename T, typename SaveConvFn, typename LoadConvFn> detail::SerializeAs<S, T> serializeAs(T&& t, SaveConvFn saveConverter, LoadConvFn loadConverter) { return detail::SerializeAs<S, T>{ std::forward<T>(t), std::move(saveConverter), std::move(loadConverter)}; } template <typename... Args> void save(const std::string& filepath, const Args&... args) { std::ofstream ofs(filepath, std::ios::binary); save(ofs, args...); } template <typename... Args> void save(std::ostream& ostr, const Args&... args) { cereal::BinaryOutputArchive ar(ostr); ar(args...); } template <typename... Args> void load(const std::string& filepath, Args&... args) { std::ifstream ifs(filepath, std::ios::binary); load(ifs, args...); } template <typename... Args> void load(std::istream& istr, Args&... args) { cereal::BinaryInputArchive ar(istr); ar(args...); } namespace detail { /** * This workaround lets us use explicit versioning for af::array; if we'd used * `save(Archive& ar, const af::array& arr, const uint32_t version)` directly, * cereal would complain there are 2 ways to serialize integer types, * because af::array has an implicit ctor from a single `long long`. * * The trick we use here is that C++'s implicit conversion sequence permits * at most one user-defined conversion. Therefore `af::array` may be implicitly * converted to `AfArraySerializeProxy`, but `int` may not. * * For more info, see https://github.com/USCiLab/cereal/issues/132 * and https://en.cppreference.com/w/cpp/language/implicit_conversion */ template <typename T> struct CerealSave { /* implicit */ CerealSave(const T& x) : val(x) {} const T& val; }; } // namespace detail } // namespace fl namespace cereal { // no versioning; simple and unlikely to ever change template <class Archive> void save(Archive& ar, const fl::detail::CerealSave<af::dim4>& dims_) { const auto& dims = dims_.val; int64_t x; for (int i = 0; i < 4; ++i) { x = dims[i]; ar(x); } } template <class Archive> void load(Archive& ar, af::dim4& dims) { int64_t x; for (int i = 0; i < 4; ++i) { ar(x); dims[i] = x; } } template <class Archive> void save( Archive& ar, const fl::detail::CerealSave<af::array>& arr_, const uint32_t /* version */) { const auto& arr = arr_.val; if (arr.issparse()) { throw cereal::Exception( "Serialzation of sparse af::array is not supported yet!"); } std::vector<uint8_t> vec(arr.bytes()); arr.host(vec.data()); ar(arr.dims(), arr.type(), vec); } template <class Archive> void load(Archive& ar, af::array& arr, const uint32_t /* version */) { af::dim4 dims; af::dtype ty; std::vector<uint8_t> vec; ar(dims, ty, vec); arr = af::array(dims, ty); arr.write(vec.data(), vec.size()); } } // namespace cereal
26.964126
79
0.684683
[ "vector" ]
e1d663a4930c08e625c6c15281ec57bf6bff6ee1
4,534
h
C
Libs/Widgets/ctkCoordinatesWidget.h
chenqifeng/CTK
5f2997fb8ab157edee4ba360e9f0f1f0e0abd513
[ "Apache-2.0" ]
1
2015-05-13T02:09:20.000Z
2015-05-13T02:09:20.000Z
Libs/Widgets/ctkCoordinatesWidget.h
medInria/CTK
00694c9f8a0da6ee28fb079902e6a8c3ec428058
[ "Apache-2.0" ]
null
null
null
Libs/Widgets/ctkCoordinatesWidget.h
medInria/CTK
00694c9f8a0da6ee28fb079902e6a8c3ec428058
[ "Apache-2.0" ]
1
2018-10-21T12:09:24.000Z
2018-10-21T12:09:24.000Z
/*========================================================================= Library: CTK Copyright (c) Kitware 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.txt 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 __ctkCoordinatesWidget_h #define __ctkCoordinatesWidget_h // Qt includes #include <QWidget> // CTK includes #include "ctkWidgetsExport.h" /// \ingroup Widgets /// /// ctkCoordinatesWidget is a simple container of dimension coordinates. /// For each coordinate a double spinbox is associated, everytime a value is /// modified, the signal valueChanged is fired. /// TODO: use pimpl class CTK_WIDGETS_EXPORT ctkCoordinatesWidget : public QWidget { Q_OBJECT Q_PROPERTY(int dimension READ dimension WRITE setDimension) /// This property controls whether the coordinates must be normalized. /// If true, the norm of the coordinates is enforced to be 1. /// False by default. Q_PROPERTY(bool normalized READ isNormalized WRITE setNormalized) Q_PROPERTY(int decimals READ decimals WRITE setDecimals) Q_PROPERTY(double singleStep READ singleStep WRITE setSingleStep STORED false) Q_PROPERTY(double minimum READ minimum WRITE setMinimum) Q_PROPERTY(double maximum READ maximum WRITE setMaximum) Q_PROPERTY(QString coordinates READ coordinatesAsString WRITE setCoordinatesAsString) public: explicit ctkCoordinatesWidget(QWidget* parent = 0); virtual ~ctkCoordinatesWidget(); /// Set/Get the dimension of the point /// The default dimension is 3 void setDimension(int dim); int dimension() const; /// Set/Get the number of decimals of each coordinate QDoubleSpinBoxes /// The default number of decimals is 3. void setDecimals(int decimals); int decimals() const; /// Set/Get the single step of each coordinate QDoubleSpinBoxes /// The default single step is 1. void setSingleStep(double step); double singleStep() const; /// Set/Get the minimum value of each coordinate QDoubleSpinBoxes /// The default minimum is -100000. void setMinimum(double minimum); double minimum() const; /// Set/Get the maximum value of each coordinate QDoubleSpinBoxes /// The default maximum is 100000. void setMaximum(double minimum); double maximum() const; /// Change the normalized property. If \a normalize is true, it normalizes /// the current coordinates, the range of possible values is reset to [-1, 1]. /// \sa isNormalized void setNormalized(bool normalize); bool isNormalized()const; /// Return the norm of the coordinates. double norm()const; /// Return the squared norm of the coordinates. double squaredNorm()const; /// Set/Get the coordinates. Use commas to separate elements, spaces are /// allowed: e.g. "0,0.0, 0." void setCoordinatesAsString(QString pos); QString coordinatesAsString()const; /// Set/Get the coordinates /// The default values are 0. void setCoordinates(double* pos); double const * coordinates()const; /// Convenient function that sets up to 4 elements of the coordinates. void setCoordinates(double x, double y = 0., double z = 0., double w = 0.); public Q_SLOTS: void normalize(); Q_SIGNALS: /// /// valueChanged is fired anytime a coordinate is modified, the returned /// value is the point coordinates /// TODO: Don't fire the signal if the new values are not changed void coordinatesChanged(double* pos); protected Q_SLOTS: void updateCoordinate(double); void updateCoordinates(); protected: void addSpinBox(); /// Normalize coordinates vector and return the previous norm. static double normalize(double* coordinates, int dimension); /// Compute the norm of a coordinates \a dimension vector static double norm(double* coordinates, int dimension); static double squaredNorm(double* coordinates, int dimension); int Decimals; double SingleStep; double Minimum; double Maximum; bool Normalized; int Dimension; double* Coordinates; QList<int> LastUserEditedCoordinates; }; #endif
32.156028
87
0.720335
[ "vector" ]
e1dd0f950d8a7391207e249242cd7b0e8d09a31a
7,668
h
C
include/third_party/blink/public/platform/web_rtc_peer_connection_handler.h
ispysoftware/spitfire
fe2b395207bdea04223854163dbd2b6404ad75f5
[ "Apache-2.0" ]
1
2022-03-23T19:48:24.000Z
2022-03-23T19:48:24.000Z
include/third_party/blink/public/platform/web_rtc_peer_connection_handler.h
ispysoftware/spitfire
fe2b395207bdea04223854163dbd2b6404ad75f5
[ "Apache-2.0" ]
null
null
null
include/third_party/blink/public/platform/web_rtc_peer_connection_handler.h
ispysoftware/spitfire
fe2b395207bdea04223854163dbd2b6404ad75f5
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2012 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * 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 Google 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. */ #ifndef THIRD_PARTY_BLINK_PUBLIC_PLATFORM_WEB_RTC_PEER_CONNECTION_HANDLER_H_ #define THIRD_PARTY_BLINK_PUBLIC_PLATFORM_WEB_RTC_PEER_CONNECTION_HANDLER_H_ #include <memory> #include <string> #include "third_party/blink/public/platform/web_rtc_stats.h" #include "third_party/blink/public/platform/web_vector.h" #include "third_party/webrtc/api/peer_connection_interface.h" #include "third_party/webrtc/api/rtc_error.h" #include "third_party/webrtc/api/rtp_transceiver_interface.h" #include "third_party/webrtc/api/stats/rtc_stats.h" namespace webrtc { enum class RTCErrorType; struct DataChannelInit; } namespace blink { class RTCAnswerOptionsPlatform; class RTCIceCandidatePlatform; class RTCOfferOptionsPlatform; class RTCRtpSenderPlatform; class RTCRtpTransceiverPlatform; class RTCSessionDescriptionPlatform; class RTCSessionDescriptionRequest; class RTCStatsRequest; class RTCVoidRequest; class WebLocalFrame; class WebMediaConstraints; class WebMediaStream; class WebMediaStreamTrack; class WebString; class WebRTCPeerConnectionHandler { public: enum class IceConnectionStateVersion { // Only applicable in Unified Plan when the JavaScript-exposed // iceConnectionState is calculated in blink. In this case, kLegacy is used // to report the webrtc::PeerConnectionInterface implementation which is not // visible in JavaScript, but still useful to track for debugging purposes. kLegacy, // The JavaScript-visible iceConnectionState. In Plan B, this is the same as // the webrtc::PeerConnectionInterface implementation. kDefault, }; virtual ~WebRTCPeerConnectionHandler() = default; virtual bool Initialize( const webrtc::PeerConnectionInterface::RTCConfiguration&, const WebMediaConstraints&) = 0; virtual void AssociateWithFrame(WebLocalFrame*) {} // Unified Plan: The list of transceivers after the createOffer() call. // Because of offerToReceive[Audio/Video] it is possible for createOffer() to // create new transceivers or update the direction of existing transceivers. // https://w3c.github.io/webrtc-pc/#legacy-configuration-extensions // Plan B: Returns an empty list. virtual WebVector<std::unique_ptr<RTCRtpTransceiverPlatform>> CreateOffer( RTCSessionDescriptionRequest*, const WebMediaConstraints&) = 0; virtual WebVector<std::unique_ptr<RTCRtpTransceiverPlatform>> CreateOffer( RTCSessionDescriptionRequest*, RTCOfferOptionsPlatform*) = 0; virtual void CreateAnswer(RTCSessionDescriptionRequest*, const WebMediaConstraints&) = 0; virtual void CreateAnswer(RTCSessionDescriptionRequest*, RTCAnswerOptionsPlatform*) = 0; virtual void SetLocalDescription(RTCVoidRequest*) = 0; virtual void SetLocalDescription(RTCVoidRequest*, RTCSessionDescriptionPlatform*) = 0; virtual void SetRemoteDescription(RTCVoidRequest*, RTCSessionDescriptionPlatform*) = 0; virtual RTCSessionDescriptionPlatform* LocalDescription() = 0; virtual RTCSessionDescriptionPlatform* RemoteDescription() = 0; virtual RTCSessionDescriptionPlatform* CurrentLocalDescription() = 0; virtual RTCSessionDescriptionPlatform* CurrentRemoteDescription() = 0; virtual RTCSessionDescriptionPlatform* PendingLocalDescription() = 0; virtual RTCSessionDescriptionPlatform* PendingRemoteDescription() = 0; virtual const webrtc::PeerConnectionInterface::RTCConfiguration& GetConfiguration() const = 0; virtual webrtc::RTCErrorType SetConfiguration( const webrtc::PeerConnectionInterface::RTCConfiguration&) = 0; virtual void AddICECandidate(RTCVoidRequest*, scoped_refptr<RTCIceCandidatePlatform>) = 0; virtual void RestartIce() = 0; virtual void GetStats(RTCStatsRequest*) = 0; // Gets stats using the new stats collection API, see // third_party/webrtc/api/stats/. These will replace the old stats collection // API when the new API has matured enough. virtual void GetStats(WebRTCStatsReportCallback, const WebVector<webrtc::NonStandardGroupId>&) = 0; virtual scoped_refptr<webrtc::DataChannelInterface> CreateDataChannel( const WebString& label, const webrtc::DataChannelInit&) = 0; virtual webrtc::RTCErrorOr<std::unique_ptr<RTCRtpTransceiverPlatform>> AddTransceiverWithTrack(const WebMediaStreamTrack&, const webrtc::RtpTransceiverInit&) = 0; virtual webrtc::RTCErrorOr<std::unique_ptr<RTCRtpTransceiverPlatform>> AddTransceiverWithKind( // webrtc::MediaStreamTrackInterface::kAudioKind or kVideoKind std::string kind, const webrtc::RtpTransceiverInit&) = 0; // Adds the track to the peer connection, returning the resulting transceiver // or error. virtual webrtc::RTCErrorOr<std::unique_ptr<RTCRtpTransceiverPlatform>> AddTrack(const WebMediaStreamTrack&, const WebVector<WebMediaStream>&) = 0; // Removes the sender. // In Plan B: Returns OK() with value nullptr on success. The sender's track // must be nulled by the caller. // In Unified Plan: Returns OK() with the updated transceiver state. virtual webrtc::RTCErrorOr<std::unique_ptr<RTCRtpTransceiverPlatform>> RemoveTrack(RTCRtpSenderPlatform*) = 0; virtual void Stop() = 0; // Returns a pointer to the underlying native PeerConnection object. virtual webrtc::PeerConnectionInterface* NativePeerConnection() = 0; virtual void RunSynchronousOnceClosureOnSignalingThread( base::OnceClosure closure, const char* trace_event_name) = 0; virtual void RunSynchronousRepeatingClosureOnSignalingThread( const base::RepeatingClosure& closure, const char* trace_event_name) = 0; // Inform chrome://webrtc-internals/ that the iceConnectionState has changed. virtual void TrackIceConnectionStateChange( IceConnectionStateVersion version, webrtc::PeerConnectionInterface::IceConnectionState state) = 0; }; } // namespace blink #endif // THIRD_PARTY_BLINK_PUBLIC_PLATFORM_WEB_RTC_PEER_CONNECTION_HANDLER_H_
45.642857
80
0.764737
[ "object" ]
e1edff02f5ed941527cf302c6c5c04969889d537
6,105
h
C
osprey/common/com/ir_bwrite.h
sharugupta/OpenUH
daddd76858a53035f5d713f648d13373c22506e8
[ "BSD-2-Clause" ]
null
null
null
osprey/common/com/ir_bwrite.h
sharugupta/OpenUH
daddd76858a53035f5d713f648d13373c22506e8
[ "BSD-2-Clause" ]
null
null
null
osprey/common/com/ir_bwrite.h
sharugupta/OpenUH
daddd76858a53035f5d713f648d13373c22506e8
[ "BSD-2-Clause" ]
null
null
null
/* Copyright (C) 2000, 2001 Silicon Graphics, Inc. All Rights Reserved. This program is free software; you can redistribute it and/or modify it under the terms of version 2 of the GNU General Public License as published by the Free Software Foundation. This program is distributed in the hope that it would be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Further, this software is distributed without any warranty that it is free of the rightful claim of any third person regarding infringement or the like. Any license provided herein, whether implied or otherwise, applies only to this software file. Patent licenses, if any, provided herein do not apply to combinations of this program with other software, or any other product whatsoever. You should have received a copy of the GNU General Public License along with this program; if not, write the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston MA 02111-1307, USA. Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pky, Mountain View, CA 94043, or: http://www.sgi.com For further information regarding this notice, see: http://oss.sgi.com/projects/GenInfo/NoticeExplan */ #ifndef __IR_BWRITE_H__ #define __IR_BWRITE_H__ #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #ifdef __MINGW32__ #include<WINDOWS.H> /* for HANDLE */ /* ideally should move def of output_file to private header * so this windows.h doesn't percolate to callers. * Problem is that windows.h needs to be included before defs.h * due to conflict with mUINT32, but defs.h usually before ir_bwrite.h */ #endif /* __MINGW32__ */ /* * This flag is usually FALSE, but bedriver may set it to TRUE so that * the backend's internal maps will be written out. */ #ifdef BACK_END extern BOOL Write_BE_Maps; extern BOOL Write_AC_INTERNAL_Map; extern BOOL Write_ALIAS_CLASS_Map; extern BOOL Write_ALIAS_CGNODE_Map; #endif /* BACK_END */ /* * Exported interface for writing WHIRL in binary form to a file. * All functions return -1 upon failure, which should be treated as * a fatal error and the process should be aborted. Also, "errno" will * be set and can be used for printing appropriate error messages. * If the operation is successful, 0 will be returned. */ typedef struct section { const char *name; /* section name */ Elf64_Shdr shdr; /* Elf section */ } Section; typedef struct output_file { char *file_name; #ifdef __MINGW32__ int output_fd; /* handle for output file */ HANDLE mapHd; /* Handle for mapped region */ #else INT output_fd; /* file id for output file */ #endif /* __MINGW32__ */ char *map_addr; /* base address of the mapped region */ off_t mapped_size; /* max. size of the mapped region */ off_t file_size; Section *section_list; /* array of Elf sections */ INT max_num_of_section; INT num_of_section; Section *cur_section; /* set by get_section() */ } Output_File; extern Output_File *Current_Output; /* Call these once at the beginning and end, respectively. */ extern Output_File *WN_open_output (char *file_name); extern void WN_close_output (Output_File *fl); extern void WN_close_file (void *fl); extern Section * get_section (Elf64_Word sh_info, const char *name, Output_File *fl); /* * Write global tables to their own Elf sections. These should only be * called after all the PUs have been written out. */ extern void WN_write_globals (Output_File *fl); extern void WN_write_dst (void *dst, Output_File *fl); extern void WN_write_strtab (const void *strtab, UINT64 size, Output_File *fl); extern void WN_write_localmap (void *localmap, Output_File *fl); extern void IPA_write_summary (void (*IPA_irb_write_summary) (Output_File*), Output_File *fl); extern void IPA_copy_PU(PU_Info *pu, char *section_base, Output_File *outfile); extern void WN_write_flags (INT argc, char **argv, Output_File *fl); extern void WN_write_revision (Output_File *fl); extern void WN_close_file (void *this_fl); #if defined(TARG_SL) extern void WN_write_isr_cg (vector<mINT32>& cg, Output_File *fl); #endif /* * Write PU section header. This must be called after writing out all the * PUs but before writing any of the global tables. */ extern void WN_write_PU_Infos (PU_Info *pu_list, Output_File *fl); /* * Write PU-specific structions to subsections of the PU section. * WN_write_tree uses the "off_map" mapping to store the subsection offsets * of the WHIRL nodes that may be referenced by the dependence graph or * prefetch pointers. */ extern void WN_write_tree (PU_Info *pu, WN_MAP off_map, Output_File *fl); extern void WN_write_symtab (PU_Info *pu, Output_File *fl); extern void WN_write_depgraph (PU_Info *pu, WN_MAP off_map, Output_File *fl); extern void WN_write_prefetch (PU_Info *pu, WN_MAP off_map, Output_File *fl); extern void WN_write_feedback (PU_Info *pu, Output_File *fl); extern void WN_write_INT32_map(PU_Info *pu, WN_MAP off_map, Output_File *fl, INT32 subsection_type, WN_MAP value_map, const char *subsection_name); extern void WN_write_voidptr_map(PU_Info *pu, WN_MAP off_map, Output_File *fl, INT32 subsection_type, WN_MAP value_map, const char *subsection_name); extern void WN_write_SSA(PU_Info *pu, Output_File *fl); #ifndef OWN_ERROR_PACKAGE /* * Define common routines for writing all the whirl sections. * These routines use the standard compiler error reporting mechanism. */ extern Output_File *Open_Output_Info (char *output_file); extern void Write_PU_Info (PU_Info *pu); extern void Write_Global_Info (PU_Info *pu_tree); extern void Close_Output_Info (void); extern void WN_write_elf_symtab (const void* symtab, UINT64 size, UINT64 entsize, UINT align, Output_File* fl); #endif #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __IR_BWRITE_H__ */
33.916667
79
0.732351
[ "vector" ]
e1f6c607d34e910938127fbc4318ba161f31cee0
1,926
h
C
DataSource/include/DPArrayController.h
AlexFedoriev/DPDataStorage
10e17cfa1df0e9448eb64d6ef7a4e95feec0d711
[ "MIT" ]
null
null
null
DataSource/include/DPArrayController.h
AlexFedoriev/DPDataStorage
10e17cfa1df0e9448eb64d6ef7a4e95feec0d711
[ "MIT" ]
null
null
null
DataSource/include/DPArrayController.h
AlexFedoriev/DPDataStorage
10e17cfa1df0e9448eb64d6ef7a4e95feec0d711
[ "MIT" ]
null
null
null
// // DPArrayController.H // DP Commons // // Created by Dmitriy Petrusevich on 23/07/15. // Copyright (c) 2015 Dmitriy Petrusevich. All rights reserved. // #import "DPBaseDataSource.h" @class DPChange; NS_ASSUME_NONNULL_BEGIN @interface DPArrayController : NSObject <DataSourceContainerController> @property (nonatomic, weak, nullable) IBOutlet id<DataSourceContainerControllerDelegate> delegate; @property (nonatomic, readonly) BOOL hasData; - (instancetype)initWithDelegate:(id<DataSourceContainerControllerDelegate> _Nullable)delegate; - (void)managedObjectContextObjectsDidChange:(NSNotification *)notification; - (void)removeAllObjects; - (void)insertObject:(id)object atIndextPath:(NSIndexPath *)indexPath; - (void)deleteObjectAtIndextPath:(NSIndexPath *)indexPath; - (void)reloadObjectAtIndextPath:(NSIndexPath *)indexPath; - (void)moveObjectAtIndextPath:(NSIndexPath *)indexPath toIndexPath:(NSIndexPath *)newIndexPath; - (void)insertSectionAtIndex:(NSUInteger)index; - (void)insertSectionObject:(id<NSFetchedResultsSectionInfo>)sectionInfo atIndex:(NSUInteger)index; - (void)removeSectionAtIndex:(NSUInteger)index; - (void)reloadSectionAtIndex:(NSUInteger)index; - (void)setSectionName:(NSString *)name atIndex:(NSUInteger)index; - (NSString *)sectionNameAtIndex:(NSUInteger)index; - (void)addObjects:(NSArray *)objects atSection:(NSInteger)section; - (void)setObjects:(NSArray *)objects atSection:(NSInteger)section; - (void)startUpdating; - (void)endUpdating; - (BOOL)isUpdating; - (BOOL)delegateResponseToDidChangeObject; - (BOOL)delegateResponseToDidChangeSection; - (BOOL)hasChanges; - (NSArray<DPChange *> *)updateChanges; - (void)applyChanges; - (void)notifyDelegate; - (NSInteger)numberOfSections; - (NSInteger)numberOfItemsInSection:(NSInteger)section; - (id)objectAtIndexPath:(NSIndexPath *)indexPath; - (NSIndexPath * _Nullable)indexPathForObject:(id)object; @end NS_ASSUME_NONNULL_END
32.644068
99
0.796469
[ "object" ]
e1f9a52923ecafcd41c531a4784d9fa405c5fa76
1,053
h
C
Basil/include/Renderer/Renderer.h
Tamookk/Basil
bdcdf4e6e13e64a34416b4412d366594f9d46f56
[ "Apache-2.0" ]
null
null
null
Basil/include/Renderer/Renderer.h
Tamookk/Basil
bdcdf4e6e13e64a34416b4412d366594f9d46f56
[ "Apache-2.0" ]
null
null
null
Basil/include/Renderer/Renderer.h
Tamookk/Basil
bdcdf4e6e13e64a34416b4412d366594f9d46f56
[ "Apache-2.0" ]
null
null
null
/* * This header decleares the base renderer class. */ #pragma once #include "Renderer/OrthographicCamera.h" #include "Renderer/RendererAPI.h" #include "Renderer/Shader.h" namespace Basil { class Renderer { public: static void init(); static void shutdown(); static void onWindowResize(unsigned int width, unsigned int height); static void beginScene(OrthographicCamera& camera); static void endScene(); static void submit(const Shared<Shader>& shader, const Shared<VertexArray>& vao, const glm::mat4& transform = glm::mat4(1.0f)); static void setClearColor(const glm::vec4& color); static void clear(); static void drawIndexed(const Shared<VertexArray>& vao, uint32_t indexCount = 0); static void drawLines(const Shared<VertexArray>& vertexArray, uint32_t vertexCount); static void setLineWidth(float width); static RendererAPI::API getAPI(); private: struct SceneData { glm::mat4 viewProjectionMatrix; }; static Unique<RendererAPI> rendererAPI; static Unique<SceneData> sceneData; }; }
30.085714
130
0.734093
[ "transform" ]
c00486577350d90c649e395b80938bd9d38dd0af
1,308
h
C
Engine/Source/FileIO/BinaryFileReader.h
jasonoscar88/Photon-v2
90649196c436261d28cc2300511b78ac88236448
[ "MIT" ]
88
2017-01-21T18:20:16.000Z
2021-12-21T02:32:04.000Z
Engine/Source/FileIO/BinaryFileReader.h
jasonoscar88/Photon-v2
90649196c436261d28cc2300511b78ac88236448
[ "MIT" ]
72
2017-07-28T10:00:35.000Z
2021-11-09T18:36:23.000Z
Engine/Source/FileIO/BinaryFileReader.h
jasonoscar88/Photon-v2
90649196c436261d28cc2300511b78ac88236448
[ "MIT" ]
8
2017-03-19T12:19:10.000Z
2020-05-19T15:15:05.000Z
#pragma once #include "FileIO/FileSystem/Path.h" #include "Common/Logger.h" #include "Common/assertion.h" #include <fstream> #include <vector> namespace ph { class BinaryFileReader { public: explicit BinaryFileReader(const Path& filePath); virtual ~BinaryFileReader(); bool open(); void close(); template<typename T> void read(T* out_buffer, std::size_t numElements = 1); private: Path m_filePath; std::ifstream m_inputStream; static const Logger logger; }; // In-header Implementations: inline BinaryFileReader::BinaryFileReader(const Path& filePath) : m_filePath(filePath), m_inputStream() {} inline BinaryFileReader::~BinaryFileReader() { close(); } inline bool BinaryFileReader::open() { m_inputStream.open(m_filePath.toString(), std::ios_base::in | std::ios_base::binary); if(!m_inputStream.good()) { logger.log(ELogLevel::WARNING_MED, "<" + m_filePath.toString() + "> open failed"); return false; } return true; } inline void BinaryFileReader::close() { m_inputStream.close(); } template<typename T> void BinaryFileReader::read(T* const out_buffer, const std::size_t numElements) { PH_ASSERT(out_buffer && numElements > 0 && m_inputStream.good()); m_inputStream.read(reinterpret_cast<char*>(out_buffer), sizeof(T) * numElements); } }// end namespace ph
19.235294
86
0.729358
[ "vector" ]
c00d3b79420156183689b9127d580ffb7815e247
1,589
h
C
SymbolExtractorAndRenamer/llvm/include/llvm/DebugInfo/CodeView/TypeDatabase.h
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
[ "Apache-2.0" ]
427
2018-05-29T14:21:02.000Z
2022-03-16T03:17:54.000Z
SymbolExtractorAndRenamer/llvm/include/llvm/DebugInfo/CodeView/TypeDatabase.h
PolideaPlayground/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
[ "Apache-2.0" ]
25
2018-07-23T08:34:15.000Z
2021-11-05T07:13:36.000Z
SymbolExtractorAndRenamer/llvm/include/llvm/DebugInfo/CodeView/TypeDatabase.h
PolideaPlayground/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
[ "Apache-2.0" ]
52
2018-07-19T19:57:32.000Z
2022-03-11T16:05:38.000Z
//===- TypeDatabase.h - A collection of CodeView type records ---*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_DEBUGINFO_CODEVIEW_TYPEDATABASE_H #define LLVM_DEBUGINFO_CODEVIEW_TYPEDATABASE_H #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" #include "llvm/DebugInfo/CodeView/TypeIndex.h" #include "llvm/DebugInfo/CodeView/TypeRecord.h" #include "llvm/Support/Allocator.h" #include "llvm/Support/StringSaver.h" namespace llvm { namespace codeview { class TypeDatabase { public: TypeDatabase() : TypeNameStorage(Allocator) {} /// Gets the type index for the next type record. TypeIndex getNextTypeIndex() const; /// Records the name of a type, and reserves its type index. void recordType(StringRef Name, const CVType &Data); /// Saves the name in a StringSet and creates a stable StringRef. StringRef saveTypeName(StringRef TypeName); StringRef getTypeName(TypeIndex Index) const; bool containsTypeIndex(TypeIndex Index) const; uint32_t size() const; private: BumpPtrAllocator Allocator; /// All user defined type records in .debug$T live in here. Type indices /// greater than 0x1000 are user defined. Subtract 0x1000 from the index to /// index into this vector. SmallVector<StringRef, 10> CVUDTNames; SmallVector<CVType, 10> TypeRecords; StringSaver TypeNameStorage; }; } } #endif
28.890909
80
0.704216
[ "vector" ]
c01354a3bf52a90d588a6e1381011c6cd8f7ff6e
2,886
c
C
trick_source/trick_utils/math/src/uniform_rnd_1.c
dexueyang/trick-dup0
2d5d5502fa896d3c42eda40ce0ee45e98ec35463
[ "NASA-1.3" ]
null
null
null
trick_source/trick_utils/math/src/uniform_rnd_1.c
dexueyang/trick-dup0
2d5d5502fa896d3c42eda40ce0ee45e98ec35463
[ "NASA-1.3" ]
null
null
null
trick_source/trick_utils/math/src/uniform_rnd_1.c
dexueyang/trick-dup0
2d5d5502fa896d3c42eda40ce0ee45e98ec35463
[ "NASA-1.3" ]
3
2021-06-22T11:02:39.000Z
2021-10-21T00:58:00.000Z
/* PURPOSE: (ICDS uniform random number generator. Almost a copy of ICDS' random number generator. See code comments for any differences.) REFERENCE: ((ICDS)) ASSUMPTIONS AND LIMITATIONS: ((If the user wants repeatability, a non zero seed should be used. If the user wants a random seed, a zero seed should be used.)) CLASS: (scheduled) LIBRARY DEPENDENCY: ((uniform_rnd_1.o)) PROGRAMMERS: (((Ray Li) (LMES/DUAL) (96 Nov) (1.0) (ICDS random number generator)) ((Robert Gay) (LinCom) (May 1998) (--) (Trick format)) ((David Hammen) (Titan-LinCom) (April 2001) (Renamed ICDS_Get_CPU_Time to total_CPU_time and made it local)) ((Robert Gay) (Titan-LinCom) (Aug 2001) (--) (Updates to put routines into trick math))) */ #include <math.h> #if __Lynx__ #include <time.h> #include <param.h> #elif ( __ghs ) #include <sys/time.h> #else #include <sys/time.h> #include <sys/param.h> #endif #include <sys/times.h> #include <limits.h> #include <unistd.h> #include "trick/rand_generator.h" #include "trick/trick_math.h" #ifndef HZ #define HZ 100 /* This is a kludge to accomodate for Darwin. On Darwin HZ is actually a kernal global variable. I suppose I should use that but this will suffice. */ #endif static double total_CPU_time(void); double uniform_rnd_1(RAND_GENERATOR * G) { /* Inout: random number seed */ static long a = 46341; /* Value of a based on F. Clark note, 4/22/92 */ static long m = 2147483647; /* Value of m based on F. Clark note, 4/22/92 */ double new_random_number; /* * NOTE: This function behaves slightly different from * ICDS's g_rnd(). * ICDS g_rnd(): * first-pass: build random number off input seed * afterwards: modify input seed, then build random number * * this function: * build random number, then modify input seed. * * This modification was made because the first-pass * special case in g_rnd() means that the first model * that uses g_rnd() will get the "first-pass" behavior on * the first pass, while all other models that use g_rnd() * will get the "afterwards" behavior on the first pass. * */ if (!(G->seed_1)) { G->seed_1 = (unsigned long) total_CPU_time(); } new_random_number = (double) G->seed_1 / (double) m; G->seed_1 = ((a * G->seed_1) % m); return (new_random_number); } /* This function returns the number of seconds that this process (and its wait'ed for children) has spend in execution (both user and system time) */ static double total_CPU_time(void) { struct tms time_buffer; times(&time_buffer); return ((time_buffer.tms_utime + time_buffer.tms_cutime + time_buffer.tms_stime + time_buffer.tms_cstime) / HZ); }
32.795455
119
0.646223
[ "model" ]
c01f24f200cd95ed5e55cbe5f2aad328dac6b121
700
h
C
tools/geom2graph/include/geom2graph/io/graph-reader.h
Notgnoshi/generative
d9702c18b59553541f0cce706089f9fad501cd33
[ "MIT" ]
5
2021-02-11T07:55:51.000Z
2022-02-10T01:11:02.000Z
tools/geom2graph/include/geom2graph/io/graph-reader.h
Notgnoshi/generative
d9702c18b59553541f0cce706089f9fad501cd33
[ "MIT" ]
67
2020-12-31T18:02:05.000Z
2022-02-21T14:57:52.000Z
tools/geom2graph/include/geom2graph/io/graph-reader.h
Notgnoshi/generative
d9702c18b59553541f0cce706089f9fad501cd33
[ "MIT" ]
null
null
null
#pragma once #include "geom2graph/noding/geometry-graph.h" #include <geos/io/WKTReader.h> #include <istream> namespace geom2graph::io { class GraphReader { public: GraphReader(std::istream& input, const geos::geom::GeometryFactory& factory) : m_input(input), m_factory(factory), m_reader(factory) { } virtual ~GraphReader() = default; //! @brief Read a graph from the given istream. virtual geom2graph::noding::GeometryGraph read() noexcept = 0; virtual void read(const std::string& line) noexcept = 0; protected: std::istream& m_input; const geos::geom::GeometryFactory& m_factory; geos::io::WKTReader m_reader; }; } // namespace geom2graph::io
25
82
0.697143
[ "geometry" ]
c0368d328269900982135344c257d6e3b212ddd1
31,050
h
C
usr/src/uts/common/sys/nxge/nxge.h
AsahiOS/gate
283d47da4e17a5871d9d575e7ffb81e8f6c52e51
[ "MIT" ]
null
null
null
usr/src/uts/common/sys/nxge/nxge.h
AsahiOS/gate
283d47da4e17a5871d9d575e7ffb81e8f6c52e51
[ "MIT" ]
null
null
null
usr/src/uts/common/sys/nxge/nxge.h
AsahiOS/gate
283d47da4e17a5871d9d575e7ffb81e8f6c52e51
[ "MIT" ]
1
2020-12-30T00:04:16.000Z
2020-12-30T00:04:16.000Z
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. */ #ifndef _SYS_NXGE_NXGE_H #define _SYS_NXGE_NXGE_H #ifdef __cplusplus extern "C" { #endif #include <nxge_mac.h> #include <nxge_ipp.h> #include <nxge_fflp.h> /* * NXGE diagnostics IOCTLS. */ #define NXGE_IOC ((((('N' << 8) + 'X') << 8) + 'G') << 8) #define NXGE_GET64 (NXGE_IOC|1) #define NXGE_PUT64 (NXGE_IOC|2) #define NXGE_GET_TX_RING_SZ (NXGE_IOC|3) #define NXGE_GET_TX_DESC (NXGE_IOC|4) #define NXGE_GLOBAL_RESET (NXGE_IOC|5) #define NXGE_TX_SIDE_RESET (NXGE_IOC|6) #define NXGE_RX_SIDE_RESET (NXGE_IOC|7) #define NXGE_RESET_MAC (NXGE_IOC|8) #define NXGE_GET_MII (NXGE_IOC|11) #define NXGE_PUT_MII (NXGE_IOC|12) #define NXGE_RTRACE (NXGE_IOC|13) #define NXGE_RTRACE_TEST (NXGE_IOC|20) #define NXGE_TX_REGS_DUMP (NXGE_IOC|21) #define NXGE_RX_REGS_DUMP (NXGE_IOC|22) #define NXGE_INT_REGS_DUMP (NXGE_IOC|23) #define NXGE_VIR_REGS_DUMP (NXGE_IOC|24) #define NXGE_VIR_INT_REGS_DUMP (NXGE_IOC|25) #define NXGE_RDUMP (NXGE_IOC|26) #define NXGE_RDC_GRPS_DUMP (NXGE_IOC|27) #define NXGE_PIO_TEST (NXGE_IOC|28) #define NXGE_GET_TCAM (NXGE_IOC|29) #define NXGE_PUT_TCAM (NXGE_IOC|30) #define NXGE_INJECT_ERR (NXGE_IOC|40) #define NXGE_RX_CLASS (NXGE_IOC|41) #define NXGE_RX_HASH (NXGE_IOC|42) #define NXGE_OK 0 #define NXGE_ERROR 0x40000000 #define NXGE_DDI_FAILED 0x20000000 #define NXGE_GET_PORT_NUM(n) n /* * Definitions for module_info. */ #define NXGE_IDNUM (0) /* module ID number */ #define NXGE_DRIVER_NAME "nxge" /* module name */ #define NXGE_MINPSZ (0) /* min packet size */ #define NXGE_MAXPSZ (ETHERMTU) /* max packet size */ #define NXGE_HIWAT (2048 * NXGE_MAXPSZ) /* hi-water mark */ #define NXGE_LOWAT (1) /* lo-water mark */ #define NXGE_HIWAT_MAX (192000 * NXGE_MAXPSZ) #define NXGE_HIWAT_MIN (2 * NXGE_MAXPSZ) #define NXGE_LOWAT_MAX (192000 * NXGE_MAXPSZ) #define NXGE_LOWAT_MIN (1) #ifndef D_HOTPLUG #define D_HOTPLUG 0x00 #endif #define INIT_BUCKET_SIZE 16 /* Initial Hash Bucket Size */ #define NXGE_CHECK_TIMER (5000) /* KT/NIU OBP creates a compatible property for KT */ #define KT_NIU_COMPATIBLE "SUNW,niusl-kt" typedef enum { param_instance, param_main_instance, param_function_number, param_partition_id, param_read_write_mode, param_fw_version, param_port_mode, param_niu_cfg_type, param_tx_quick_cfg, param_rx_quick_cfg, param_master_cfg_enable, param_master_cfg_value, param_autoneg, param_anar_10gfdx, param_anar_10ghdx, param_anar_1000fdx, param_anar_1000hdx, param_anar_100T4, param_anar_100fdx, param_anar_100hdx, param_anar_10fdx, param_anar_10hdx, param_anar_asmpause, param_anar_pause, param_use_int_xcvr, param_enable_ipg0, param_ipg0, param_ipg1, param_ipg2, param_txdma_weight, param_txdma_channels_begin, param_txdma_channels, param_txdma_info, param_rxdma_channels_begin, param_rxdma_channels, param_rxdma_drr_weight, param_rxdma_full_header, param_rxdma_info, param_rxdma_rbr_size, param_rxdma_rcr_size, param_default_port_rdc, param_rxdma_intr_time, param_rxdma_intr_pkts, param_rdc_grps_start, param_rx_rdc_grps, param_default_grp0_rdc, param_default_grp1_rdc, param_default_grp2_rdc, param_default_grp3_rdc, param_default_grp4_rdc, param_default_grp5_rdc, param_default_grp6_rdc, param_default_grp7_rdc, param_info_rdc_groups, param_start_ldg, param_max_ldg, param_mac_2rdc_grp, param_vlan_2rdc_grp, param_fcram_part_cfg, param_fcram_access_ratio, param_tcam_access_ratio, param_tcam_enable, param_hash_lookup_enable, param_llc_snap_enable, param_h1_init_value, param_h2_init_value, param_class_cfg_ether_usr1, param_class_cfg_ether_usr2, param_class_cfg_ip_usr4, param_class_cfg_ip_usr5, param_class_cfg_ip_usr6, param_class_cfg_ip_usr7, param_class_opt_ip_usr4, param_class_opt_ip_usr5, param_class_opt_ip_usr6, param_class_opt_ip_usr7, param_class_opt_ipv4_tcp, param_class_opt_ipv4_udp, param_class_opt_ipv4_ah, param_class_opt_ipv4_sctp, param_class_opt_ipv6_tcp, param_class_opt_ipv6_udp, param_class_opt_ipv6_ah, param_class_opt_ipv6_sctp, param_nxge_debug_flag, param_npi_debug_flag, param_dump_rdc, param_dump_tdc, param_dump_mac_regs, param_dump_ipp_regs, param_dump_fflp_regs, param_dump_vlan_table, param_dump_rdc_table, param_dump_ptrs, param_end } nxge_param_index_t; typedef enum { SOLARIS_DOMAIN, SOLARIS_SERVICE_DOMAIN, SOLARIS_GUEST_DOMAIN, LINUX_SERVICE_DOMAIN, LINUX_GUEST_DOMAIN } nxge_environs_t; /* * Named Dispatch Parameter Management Structure */ typedef int (*nxge_ndgetf_t)(p_nxge_t, queue_t *, MBLKP, caddr_t, cred_t *); typedef int (*nxge_ndsetf_t)(p_nxge_t, queue_t *, MBLKP, char *, caddr_t, cred_t *); #define NXGE_PARAM_READ 0x00000001ULL #define NXGE_PARAM_WRITE 0x00000002ULL #define NXGE_PARAM_SHARED 0x00000004ULL #define NXGE_PARAM_PRIV 0x00000008ULL #define NXGE_PARAM_RW NXGE_PARAM_READ | NXGE_PARAM_WRITE #define NXGE_PARAM_RWS NXGE_PARAM_RW | NXGE_PARAM_SHARED #define NXGE_PARAM_RWP NXGE_PARAM_RW | NXGE_PARAM_PRIV #define NXGE_PARAM_RXDMA 0x00000010ULL #define NXGE_PARAM_TXDMA 0x00000020ULL #define NXGE_PARAM_CLASS_GEN 0x00000040ULL #define NXGE_PARAM_MAC 0x00000080ULL #define NXGE_PARAM_CLASS_BIN NXGE_PARAM_CLASS_GEN | NXGE_PARAM_BASE_BIN #define NXGE_PARAM_CLASS_HEX NXGE_PARAM_CLASS_GEN | NXGE_PARAM_BASE_HEX #define NXGE_PARAM_CLASS NXGE_PARAM_CLASS_HEX #define NXGE_PARAM_CMPLX 0x00010000ULL #define NXGE_PARAM_NDD_WR_OK 0x00020000ULL #define NXGE_PARAM_INIT_ONLY 0x00040000ULL #define NXGE_PARAM_INIT_CONFIG 0x00080000ULL #define NXGE_PARAM_READ_PROP 0x00100000ULL #define NXGE_PARAM_PROP_ARR32 0x00200000ULL #define NXGE_PARAM_PROP_ARR64 0x00400000ULL #define NXGE_PARAM_PROP_STR 0x00800000ULL #define NXGE_PARAM_BASE_DEC 0x00000000ULL #define NXGE_PARAM_BASE_BIN 0x10000000ULL #define NXGE_PARAM_BASE_HEX 0x20000000ULL #define NXGE_PARAM_BASE_STR 0x40000000ULL #define NXGE_PARAM_DONT_SHOW 0x80000000ULL #define NXGE_PARAM_ARRAY_CNT_MASK 0x0000ffff00000000ULL #define NXGE_PARAM_ARRAY_CNT_SHIFT 32ULL #define NXGE_PARAM_ARRAY_ALLOC_MASK 0xffff000000000000ULL #define NXGE_PARAM_ARRAY_ALLOC_SHIFT 48ULL typedef struct _nxge_param_t { int (*getf)(); int (*setf)(); /* null for read only */ uint64_t type; /* R/W/ Common/Port/ .... */ uint64_t minimum; uint64_t maximum; uint64_t value; /* for array params, pointer to value array */ uint64_t old_value; /* for array params, pointer to old_value array */ char *fcode_name; char *name; } nxge_param_t, *p_nxge_param_t; /* * Do not change the order of the elements of this enum as that will * break the driver code. */ typedef enum { nxge_lb_normal, nxge_lb_ext10g, nxge_lb_ext1000, nxge_lb_ext100, nxge_lb_ext10, nxge_lb_phy10g, nxge_lb_phy1000, nxge_lb_phy, nxge_lb_serdes10g, nxge_lb_serdes1000, nxge_lb_serdes, nxge_lb_mac10g, nxge_lb_mac1000, nxge_lb_mac } nxge_lb_t; enum nxge_mac_state { NXGE_MAC_STOPPED = 0, NXGE_MAC_STARTED, NXGE_MAC_STOPPING }; /* * Private DLPI full dlsap address format. */ typedef struct _nxge_dladdr_t { ether_addr_st dl_phys; uint16_t dl_sap; } nxge_dladdr_t, *p_nxge_dladdr_t; typedef struct _mc_addr_t { ether_addr_st multcast_addr; uint_t mc_addr_cnt; } mc_addr_t, *p_mc_addr_t; typedef struct _mc_bucket_t { p_mc_addr_t addr_list; uint_t list_size; } mc_bucket_t, *p_mc_bucket_t; typedef struct _mc_table_t { p_mc_bucket_t bucket_list; uint_t buckets_used; } mc_table_t, *p_mc_table_t; typedef struct _filter_t { uint32_t all_phys_cnt; uint32_t all_multicast_cnt; uint32_t all_sap_cnt; } filter_t, *p_filter_t; typedef struct _nxge_port_stats_t { /* * Overall structure size */ size_t stats_size; /* * Link Input/Output stats */ uint64_t ipackets; uint64_t ierrors; uint64_t opackets; uint64_t oerrors; uint64_t collisions; /* * MIB II variables */ uint64_t rbytes; /* # bytes received */ uint64_t obytes; /* # bytes transmitted */ uint32_t multircv; /* # multicast packets received */ uint32_t multixmt; /* # multicast packets for xmit */ uint32_t brdcstrcv; /* # broadcast packets received */ uint32_t brdcstxmt; /* # broadcast packets for xmit */ uint32_t norcvbuf; /* # rcv packets discarded */ uint32_t noxmtbuf; /* # xmit packets discarded */ /* * Lets the user know the MTU currently in use by * the physical MAC port. */ nxge_lb_t lb_mode; uint32_t qos_mode; uint32_t trunk_mode; uint32_t poll_mode; /* * Tx Statistics. */ uint32_t tx_inits; uint32_t tx_starts; uint32_t tx_nocanput; uint32_t tx_msgdup_fail; uint32_t tx_allocb_fail; uint32_t tx_no_desc; uint32_t tx_dma_bind_fail; uint32_t tx_uflo; uint32_t tx_hdr_pkts; uint32_t tx_ddi_pkts; uint32_t tx_dvma_pkts; uint32_t tx_max_pend; /* * Rx Statistics. */ uint32_t rx_inits; uint32_t rx_hdr_pkts; uint32_t rx_mtu_pkts; uint32_t rx_split_pkts; uint32_t rx_no_buf; uint32_t rx_no_comp_wb; uint32_t rx_ov_flow; uint32_t rx_len_mm; uint32_t rx_tag_err; uint32_t rx_nocanput; uint32_t rx_msgdup_fail; uint32_t rx_allocb_fail; /* * Receive buffer management statistics. */ uint32_t rx_new_pages; uint32_t rx_new_hdr_pgs; uint32_t rx_new_mtu_pgs; uint32_t rx_new_nxt_pgs; uint32_t rx_reused_pgs; uint32_t rx_hdr_drops; uint32_t rx_mtu_drops; uint32_t rx_nxt_drops; /* * Receive flow statistics */ uint32_t rx_rel_flow; uint32_t rx_rel_bit; uint32_t rx_pkts_dropped; /* * PCI-E Bus Statistics. */ uint32_t pci_bus_speed; uint32_t pci_err; uint32_t pci_rta_err; uint32_t pci_rma_err; uint32_t pci_parity_err; uint32_t pci_bad_ack_err; uint32_t pci_drto_err; uint32_t pci_dmawz_err; uint32_t pci_dmarz_err; uint32_t rx_taskq_waits; uint32_t tx_jumbo_pkts; /* * Some statistics added to support bringup, these * should be removed. */ uint32_t user_defined; } nxge_port_stats_t, *p_nxge_port_stats_t; typedef struct _nxge_stats_t { /* * Overall structure size */ size_t stats_size; kstat_t *ksp; kstat_t *rdc_ksp[NXGE_MAX_RDCS]; kstat_t *tdc_ksp[NXGE_MAX_TDCS]; kstat_t *rdc_sys_ksp; kstat_t *fflp_ksp[1]; kstat_t *ipp_ksp; kstat_t *txc_ksp; kstat_t *mac_ksp; kstat_t *zcp_ksp; kstat_t *port_ksp; kstat_t *mmac_ksp; nxge_mac_stats_t mac_stats; /* Common MAC Statistics */ nxge_xmac_stats_t xmac_stats; /* XMAC Statistics */ nxge_bmac_stats_t bmac_stats; /* BMAC Statistics */ nxge_rx_ring_stats_t rx_stats; /* per port RX stats */ nxge_ipp_stats_t ipp_stats; /* per port IPP stats */ nxge_zcp_stats_t zcp_stats; /* per port IPP stats */ nxge_rx_ring_stats_t rdc_stats[NXGE_MAX_RDCS]; /* per rdc stats */ nxge_rdc_sys_stats_t rdc_sys_stats; /* per port RDC stats */ nxge_tx_ring_stats_t tx_stats; /* per port TX stats */ nxge_txc_stats_t txc_stats; /* per port TX stats */ nxge_tx_ring_stats_t tdc_stats[NXGE_MAX_TDCS]; /* per tdc stats */ nxge_fflp_stats_t fflp_stats; /* fflp stats */ nxge_port_stats_t port_stats; /* fflp stats */ nxge_mmac_stats_t mmac_stats; /* Multi mac. stats */ } nxge_stats_t, *p_nxge_stats_t; typedef struct _nxge_intr_t { boolean_t intr_registered; /* interrupts are registered */ boolean_t intr_enabled; /* interrupts are enabled */ boolean_t niu_msi_enable; /* debug or configurable? */ int intr_types; /* interrupt types supported */ int intr_type; /* interrupt type to add */ int max_int_cnt; /* max MSIX/INT HW supports */ int start_inum; /* start inum (in sequence?) */ int msi_intx_cnt; /* # msi/intx ints returned */ int intr_added; /* # ints actually needed */ int intr_cap; /* interrupt capabilities */ size_t intr_size; /* size of array to allocate */ ddi_intr_handle_t *htable; /* For array of interrupts */ /* Add interrupt number for each interrupt vector */ int pri; } nxge_intr_t, *p_nxge_intr_t; typedef struct _nxge_ldgv_t { uint8_t ndma_ldvs; uint8_t nldvs; uint8_t maxldgs; uint8_t maxldvs; uint8_t ldg_intrs; uint32_t tmres; p_nxge_ldg_t ldgp; p_nxge_ldv_t ldvp; p_nxge_ldv_t ldvp_syserr; boolean_t ldvp_syserr_alloced; } nxge_ldgv_t, *p_nxge_ldgv_t; typedef enum { NXGE_TRANSMIT_GROUP, /* Legacy transmit group */ NXGE_RECEIVE_GROUP, /* Legacy receive group */ NXGE_VR_GROUP, /* Virtualization Region group */ EXT_TRANSMIT_GROUP, /* External (Crossbow) transmit group */ EXT_RECEIVE_GROUP /* External (Crossbow) receive group */ } nxge_grp_type_t; #define NXGE_ILLEGAL_CHANNEL (NXGE_MAX_TDCS + 1) typedef uint8_t nxge_channel_t; typedef struct nxge_grp { nxge_t *nxge; nxge_grp_type_t type; /* Tx or Rx */ int sequence; /* When it was created. */ int index; /* nxge_grp_set_t.group[index] */ struct nx_dc *dc; /* Linked list of DMA channels. */ size_t count; /* A count of <dc> above. */ boolean_t active; /* Is it being used? */ dc_map_t map; /* A bitmap of the channels in <dc>. */ nxge_channel_t legend[NXGE_MAX_TDCS]; } nxge_grp_t; typedef struct { lg_map_t map; size_t count; } lg_data_t; typedef struct { dc_map_t map; size_t count; } dc_data_t; #define NXGE_DC_SET(map, channel) map |= (1 << channel) #define NXGE_DC_RESET(map, channel) map &= (~(1 << channel)) /* For now, we only support up to 8 RDC/TDC groups */ #define NXGE_LOGICAL_GROUP_MAX NXGE_MAX_RDC_GROUPS typedef struct { int sequence; /* To order groups in time. */ /* These are this instance's logical groups. */ nxge_grp_t *group[NXGE_LOGICAL_GROUP_MAX]; lg_data_t lg; dc_data_t shared; /* These DCs are being shared. */ dc_data_t owned; /* These DCs belong to me. */ dc_data_t dead; /* These DCs are in an error state. */ } nxge_grp_set_t; /* * Transmit Ring Group * TX groups will be used exclusively for the purpose of Hybrid I/O. From * the point of view of the nxge driver, the groups will be software * constructs which will be used to establish the relationship between TX * rings and shares. * * Receive Ring Group * One of the advanced virtualization features is the ability to bundle * multiple Receive Rings in a single group. One or more MAC addresses may * be assigned to a group. Incoming packets destined to the group's MAC * address(es) are delivered to any ring member, according to a programmable * or predefined RTS policy. Member rings can be polled individually. * RX ring groups can come with a predefined set of member rings, or they * are programmable by adding and removing rings to/from them. */ typedef struct _nxge_ring_group_t { mac_group_handle_t ghandle; p_nxge_t nxgep; boolean_t started; boolean_t port_default_grp; mac_ring_type_t type; int gindex; int sindex; int rdctbl; int n_mac_addrs; } nxge_ring_group_t; /* * Ring Handle */ typedef struct _nxge_ring_handle_t { p_nxge_t nxgep; int index; /* port-wise */ mac_ring_handle_t ring_handle; uint64_t ring_gen_num; /* For RX Ring Start */ uint32_t channel; } nxge_ring_handle_t, *p_nxge_ring_handle_t; /* * Share Handle */ typedef struct _nxge_share_handle_t { p_nxge_t nxgep; /* Driver Handle */ int index; void *vrp; uint64_t tmap; uint64_t rmap; int rxgroup; boolean_t active; } nxge_share_handle_t; /* * Neptune Device instance state information. * * Each instance is dynamically allocated on first attach. */ struct _nxge_t { dev_info_t *dip; /* device instance */ dev_info_t *p_dip; /* Parent's device instance */ int instance; /* instance number */ int function_num; /* device function number */ int nports; /* # of ports on this device */ int board_ver; /* Board Version */ int use_partition; /* partition is enabled */ uint32_t drv_state; /* driver state bit flags */ uint64_t nxge_debug_level; /* driver state bit flags */ kmutex_t genlock[1]; enum nxge_mac_state nxge_mac_state; p_dev_regs_t dev_regs; npi_handle_t npi_handle; npi_handle_t npi_pci_handle; npi_handle_t npi_reg_handle; npi_handle_t npi_msi_handle; npi_handle_t npi_vreg_handle; npi_handle_t npi_v2reg_handle; nxge_xcvr_table_t xcvr; boolean_t hot_swappable_phy; boolean_t phy_absent; uint32_t xcvr_addr; uint16_t chip_id; nxge_nlp_conn_t nlp_conn; nxge_phy_prop_t phy_prop; nxge_serdes_prop_t srds_prop; nxge_mac_t mac; nxge_ipp_t ipp; nxge_txc_t txc; nxge_classify_t classifier; mac_handle_t mach; /* mac module handle */ p_nxge_stats_t statsp; uint32_t param_count; p_nxge_param_t param_arr; uint32_t param_en_pause:1, param_en_asym_pause:1, param_en_1000fdx:1, param_en_100fdx:1, param_en_10fdx:1, param_pad_to_32:27; nxge_hw_list_t *nxge_hw_p; /* pointer to per Neptune */ niu_type_t niu_type; platform_type_t platform_type; boolean_t os_addr_mode32; /* set to 1 for 32 bit mode */ uint8_t def_rdc; nxge_intr_t nxge_intr_type; nxge_dma_pt_cfg_t pt_config; nxge_class_pt_cfg_t class_config; /* Logical device and group data structures. */ p_nxge_ldgv_t ldgvp; npi_vpd_info_t vpd_info; ether_addr_st factaddr; /* factory mac address */ ether_addr_st ouraddr; /* individual address */ boolean_t primary; /* primary addr set?. */ kmutex_t ouraddr_lock; /* lock to protect to uradd */ ddi_iblock_cookie_t interrupt_cookie; /* * Blocks of memory may be pre-allocated by the * partition manager or the driver. They may include * blocks for configuration and buffers. The idea is * to preallocate big blocks of contiguous areas in * system memory (i.e. with IOMMU). These blocks then * will be broken up to a fixed number of blocks with * each block having the same block size (4K, 8K, 16K or * 32K) in the case of buffer blocks. For systems that * do not support DVMA, more than one big block will be * allocated. */ uint32_t rx_default_block_size; nxge_rx_block_size_t rx_bksize_code; p_nxge_dma_pool_t rx_buf_pool_p; p_nxge_dma_pool_t rx_cntl_pool_p; p_nxge_dma_pool_t tx_buf_pool_p; p_nxge_dma_pool_t tx_cntl_pool_p; /* Receive buffer block ring and completion ring. */ p_rx_rbr_rings_t rx_rbr_rings; p_rx_rcr_rings_t rx_rcr_rings; p_rx_mbox_areas_t rx_mbox_areas_p; uint32_t rdc_mask; /* Transmit descriptors rings */ p_tx_rings_t tx_rings; p_tx_mbox_areas_t tx_mbox_areas_p; ddi_dma_handle_t dmasparehandle; ulong_t sys_page_sz; ulong_t sys_page_mask; int suspended; mii_bmsr_t bmsr; /* xcvr status at last poll. */ mii_bmsr_t soft_bmsr; /* xcvr status kept by SW. */ kmutex_t mif_lock; /* Lock to protect the list. */ void (*mii_read)(); void (*mii_write)(); void (*mii_poll)(); filter_t filter; /* Current instance filter */ p_hash_filter_t hash_filter; /* Multicast hash filter. */ krwlock_t filter_lock; /* Lock to protect filters. */ ulong_t sys_burst_sz; uint8_t cache_line; timeout_id_t nxge_link_poll_timerid; timeout_id_t nxge_timerid; uint_t need_periodic_reclaim; timeout_id_t reclaim_timer; uint8_t msg_min; uint8_t crc_size; boolean_t hard_props_read; uint32_t nxge_ncpus; uint16_t intr_timeout; uint16_t intr_threshold; int fm_capabilities; /* FMA capabilities */ uint32_t nxge_port_rbr_size; uint32_t nxge_port_rbr_spare_size; uint32_t nxge_port_rcr_size; uint32_t nxge_port_rx_cntl_alloc_size; uint32_t nxge_port_tx_ring_size; nxge_mmac_t nxge_mmac_info; #if defined(sun4v) boolean_t niu_hsvc_available; hsvc_info_t niu_hsvc; uint64_t niu_min_ver; #endif boolean_t link_notify; int link_check_count; kmutex_t poll_lock; kcondvar_t poll_cv; link_mon_enable_t poll_state; #define NXGE_MAGIC 0x3ab434e3 uint32_t nxge_magic; int soft_lso_enable; /* The following fields are LDOMs-specific additions. */ nxge_environs_t environs; ether_addr_t hio_mac_addr; uint32_t niu_cfg_hdl; kmutex_t group_lock; struct nxge_hio_vr *hio_vr; nxge_grp_set_t rx_set; nxge_grp_set_t tx_set; boolean_t tdc_is_shared[NXGE_MAX_TDCS]; /* Ring Handles */ nxge_ring_handle_t tx_ring_handles[NXGE_MAX_TDCS]; nxge_ring_handle_t rx_ring_handles[NXGE_MAX_RDCS]; nxge_ring_group_t tx_hio_groups[NXGE_MAX_TDC_GROUPS]; nxge_ring_group_t rx_hio_groups[NXGE_MAX_RDC_GROUPS]; nxge_share_handle_t shares[NXGE_MAX_VRS]; /* * KT-NIU: * KT family will have up to 4 NIUs per system. * Differences between N2/NIU and KT/NIU: * SerDes, Hypervisor interfaces, * additional NIU classification features. */ niu_hw_type_t niu_hw_type; }; /* * Driver state flags. */ #define STATE_REGS_MAPPED 0x000000001 /* device registers mapped */ #define STATE_KSTATS_SETUP 0x000000002 /* kstats allocated */ #define STATE_NODE_CREATED 0x000000004 /* device node created */ #define STATE_HW_CONFIG_CREATED 0x000000008 /* hardware properties */ #define STATE_HW_INITIALIZED 0x000000010 /* hardware initialized */ #define STATE_MDIO_LOCK_INIT 0x000000020 /* mdio lock initialized */ #define STATE_MII_LOCK_INIT 0x000000040 /* mii lock initialized */ #define STOP_POLL_THRESH 9 #define START_POLL_THRESH 2 typedef struct _nxge_port_kstat_t { /* * Transciever state informations. */ kstat_named_t xcvr_inits; kstat_named_t xcvr_inuse; kstat_named_t xcvr_addr; kstat_named_t xcvr_id; kstat_named_t cap_autoneg; kstat_named_t cap_10gfdx; kstat_named_t cap_10ghdx; kstat_named_t cap_1000fdx; kstat_named_t cap_1000hdx; kstat_named_t cap_100T4; kstat_named_t cap_100fdx; kstat_named_t cap_100hdx; kstat_named_t cap_10fdx; kstat_named_t cap_10hdx; kstat_named_t cap_asmpause; kstat_named_t cap_pause; /* * Link partner capabilities. */ kstat_named_t lp_cap_autoneg; kstat_named_t lp_cap_10gfdx; kstat_named_t lp_cap_10ghdx; kstat_named_t lp_cap_1000fdx; kstat_named_t lp_cap_1000hdx; kstat_named_t lp_cap_100T4; kstat_named_t lp_cap_100fdx; kstat_named_t lp_cap_100hdx; kstat_named_t lp_cap_10fdx; kstat_named_t lp_cap_10hdx; kstat_named_t lp_cap_asmpause; kstat_named_t lp_cap_pause; /* * Shared link setup. */ kstat_named_t link_T4; kstat_named_t link_speed; kstat_named_t link_duplex; kstat_named_t link_asmpause; kstat_named_t link_pause; kstat_named_t link_up; /* * Lets the user know the MTU currently in use by * the physical MAC port. */ kstat_named_t mac_mtu; kstat_named_t lb_mode; kstat_named_t qos_mode; kstat_named_t trunk_mode; /* * Misc MAC statistics. */ kstat_named_t ifspeed; kstat_named_t promisc; kstat_named_t rev_id; /* * Some statistics added to support bringup, these * should be removed. */ kstat_named_t user_defined; } nxge_port_kstat_t, *p_nxge_port_kstat_t; typedef struct _nxge_rdc_kstat { /* * Receive DMA channel statistics. */ kstat_named_t ipackets; kstat_named_t rbytes; kstat_named_t errors; kstat_named_t dcf_err; kstat_named_t rcr_ack_err; kstat_named_t dc_fifoflow_err; kstat_named_t rcr_sha_par_err; kstat_named_t rbr_pre_par_err; kstat_named_t wred_drop; kstat_named_t rbr_pre_emty; kstat_named_t rcr_shadow_full; kstat_named_t rbr_tmout; kstat_named_t rsp_cnt_err; kstat_named_t byte_en_bus; kstat_named_t rsp_dat_err; kstat_named_t pkt_too_long_err; kstat_named_t compl_l2_err; kstat_named_t compl_l4_cksum_err; kstat_named_t compl_zcp_soft_err; kstat_named_t compl_fflp_soft_err; kstat_named_t config_err; kstat_named_t rcrincon; kstat_named_t rcrfull; kstat_named_t rbr_empty; kstat_named_t rbrfull; kstat_named_t rbrlogpage; kstat_named_t cfiglogpage; kstat_named_t port_drop_pkt; kstat_named_t rcr_to; kstat_named_t rcr_thresh; kstat_named_t rcr_mex; kstat_named_t id_mismatch; kstat_named_t zcp_eop_err; kstat_named_t ipp_eop_err; } nxge_rdc_kstat_t, *p_nxge_rdc_kstat_t; typedef struct _nxge_rdc_sys_kstat { /* * Receive DMA system statistics. */ kstat_named_t pre_par; kstat_named_t sha_par; kstat_named_t id_mismatch; kstat_named_t ipp_eop_err; kstat_named_t zcp_eop_err; } nxge_rdc_sys_kstat_t, *p_nxge_rdc_sys_kstat_t; typedef struct _nxge_tdc_kstat { /* * Transmit DMA channel statistics. */ kstat_named_t opackets; kstat_named_t obytes; kstat_named_t oerrors; kstat_named_t tx_inits; kstat_named_t tx_no_buf; kstat_named_t mbox_err; kstat_named_t pkt_size_err; kstat_named_t tx_ring_oflow; kstat_named_t pref_buf_ecc_err; kstat_named_t nack_pref; kstat_named_t nack_pkt_rd; kstat_named_t conf_part_err; kstat_named_t pkt_prt_err; kstat_named_t reset_fail; /* used to in the common (per port) counter */ kstat_named_t tx_starts; kstat_named_t tx_nocanput; kstat_named_t tx_msgdup_fail; kstat_named_t tx_allocb_fail; kstat_named_t tx_no_desc; kstat_named_t tx_dma_bind_fail; kstat_named_t tx_uflo; kstat_named_t tx_hdr_pkts; kstat_named_t tx_ddi_pkts; kstat_named_t tx_dvma_pkts; kstat_named_t tx_max_pend; } nxge_tdc_kstat_t, *p_nxge_tdc_kstat_t; typedef struct _nxge_txc_kstat { /* * Transmit port TXC block statistics. */ kstat_named_t pkt_stuffed; kstat_named_t pkt_xmit; kstat_named_t ro_correct_err; kstat_named_t ro_uncorrect_err; kstat_named_t sf_correct_err; kstat_named_t sf_uncorrect_err; kstat_named_t address_failed; kstat_named_t dma_failed; kstat_named_t length_failed; kstat_named_t pkt_assy_dead; kstat_named_t reorder_err; } nxge_txc_kstat_t, *p_nxge_txc_kstat_t; typedef struct _nxge_ipp_kstat { /* * Receive port IPP block statistics. */ kstat_named_t eop_miss; kstat_named_t sop_miss; kstat_named_t dfifo_ue; kstat_named_t ecc_err_cnt; kstat_named_t pfifo_perr; kstat_named_t pfifo_over; kstat_named_t pfifo_und; kstat_named_t bad_cs_cnt; kstat_named_t pkt_dis_cnt; } nxge_ipp_kstat_t, *p_nxge_ipp_kstat_t; typedef struct _nxge_zcp_kstat { /* * ZCP statistics. */ kstat_named_t errors; kstat_named_t inits; kstat_named_t rrfifo_underrun; kstat_named_t rrfifo_overrun; kstat_named_t rspfifo_uncorr_err; kstat_named_t buffer_overflow; kstat_named_t stat_tbl_perr; kstat_named_t dyn_tbl_perr; kstat_named_t buf_tbl_perr; kstat_named_t tt_program_err; kstat_named_t rsp_tt_index_err; kstat_named_t slv_tt_index_err; kstat_named_t zcp_tt_index_err; kstat_named_t access_fail; kstat_named_t cfifo_ecc; } nxge_zcp_kstat_t, *p_nxge_zcp_kstat_t; typedef struct _nxge_mac_kstat { /* * Transmit MAC statistics. */ kstat_named_t tx_frame_cnt; kstat_named_t tx_underflow_err; kstat_named_t tx_overflow_err; kstat_named_t tx_maxpktsize_err; kstat_named_t tx_fifo_xfr_err; kstat_named_t tx_byte_cnt; /* * Receive MAC statistics. */ kstat_named_t rx_frame_cnt; kstat_named_t rx_underflow_err; kstat_named_t rx_overflow_err; kstat_named_t rx_len_err_cnt; kstat_named_t rx_crc_err_cnt; kstat_named_t rx_viol_err_cnt; kstat_named_t rx_byte_cnt; kstat_named_t rx_hist1_cnt; kstat_named_t rx_hist2_cnt; kstat_named_t rx_hist3_cnt; kstat_named_t rx_hist4_cnt; kstat_named_t rx_hist5_cnt; kstat_named_t rx_hist6_cnt; kstat_named_t rx_hist7_cnt; kstat_named_t rx_broadcast_cnt; kstat_named_t rx_mult_cnt; kstat_named_t rx_frag_cnt; kstat_named_t rx_frame_align_err_cnt; kstat_named_t rx_linkfault_err_cnt; kstat_named_t rx_local_fault_err_cnt; kstat_named_t rx_remote_fault_err_cnt; } nxge_mac_kstat_t, *p_nxge_mac_kstat_t; typedef struct _nxge_xmac_kstat { /* * XMAC statistics. */ kstat_named_t tx_frame_cnt; kstat_named_t tx_underflow_err; kstat_named_t tx_maxpktsize_err; kstat_named_t tx_overflow_err; kstat_named_t tx_fifo_xfr_err; kstat_named_t tx_byte_cnt; kstat_named_t rx_frame_cnt; kstat_named_t rx_underflow_err; kstat_named_t rx_overflow_err; kstat_named_t rx_crc_err_cnt; kstat_named_t rx_len_err_cnt; kstat_named_t rx_viol_err_cnt; kstat_named_t rx_byte_cnt; kstat_named_t rx_hist1_cnt; kstat_named_t rx_hist2_cnt; kstat_named_t rx_hist3_cnt; kstat_named_t rx_hist4_cnt; kstat_named_t rx_hist5_cnt; kstat_named_t rx_hist6_cnt; kstat_named_t rx_hist7_cnt; kstat_named_t rx_broadcast_cnt; kstat_named_t rx_mult_cnt; kstat_named_t rx_frag_cnt; kstat_named_t rx_frame_align_err_cnt; kstat_named_t rx_linkfault_err_cnt; kstat_named_t rx_remote_fault_err_cnt; kstat_named_t rx_local_fault_err_cnt; kstat_named_t rx_pause_cnt; kstat_named_t xpcs_deskew_err_cnt; kstat_named_t xpcs_ln0_symbol_err_cnt; kstat_named_t xpcs_ln1_symbol_err_cnt; kstat_named_t xpcs_ln2_symbol_err_cnt; kstat_named_t xpcs_ln3_symbol_err_cnt; } nxge_xmac_kstat_t, *p_nxge_xmac_kstat_t; typedef struct _nxge_bmac_kstat { /* * BMAC statistics. */ kstat_named_t tx_frame_cnt; kstat_named_t tx_underrun_err; kstat_named_t tx_max_pkt_err; kstat_named_t tx_byte_cnt; kstat_named_t rx_frame_cnt; kstat_named_t rx_byte_cnt; kstat_named_t rx_overflow_err; kstat_named_t rx_align_err_cnt; kstat_named_t rx_crc_err_cnt; kstat_named_t rx_len_err_cnt; kstat_named_t rx_viol_err_cnt; kstat_named_t rx_pause_cnt; kstat_named_t tx_pause_state; kstat_named_t tx_nopause_state; } nxge_bmac_kstat_t, *p_nxge_bmac_kstat_t; typedef struct _nxge_fflp_kstat { /* * FFLP statistics. */ kstat_named_t fflp_tcam_perr; kstat_named_t fflp_tcam_ecc_err; kstat_named_t fflp_vlan_perr; kstat_named_t fflp_hasht_lookup_err; kstat_named_t fflp_hasht_data_err[MAX_PARTITION]; } nxge_fflp_kstat_t, *p_nxge_fflp_kstat_t; typedef struct _nxge_mmac_kstat { kstat_named_t mmac_max_addr_cnt; kstat_named_t mmac_avail_addr_cnt; kstat_named_t mmac_addr1; kstat_named_t mmac_addr2; kstat_named_t mmac_addr3; kstat_named_t mmac_addr4; kstat_named_t mmac_addr5; kstat_named_t mmac_addr6; kstat_named_t mmac_addr7; kstat_named_t mmac_addr8; kstat_named_t mmac_addr9; kstat_named_t mmac_addr10; kstat_named_t mmac_addr11; kstat_named_t mmac_addr12; kstat_named_t mmac_addr13; kstat_named_t mmac_addr14; kstat_named_t mmac_addr15; kstat_named_t mmac_addr16; } nxge_mmac_kstat_t, *p_nxge_mmac_kstat_t; /* * Prototype definitions. */ nxge_status_t nxge_init(p_nxge_t); void nxge_uninit(p_nxge_t); void nxge_get64(p_nxge_t, p_mblk_t); void nxge_put64(p_nxge_t, p_mblk_t); void nxge_pio_loop(p_nxge_t, p_mblk_t); typedef void (*fptrv_t)(); timeout_id_t nxge_start_timer(p_nxge_t, fptrv_t, int); void nxge_stop_timer(p_nxge_t, timeout_id_t); #ifdef __cplusplus } #endif #endif /* _SYS_NXGE_NXGE_H */
26.026823
79
0.783092
[ "vector" ]
c036f5324ef77889f0b32bd681d56bf49cc19a9f
9,222
h
C
src/util.h
dglatting/attic-sensors
8f918e6dace124253e3214ecf42755c08097e406
[ "MIT" ]
null
null
null
src/util.h
dglatting/attic-sensors
8f918e6dace124253e3214ecf42755c08097e406
[ "MIT" ]
null
null
null
src/util.h
dglatting/attic-sensors
8f918e6dace124253e3214ecf42755c08097e406
[ "MIT" ]
null
null
null
/* -*- c++ -*- */ /* * Copyright (c) 2015,2018,2019 Dennis Glatting. * Copyright (c) 2018 atfCYBER. All Rights Reserved. * * 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. * * * This is a header file that holds common definitions, prototypes, * and a few inline functions used across the the client/server * objects and routines. The "common" are a sort of grab bag. * * * $Log: util.h,v $ * Revision 1.37 2019/10/19 01:07:19 root * Fixed minor formatting bug. * * Revision 1.36 2019/10/07 03:42:36 root * Shortened the function quoteStr(). * * Revision 1.35 2019/10/01 04:50:51 root * Changed a couple of decls. * * Revision 1.34 2019/09/27 07:41:57 root * Introduced "structured bindings." e=enum,i=int,f=float,b=bits,m=mask. * * Revision 1.33 2019/09/26 19:04:30 root * Added errno2str() with void param because sometimes the param is * errno itself. * * Revision 1.32 2019/09/26 04:48:02 root * Removed __ signed/unsigned integer decls. * * Revision 1.31 2019/09/10 04:34:16 root * Added a function similar to Python's round(). * * Revision 1.30 2019/09/04 04:23:47 root * Added MIT copyright notice. * * Revision 1.29 2019/08/27 07:09:13 root * It crashes the kernel, so that's nice. * * Revision 1.28 2019/08/27 01:01:34 root * Adding additional utilities to source. * * Revision 1.27 2018/08/21 21:47:30 root * Created/implemented a bunch of utility subroutines to standardize * print output and reduce memory errors. * * Revision 1.26 2018/08/20 09:18:41 root * Logging subsysten to reduce the boost bloat. * / * * Revision 1.25 2018/08/17 08:40:13 root * Modified string_for() for better memory utilization. Added function * to dump the string map for debug. * * Revision 1.24 2018/08/16 10:34:08 root * Added a common regex flag def for identities. Added a string_for() * for char*. * * Revision 1.23 2018/08/11 04:33:07 root * Lazy keys were a bad idea. * * Revision 1.22 2018/08/04 04:40:08 root * First integration of lazy key pre-debug. * * Revision 1.21 2018/07/21 06:47:01 root * Removed unneeded #include statements. * * Revision 1.20 2018/07/20 06:09:02 root * IPv4 now works. * Added template wrappers for the Berkeley socket functions. * * Revision 1.19 2018/07/18 09:30:47 root * Too many changes to comment on. * * Revision 1.18 2018/07/11 09:15:19 root * I moved usage() to opts.cc where it was closer to the options. * * Revision 1.17 2018/07/04 08:44:34 root * Forced check-in of a working branch of code before the next round * of revisions. This version ran for 24 hours across a 3x3 node WiFi * network, consuming ~12Mb/sec of bandwidth and showing no apparent * memory of leakages. The next version of this code is to organise * key from tiered arrays into sets with individual keys (elements) * belonging to a set, resulting in sets of sets. The "array" and * "name" identifiers will be respectably replaced with "set" and * "elem"(element). Code will be added to form intersections of * sets. Code will also be added (i.e., SQLite) to store elements * (keys) in a database where should be more manageable in standard * form. * * Revision 1.16 2018/07/02 02:57:48 root * Client and server are now talking TCP/TLS although some more * debugging is necessary. * * Revision 1.15 2018/06/29 07:05:07 root * Restructured the _ntoa() routines and added some new utility * function declarations. * * Revision 1.14 2018/06/27 17:49:47 root * In c++ threads cannot create threads. That means redesign of the server. * * Revision 1.13 2018/06/26 00:33:06 root * I forgot a header file. * * Revision 1.12 2018/06/26 00:00:21 root * Added more utility routines. * * Revision 1.11 2018/06/16 00:56:49 root * Added atfCYBER copyright. * * Revision 1.10 2018/06/15 07:23:19 root * The client and server now talk to each other. * * Revision 1.9 2018/06/12 05:48:41 root * Everything compiles and links. Now on to actual client/server testing. * Will enable selection between IPv6/IPv4 in future. * Will optimize threading in server in future. * * Revision 1.8 2018/06/06 01:53:45 root * The client code compiles and links. Archiving before debug. * * Revision 1.7 2018/06/05 18:14:31 root * At this point the client compiles but does not link, which is * expected. I'm saving a copy of the files before I start that * part of the work. * * Revision 1.5 2016/07/14 00:09:57 root * Modified the key extractor to modulo key size. * * Revision 1.4 2015/12/27 08:28:14 root * *** empty log message *** * * Revision 1.3 2015/12/22 02:00:50 root * Saving a working copy. * * Revision 1.2 2015/12/14 01:30:58 root * *** empty log message *** * * Revision 1.1 2015/12/07 00:08:21 root * Initial revision * */ #ifndef __UTIL_H__ #define __UTIL_H__ extern "C" { #include <assert.h> #include <sys/types.h> } #include <chrono> #include <memory> #include <regex> #include <sstream> #include <string> #include <thread> #include "opts.h" #define _UTIL_H_ID "$Id: util.h,v 1.37 2019/10/19 01:07:19 root Exp $" // Make modulo math work the way I want it to work. inline int modulo( int m, int n ) { return m >= 0 ? m % n : ( n - std::abs( m % n )) % n; } // Round up a number to the number of digits after the decimal // point. For example, roundup( 1.37, 1 ) = 1.4. float roundz( const float num, const u_int digits ); // A handle little routine I like to use to manage dirty work. inline std::time_t t_now( void ) { return std::chrono::system_clock::to_time_t ( std::chrono::system_clock::now()); } // Return a thread ID is a commonly used printable form. const std::string _tid( std::thread::id ); inline const std::string _tid( void ) { return _tid( std::this_thread::get_id()); } // Convert a binary string into ASCII hexadecimal form const std::string _vtoa( const std::vector<uint8_t>& v ); const std::string _vtoa( const u_char* v, size_t len ); // Convert certain data types into hexadecimal strings suitable for // printing - "type to hex." const std::string t2hex( u_int ); const std::string t2hex( u_short ); const std::string t2hex( u_char ); inline const std::string t2hex( int w ) { return t2hex( u_int( w )); } inline const std::string t2Hex( short w ) { return t2hex( u_short( w )); } inline const std::string t2hex( char w ) { return t2hex( u_char( w )); } // This function is used by routines to log regex match // information. This routine logs as verbose. void _log_match( const std::cmatch& m ); // Return a commonly formatted errno string for inclusion in a log // line. const std::string errno2str( const int ); inline const std::string errno2str( void ) { return errno2str( errno ); } // Return something quoted. const std::string quote( const std::string& ); const std::string quote( const int& ); const std::string quote( const char& ); inline const std::string quote( const char* s ) { assert( s ); return quote( std::string( s )); } // Bit shift functions. // // Since this application is i2c oriented, the shift is limited to 8 // bits. inline uint8_t _bit_shift_left( int s ) { assert(( s >= 0 ) && ( s <= 7 )); static const std::vector< uint8_t > b { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80 }; return b[ s ]; } inline uint8_t _bit_shift_right( int s ) { assert(( s >= 0 ) && ( s <= 7 )); static const std::vector< uint8_t > b { 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 }; return b[ s ]; } // Return a thing inside parenthesis. const std::string parenQuote( const char* ); const std::string parenQuote( const std::string& ); const std::string paren( const int ); const std::string paren( const u_int ); const std::string paren( const long ); const std::string paren( const u_long ); const std::string paren( const char* ); const std::string paren( const std::string& ); // Template used to create a std::unique_ptr<> with a custom deleter template< typename T > using deleted_unique_ptr = std::unique_ptr< T, std::function<void(T*)>>; #endif // LocalWords: PSK crypto BeagleBone getpeername URI URIs errno
26.198864
75
0.691824
[ "vector" ]
c03a10e43c182892a557075839989ce1948edef9
9,599
h
C
common/Common.h
xcheng85/OpenGLSandbox
ae976e1d12fb43870b3683c3c45de85f43ca260d
[ "MIT" ]
1
2020-06-22T15:22:58.000Z
2020-06-22T15:22:58.000Z
common/Common.h
xcheng85/OpenGLSandbox
ae976e1d12fb43870b3683c3c45de85f43ca260d
[ "MIT" ]
null
null
null
common/Common.h
xcheng85/OpenGLSandbox
ae976e1d12fb43870b3683c3c45de85f43ca260d
[ "MIT" ]
null
null
null
#pragma once #include <assert.h> #include <string> #include <vector> #include <memory> namespace OpenGLSandbox { namespace Common { inline static const unsigned int MAX_ATTRIBUTES = 16; enum class DataType { UNSIGNED_INT_8, UNSIGNED_INT_16, UNSIGNED_INT_32, UNSIGNED_INT_64, INT_8, INT_16, INT_32, INT_64, FLOAT_16, FLOAT_32, FLOAT_64, NUM_DATATYPES, UNKNOWN }; inline size_t getSizeOf(DataType dataType) { switch (dataType) { case DataType::INT_8: case DataType::UNSIGNED_INT_8: return 1; case DataType::INT_16: case DataType::UNSIGNED_INT_16: case DataType::FLOAT_16: return 2; case DataType::INT_32: case DataType::UNSIGNED_INT_32: case DataType::FLOAT_32: return 4; case DataType::INT_64: case DataType::UNSIGNED_INT_64: case DataType::FLOAT_64: return 8; case DataType::UNKNOWN: return 0; default: assert(false); return 0; } }; // VertexFormatInfo // represent one such as position or normal or tex struct VertexInputAttributeDescription { uint8_t bindingIndex; // layout = 0, 1, 2 uint8_t streamId; // 8 bit is enough, position and normal may be in different buffer size_t offset; // size_t stride; // bool normalized; // ?? DataType dataType; //float, int, uint8_t numComponents; // ivec2, vec3, dvec4, etc. }; struct VertexInputAttributeCreateInfo { std::vector<VertexInputAttributeDescription> vertexInputAttributes; }; class IVertexInputAttribute { public: virtual ~IVertexInputAttribute(){}; }; enum class BufferFormat { UNKNOWN, FLOAT, FLOAT2, FLOAT3, FLOAT4, INT_8, INT2_8, INT3_8, INT4_8, INT_16, INT2_16, INT3_16, INT4_16, INT_32, INT2_32, INT3_32, INT4_32, UINT_8, UINT2_8, UINT3_8, UINT4_8, UINT_16, UINT2_16, UINT3_16, UINT4_16, UINT_32, UINT2_32, UINT3_32, UINT4_32, NATIVE, NUM_BUFFERFORMATS }; enum class AccessType { NONE, READ_ONLY, WRITE_ONLY, READ_WRITE }; enum class BufferCreateInfoType { GL, VULKAN, DX }; struct BufferCreateInfo { BufferCreateInfo(BufferCreateInfoType type = BufferCreateInfoType::GL) : type(type) { } virtual ~BufferCreateInfo() { } BufferCreateInfoType type; }; class IBuffer { public: virtual ~IBuffer(){}; }; // number of vertices // each vertices have different vertex attributes, they can come from different buffer, or come from same buffer with different offset // multiple buffers/streams // each has different offset in that stream could be different // buffer use as a source of vertex buffer, // reference vulkan vkCmdBindVertexBuffers struct VertexInputBindingCreateInfo { //binding slot, pBuffer and offset std::vector<std::tuple<size_t, IBuffer *, size_t>> bufferDescs; size_t numVertices; }; class IVertexInputBinding { public: virtual ~IVertexInputBinding(){}; }; struct PipelineVertexInputStateCreateInfo { IVertexInputBinding *pVertexInputBinding; IVertexInputAttribute *pVertexInputAttribute; }; class IPipelineVertexInputState { public: virtual ~IPipelineVertexInputState(){}; }; struct IndexBufferCreateInfo { IBuffer *buffer; size_t offset; size_t count; DataType indexType; // uint16, uint32 }; class IIndexBuffer { public: virtual ~IIndexBuffer(){}; }; enum class InternalTextureFormat { R8, R16, RG8, RG16, RGB8, RGB16, RGBA8, RGBA16, R16F, RG16F, RGB16F, RGBA16F, R32F, RG32F, RGB32F, RGBA32F, R8I, R8UI, R16I, R16UI, R32I, R32UI, RG8I, RG8UI, RG16I, RG16UI, RG32I, RG32UI, RGB8I, RGB8UI, RGB16I, RGB16UI, RGB32I, RGB32UI, RGBA8I, RGBA8UI, RGBA16I, RGBA16UI, RGBA32I, RGBA32UI, COMPRESSED_R, COMPRESSED_RG, COMPRESSED_RGB, COMPRESSED_RGBA, COMPRESSED_SRGB, COMPRESSED_SRGB_ALPHA, ALPHA, LUMINANCE, LUMINANCE_ALPHA, RGB, RGBA, NATIVE, NUM_INTERNALTEXTUREFORMATS }; // for cube maps, either use a native data type // or pass in the faces via TextureDataPtr // with 6 layers: +x,-x,+y,-y,+z,-z enum class TextureType { _1D, _1D_ARRAY, _2D, _2D_ARRAY, _3D, BUFFER, CUBEMAP, //CUBEMAP_ARRAY, NATIVE, NUM_TEXTURETYPES }; enum class TextureDataType { POINTER, BUFFER, NATIVE, // shared resource coming from glWrapper NUM_TEXTUREDATATYPES }; enum class PixelFormat { R, RG, RGB, RGBA, BGR, BGRA, LUMINANCE, ALPHA, LUMINANCE_ALPHA, DEPTH_COMPONENT, DEPTH_STENCIL, STENCIL_INDEX, NATIVE, NUM_PIXELFORMATS, UNKNOWN }; struct TextureCreateInfo { virtual ~TextureCreateInfo(){}; TextureType type; InternalTextureFormat internalFormat; PixelFormat pixelFormat; DataType dataType; size_t width; size_t height; size_t depth; size_t numLayers; bool useMipmaps; }; class TextureData { public: TextureData(TextureDataType type); virtual ~TextureData(); TextureDataType getTextureDataType() const { return type; } private: TextureDataType type; }; class TextureDataBuffer : public TextureData { public: TextureDataBuffer(const std::shared_ptr<IBuffer> &buffer); private: std::shared_ptr<IBuffer> buffer_; }; class TextureDataPtr : public TextureData { public: // real data TextureDataPtr(const void *data, PixelFormat pixelFormat, DataType pixelDataType); // 2d : mipmap0...n TextureDataPtr(const void *const *data, unsigned int numMipMapLevels, PixelFormat pixelFormat, DataType pixelDataType); // 2d : lay0: mimap0...n lay1: mimap0...n TextureDataPtr(const void *const *data, unsigned int numMipMapLevels, unsigned int numLayers, PixelFormat pixelFormat, DataType pixelDataType); inline auto getPixelFormat() const { return pixelFormat_; } inline auto getDataType() const { return dataType_; } inline auto getNumMipMapLevels() const { return numMipMapLevels_; } inline auto getNumLayers() const { return numLayers_; } // return raw ptr, could read/write auto getDataPtr() const { return pData_; }; private: // //const void *pData_; // could be hetregenous vector to some pointer, float array void const *const *pData_; // vector of vector, 1darray, cubemap // array of pointer unsigned int numLayers_; unsigned int numMipMapLevels_; PixelFormat pixelFormat_; DataType dataType_; }; class ITexture { public: virtual ~ITexture(){}; }; }; // namespace Common }; // namespace OpenGLSandbox
24.932468
155
0.474945
[ "vector" ]
c03f701615430d3899015e48c3371f768e693e57
8,476
h
C
aws-cpp-sdk-kms/include/aws/kms/model/ScheduleKeyDeletionResult.h
Nexuscompute/aws-sdk-cpp
e7ef485e46e6962c9e084b8c9b104c1bfcceaf26
[ "Apache-2.0" ]
1
2022-01-05T18:20:03.000Z
2022-01-05T18:20:03.000Z
aws-cpp-sdk-kms/include/aws/kms/model/ScheduleKeyDeletionResult.h
Nexuscompute/aws-sdk-cpp
e7ef485e46e6962c9e084b8c9b104c1bfcceaf26
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-kms/include/aws/kms/model/ScheduleKeyDeletionResult.h
Nexuscompute/aws-sdk-cpp
e7ef485e46e6962c9e084b8c9b104c1bfcceaf26
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/kms/KMS_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/DateTime.h> #include <aws/kms/model/KeyState.h> #include <utility> namespace Aws { template<typename RESULT_TYPE> class AmazonWebServiceResult; namespace Utils { namespace Json { class JsonValue; } // namespace Json } // namespace Utils namespace KMS { namespace Model { class AWS_KMS_API ScheduleKeyDeletionResult { public: ScheduleKeyDeletionResult(); ScheduleKeyDeletionResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); ScheduleKeyDeletionResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); /** * <p>The Amazon Resource Name (<a * href="https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-key-ARN">key * ARN</a>) of the KMS key whose deletion is scheduled.</p> */ inline const Aws::String& GetKeyId() const{ return m_keyId; } /** * <p>The Amazon Resource Name (<a * href="https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-key-ARN">key * ARN</a>) of the KMS key whose deletion is scheduled.</p> */ inline void SetKeyId(const Aws::String& value) { m_keyId = value; } /** * <p>The Amazon Resource Name (<a * href="https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-key-ARN">key * ARN</a>) of the KMS key whose deletion is scheduled.</p> */ inline void SetKeyId(Aws::String&& value) { m_keyId = std::move(value); } /** * <p>The Amazon Resource Name (<a * href="https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-key-ARN">key * ARN</a>) of the KMS key whose deletion is scheduled.</p> */ inline void SetKeyId(const char* value) { m_keyId.assign(value); } /** * <p>The Amazon Resource Name (<a * href="https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-key-ARN">key * ARN</a>) of the KMS key whose deletion is scheduled.</p> */ inline ScheduleKeyDeletionResult& WithKeyId(const Aws::String& value) { SetKeyId(value); return *this;} /** * <p>The Amazon Resource Name (<a * href="https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-key-ARN">key * ARN</a>) of the KMS key whose deletion is scheduled.</p> */ inline ScheduleKeyDeletionResult& WithKeyId(Aws::String&& value) { SetKeyId(std::move(value)); return *this;} /** * <p>The Amazon Resource Name (<a * href="https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-key-ARN">key * ARN</a>) of the KMS key whose deletion is scheduled.</p> */ inline ScheduleKeyDeletionResult& WithKeyId(const char* value) { SetKeyId(value); return *this;} /** * <p>The date and time after which KMS deletes the KMS key.</p> <p>If the KMS key * is a multi-Region primary key with replica keys, this field does not appear. The * deletion date for the primary key isn't known until its last replica key is * deleted.</p> */ inline const Aws::Utils::DateTime& GetDeletionDate() const{ return m_deletionDate; } /** * <p>The date and time after which KMS deletes the KMS key.</p> <p>If the KMS key * is a multi-Region primary key with replica keys, this field does not appear. The * deletion date for the primary key isn't known until its last replica key is * deleted.</p> */ inline void SetDeletionDate(const Aws::Utils::DateTime& value) { m_deletionDate = value; } /** * <p>The date and time after which KMS deletes the KMS key.</p> <p>If the KMS key * is a multi-Region primary key with replica keys, this field does not appear. The * deletion date for the primary key isn't known until its last replica key is * deleted.</p> */ inline void SetDeletionDate(Aws::Utils::DateTime&& value) { m_deletionDate = std::move(value); } /** * <p>The date and time after which KMS deletes the KMS key.</p> <p>If the KMS key * is a multi-Region primary key with replica keys, this field does not appear. The * deletion date for the primary key isn't known until its last replica key is * deleted.</p> */ inline ScheduleKeyDeletionResult& WithDeletionDate(const Aws::Utils::DateTime& value) { SetDeletionDate(value); return *this;} /** * <p>The date and time after which KMS deletes the KMS key.</p> <p>If the KMS key * is a multi-Region primary key with replica keys, this field does not appear. The * deletion date for the primary key isn't known until its last replica key is * deleted.</p> */ inline ScheduleKeyDeletionResult& WithDeletionDate(Aws::Utils::DateTime&& value) { SetDeletionDate(std::move(value)); return *this;} /** * <p>The current status of the KMS key.</p> <p>For more information about how key * state affects the use of a KMS key, see <a * href="https://docs.aws.amazon.com/kms/latest/developerguide/key-state.html">Key * states of KMS keys</a> in the <i>Key Management Service Developer Guide</i>.</p> */ inline const KeyState& GetKeyState() const{ return m_keyState; } /** * <p>The current status of the KMS key.</p> <p>For more information about how key * state affects the use of a KMS key, see <a * href="https://docs.aws.amazon.com/kms/latest/developerguide/key-state.html">Key * states of KMS keys</a> in the <i>Key Management Service Developer Guide</i>.</p> */ inline void SetKeyState(const KeyState& value) { m_keyState = value; } /** * <p>The current status of the KMS key.</p> <p>For more information about how key * state affects the use of a KMS key, see <a * href="https://docs.aws.amazon.com/kms/latest/developerguide/key-state.html">Key * states of KMS keys</a> in the <i>Key Management Service Developer Guide</i>.</p> */ inline void SetKeyState(KeyState&& value) { m_keyState = std::move(value); } /** * <p>The current status of the KMS key.</p> <p>For more information about how key * state affects the use of a KMS key, see <a * href="https://docs.aws.amazon.com/kms/latest/developerguide/key-state.html">Key * states of KMS keys</a> in the <i>Key Management Service Developer Guide</i>.</p> */ inline ScheduleKeyDeletionResult& WithKeyState(const KeyState& value) { SetKeyState(value); return *this;} /** * <p>The current status of the KMS key.</p> <p>For more information about how key * state affects the use of a KMS key, see <a * href="https://docs.aws.amazon.com/kms/latest/developerguide/key-state.html">Key * states of KMS keys</a> in the <i>Key Management Service Developer Guide</i>.</p> */ inline ScheduleKeyDeletionResult& WithKeyState(KeyState&& value) { SetKeyState(std::move(value)); return *this;} /** * <p>The waiting period before the KMS key is deleted. </p> <p>If the KMS key is a * multi-Region primary key with replicas, the waiting period begins when the last * of its replica keys is deleted. Otherwise, the waiting period begins * immediately.</p> */ inline int GetPendingWindowInDays() const{ return m_pendingWindowInDays; } /** * <p>The waiting period before the KMS key is deleted. </p> <p>If the KMS key is a * multi-Region primary key with replicas, the waiting period begins when the last * of its replica keys is deleted. Otherwise, the waiting period begins * immediately.</p> */ inline void SetPendingWindowInDays(int value) { m_pendingWindowInDays = value; } /** * <p>The waiting period before the KMS key is deleted. </p> <p>If the KMS key is a * multi-Region primary key with replicas, the waiting period begins when the last * of its replica keys is deleted. Otherwise, the waiting period begins * immediately.</p> */ inline ScheduleKeyDeletionResult& WithPendingWindowInDays(int value) { SetPendingWindowInDays(value); return *this;} private: Aws::String m_keyId; Aws::Utils::DateTime m_deletionDate; KeyState m_keyState; int m_pendingWindowInDays; }; } // namespace Model } // namespace KMS } // namespace Aws
40.94686
136
0.674729
[ "model" ]
c0436c27851b0be94d3d6337942cefa681a0490e
7,749
h
C
src/format.h
TarCV/botc
96dab0ac7c81dfbbfdaa18ca7a0dd3c7541ff674
[ "BSD-3-Clause" ]
1
2020-04-15T21:08:26.000Z
2020-04-15T21:08:26.000Z
src/format.h
TarCV/botc
96dab0ac7c81dfbbfdaa18ca7a0dd3c7541ff674
[ "BSD-3-Clause" ]
16
2019-02-03T05:52:49.000Z
2021-08-14T17:15:20.000Z
src/format.h
TarCV/botc
96dab0ac7c81dfbbfdaa18ca7a0dd3c7541ff674
[ "BSD-3-Clause" ]
1
2020-04-04T11:45:53.000Z
2020-04-04T11:45:53.000Z
/* Copyright 2012-2014 Teemu Piippo Copyright 2019-2020 TarCV 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. */ #ifndef BOTC_FORMAT_H #define BOTC_FORMAT_H #include <vector> #include "stringClass.h" #include "list.h" #include "enumstrings.h" inline String MakeFormatArgument (const String& a) { return a; } inline String MakeFormatArgument (char a) { return String (a); } inline String MakeFormatArgument (int a) { return String::fromNumber (a); } inline String MakeFormatArgument (long a) { return String::fromNumber (a); } inline String MakeFormatArgument (long long a) { return String::fromNumber (a); } inline String MakeFormatArgument (double a) { return String::fromNumber (a); } inline String MakeFormatArgument (size_t a) { return String::fromNumber (long (a)); } inline String MakeFormatArgument (const char* a) { return a; } inline String MakeFormatArgument (const void* a) { String text; text.sprintf ("%p", a); return text; } inline String MakeFormatArgument (std::nullptr_t) { return "(nullptr)"; } template<class T> inline String MakeFormatArgument (List<T> const& list) { String result; if (list.isEmpty()) return "{}"; result = "{ "; for (auto it = list.begin(); it != list.end(); ++it) { if (it != list.begin()) result += ", "; result += MakeFormatArgument (*it); } result += " }"; return result; } class FormatArgument { public: template<typename T> FormatArgument (const T& a) : m_text (MakeFormatArgument (a)) {} inline const String& text() const { return m_text; } private: String m_text; }; #ifndef IN_IDE_PARSER # ifdef DEBUG # define devf(...) PrintTo (stderr, __VA_ARGS__) # define dvalof( A ) PrintTo (stderr, "value of '%1' = %2\n", #A, A) # else # define devf(...) # define dvalof( A ) # endif // DEBUG #else // print something in debug builds void devf (void, ...); // print the value of @a void dvalof (void a); #endif // IN_IDE_PARSER // _________________________________________________________________________________________________ // // Formats the given string with the given args. // String formatArgs (const String& fmtstr, const std::vector<String>& args); // _________________________________________________________________________________________________ // // Expands the given arguments into a vector of strings. // template<typename T, typename... RestTypes> void expandFormatArguments (std::vector<String>& data, const T& arg, const RestTypes& ... rest) { data.push_back (FormatArgument (arg).text()); expandFormatArguments (data, rest...); } static void expandFormatArguments (std::vector<String>& data) __attribute__ ( (unused)); static void expandFormatArguments (std::vector<String>& data) { (void) data; } // _________________________________________________________________________________________________ // // Formats the given formatter string and args and returns the string. // This is essentially a modernized sprintf. // // Args in the format string take the form %n where n is a digit. The argument // will be expanded to the nth argument passed. This is essentially Qt's // QString::arg() syntax. Note: %0 is invalid. // // Arguments can be passed a modifier which takes the form of a character // just before the digit. Currently supported modifiers are s, d and x. // // - s: The argument will expand into "s" if it would've not expanded into "1" // otherwise. If it would have expanded into "1" it will expand into an // empty string. // // - d: The argument expands into the numeric form of the first character of // its previous expansion. Use this to get numeric forms of @c char // arguments. // // - x: The numeric argument will be represented in hexadecimal notation. This // will work if the argument is a string representing a number. If the // argument did not expand into a number in the first place, 0 is used // and 0x0 is printed. // template<typename... argtypes> String format (const String& fmtstr, const argtypes&... raw_args) { std::vector<String> args; expandFormatArguments (args, raw_args...); ASSERT_EQ (args.size(), sizeof... (raw_args)) return formatArgs (fmtstr, args); } // _________________________________________________________________________________________________ // // This is an overload of format() where no arguments are supplied. // It returns the formatter string as-is. // static String format (const String& fmtstr) __attribute__ ( (unused)); static String format (const String& fmtstr) { return fmtstr; } // _________________________________________________________________________________________________ // // Processes the given formatter string using format() and prints it to the // specified file pointer. // template<typename... argtypes> void printTo (FILE* fp, const String& fmtstr, const argtypes&... args) { fprintf (fp, "%s", format (fmtstr, args...).c_str()); } // _________________________________________________________________________________________________ // // Processes the given formatter string using format() and appends it to the // specified file by name. // template<typename... argtypes> void printTo (const String& filename, const String& fmtstr, const argtypes&... args) { FILE* fp = fopen (filename, "a"); if (fp != null) { fprintf (fp, "%s", format (fmtstr, args...).c_str()); fflush (fp); fclose (fp); } } // _________________________________________________________________________________________________ // // Processes the given formatter string using format() and prints the result to // stdout. // template<typename... argtypes> void print (const String& fmtstr, const argtypes&... args) { printTo (stdout, fmtstr, args...); } // _________________________________________________________________________________________________ // // Throws an std::runtime_error with the processed formatted string. The program // execution terminates after a call to this function as the exception is first // caught in main() which prints the error to stderr and then exits. // template<typename... argtypes> void error (const char* fmtstr, const argtypes&... args) { error (format (String (fmtstr), args...)); } // // An overload of error() with no string formatting in between. // void error (const String& msg); #endif // BOTC_FORMAT_H
28.384615
100
0.743451
[ "vector" ]
c059bcc78e065e511be1c8b6b444b342f05c62bb
1,136
h
C
source/bloc.h
deyahruhd/terramagna
931887afad11c6cf2c071cac9fc0ed24a15067de
[ "MIT" ]
null
null
null
source/bloc.h
deyahruhd/terramagna
931887afad11c6cf2c071cac9fc0ed24a15067de
[ "MIT" ]
null
null
null
source/bloc.h
deyahruhd/terramagna
931887afad11c6cf2c071cac9fc0ed24a15067de
[ "MIT" ]
null
null
null
#ifndef BLOC_h #define BLOC_h #include "vec.h" #include <vector> #include "color.h" #define world_bloc_width 32 namespace game { class vertexbuffer; class bloc { public: bloc (vec3 position); bloc (vec3 position, vec3 bounds); bloc (void); ~bloc (void); void clear (void); const color get (vec3 loc) const; const color get (unsigned int loc) const; const vec3 get_bounds (void) const; const vec3 get_position (void) const; bool is_full (void) const; bool is_null (void) const; void reinitialize (void); void resize (void); bool set (vec3 loc, color c); bool set (unsigned int loc, color c); void set_bounds (vec3 bounds); void set_position (vec3 position); private: vec3 bounds, prev_bounds, position; std::vector <int> data; void initialize (void); }; unsigned int get_1d_index (vec3 loc, vec3 bounds); vec3 get_3d_index (unsigned int loc, vec3 bounds); void populate (vertexbuffer & ve, bloc & b); void populate (vertexbuffer & ve, vertexbuffer & ve_bounding_box, vertexbuffer & ve_grid, bloc & b); } #endif
21.037037
102
0.661972
[ "vector" ]
c062098e074382fd135a2984408017a1ac097f6a
2,919
h
C
Src/Engine_Interface/UIControl.h
dingpong/Old-GameEngine-BaseProject
a04d634dcfe04300525198b26d167603299bd4ac
[ "MIT" ]
null
null
null
Src/Engine_Interface/UIControl.h
dingpong/Old-GameEngine-BaseProject
a04d634dcfe04300525198b26d167603299bd4ac
[ "MIT" ]
null
null
null
Src/Engine_Interface/UIControl.h
dingpong/Old-GameEngine-BaseProject
a04d634dcfe04300525198b26d167603299bd4ac
[ "MIT" ]
null
null
null
#ifndef __UICONTROL_H__ #define __UICONTROL_H__ //----------------------------------------------------------------------------- // Base class for controls //----------------------------------------------------------------------------- class __declspec(dllexport) cUIControl { public: cUIControl( cUIDialog *pDialog = NULL ); virtual ~cUIControl(); virtual HRESULT OnInit() { return S_OK; } virtual void Refresh(); virtual void Render( IDirect3DDevice9* pd3dDevice ) { }; // Windows message handler virtual BOOL MsgProc( UINT uMsg, WPARAM wParam, LPARAM lParam ) { return FALSE; } virtual BOOL HandleKeyboard( UINT uMsg, WPARAM wParam, LPARAM lParam ) { return FALSE; } virtual BOOL HandleMouse( UINT uMsg, POINT pt, WPARAM wParam, LPARAM lParam ) { return FALSE; } virtual BOOL CanHaveFocus() { return FALSE; } virtual void OnFocusIn() { m_bHasFocus = TRUE; } virtual void OnFocusOut() { m_bHasFocus = FALSE; } virtual void OnMouseEnter() { m_bMouseOver = TRUE; } virtual void OnMouseLeave() { m_bMouseOver = FALSE; } virtual void OnHotkey() {} virtual BOOL ContainsPoint( POINT pt ) { return PtInRect( &m_rcBoundingBox, pt ); } virtual void SetEnabled( BOOL bEnabled ) { m_bEnabled = bEnabled; } virtual BOOL GetEnabled() { return m_bEnabled; } virtual void SetVisible( BOOL bVisible ) { m_bVisible = bVisible; } virtual BOOL GetVisible() { return m_bVisible; } UINT GetType() const { return m_Type; } int GetIDC() const { return m_IDC; } void SetIDC( int IDC ) { m_IDC = IDC; } int GetIDE() const { return m_IDE; } void SetIDE( int IDE ) { m_IDE = IDE; } void SetLocation( int x, int y ) { m_x = x; m_y = y; UpdateRects(); } void SetSize( int width, int height ) { m_width = width; m_height = height; UpdateRects(); } void SetHotkey( UINT nHotkey ) { m_nHotkey = nHotkey; } UINT GetHotkey() { return m_nHotkey; } void SetUserData( void *pUserData ) { m_pUserData = pUserData; } void *GetUserData() const { return m_pUserData; } BOOL m_bVisible; // Shown/hidden flag BOOL m_bMouseOver; // Mouse pointer is above control BOOL m_bHasFocus; // Control has input focus BOOL m_bIsDefault; // Is the default control // Size, scale, and positioning members int m_x, m_y; int m_width, m_height; // These members are set by the container cUIDialog* m_pDialog; // Parent container UINT m_Index; // Index within the control list protected: virtual void UpdateRects(); int m_IDC; // control ID number int m_IDE; // element ID number UI_CONTROL_TYPE m_Type; // Control type, set once in constructor UINT m_nHotkey; // Virtual key code for this control's hotkey void* m_pUserData; // Data associated with this control that is set by user. BOOL m_bEnabled; // Enable/disabled flag RECT m_rcBoundingBox; // Rectangle defining the active region of the control }; #include "UIStatic.h" #endif
34.75
96
0.664954
[ "render" ]
c0718511b5cf5c0a2954dc2c43fa568e3f060a6d
850
h
C
src/ui/Screen.h
mcmatrix/cnc3018-offline-controller
604e63a1f39e0742ba4f8c7e4cf2bad8d5b67e47
[ "MIT" ]
14
2021-09-10T18:33:43.000Z
2022-02-12T12:00:20.000Z
src/ui/Screen.h
mcmatrix/cnc3018-offline-controller
604e63a1f39e0742ba4f8c7e4cf2bad8d5b67e47
[ "MIT" ]
7
2021-10-02T13:00:01.000Z
2022-03-31T10:15:04.000Z
src/ui/Screen.h
mcmatrix/cnc3018-offline-controller
604e63a1f39e0742ba4f8c7e4cf2bad8d5b67e47
[ "MIT" ]
4
2021-09-15T11:56:24.000Z
2022-02-14T12:11:30.000Z
#pragma once #include <Arduino.h> #include <U8g2lib.h> #include <etl/vector.h> #include "../devices/GCodeDevice.h" #include "Display.h" #include "../debug.h" #define S_DEBUGF LOGF #define S_DEBUGS LOGLN class Screen { public: Screen() : firstDisplayedMenuItem(0) {} void setDirty(bool fdirty=true) { Display::getDisplay()->setDirty(fdirty); } virtual void begin() { setDirty(true); } virtual void loop() {} void draw(); protected: using Evt = Display::ButtonEvent; etl::vector<MenuItem, 10> menuItems; virtual void drawContents() = 0; virtual void onButton(int bt, Display::ButtonEvent arg) {}; virtual void onMenuItemSelected(MenuItem & item) {}; virtual void onShow() {}; virtual void onHide() {}; private: size_t firstDisplayedMenuItem; friend class Display; };
15.740741
80
0.661176
[ "vector" ]
c073cde1c09fddabe75cb82067956823b44b5b04
4,187
h
C
include/Visualization.h
raiinboow/Camera_Data_Processing
8fb3e57f4df44f193d688ca017875cbb342c3260
[ "MIT" ]
1
2021-09-19T01:38:28.000Z
2021-09-19T01:38:28.000Z
include/Visualization.h
raiinboow/Camera_Data_Processing
8fb3e57f4df44f193d688ca017875cbb342c3260
[ "MIT" ]
null
null
null
include/Visualization.h
raiinboow/Camera_Data_Processing
8fb3e57f4df44f193d688ca017875cbb342c3260
[ "MIT" ]
2
2021-02-06T23:19:53.000Z
2021-03-30T00:41:32.000Z
/***************************************************************** Author: J. Gong Date: 2020-12-24 Description: Visualization *****************************************************************/ #pragma once #include <opencv2/opencv.hpp> #include "Lane.h" using namespace std; using namespace cv; /***************************************************************** Class Name: Visualization Description: Class to visualize lane and object *****************************************************************/ class Visualization{ private: Scalar lane_color; int lane_thickness; Scalar box_color; int box_thickness; public: /*Funciton Name: Visualization() */ /*Description: Default constructor */ /*Input: void */ Visualization(); /*Funciton Name: DrawLane(Mat img, MonoLane lane) */ /*Description: Visualize lane on image */ /*Input: Mat img - source image MonoLane lane - MonoLane */ /*Output: Mat image with lanes */ Mat DrawLane(Mat img, MonoLane lane); /*Funciton Name: DrawBox(Mat img, vector<Object_2D> list_2D) */ /*Description: Visualize objects on image */ /*Input: Mat img - source image vector<Object_2D> list_2D - 2D object list */ /*Output: Mat image with objects */ Mat DrawBox(Mat img, vector<Object_2D> list_2D); /*Funciton Name: SetLaneColor(Scalar lc) */ /*Description: Set lane color */ /*Input: Scalar lc - BGR scalar */ /*Output: void */ void SetLaneColor(Scalar lc); /*Funciton Name: SetLaneThickness(int lt) */ /*Description: Set lane thickness */ /*Input: int lt - thickness */ /*Output: void */ void SetLaneThickness(int lt); /*Funciton Name: SetBoxColor(Scalar bc) */ /*Description: Set box color */ /*Input: Scalar bc - BGR scalar */ /*Output: void */ void SetBoxColor(Scalar bc); /*Funciton Name: SetBoxThickness(int bt) */ /*Description: Set box thickness */ /*Input: int bt - thickness */ /*Output: void */ void SetBoxThickness(int bt); };
47.044944
136
0.278242
[ "object", "vector" ]
c07783c21aa2395d77a801edc3e1868d07d0d889
14,547
h
C
include/IStreamer.h
MagicAtom/Irrlicht
df84fd5c472ab619261e6dd092013bca1745eb5e
[ "MIT" ]
null
null
null
include/IStreamer.h
MagicAtom/Irrlicht
df84fd5c472ab619261e6dd092013bca1745eb5e
[ "MIT" ]
null
null
null
include/IStreamer.h
MagicAtom/Irrlicht
df84fd5c472ab619261e6dd092013bca1745eb5e
[ "MIT" ]
null
null
null
// // IStreamer.h // Irrlicht_OSX // // Created by 宋庭聿 on 2021/11/22. // #ifndef __IRR_I_RTC_STREAMER_H #define __IRR_I_RTC_STREAMER_H #include "nlohmann/json.hpp" #include "IH264FileParser.h" #include "IRtcHelpers.h" #include <memory> namespace irr{ namespace video{ using namespace rtc; using namespace std; class IRTCStreamer{ template <class T> weak_ptr<T> make_weak_ptr(shared_ptr<T> ptr) { return ptr; } using json = nlohmann::json; public: IRTCStreamer(std::string ipAddr,int port):defaultIpAddress(ipAddr),defaultPort(port){ ws = make_shared<WebSocket>(); rtcThread = new DispatchQueue("RtcThread") ; video = make_shared<H264FileParser>(25,true); } void setUp(){ Configuration* config = &rtc_config; string stunServer = "stun:stun.l.google.com:19302"; cout << "Stun server is " << stunServer << endl; rtc_config.iceServers.emplace_back(stunServer); rtc_config.disableAutoNegotiation = true; string localId = "server"; cout << "The local ID is: " << localId << endl; // ws = make_shared<WebSocket>(); ws->onOpen([]() { cout << "WebSocket connected, signaling ready" << endl; }); ws->onClosed([]() { cout << "WebSocket closed" << endl; }); ws->onError([](const string &error) { cout << "WebSocket failed: " << error << endl; }); ws->onMessage([&](variant<binary, string> data) { if (!holds_alternative<string>(data)) return; json message = json::parse(get<string>(data)); rtcThread->dispatch([this,message]() { wsOnMessage(message, rtc_config, ws); }); }); const string url = "ws://" + defaultIpAddress + ":" + to_string(defaultPort) + "/" + localId; cout << "Url is " << url << endl; ws->open(url); cout << "Waiting for signaling to be connected..." << endl; while (!ws->isOpen()) { if (ws->isClosed()) return; this_thread::sleep_for(100ms); } //cout<<"Cleaning up..."<<endl; cout<<"websocket setup"<<endl; return; } void publish(uint8_t *buf, int size){ int index = 0; if(avStream.has_value() == false || !avStream.value()->isRunning) return; std::vector<uint8_t> buffer(buf,buf+size*sizeof(uint8_t)); video->loadNextSample(buffer); avStream.value()->publishSample(); video->clearSentSample(); } ~IRTCStreamer(){ dc->close(); pc->close(); ws->close(); } protected: rtc::Configuration rtc_config; shared_ptr<WebSocket> ws; std::shared_ptr<H264FileParser> video; optional<shared_ptr<Stream>> avStream; DispatchQueue* rtcThread; shared_ptr<DataChannel> dc; shared_ptr<PeerConnection> pc; int cache_index; std::vector<uint8_t> buffer_cache; std::string defaultIpAddress; int defaultPort; unordered_map<string, shared_ptr<Client>> clients{}; shared_ptr<Client> createPeerConnection(const Configuration &config, weak_ptr<WebSocket> wws, string id){ pc = make_shared<PeerConnection>(config); auto client = make_shared<Client>(pc); pc->onStateChange([this,id](PeerConnection::State state) { cout << "State: " << state << endl; if (state == PeerConnection::State::Disconnected || state == PeerConnection::State::Failed || state == PeerConnection::State::Closed) { // remove disconnected client rtcThread->dispatch([this,id]() { clients.erase(id); }); } }); pc->onGatheringStateChange( [this,wpc = make_weak_ptr(pc), id, wws](PeerConnection::GatheringState state) { cout << "Gathering State: " << state << endl; if (state == PeerConnection::GatheringState::Complete) { if(auto pc = wpc.lock()) { auto description = pc->localDescription(); json message = { {"id", id}, {"type", description->typeString()}, {"sdp", string(description.value())} }; // Gathering complete, send answer if (auto ws = wws.lock()) { ws->send(message.dump()); } } } }); client->video = addVideo(pc, 102, 1, "video-stream", "stream1", [this,id, wc = make_weak_ptr(client)]() { rtcThread->dispatch([this,wc]() { if (auto c = wc.lock()) { addToStream(c, true); } }); cout << "Video from " << id << " opened" << endl; }); dc = pc->createDataChannel("ping-pong"); dc->onOpen([id, wdc = make_weak_ptr(dc)]() { if (auto dc = wdc.lock()) { dc->send("Ping"); } }); dc->onMessage(nullptr, [id, wdc = make_weak_ptr(dc)](string msg) { cout << "Message from " << id << " received: " << msg << endl; if (auto dc = wdc.lock()) { dc->send("Ping"); } }); client->dataChannel = dc; pc->setLocalDescription(); return client; } shared_ptr<Stream> createStream(const unsigned int fps){ auto stream = make_shared<Stream>(video); // set callback responsible for sample sending std::cout<<"new stream created"<<std::endl; stream->onSample([this,ws = make_weak_ptr(stream)](Stream::StreamSourceType type, uint64_t sampleTime, rtc::binary sample) { vector<ClientTrack> tracks{}; string streamType = type == Stream::StreamSourceType::Video ? "video" : "audio"; // get track for given type function<optional<shared_ptr<ClientTrackData>> (shared_ptr<Client>)> getTrackData = [type](shared_ptr<Client> client) { return client->video; }; // get all clients with Ready state for(auto id_client: clients) { auto id = id_client.first; auto client = id_client.second; auto optTrackData = getTrackData(client); if (client->getState() == Client::State::Ready && optTrackData.has_value()) { auto trackData = optTrackData.value(); tracks.push_back(ClientTrack(id, trackData)); } } if (!tracks.empty()) { for (auto clientTrack: tracks) { auto client = clientTrack.id; auto trackData = clientTrack.trackData; // sample time is in us, we need to convert it to seconds auto elapsedSeconds = double(sampleTime) / (1000 * 1000); auto rtpConfig = trackData->sender->rtpConfig; // get elapsed time in clock rate uint32_t elapsedTimestamp = rtpConfig->secondsToTimestamp(elapsedSeconds); // set new timestamp rtpConfig->timestamp = rtpConfig->startTimestamp + elapsedTimestamp; // get elapsed time in clock rate from last RTCP sender report auto reportElapsedTimestamp = rtpConfig->timestamp - trackData->sender->previousReportedTimestamp; // check if last report was at least 1 second ago if (rtpConfig->timestampToSeconds(reportElapsedTimestamp) > 1) { trackData->sender->setNeedsToReport(); } cout << "Sending " << streamType << " sample with size: " << to_string(sample.size()) << " to " << client << endl; bool send = false; try { // send sample send = trackData->track->send(sample); } catch (...) { send = false; } if (!send) { cerr << "Unable to send "<< streamType << " packet" << endl; break; } } } rtcThread->dispatch([this,ws]() { if (clients.empty()) { // we have no clients, stop the stream if (auto stream = ws.lock()) { stream->stop(); } } }); }); return stream; } void addToStream(shared_ptr<Client> client, bool isAddingVideo){ if (client->getState() == Client::State::Waiting) { client->setState(Client::State::WaitingForVideo);} if (client->getState() == Client::State::WaitingForVideo) { // Audio and video tracks are collected now assert(client->video.has_value()); auto video = client->video.value(); auto currentTimeInMicroSeconds = [](){ struct timeval time; gettimeofday(&time, NULL); return uint64_t(time.tv_sec) * 1000 * 1000 + time.tv_usec; }; auto currentTime_us = double(currentTimeInMicroSeconds()); auto currentTime_s = currentTime_us / (1000 * 1000); // set start time of stream video->sender->rtpConfig->setStartTime(currentTime_s, RtpPacketizationConfig::EpochStart::T1970); // start stat recording of RTCP SR video->sender->startRecording(); if (avStream.has_value()) { sendInitialNalus(avStream.value(), video); } client->setState(Client::State::Ready); } if (client->getState() == Client::State::Ready) { startStream(); }} void startStream(){ shared_ptr<Stream> stream; if (avStream.has_value()) { stream = avStream.value(); if (stream->isRunning) { // stream is already running return; } } else { stream = createStream(30); avStream = stream; } stream->start(); } void wsOnMessage(json message,Configuration config, shared_ptr<WebSocket> ws) { auto it = message.find("id"); if (it == message.end()) return; string id = it->get<string>(); it = message.find("type"); if (it == message.end()) return; string type = it->get<string>(); if (type == "streamRequest") { shared_ptr<Client> c = createPeerConnection(config, make_weak_ptr(ws), id); clients.emplace(id, c); } else if (type == "answer") { shared_ptr<Client> c; if (auto jt = clients.find(id); jt != clients.end()) { auto pc = clients.at(id)->peerConnection; auto sdp = message["sdp"].get<string>(); auto description = Description(sdp, type); pc->setRemoteDescription(description); } } } shared_ptr<ClientTrackData> addVideo(const shared_ptr<PeerConnection> pc, const uint8_t payloadType, const uint32_t ssrc, const string cname, const string msid, const function<void(void)> onOpen) { auto video = Description::Video(cname); video.addH264Codec(payloadType); video.addSSRC(ssrc, cname, msid, cname); auto track = pc->addTrack(video); // create RTP configuration auto rtpConfig = make_shared<RtpPacketizationConfig>(ssrc, cname, payloadType, H264RtpPacketizer::defaultClockRate); // create packetizer //auto packetizer = make_shared<H264RtpPacketizer>(H264RtpPacketizer::Separator::LongStartSequence, rtpConfig); auto packetizer =make_shared<H264RtpPacketizer>(H264RtpPacketizer::Separator::StartSequence,rtpConfig); // create H264 handler auto h264Handler = make_shared<H264PacketizationHandler>(packetizer); // add RTCP SR handler auto srReporter = make_shared<RtcpSrReporter>(rtpConfig); h264Handler->addToChain(srReporter); // add RTCP NACK handler auto nackResponder = make_shared<RtcpNackResponder>(); h264Handler->addToChain(nackResponder); // set handler track->setMediaHandler(h264Handler); track->onOpen(onOpen); auto trackData = make_shared<ClientTrackData>(track, srReporter); return trackData; } void sendInitialNalus(shared_ptr<Stream> stream, shared_ptr<ClientTrackData> video) { // auto h264 = dynamic_cast<H264FileParser *>(stream->video.get()); // auto initialNalus = h264->initialNALUS(); // // // send previous NALU key frame so users don't have to wait to see stream works // if (!initialNalus.empty()) { // // const double frameDuration_s = double(h264->sampleDuration_us) / (1000 * 1000); // const double frameDuration_s = double(30) / (1000 * 1000); // const uint32_t frameTimestampDuration = video->sender->rtpConfig->secondsToTimestamp(frameDuration_s); // video->sender->rtpConfig->timestamp = video->sender->rtpConfig->startTimestamp - frameTimestampDuration * 2; // video->track->send(initialNalus); // video->sender->rtpConfig->timestamp += frameTimestampDuration; // // Send initial NAL units again to start stream in firefox browser // video->track->send(initialNalus); // } } }; } // end namespace video } // end namespace irr #endif /* IStreamer_h */
40.86236
134
0.522651
[ "vector" ]
c07feca032a9934a6faebffe381e70791ebb7b31
2,400
c
C
kubernetes/unit-test/test_io_k8s_api_autoscaling_v1_scale_status.c
zouxiaoliang/nerv-kubernetes-client-c
07528948c643270fd757d38edc68da8c9628ee7a
[ "Apache-2.0" ]
null
null
null
kubernetes/unit-test/test_io_k8s_api_autoscaling_v1_scale_status.c
zouxiaoliang/nerv-kubernetes-client-c
07528948c643270fd757d38edc68da8c9628ee7a
[ "Apache-2.0" ]
null
null
null
kubernetes/unit-test/test_io_k8s_api_autoscaling_v1_scale_status.c
zouxiaoliang/nerv-kubernetes-client-c
07528948c643270fd757d38edc68da8c9628ee7a
[ "Apache-2.0" ]
null
null
null
#ifndef io_k8s_api_autoscaling_v1_scale_status_TEST #define io_k8s_api_autoscaling_v1_scale_status_TEST // the following is to include only the main from the first c file #ifndef TEST_MAIN #define TEST_MAIN #define io_k8s_api_autoscaling_v1_scale_status_MAIN #endif // TEST_MAIN #include <stdlib.h> #include <string.h> #include <stdio.h> #include <stdbool.h> #include "../external/cJSON.h" #include "../model/io_k8s_api_autoscaling_v1_scale_status.h" io_k8s_api_autoscaling_v1_scale_status_t* instantiate_io_k8s_api_autoscaling_v1_scale_status(int include_optional); io_k8s_api_autoscaling_v1_scale_status_t* instantiate_io_k8s_api_autoscaling_v1_scale_status(int include_optional) { io_k8s_api_autoscaling_v1_scale_status_t* io_k8s_api_autoscaling_v1_scale_status = NULL; if (include_optional) { io_k8s_api_autoscaling_v1_scale_status = io_k8s_api_autoscaling_v1_scale_status_create( 56, "0" ); } else { io_k8s_api_autoscaling_v1_scale_status = io_k8s_api_autoscaling_v1_scale_status_create( 56, "0" ); } return io_k8s_api_autoscaling_v1_scale_status; } #ifdef io_k8s_api_autoscaling_v1_scale_status_MAIN void test_io_k8s_api_autoscaling_v1_scale_status(int include_optional) { io_k8s_api_autoscaling_v1_scale_status_t* io_k8s_api_autoscaling_v1_scale_status_1 = instantiate_io_k8s_api_autoscaling_v1_scale_status(include_optional); cJSON* jsonio_k8s_api_autoscaling_v1_scale_status_1 = io_k8s_api_autoscaling_v1_scale_status_convertToJSON(io_k8s_api_autoscaling_v1_scale_status_1); printf("io_k8s_api_autoscaling_v1_scale_status :\n%s\n", cJSON_Print(jsonio_k8s_api_autoscaling_v1_scale_status_1)); io_k8s_api_autoscaling_v1_scale_status_t* io_k8s_api_autoscaling_v1_scale_status_2 = io_k8s_api_autoscaling_v1_scale_status_parseFromJSON(jsonio_k8s_api_autoscaling_v1_scale_status_1); cJSON* jsonio_k8s_api_autoscaling_v1_scale_status_2 = io_k8s_api_autoscaling_v1_scale_status_convertToJSON(io_k8s_api_autoscaling_v1_scale_status_2); printf("repeating io_k8s_api_autoscaling_v1_scale_status:\n%s\n", cJSON_Print(jsonio_k8s_api_autoscaling_v1_scale_status_2)); } int main() { test_io_k8s_api_autoscaling_v1_scale_status(1); test_io_k8s_api_autoscaling_v1_scale_status(0); printf("Hello world \n"); return 0; } #endif // io_k8s_api_autoscaling_v1_scale_status_MAIN #endif // io_k8s_api_autoscaling_v1_scale_status_TEST
39.344262
185
0.855833
[ "model" ]
c087c92fb8d1b0489ed4b9f61bb55c0f1f75039f
569
c
C
gcc-gcc-7_3_0-release/gcc/testsuite/gcc.target/powerpc/p8vector-builtin-6.c
best08618/asylo
5a520a9f5c461ede0f32acc284017b737a43898c
[ "Apache-2.0" ]
7
2020-05-02T17:34:05.000Z
2021-10-17T10:15:18.000Z
gcc-gcc-7_3_0-release/gcc/testsuite/gcc.target/powerpc/p8vector-builtin-6.c
best08618/asylo
5a520a9f5c461ede0f32acc284017b737a43898c
[ "Apache-2.0" ]
null
null
null
gcc-gcc-7_3_0-release/gcc/testsuite/gcc.target/powerpc/p8vector-builtin-6.c
best08618/asylo
5a520a9f5c461ede0f32acc284017b737a43898c
[ "Apache-2.0" ]
2
2020-07-27T00:22:36.000Z
2021-04-01T09:41:02.000Z
/* { dg-do compile { target { powerpc*-*-* } } } */ /* { dg-skip-if "" { powerpc*-*-darwin* } { "*" } { "" } } */ /* { dg-require-effective-target powerpc_p8vector_ok } */ /* { dg-skip-if "do not override -mcpu" { powerpc*-*-* } { "-mcpu=*" } { "-mcpu=power8" } } */ /* { dg-options "-mcpu=power8 -O2" } */ vector float dbl_to_float_p8 (double x) { return __builtin_vsx_xscvdpspn (x); } double float_to_dbl_p8 (vector float x) { return __builtin_vsx_xscvspdpn (x); } /* { dg-final { scan-assembler "xscvdpspn" } } */ /* { dg-final { scan-assembler "xscvspdpn" } } */
47.416667
94
0.595782
[ "vector" ]
c088ad5f7f5fe550aa121467a99693eadbd754b7
426
h
C
include/file_picker.h
minecraft-linux/file-picker
54b36967c46fa2e0baf273a422ea010dbe5841db
[ "MIT" ]
null
null
null
include/file_picker.h
minecraft-linux/file-picker
54b36967c46fa2e0baf273a422ea010dbe5841db
[ "MIT" ]
2
2018-06-17T13:48:59.000Z
2018-06-17T13:55:01.000Z
include/file_picker.h
minecraft-linux/file-picker
54b36967c46fa2e0baf273a422ea010dbe5841db
[ "MIT" ]
3
2019-11-01T20:29:11.000Z
2021-07-29T13:10:45.000Z
#pragma once #include <string> #include <vector> class FilePicker { public: enum class Mode { OPEN, SAVE }; virtual ~FilePicker() {} virtual void setTitle(std::string const& title) = 0; virtual void setMode(Mode mode) = 0; virtual void setFileNameFilters(std::vector<std::string> const& patterns) = 0; virtual bool show() = 0; virtual std::string getPickedFile() const = 0; };
17.04
82
0.640845
[ "vector" ]
c0919293ace40c20ec18cd2dda3da23a94441a11
2,805
c
C
permute.c.old.c
krautware/python
d0f0b2f8812e2053cee9def2ba08d7cf4b443eb7
[ "MIT" ]
null
null
null
permute.c.old.c
krautware/python
d0f0b2f8812e2053cee9def2ba08d7cf4b443eb7
[ "MIT" ]
null
null
null
permute.c.old.c
krautware/python
d0f0b2f8812e2053cee9def2ba08d7cf4b443eb7
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <time.h> #include <inttypes.h> #include <string.h> #define MAX_SIZE 12 #define SUCCESS 0 #define FAILURE -1 int tsp[MAX_SIZE + 10] = {0}; uint64_t permute(int n, int *vec, uint64_t (*c)(uint64_t, int)){ #define MAX_STACK 30 uint64_t counter = 0; int stack[MAX_STACK][2]; int d, l, i; for(i = 1; i < MAX_STACK; ++i){ stack[i][0] = 0, stack[i][1] = i; } d = 1; while(d > 0){ if(stack[d][0] <= n - d){ stack[d][0]++; if(vec[l = stack[d][1]] == d){ vec[l++] = 0; } if(l > n){ l = 1; } while(vec[l] != 0){ l++; if(l > n){ l = 1; } } vec[l] = d; /* if((vec[i = stack[d][1]] == d) && (i != l)){ vec[i] = 0; } */ stack[d][1] = l; if(d == n){ counter++; c(counter, n); vec[l] = 0; stack[d][0] = 0; --d; } else{ d++; } } else{ stack[d][0] = 0; vec[l = stack[d][1]] = 0; stack[d][1] = ++l; --d; } } return counter; } uint64_t call_path(uint64_t nr, int ende){ static uint64_t counter = 0; int i, j; int control[ende + 1]; int res = SUCCESS; if(nr == 0){ return counter; } for(i = 1; i <= ende; ++i){ control[i] = 0; } for(i = 1; i <= ende; ++i){ control[tsp[i]]++; } for(i = 1; i <= ende; ++i){ if(control[i] != 1){ /* Failure! */ counter++; printf("\nFehler in %" PRIu64 ". Permutation: %d fehlt!", nr, i); for(j = 1; j <= ende; ++j){ printf("%3d ", tsp[j]); } res = FAILURE; break; } } return (uint64_t) res; } int main(int argc, char *argv[]){ uint64_t (*calc) (uint64_t, int); uint64_t perm, failure; int max_size = MAX_SIZE; int h = 0; calc = call_path; if(argc > 1){ if((h = atoi(argv[argc -1])) != 0){ max_size = h; } } for(int i = 0; i < argc; ++i){ printf("Command line arg %2d: %s\n", i, argv[i]); if((h = atoi(argv[i])) != 0){ printf("Command line arg %2d: %s\n", h, argv[i]); } } printf("\n%" PRIu64 " Permutationen!\n", perm = permute(max_size - 1, tsp, calc)); printf("\n%" PRIu64 " Fehler in permute()\n", failure = calc(0, 0)); printf("\n%2.2f%% Fehlerrate", ((double)failure/perm)*100); }
23.375
86
0.393583
[ "3d" ]
c0944d69a09fed7b80c962a36f5fb829f9bf4540
3,868
h
C
src/Property.h
lkucalaba/tiscamera
e1fa7b21bb4dd777ae8039dfa072cfa2daa88244
[ "Apache-2.0" ]
241
2015-02-20T09:10:41.000Z
2022-03-18T08:53:26.000Z
src/Property.h
lkucalaba/tiscamera
e1fa7b21bb4dd777ae8039dfa072cfa2daa88244
[ "Apache-2.0" ]
435
2015-01-19T10:18:01.000Z
2022-03-28T08:03:08.000Z
src/Property.h
lkucalaba/tiscamera
e1fa7b21bb4dd777ae8039dfa072cfa2daa88244
[ "Apache-2.0" ]
141
2015-01-03T17:54:08.000Z
2022-02-09T09:55:15.000Z
/* * Copyright 2014 The Imaging Source Europe GmbH * * 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 TCAM_PROPERTY_H #define TCAM_PROPERTY_H #include "base_types.h" #include "PropertyImpl.h" #include <memory> #include <string> #include <vector> #include <map> namespace tcam { class Property : public PropertyImpl { public: enum VALUE_TYPE { UNDEFINED = 0, BOOLEAN, STRING, ENUM, INTEGER, INTSWISSKNIFE, FLOAT, COMMAND, BUTTON, }; Property(); Property (const tcam_device_property&, VALUE_TYPE); Property (const tcam_device_property&, const std::map<std::string, int>&, VALUE_TYPE); Property (const Property& other) = default; virtual ~Property (); virtual Property& operator= (const Property&); void reset (); /** * @brief update the property so that it will hold up to date information * @return true on success */ bool update (); /** * @return TCAM_PROPERTY_ID of the property */ TCAM_PROPERTY_ID get_ID () const; /** * */ std::string get_name () const; /** * */ TCAM_PROPERTY_TYPE get_type () const; /** * Convenience check for read-only and disabled */ bool can_be_changed () const; /** * @return true if property can not be written */ bool is_read_only () const; /** * @return true if property can not be read */ bool is_write_only () const; /** * */ bool is_disabled () const; bool is_external () const; /** * */ uint32_t get_flags () const; struct tcam_device_property get_struct () const; bool set_value (const struct tcam_device_property&); bool set_value (const int64_t& value, bool notify_impl = true); bool set_value (const double& value, bool notify_impl = true); bool set_value (const bool& value, bool notify_impl = true); bool set_value (const std::string& value, bool notify_impl = true); bool set_value (); bool set_flags (uint32_t new_flags); bool set_struct (const struct tcam_device_property&); /** * Set value from given tcam_device_property * @return true on success */ void set_struct_value (const struct tcam_device_property&); void get_struct_value (struct tcam_device_property& p); Property::VALUE_TYPE get_value_type () const; std::string to_string () const; bool from_string (const std::string&); bool set_property (const Property&); bool set_property_from_struct (const tcam_device_property&); bool get_property (Property&); bool get_property_from_struct (tcam_device_property&); // only applicable to enums std::vector<std::string> get_possible_values() const; protected: std::weak_ptr<PropertyImpl> impl; Property::VALUE_TYPE value_type; // internal storage struct tcam_device_property prop; // reference of initial state const struct tcam_device_property ref_prop; std::map<std::string, int> string_map; // internal method that notifies implementations about requests void notify_impl (); }; TCAM_PROPERTY_TYPE value_type_to_ctrl_type (const Property::VALUE_TYPE& t); } /* namespace tcam */ #endif /* TCAM_PROPERTY_H */
21.730337
77
0.659255
[ "vector" ]
c0995e91c2c6af979ff9a74d639d7715eeb05db3
6,806
h
C
include/server/database.h
Niklas-Seppala/todo-server
25a933d6854d8df28a8d2302f315980bb1d2b1d5
[ "MIT" ]
null
null
null
include/server/database.h
Niklas-Seppala/todo-server
25a933d6854d8df28a8d2302f315980bb1d2b1d5
[ "MIT" ]
null
null
null
include/server/database.h
Niklas-Seppala/todo-server
25a933d6854d8df28a8d2302f315980bb1d2b1d5
[ "MIT" ]
null
null
null
/** * @file database.h * @author Niklas Seppala * @brief Module for todo-server database functions. * @version 0.1 * @date 2021-02-10 * * @copyright Copyright (c) 2021 */ #ifndef DATABASE_H #define DATABASE_H #include <mysql/mysql.h> #include "lib/common.h" // Size of the SQL statement #define SQL_SIZE 256 // Doubles the size of escaped SQL statment #define escape_len(init_size) init_size * 2 #define fcount_exclude_id(count) count - 1 /*******************************************************************/ /******************** Database model structs ********************/ /*******************************************************************/ /** * @brief Type for serialized model. Data model * fields get serialized to strings for * SQL escaping later. Strings are stored * to heap and reference to those strings are * held by char **, aka. ser_model_t. */ typedef char **ser_model_t; /******************** TASK MODEL ********************/ #define MODEL_TASK_FCOUNT 3 #define MODEL_TASK_CNT_LEN 512 #define TASK_ID_FIELD 0 #define TASK_USERID_FIELD 1 #define TASK_CONTENT_FIELD 2 /** * @brief Holds data from task table */ typedef struct task_model { int id; int user_id; char content[MODEL_TASK_CNT_LEN]; // TODO: decide some length } task_model_t; /******************** USER MODEL ********************/ #define MODEL_USER_FCOUNT 2 #define MODEL_USER_NAME_LEN 15 #define USER_ID_FIELD 0 #define USER_USRNAME_FIELD 1 /** * @brief Holds data from user table */ typedef struct user_model { int id; char username[MODEL_USER_NAME_LEN]; } user_model_t; #define DB_INFO_STR_LEN 32 /** * @brief Holds data required for database connection creation. */ typedef struct db_info { char host[DB_INFO_STR_LEN]; char user[DB_INFO_STR_LEN]; char pw[DB_INFO_STR_LEN]; char db_name[DB_INFO_STR_LEN]; unsigned long flags; } db_info_t; /** * @brief Frees the allocated serialized model. * * @param model serialized model * @param size serialized model count */ void db_free_serialized_model(ser_model_t *model, int size); /** * @brief Serialize user model to ser_model_t. * * @param user user mode to be serialized * @param field what model fields to serialize * @param len field count * @param serialized result storage */ void serialize_user_model(user_model_t *user, int *field, int len, ser_model_t *serialized); /** * @brief Serialize task model to ser_model_t. * * @param task task model to be serialized. * @param field what model fields to serialize * @param len field count * @param serialized result storage */ void serialize_task_model(task_model_t *task, int *field, int len, ser_model_t *serialized); /** * @brief Copies parameter strings to db_info_t struct. * * @param db_info destination struct address. * @param db_name database name * @param host host * @param user username * @param pw password * @param flags additional flags. @see mysql_real_connect() */ void db_create_info(db_info_t *db_info, const char *db_name, const char *host, const char *user, const char *pw, const unsigned long flags); /** * @brief Initializes application database. * * @param db_info Connection information * @return int SUCCESS if ok, else ERROR */ int db_init(db_info_t *db_info); /** * @brief When quiting thread, call this function to let mysql library * clear internal things up. */ void db_thread_quit(); /** * @brief Closes MySQL connection and frees allocated memory. * * @param db MySQL connection to be closed. */ void db_close(MYSQL *db); /** * @brief Initializes and connects to MySQL database. Make sure to * call db_init() before this function. The resulting connection * object must be freed after use with db_close(). * ALLOCATES HEAP MEMORY! * * @return MYSQL* open MySQL database connection. */ MYSQL *db_open(); /** * @brief Performs a INSERT SQL statement to set provided user model * to database. Passed databasse connection MUST be initialized * and open. * * @param db open MySQL database connection * @param model user model to be inserted * @return int affected row count */ int db_insert_user(MYSQL *db, user_model_t *model); /** * @brief * * @param db * @param sql * @param argc * @param ... * @return int */ int db_delete(MYSQL *db, const char *sql, const int argc, ...); /** * @brief Preforms a SELECT SQL statement to fetch data from database. * Fetched data is aggregated to heap allocated linked list. * Passed database connection MUST be initialized and opened. * ALLOCATES HEAP MEMORY! * * @param db open MySQL database connection * @param deserialize_cb callback function to handle deserialization * from MYSQL_RES object to table model * @param results linked list head for results * @param sql SQL statement format string * @param argc count of variadic arguments * @param ... variadic args for SQL format string * @return int row count */ int db_select(MYSQL *db, void (*deserialize_cb)(MYSQL_RES *, void *, int, char **), void *results, char *sql, const int argc, ...); int select_static(MYSQL *db, void (*deserialize_cb)(MYSQL_RES *, void *, int, char **), void *results, char *sql, const int argc, ser_model_t model); /*******************************************************************/ /************** DEFAULT DESERIALIZATION CALLBACKS **************/ /*******************************************************************/ /** * @brief Default deserializer callback for user data models. * * @param db_results MySQL result set pointer. * @param real_results linked list head where result models are gathered. * @param fcount field count in result set * @param fnames names of the fields in result set. */ void db_deserialize_users(MYSQL_RES *db_results, void *real_results, int fcount, char **fnames); /** * @brief Default deserializer callback for task data models. * * @param db_results MySQL result set pointer * @param real_results linked list head where result models are gathered. * @param fcount field count in result set * @param fnames name of the fields in result set */ void db_deserialize_tasks(MYSQL_RES *db_results, void *real_results, int fcount, char **fnames); #endif // DATABASE_H
28.358333
76
0.619747
[ "object", "model" ]
69d9db6e874cb451afe313073918684e4fa8245b
5,474
h
C
antiddos/include/tencentcloud/antiddos/v20200309/model/DDoSGeoIPBlockConfig.h
milezhang/tencentcloud-sdk-cpp
cbe6b13912dd1582bf7a95cfc9c6303bdc874e1d
[ "Apache-2.0" ]
43
2019-08-14T08:14:12.000Z
2022-03-30T12:35:09.000Z
antiddos/include/tencentcloud/antiddos/v20200309/model/DDoSGeoIPBlockConfig.h
milezhang/tencentcloud-sdk-cpp
cbe6b13912dd1582bf7a95cfc9c6303bdc874e1d
[ "Apache-2.0" ]
12
2019-07-15T10:44:59.000Z
2021-11-02T12:35:00.000Z
antiddos/include/tencentcloud/antiddos/v20200309/model/DDoSGeoIPBlockConfig.h
milezhang/tencentcloud-sdk-cpp
cbe6b13912dd1582bf7a95cfc9c6303bdc874e1d
[ "Apache-2.0" ]
28
2019-07-12T09:06:22.000Z
2022-03-30T08:04:18.000Z
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef TENCENTCLOUD_ANTIDDOS_V20200309_MODEL_DDOSGEOIPBLOCKCONFIG_H_ #define TENCENTCLOUD_ANTIDDOS_V20200309_MODEL_DDOSGEOIPBLOCKCONFIG_H_ #include <string> #include <vector> #include <map> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> #include <tencentcloud/core/AbstractModel.h> namespace TencentCloud { namespace Antiddos { namespace V20200309 { namespace Model { /** * DDoS防护的区域封禁配置 */ class DDoSGeoIPBlockConfig : public AbstractModel { public: DDoSGeoIPBlockConfig(); ~DDoSGeoIPBlockConfig() = default; void ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const; CoreInternalOutcome Deserialize(const rapidjson::Value &value); /** * 获取区域类型,取值[ oversea(海外) china(国内) customized(自定义地区) ] * @return RegionType 区域类型,取值[ oversea(海外) china(国内) customized(自定义地区) ] */ std::string GetRegionType() const; /** * 设置区域类型,取值[ oversea(海外) china(国内) customized(自定义地区) ] * @param RegionType 区域类型,取值[ oversea(海外) china(国内) customized(自定义地区) ] */ void SetRegionType(const std::string& _regionType); /** * 判断参数 RegionType 是否已赋值 * @return RegionType 是否已赋值 */ bool RegionTypeHasBeenSet() const; /** * 获取封禁动作,取值[ drop(拦截) trans(放行) ] * @return Action 封禁动作,取值[ drop(拦截) trans(放行) ] */ std::string GetAction() const; /** * 设置封禁动作,取值[ drop(拦截) trans(放行) ] * @param Action 封禁动作,取值[ drop(拦截) trans(放行) ] */ void SetAction(const std::string& _action); /** * 判断参数 Action 是否已赋值 * @return Action 是否已赋值 */ bool ActionHasBeenSet() const; /** * 获取配置ID,配置添加成功后生成;添加新配置时不用填写此字段,修改或删除配置时需要填写配置ID * @return Id 配置ID,配置添加成功后生成;添加新配置时不用填写此字段,修改或删除配置时需要填写配置ID */ std::string GetId() const; /** * 设置配置ID,配置添加成功后生成;添加新配置时不用填写此字段,修改或删除配置时需要填写配置ID * @param Id 配置ID,配置添加成功后生成;添加新配置时不用填写此字段,修改或删除配置时需要填写配置ID */ void SetId(const std::string& _id); /** * 判断参数 Id 是否已赋值 * @return Id 是否已赋值 */ bool IdHasBeenSet() const; /** * 获取当RegionType为customized时,必须填写AreaList,且最多填写128个; * @return AreaList 当RegionType为customized时,必须填写AreaList,且最多填写128个; */ std::vector<int64_t> GetAreaList() const; /** * 设置当RegionType为customized时,必须填写AreaList,且最多填写128个; * @param AreaList 当RegionType为customized时,必须填写AreaList,且最多填写128个; */ void SetAreaList(const std::vector<int64_t>& _areaList); /** * 判断参数 AreaList 是否已赋值 * @return AreaList 是否已赋值 */ bool AreaListHasBeenSet() const; private: /** * 区域类型,取值[ oversea(海外) china(国内) customized(自定义地区) ] */ std::string m_regionType; bool m_regionTypeHasBeenSet; /** * 封禁动作,取值[ drop(拦截) trans(放行) ] */ std::string m_action; bool m_actionHasBeenSet; /** * 配置ID,配置添加成功后生成;添加新配置时不用填写此字段,修改或删除配置时需要填写配置ID */ std::string m_id; bool m_idHasBeenSet; /** * 当RegionType为customized时,必须填写AreaList,且最多填写128个; */ std::vector<int64_t> m_areaList; bool m_areaListHasBeenSet; }; } } } } #endif // !TENCENTCLOUD_ANTIDDOS_V20200309_MODEL_DDOSGEOIPBLOCKCONFIG_H_
28.962963
116
0.490135
[ "vector", "model" ]
69e0027b84b4a095a599406900ae7798e8da77f2
17,291
h
C
include/data_management/data_source/csv_feature_manager.h
zjf2012/daal
1d53cb3d71fb8f49fc7d79e50ca3c503c40a2b04
[ "Apache-2.0" ]
null
null
null
include/data_management/data_source/csv_feature_manager.h
zjf2012/daal
1d53cb3d71fb8f49fc7d79e50ca3c503c40a2b04
[ "Apache-2.0" ]
null
null
null
include/data_management/data_source/csv_feature_manager.h
zjf2012/daal
1d53cb3d71fb8f49fc7d79e50ca3c503c40a2b04
[ "Apache-2.0" ]
null
null
null
/* file: csv_feature_manager.h */ /******************************************************************************* * Copyright 2014-2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ /* //++ // Implementation of the CSV feature manager class. //-- */ #ifndef __CSV_FEATURE_MANAGER_H__ #define __CSV_FEATURE_MANAGER_H__ #include "data_management/data/numeric_table.h" #include "data_management/features/shortcuts.h" #include "data_management/data_source/data_source.h" #include "data_management/data_source/internal/csv_feature_utils.h" #include "data_management/data_source/modifiers/csv/shortcuts.h" #include "data_management/data_source/modifiers/csv/internal/engine.h" namespace daal { namespace data_management { /** * <a name="DAAL-CLASS-DATA_MANAGEMENT__FEATUREAUXDATA"></a> * \brief Structure for auxiliary data used for feature extraction. */ struct FeatureAuxData { FeatureAuxData() : idx(0), wide(1), dsFeat(0), ntFeat(0), nCats(0) { } explicit FeatureAuxData(size_t index, DataSourceFeature *dataSourceFeature, NumericTableFeature *numericTableFeature) : idx(index), dsFeat(dataSourceFeature), ntFeat(numericTableFeature), wide(1), nCats(0), buffer() { } size_t idx; size_t wide; size_t nCats; DataSourceFeature *dsFeat; NumericTableFeature *ntFeat; std::string buffer; }; typedef void (*functionT)(const char* word, FeatureAuxData& aux, DAAL_DATA_TYPE* arr); /** * <a name="DAAL-CLASS-DATA_MANAGEMENT__MODIFIERIFACE"></a> * \brief Abstract interface class that defines the interface for a features modifier */ class ModifierIface { public: virtual void apply(services::Collection<functionT> &funcList, services::Collection<FeatureAuxData> &auxVect) const = 0; virtual ~ModifierIface() {} static void contFunc(const char* word, FeatureAuxData& aux, DAAL_DATA_TYPE* arr) { DAAL_DATA_TYPE f; readNumeric<>( word, f ); arr[ aux.idx ] = f; } static void catFunc(const char* word, FeatureAuxData& aux, DAAL_DATA_TYPE* arr) { aux.buffer.assign(word); CategoricalFeatureDictionary *catDict = aux.dsFeat->getCategoricalDictionary(); CategoricalFeatureDictionary::iterator it = catDict->find( aux.buffer ); if( it != catDict->end() ) { arr[ aux.idx ] = (DAAL_DATA_TYPE)it->second.first; it->second.second++; } else { int index = (int)(catDict->size()); catDict->insert( std::pair<std::string, std::pair<int, int> >( aux.buffer, std::pair<int, int>(index, 1) ) ); arr[ aux.idx ] = (DAAL_DATA_TYPE)index; aux.ntFeat->categoryNumber = index + 1; } } static void nullFunc(const char* word, FeatureAuxData& aux, DAAL_DATA_TYPE* arr) { } protected: template<class T> static void readNumeric(const char *text, T &f) { f = daal::services::daal_string_to_float(text, 0); } static void binFunc(const char* word, FeatureAuxData& aux, DAAL_DATA_TYPE* arr) { aux.buffer.assign(word); CategoricalFeatureDictionary *catDict = aux.dsFeat->getCategoricalDictionary(); CategoricalFeatureDictionary::iterator it = catDict->find( aux.buffer ); size_t index = 0; if( it != catDict->end() ) { index = it->second.first; it->second.second++; } else { index = catDict->size(); catDict->insert( std::pair<std::string, std::pair<int, int> >( aux.buffer, std::pair<int, int>((int)index, 1) ) ); aux.ntFeat->categoryNumber = index + 1; } size_t nCats = aux.nCats; for(size_t i=0; i<nCats; i++) { arr[ aux.idx + i ] = (DAAL_DATA_TYPE)(i == index); } } }; /** * <a name="DAAL-CLASS-DATA_MANAGEMENT__MAKECATEGORICAL"></a> * \brief Methods of the class to set a feature categorical. */ class MakeCategorical : public ModifierIface { size_t idx; public: MakeCategorical(size_t idx) : idx(idx) {} virtual ~MakeCategorical() {} virtual void apply(services::Collection<functionT> &funcList, services::Collection<FeatureAuxData> &auxVect) const { size_t nCols = funcList.size(); if(idx < nCols) { funcList[idx] = catFunc; auxVect[idx].buffer.resize(1024); } } }; /** * <a name="DAAL-CLASS-DATA_MANAGEMENT__MAKECATEBINARY"></a> * \brief Methods of the class to set a feature binary categorical. */ class OneHotEncoder : public ModifierIface { size_t idx; size_t nCats; public: OneHotEncoder(size_t idx, size_t nCats) : idx(idx), nCats(nCats) {} virtual ~OneHotEncoder() {} virtual void apply(services::Collection<functionT> &funcList, services::Collection<FeatureAuxData> &auxVect) const { size_t nCols = funcList.size(); if(idx < nCols) { funcList[idx] = binFunc; auxVect[idx].buffer.resize(1024); auxVect[idx].nCats = nCats; auxVect[idx].wide = nCats; } size_t nNTCols = 0; for(size_t i=0; i<nCols; i++) { auxVect[i].idx = nNTCols; nNTCols += auxVect[i].wide; } } }; /** * <a name="DAAL-CLASS-DATA_MANAGEMENT__COLUMNFILTER"></a> * \brief Methods of the class to filter out data source features from output numeric table. */ class ColumnFilter : public ModifierIface { bool oddFlag; bool evenFlag; bool noneFlag; bool listFlag; services::Collection<size_t> validList; public: ColumnFilter() : oddFlag(false), evenFlag(false), noneFlag(false), listFlag(false) {} virtual ~ColumnFilter() {} ColumnFilter& odd() { oddFlag=true; return *this;} ColumnFilter& even() {evenFlag=true; return *this;} ColumnFilter& none() {noneFlag=true; return *this;} ColumnFilter& list(services::Collection<size_t> valid) {validList=valid; listFlag=true; return *this;} virtual void apply(services::Collection<functionT> &funcList, services::Collection<FeatureAuxData> &auxVect) const { size_t nCols = funcList.size(); if( oddFlag ) { for(size_t i=0; i<nCols; i+=2) { funcList[i] = nullFunc; auxVect[i].wide = 0; } } if( evenFlag ) { for(size_t i=1; i<nCols; i+=2) { funcList[i] = nullFunc; auxVect[i].wide = 0; } } if( noneFlag ) { for(size_t i=0; i<nCols; i++) { funcList[i] = nullFunc; auxVect[i].wide = 0; } } if( listFlag ) { services::Collection<bool> flags(nCols); for(size_t i=0; i<nCols; i++) { flags[i] = false; } for(size_t i=0; i<validList.size(); i++) { size_t el = validList[i]; if(el<nCols) { flags[el] = true; } } for(size_t i=0; i<nCols; i++) { if(flags[i]) continue; funcList[i] = nullFunc; auxVect[i].wide = 0; } } size_t nNTCols = 0; for(size_t i=0; i<nCols; i++) { auxVect[i].idx = nNTCols; nNTCols += auxVect[i].wide; } } }; namespace interface1 { /** * @defgroup data_sources Data Sources * \brief Specifies methods to access data * @ingroup data_management * @{ */ /** * <a name="DAAL-CLASS-DATA_MANAGEMENT__CSVFEATUREMANAGER"></a> * \brief Methods of the class to preprocess data represented in the CSV format. */ class CSVFeatureManager : public StringRowFeatureManagerIface { public: /** * Default constructor */ CSVFeatureManager() : _delimiter(','), _numberOfTokens(0), _isHeaderParsed(false) { } virtual ~CSVFeatureManager() { } /** * Sets a new character as a delimiter for parsing CSV data (default ',') */ void setDelimiter( char delimiter ) { _delimiter = delimiter; } public: /** * Gets number of columns which must be allocated in numeric table * \return The number of columns in numeric table */ size_t getNumericTableNumberOfColumns() const { if (_modifiersManager) { return _modifiersManager->getNumberOfOutputFeatures(); } const size_t nDSCols = auxVect.size(); return auxVect[nDSCols - 1].idx + auxVect[nDSCols - 1].wide; } /** * Sets information about features from the given dictionary * \param dictionary The data source dictionary */ services::Status setFeatureDetailsFromDictionary(DataSourceDictionary *dictionary) { DAAL_CHECK( dictionary, services::ErrorNullPtr ); auxVect.clear(); funcList.clear(); fillAuxVectAndFuncList(*dictionary); _numberOfTokens = dictionary->getNumberOfFeatures(); return services::Status(); } /** * Adds a simple feature modifier * \param[in] modifier The modifier */ void addModifier(const ModifierIface &modifier) { modifier.apply(funcList, auxVect); } /** * Adds extended feature modifier * \param[in] featureIds The identifiers of the features to be modified * \param[in] modifier The feature modifier * \param[out] status (optional) The pointer to status object * \return Reference to itself */ CSVFeatureManager &addModifier(const features::FeatureIdCollectionIfacePtr &featureIds, const modifiers::csv::FeatureModifierIfacePtr &modifier, services::Status *status = NULL) { services::Status localStatus; if (!_modifiersManager) { _modifiersManager = modifiers::csv::internal::ModifiersManager::create(&localStatus); if (!localStatus) { services::internal::tryAssignStatusAndThrow(status, localStatus); return *this; } } localStatus |= _modifiersManager->addModifier(featureIds, modifier); if (!localStatus) { services::internal::tryAssignStatusAndThrow(status, localStatus); return *this; } return *this; } /** * Parses a string that represents header of CSV data * \param[in] rawRowData Array of characters with the string that represents the feature vector * \param[in] rawDataSize Size of the rawRowData array */ void parseRowAsHeader(char *rawRowData, size_t rawDataSize) { DAAL_ASSERT( rawRowData ); internal::CSVRowTokenizer tokenizer(rawRowData, rawDataSize, _delimiter); for (tokenizer.reset(); tokenizer.good(); tokenizer.next()) { _featuresInfo.addFeatureName(tokenizer.getCurrentToken()); } } /** * Parses a string that represents a feature vector and fills provided data source dictionary * \param[in] rawRowData Array of characters with the string that represents the feature vector * \param[in] rawDataSize Size of the rawRowData array * \param[in] dictionary Pointer to the dictionary */ virtual void parseRowAsDictionary(char *rawRowData, size_t rawDataSize, DataSourceDictionary *dictionary) DAAL_C11_OVERRIDE { DAAL_ASSERT( rawRowData ); DAAL_ASSERT( dictionary ); _numberOfTokens = 0; internal::CSVRowTokenizer tokenizer(rawRowData, rawDataSize, _delimiter); for (tokenizer.reset(); tokenizer.good(); tokenizer.next()) { _numberOfTokens++; _featuresInfo.addFeatureType(tokenizer.getCurrentToken()); } if (_modifiersManager) { _modifiersManager->prepare(_featuresInfo); _modifiersManager->fillDictionary(*dictionary); } else { fillDictionaryWithoutModifiers(*dictionary); } } /** * Parses a string that represents a feature vector and converts it into a numeric representation * \param[in] rawRowData Array of characters with the string that represents the feature vector * \param[in] rawDataSize Size of the rawRowData array * \param[in] dictionary Pointer to the dictionary * \param[out] rowBuffer Pointer to a Buffer View to store the result of parsing * \param[in] ntRowIndex Position in the Numeric Table at which to store the result of parsing */ virtual void parseRowIn(char *rawRowData, size_t rawDataSize, DataSourceDictionary *dictionary, services::BufferView<DAAL_DATA_TYPE> &rowBuffer, size_t ntRowIndex) DAAL_C11_OVERRIDE { DAAL_ASSERT( dictionary ); DAAL_ASSERT( rawRowData ); size_t i = 0; internal::CSVRowTokenizer tokenizer(rawRowData, rawDataSize, _delimiter); if (_modifiersManager) { for (tokenizer.reset(); tokenizer.good() && i < _numberOfTokens; tokenizer.next(), i++) { _modifiersManager->setToken(i, tokenizer.getCurrentToken()); } _modifiersManager->applyModifiers(rowBuffer); } else { DAAL_DATA_TYPE *row = rowBuffer.data(); for (tokenizer.reset(); tokenizer.good() && i < _numberOfTokens; tokenizer.next(), i++) { const services::StringView token = tokenizer.getCurrentToken(); funcList[i](token.c_str(), auxVect[i], row); } } } /** * Finalizes CSV data parsing * \param[in] dictionary Pointer to the dictionary */ void finalize(DataSourceDictionary *dictionary) { if (_modifiersManager) { _modifiersManager->finalize(); _modifiersManager->fillDictionary(*dictionary); } } private: void fillDictionaryWithoutModifiers(DataSourceDictionary &dictionary) { const size_t nFeatures = _featuresInfo.getNumberOfFeatures(); dictionary.setNumberOfFeatures(nFeatures); for (size_t i = 0; i < nFeatures; i++) { features::FeatureType fType = _featuresInfo.getDetectedFeatureType(i); dictionary[i].ntFeature.featureType = fType; switch (fType) { case features::DAAL_CONTINUOUS: dictionary[i].ntFeature.setType<DAAL_DATA_TYPE>(); break; case features::DAAL_ORDINAL: case features::DAAL_CATEGORICAL: dictionary[i].ntFeature.setType<int>(); break; } } fillAuxVectAndFuncList(dictionary); } void fillAuxVectAndFuncList(DataSourceDictionary &dictionary) { const size_t nFeatures = dictionary.getNumberOfFeatures(); auxVect.resize(nFeatures); funcList.resize(nFeatures); for (size_t i = 0; i < nFeatures; i++) { DataSourceFeature &feature = dictionary[i]; NumericTableFeature &ntFeature = feature.ntFeature; auxVect.push_back(FeatureAuxData(i, &feature, &ntFeature)); funcList.push_back(getModifierFunctionPtr(ntFeature)); } } static functionT getModifierFunctionPtr(const NumericTableFeature &ntFeature) { switch (ntFeature.featureType) { case features::DAAL_CONTINUOUS: return ModifierIface::contFunc; case features::DAAL_ORDINAL: case features::DAAL_CATEGORICAL: return ModifierIface::catFunc; } return ModifierIface::nullFunc; } protected: char _delimiter; services::Collection<functionT> funcList; services::Collection<FeatureAuxData> auxVect; private: bool _isHeaderParsed; size_t _numberOfTokens; BlockDescriptor<DAAL_DATA_TYPE> _currentRowBlock; internal::CSVFeaturesInfo _featuresInfo; modifiers::csv::internal::ModifiersManagerPtr _modifiersManager; }; /** @} */ } // namespace interface1 using interface1::CSVFeatureManager; } // namespace data_management } // namespace daal #endif
30.176265
126
0.601122
[ "object", "vector" ]
69e56dbb3d7bcad83e12a0844a9628f8e5258bb5
1,870
h
C
toasty-plugin-test/platforms/ios/frameworks/ScanditCaptureCore.framework/Headers/SDCFeedback.h
AshwinKumaravel/ToastyPluginTest
982322cdae81f4537ec5cdbd9d523f5ab3000693
[ "MIT" ]
null
null
null
toasty-plugin-test/platforms/ios/frameworks/ScanditCaptureCore.framework/Headers/SDCFeedback.h
AshwinKumaravel/ToastyPluginTest
982322cdae81f4537ec5cdbd9d523f5ab3000693
[ "MIT" ]
null
null
null
toasty-plugin-test/platforms/ios/frameworks/ScanditCaptureCore.framework/Headers/SDCFeedback.h
AshwinKumaravel/ToastyPluginTest
982322cdae81f4537ec5cdbd9d523f5ab3000693
[ "MIT" ]
null
null
null
/* * This file is part of the Scandit Data Capture SDK * * Copyright (C) 2017- Scandit AG. All rights reserved. */ #import <Foundation/Foundation.h> #import <ScanditCaptureCore/SDCBase.h> @class SDCVibration; @class SDCSound; NS_ASSUME_NONNULL_BEGIN /** * Added in version 6.0.0 * * A feedback consisting of a sound and vibration, for example to be provided by a device when a code has been successfully scanned. */ NS_SWIFT_NAME(Feedback) SDC_EXPORTED_SYMBOL @interface SDCFeedback : NSObject /** * Added in version 6.0.0 * * The default feedback consisting of a default sound and a default vibration. */ @property (class, nonatomic, readonly) SDCFeedback *defaultFeedback; /** * Added in version 6.0.0 * * Creates a Feedback that emits the given vibration and plays the given sound. */ - (instancetype)initWithVibration:(nullable SDCVibration *)vibration sound:(nullable SDCSound *)sound; /** * Added in version 6.0.0 * * The vibration to be emitted when a feedback is required. If nil, no vibration is emitted. This property is further influenced by the device’s ring mode: the device may not vibrate even if this property is properly set to a non-nil instance. */ @property (nonatomic, nullable, readonly) SDCVibration *vibration; /** * Added in version 6.0.0 * * The sound to be played when a feedback is required. If nil, no sound is played. Depending on the device’s ring mode and/or volume settings, no sound may be played even if this property is properly set to a non-nil instance. */ @property (nonatomic, nullable, readonly) SDCSound *sound; /** * Added in version 6.0.0 * * Emits the feedback defined by this object. This method is further influenced by the device’s ring mode and/or volume settings - check sound and vibration for more details. */ - (void)emit; @end NS_ASSUME_NONNULL_END
29.68254
243
0.733155
[ "object" ]
69e60ea84c78a53a92fdbc25ee96b5952b40efe2
889
h
C
src/TREngine/Core/Render/ShaderProgram.h
CXUtk/TRV2
945950012e2385aeb24e80bf5e876703445ba423
[ "Apache-2.0" ]
null
null
null
src/TREngine/Core/Render/ShaderProgram.h
CXUtk/TRV2
945950012e2385aeb24e80bf5e876703445ba423
[ "Apache-2.0" ]
15
2021-09-04T13:02:51.000Z
2021-10-05T05:51:31.000Z
src/TREngine/Core/Render/ShaderProgram.h
CXUtk/TRV2
945950012e2385aeb24e80bf5e876703445ba423
[ "Apache-2.0" ]
null
null
null
#pragma once #include <glm/glm.hpp> #include <vector> #include <Graphics/Graphics_Interfaces.h> #include <Core.h> TRV2_NAMESPACE_BEGIN enum class ShaderUniformType { Int, Int2, Int3, Int4, Float, Float2, Float3, Float4, FloatVector, Matrix4x4, }; class ShaderProgram : public IGraphicsResource { public: ShaderProgram(IGraphicsResourceManager* resourceManager, const RawShader* vertexShader, const RawShader* fragmentShader); ShaderProgram(IGraphicsResourceManager* resourceManager, const std::vector<const RawShader*>& shaders); virtual ~ShaderProgram(); virtual IShaderProgramHandle GetHandle() const { return _handle; } void SetParameterfm4x4(const std::string& name, const glm::mat4& value); void SetParameter1i(const std::string& name, int value); private: IShaderProgramHandle _handle; }; TRV2_NAMESPACE_END
22.794872
125
0.737908
[ "vector" ]
69eea1002366d89549feb815bc3704c31613b5e3
15,475
c
C
mc/model/com.mentor.nucleus.bp.core/src416/c/t.sys_factory.c
NDGuthrie/bposs
2c47abf74a3e6fadb174b08e57aa66a209400606
[ "Apache-2.0" ]
1
2018-01-24T16:28:01.000Z
2018-01-24T16:28:01.000Z
mc/model/com.mentor.nucleus.bp.core/src418/c/t.sys_factory.c
NDGuthrie/bposs
2c47abf74a3e6fadb174b08e57aa66a209400606
[ "Apache-2.0" ]
null
null
null
mc/model/com.mentor.nucleus.bp.core/src418/c/t.sys_factory.c
NDGuthrie/bposs
2c47abf74a3e6fadb174b08e57aa66a209400606
[ "Apache-2.0" ]
null
null
null
T_b("/*--------------------------------------------------------------------------"); T_b("\n"); T_b(" "); T_b("* File: "); T_b(te_file->factory); T_b("."); T_b(te_file->src_file_ext); T_b("\n"); T_b(" "); T_b("*"); T_b("\n"); T_b(" "); T_b("* Description:"); T_b("\n"); T_b(" "); T_b("* "); T_b(te_copyright->body); T_b("\n"); T_b(" "); T_b("*--------------------------------------------------------------------------*/"); T_b("\n"); T_b("#include \""); T_b(te_file->types); T_b("."); T_b(te_file->hdr_file_ext); T_b("\""); T_b("\n"); if ( 0==strcmp("C",te_target->language) ) { T_b(all_domain_include_files); T_b("\n"); } T_b(te_file->arc_path); if ( te_sys->InstanceLoading ) { T_b("Escher_iHandle_t Escher_instance_cache[ 1000000 ];"); T_b("\n"); } if ( 0==strcmp("C",te_target->language) ) { T_b(system_class_array->class_info); T_b("\n"); } T_b("/*"); T_b("\n"); T_b(" "); T_b("* Create an instance of the class numbered on the input."); T_b("\n"); T_b(" "); T_b("* Return the handle of the created instance."); T_b("\n"); T_b(" "); T_b("*/"); T_b("\n"); T_b(te_instance->handle); T_b("\n"); T_b(te_instance->scope); T_b(te_instance->create); T_b("("); T_b("\n"); T_b(" "); T_b("const "); T_b(te_typemap->domain_number_name); T_b(" domain_num,"); T_b("\n"); T_b(" "); T_b("const "); T_b(te_typemap->object_number_name); T_b(" class_num"); T_b("\n"); T_b(")"); T_b("\n"); T_b("{"); T_b("\n"); T_b(" "); T_b(te_set->element_type); T_b(" * node;"); T_b("\n"); T_b(" "); T_b(te_instance->handle); T_b(" instance;"); T_b("\n"); T_b(" "); T_b(te_cia->class_info_type); T_b(" * dci = "); if ( 0==strcmp("C++",te_target->language) ) { T_b(te_instance->get_dci); T_b("(class_num);"); T_b("\n"); } else { T_b("*("); T_b(te_cia->class_info_name); T_b("[ "); T_b(domain_num_var); T_b(" ] + class_num);"); T_b("\n"); } if ( te_thread->enabled ) { T_b(" "); T_b(te_thread->mutex_lock); T_b("( SEMAPHORE_FLAVOR_INSTANCE );"); T_b("\n"); } T_b(" "); T_b("node = dci->"); T_b(te_extent->inactive); T_b(".head;"); T_b("\n"); T_b(" "); T_b("if ( 0 == node ) {"); T_b("\n"); if ( te_sys->UnitsToDynamicallyAllocate != 0 ) { T_b(" "); T_b(te_set->element_type); T_b(" * container ="); T_b("\n"); T_b(" "); T_b("( "); T_b(te_set->element_type); T_b(" *) "); T_b(te_dma->allocate); T_b("( "); T_b(te_sys->UnitsToDynamicallyAllocate); T_b(" * sizeof( "); T_b(te_set->element_type); T_b(" ) );"); T_b("\n"); T_b(" "); T_b(te_instance->handle); T_b(" pool = ( "); T_b(te_instance->handle); T_b(" ) "); T_b(te_dma->allocate); T_b("( "); T_b(te_sys->UnitsToDynamicallyAllocate); T_b(" * dci->"); T_b(te_extent->size_name); T_b(" );"); T_b("\n"); T_b(" "); T_b("if ( ( 0 == container ) || ( 0 == pool ) ) {"); T_b("\n"); T_b(" "); T_b(te_callout->object_pool_empty); T_b("( "); T_b(domain_num_var); T_b(", class_num );"); T_b("\n"); T_b(" "); T_b("} else {"); T_b("\n"); T_b(" "); T_b(te_string->memset); T_b("( pool, 0, "); T_b(te_sys->UnitsToDynamicallyAllocate); T_b(" * dci->"); T_b(te_extent->size_name); T_b(" );"); T_b("\n"); T_b(" "); T_b("dci->"); T_b(te_extent->inactive); T_b(".head = "); T_b(te_set->insert_block); T_b("("); T_b("\n"); T_b(" "); T_b("container, (const u1_t *) pool, dci->"); T_b(te_extent->size_name); T_b(", "); T_b(te_sys->UnitsToDynamicallyAllocate); T_b(" );"); T_b("\n"); T_b(" "); T_b("node = dci->"); T_b(te_extent->inactive); T_b(".head;"); T_b("\n"); T_b(" "); T_b("}"); T_b("\n"); } else { T_b(" "); T_b(te_callout->object_pool_empty); T_b("( "); T_b(domain_num_var); T_b(", class_num );"); T_b("\n"); } T_b(" "); T_b("}"); T_b("\n"); T_b(" "); T_b("dci->"); T_b(te_extent->inactive); T_b(".head = dci->"); T_b(te_extent->inactive); T_b(".head->next;"); T_b("\n"); T_b(" "); T_b("instance = ("); T_b(te_instance->handle); T_b(") node->object;"); T_b("\n"); T_b(" "); T_b("if ( 0 != dci->"); T_b(te_extent->istate_name); T_b(" ) {"); T_b("\n"); T_b(" "); T_b("instance->"); T_b(te_instance->current_state); T_b(" = dci->"); T_b(te_extent->istate_name); T_b(";"); T_b("\n"); T_b(" "); T_b("}"); T_b("\n"); if ( te_sys->InstanceLoading ) { T_b(" "); T_b("if ( 0 == dci->active->head ) {"); T_b("\n"); T_b(" "); T_b("dci->"); T_b(te_extent->active); T_b(".head = node;"); T_b("\n"); T_b(" "); T_b("} else {"); T_b("\n"); T_b(" "); T_b("dci->"); T_b(te_extent->active); T_b(".tail->next = node;"); T_b("\n"); T_b(" "); T_b("}"); T_b("\n"); T_b(" "); T_b("dci->"); T_b(te_extent->active); T_b(".tail = node;"); T_b("\n"); T_b(" "); T_b("node->next = 0;"); T_b("\n"); } else { T_b(" "); T_b(te_set->insert_instance); T_b("( &dci->"); T_b(te_extent->active); T_b(", node );"); T_b("\n"); } if ( te_thread->enabled ) { T_b(" "); T_b(te_thread->mutex_unlock); T_b("( SEMAPHORE_FLAVOR_INSTANCE );"); T_b("\n"); } T_b(" "); T_b("return instance;"); T_b("\n"); T_b("}"); T_b("\n"); if ( te_sys->PersistentClassCount > 0 ) { T_b(te_instance->handle); T_b("\n"); T_b(te_instance->scope); T_b(te_instance->create_persistent); T_b("("); T_b("\n"); T_b(" "); T_b("const "); T_b(te_typemap->domain_number_name); T_b(" domain_num,"); T_b("\n"); T_b(" "); T_b("const "); T_b(te_typemap->object_number_name); T_b(" class_num )"); T_b("\n"); T_b("{ /* Use this interface to create persistent instances. */"); T_b("\n"); T_b(" "); T_b(te_instance->handle); T_b(" instance = "); T_b(te_instance->scope); T_b(te_instance->create); T_b("( domain_num, class_num );"); T_b("\n"); T_b(" "); T_b("/* Mark the persistent instance as \"clean\". */"); T_b("\n"); T_b(" "); T_b("instance->"); T_b(te_persist->dirty_name); T_b(" = "); T_b(te_persist->dirty_clean); T_b(";"); T_b("\n"); T_b(" "); T_b(persist_check_mark->name); T_b("( instance, "); T_b(domain_num_var); T_b(", class_num );"); T_b("\n"); T_b(" "); T_b("return instance;"); T_b("\n"); T_b("}"); T_b("\n"); } T_b("/*"); T_b("\n"); T_b(" "); T_b("* Delete an instance of the class passed and numbered on the input."); T_b("\n"); T_b(" "); T_b("*/"); T_b("\n"); T_b("void"); T_b("\n"); T_b(te_instance->scope); T_b(te_instance->delete); T_b("("); T_b("\n"); T_b(" "); T_b(te_instance->handle); T_b(" instance,"); T_b("\n"); T_b(" "); T_b("const "); T_b(te_typemap->domain_number_name); T_b(" domain_num,"); T_b("\n"); T_b(" "); T_b("const "); T_b(te_typemap->object_number_name); T_b(" class_num"); T_b("\n"); T_b(")"); T_b("\n"); T_b("{"); T_b("\n"); T_b(" "); T_b(te_set->element_type); T_b(" * node;"); T_b("\n"); T_b(" "); T_b(te_cia->class_info_type); T_b(" * dci = "); if ( 0==strcmp("C++",te_target->language) ) { T_b(te_instance->get_dci); T_b("(class_num);"); T_b("\n"); } else { T_b("*("); T_b(te_cia->class_info_name); T_b("[ "); T_b(domain_num_var); T_b(" ] + class_num);"); T_b("\n"); } if ( te_thread->enabled ) { T_b(" "); T_b(te_thread->mutex_lock); T_b("( SEMAPHORE_FLAVOR_INSTANCE );"); T_b("\n"); } if ( te_sys->CollectionsFlavor == 20 ) { if ( te_sys->UnitsToDynamicallyAllocate != 0 ) { T_b(" "); T_b("node = ( "); T_b(te_set->element_type); T_b(" * ) "); T_b(te_set->contains); T_b("( &dci->"); T_b(te_extent->active); T_b(", instance );"); T_b("\n"); } else { T_b(" "); T_b("node = &dci->"); T_b(te_extent->container_name); T_b("[ 0 ] +"); T_b("\n"); T_b(" "); T_b("(((char *) instance - (char *) dci->"); T_b(te_extent->pool_name); T_b(" ) / dci->"); T_b(te_extent->size_name); T_b(" );"); T_b("\n"); } T_b(" "); T_b(te_dlist->remove_node); T_b("( &dci->"); T_b(te_extent->active); T_b(", node );"); T_b("\n"); } else { T_b(" "); T_b("node = "); T_b(te_slist->remove_node); T_b("( &dci->active, instance );"); T_b("\n"); } T_b(" "); T_b("node->next = dci->"); T_b(te_extent->inactive); T_b(".head;"); T_b("\n"); T_b(" "); T_b("dci->"); T_b(te_extent->inactive); T_b(".head = node;"); T_b("\n"); T_b(" "); T_b("/* Initialize storage to zero. */"); T_b("\n"); T_b(" "); T_b(te_string->memset); T_b("( instance, 0, dci->"); T_b(te_extent->size_name); T_b(" );"); T_b("\n"); if ( te_thread->enabled ) { T_b(" "); T_b(te_thread->mutex_unlock); T_b("( SEMAPHORE_FLAVOR_INSTANCE );"); T_b("\n"); } T_b("}"); T_b("\n"); if ( te_sys->PersistentClassCount > 0 ) { T_b("void"); T_b("\n"); T_b(te_instance->scope); T_b(te_instance->delete_persistent); T_b("("); T_b("\n"); T_b(" "); T_b(te_instance->handle); T_b(" instance,"); T_b("\n"); T_b(" "); T_b("const "); T_b(te_typemap->domain_number_name); T_b(" domain_num,"); T_b("\n"); T_b(" "); T_b("const "); T_b(te_typemap->object_number_name); T_b(" class_num )"); T_b("\n"); T_b("{ /* Use this interface to delete persistent instances. */"); T_b("\n"); T_b(" "); T_b(te_instance->scope); T_b(te_instance->delete); T_b("( instance, "); T_b(domain_num_var); T_b(", class_num );"); T_b("\n"); T_b(" "); T_b("Escher_PersistDelete( instance, domain_num, class_num );"); T_b("\n"); T_b("}"); T_b("\n"); } if ( te_sys->InstanceLoading ) { T_b("typedef void (*brf)( Escher_iHandle_t );"); T_b("\n"); T_b("static brf batch_relaters[] = {"); T_b("\n"); T_b(all_batch_relaters); T_b(""); T_b("};"); T_b("\n"); T_b("/*"); T_b("\n"); T_b(" "); T_b("* Self- inter-relate instances one to another."); T_b("\n"); T_b(" "); T_b("*/"); T_b("\n"); T_b("void "); T_b(te_prefix->result); T_b("batch_relate( const "); T_b(te_typemap->domain_number_name); T_b(", const "); T_b(te_typemap->object_number_name); T_b(" );"); T_b("\n"); T_b("void "); T_b(te_prefix->result); T_b("batch_relate("); T_b("\n"); T_b(" "); T_b("const "); T_b(te_typemap->domain_number_name); T_b(" domain_num,"); T_b("\n"); T_b(" "); T_b("const "); T_b(te_typemap->object_number_name); T_b(" class_num"); T_b("\n"); T_b(")"); T_b("\n"); T_b("{"); T_b("\n"); T_b(" "); T_b(te_typemap->instance_index_name); T_b(" i;"); T_b("\n"); T_b(" "); T_b(te_set->iterator_class_name); T_b(" iterator;"); T_b("\n"); T_b(" "); T_b(te_instance->handle); T_b(" instance;"); T_b("\n"); T_b(" "); T_b(te_cia->class_info_type); T_b(" * dci = "); if ( 0==strcmp("C++",te_target->language) ) { T_b(te_instance->get_dci); T_b("(class_num);"); T_b("\n"); } else { T_b("*("); T_b(te_cia->class_info_name); T_b("[ domain_num ] + class_num);"); T_b("\n"); } T_b(" "); T_b(te_set->iterator_reset); T_b("( &iterator, &dci->"); T_b(te_extent->active); T_b(" );"); T_b("\n"); T_b(" "); T_b("/* Cycle through the active list of instances of this class. */"); T_b("\n"); T_b(" "); T_b("while ( (instance = "); T_b(te_set->iterator_next); T_b("( &iterator )) != 0 ) {"); T_b("\n"); T_b(" "); T_b("if ( 0 != batch_relaters[ class_num ] ) {"); T_b("\n"); T_b(" "); T_b("(batch_relaters[ class_num ])( instance );"); T_b("\n"); T_b(" "); T_b("}"); T_b("\n"); T_b(" "); T_b("}"); T_b("\n"); T_b("}"); T_b("\n"); T_b(all_instance_dumpersd); T_b(""); T_b("static "); T_b(te_prefix->result); T_b("idf * instance_dumpers[ SYSTEM_DOMAIN_COUNT ] = {"); T_b("\n"); T_b(all_instance_dumpers); T_b(""); T_b("};"); T_b("\n"); T_b("/*"); T_b("\n"); T_b(" "); T_b("* Dump out instances of this class."); T_b("\n"); T_b(" "); T_b("*/"); T_b("\n"); T_b("void "); T_b(te_prefix->result); T_b("dump_instances( const "); T_b(te_typemap->domain_number_name); T_b(", const "); T_b(te_typemap->object_number_name); T_b(" );"); T_b("\n"); T_b("void "); T_b(te_prefix->result); T_b("dump_instances("); T_b("\n"); T_b(" "); T_b("const "); T_b(te_typemap->domain_number_name); T_b(" domain_num,"); T_b("\n"); T_b(" "); T_b("const "); T_b(te_typemap->object_number_name); T_b(" class_num"); T_b("\n"); T_b(")"); T_b("\n"); T_b("{"); T_b("\n"); T_b(" "); T_b(te_set->iterator_class_name); T_b(" iterator;"); T_b("\n"); T_b(" "); T_b(te_instance->handle); T_b(" instance;"); T_b("\n"); T_b(" "); T_b(te_prefix->result); T_b("idf * instance_dumper = instance_dumpers[ domain_num ];"); T_b("\n"); T_b(" "); T_b(te_cia->class_info_type); T_b(" * dci = "); if ( 0==strcmp("C++",te_target->language) ) { T_b(te_instance->get_dci); T_b("(class_num);"); T_b("\n"); } else { T_b("*("); T_b(te_cia->class_info_name); T_b("[ domain_num ] + class_num);"); T_b("\n"); } T_b(" "); T_b("if ( 0 != *instance_dumper[ class_num ] ) {"); T_b("\n"); T_b(" "); T_b(te_set->iterator_reset); T_b("( &iterator, &dci->"); T_b(te_extent->active); T_b(" );"); T_b("\n"); T_b(" "); T_b("/* Cycle through the active list of instances of this class. */"); T_b("\n"); T_b(" "); T_b("while ( (instance = "); T_b(te_set->iterator_next); T_b("( &iterator )) != 0 ) {"); T_b("\n"); T_b(" "); T_b("(*instance_dumper[ class_num ])( instance );"); T_b("\n"); T_b(" "); T_b("}"); T_b("\n"); T_b(" "); T_b("}"); T_b("\n"); T_b("}"); T_b("\n"); } T_b("/*"); T_b("\n"); T_b(" "); T_b("* Initialize object factory services."); T_b("\n"); T_b(" "); T_b("* Initialize class instance storage free pool (inanimate list)"); T_b("\n"); T_b(" "); T_b("* by linking the empty instances into a collection."); T_b("\n"); T_b(" "); T_b("*/"); T_b("\n"); T_b("void"); T_b("\n"); T_b(te_instance->scope); T_b(te_instance->factory_init); T_b("("); T_b("\n"); T_b(" "); T_b("const "); T_b(te_typemap->domain_number_name); T_b(" domain_num,"); T_b("\n"); T_b(" "); T_b("const "); T_b(te_typemap->object_number_name); T_b(" class_num )"); T_b("\n"); T_b("{"); T_b("\n"); T_b(" "); T_b(te_cia->class_info_type); T_b(" * dci = "); if ( 0==strcmp("C++",te_target->language) ) { T_b(te_instance->get_dci); T_b("(class_num);"); T_b("\n"); } else { T_b("*("); T_b(te_cia->class_info_name); T_b("[ domain_num ] + class_num);"); T_b("\n"); } T_b(" "); T_b("if ( 0 != dci ) {"); T_b("\n"); if ( te_thread->flavor == "OSX" ) { T_b(" "); T_b("u1_t * zero = (u1_t *) dci->"); T_b(te_extent->pool_name); T_b(";"); T_b("\n"); T_b(" "); T_b("s4_t zi = dci->"); T_b(te_extent->population_name); T_b(" * dci->"); T_b(te_extent->size_name); T_b(";"); T_b("\n"); T_b(" "); T_b("while ( 0 < zi-- ) { *zero++ = 0; }"); T_b("\n"); } if ( te_sys->PEIClassCount > 0 ) { T_b(" "); T_b("int i = (intptr_t) dci->"); T_b(te_extent->active); T_b(".head;"); T_b("\n"); T_b(" "); T_b("dci->"); T_b(te_extent->active); T_b(".head = "); T_b(te_set->insert_block); T_b("("); T_b("\n"); T_b(" "); T_b("dci->"); T_b(te_extent->container_name); T_b(","); T_b("\n"); T_b(" "); T_b("(const u1_t *) dci->"); T_b(te_extent->pool_name); T_b(","); T_b("\n"); T_b(" "); T_b("dci->"); T_b(te_extent->size_name); T_b(","); T_b("\n"); T_b(" "); T_b("i );"); T_b("\n"); T_b(" "); T_b("dci->"); T_b(te_extent->inactive); T_b(".head = "); T_b(te_set->insert_block); T_b("("); T_b("\n"); T_b(" "); T_b("dci->"); T_b(te_extent->container_name); T_b(" + i,"); T_b("\n"); T_b(" "); T_b("(const u1_t *) dci->"); T_b(te_extent->pool_name); T_b(" + ( i * dci->"); T_b(te_extent->size_name); T_b(" ),"); T_b("\n"); T_b(" "); T_b("dci->"); T_b(te_extent->size_name); T_b(","); T_b("\n"); T_b(" "); T_b("dci->"); T_b(te_extent->population_name); T_b(" - i );"); T_b("\n"); } else { T_b(" "); T_b("dci->"); T_b(te_extent->active); T_b(".head = 0;"); T_b("\n"); T_b(" "); T_b("dci->"); T_b(te_extent->inactive); T_b(".head = "); T_b(te_set->insert_block); T_b("("); T_b("\n"); T_b(" "); T_b("dci->"); T_b(te_extent->container_name); T_b(","); T_b("\n"); T_b(" "); T_b("(const u1_t *) dci->"); T_b(te_extent->pool_name); T_b(","); T_b("\n"); T_b(" "); T_b("dci->"); T_b(te_extent->size_name); T_b(","); T_b("\n"); T_b(" "); T_b("dci->"); T_b(te_extent->population_name); T_b(" );"); T_b("\n"); } T_b(" "); T_b("}"); T_b("\n"); T_b("}"); T_b("\n"); T_b(te_file->arc_path);
18.667069
85
0.552569
[ "object" ]
69f28e2c7f3bce305ff5871fefada4d78164c2f2
893
h
C
Summer Engine/Source Code/ModuleMenu.h
albertec1/Summer-Engine
088c7acb1d953ff787823795ac575452db2e08b0
[ "MIT" ]
null
null
null
Summer Engine/Source Code/ModuleMenu.h
albertec1/Summer-Engine
088c7acb1d953ff787823795ac575452db2e08b0
[ "MIT" ]
null
null
null
Summer Engine/Source Code/ModuleMenu.h
albertec1/Summer-Engine
088c7acb1d953ff787823795ac575452db2e08b0
[ "MIT" ]
null
null
null
#ifndef __ModuleEditor_H__ #define __ModuleEditor_H__ #include "Module.h" #include "Globals.h" #include <vector> class Window; class WinConsole; class WinConfiguration; //class WinInspector; //class WinHierarchy; class ModuleMenu : public Module { public: ModuleMenu(Application* app, bool start_enabled = true); ~ModuleMenu(); bool Start() override; update_status Update(float dt) override; bool CleanUp() override; void AddWindow(Window* window); void LogFPS(float fps, float ms); void Log(const char* text); inline bool UsingKeyboard() const { return usingKeyboard; } void Render(); public: bool showDemoWindow; bool usingKeyboard; bool usingMouse; std::vector<Window*> winArray; WinConsole* console = nullptr; WinConfiguration* configuration = nullptr; //WinInspector* inspector = nullptr; //WinHierarchy* hierarchy = nullptr; // }; #endif //__ModuleEditor_H__
19.844444
60
0.753639
[ "render", "vector" ]
69fdf66b2c8817fde0214501d0a3626e86b8e6b9
2,218
h
C
include/behemat/Warstomper.h
rweyrauch/AoSSimulator
d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b
[ "MIT" ]
5
2019-02-01T01:41:19.000Z
2021-06-17T02:16:13.000Z
include/behemat/Warstomper.h
rweyrauch/AoSSimulator
d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b
[ "MIT" ]
2
2020-01-14T16:57:42.000Z
2021-04-01T00:53:18.000Z
include/behemat/Warstomper.h
rweyrauch/AoSSimulator
d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b
[ "MIT" ]
1
2019-03-02T20:03:51.000Z
2019-03-02T20:03:51.000Z
/* * Warhammer Age of Sigmar battle simulator. * * Copyright (C) 2020 by Rick Weyrauch - rpweyrauch@gmail.com * * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) */ #pragma once #include <behemat/SonsOfBehemat.h> namespace SonsOfBehemat { class Warstomper : public SonsOfBehematBase { public: static Unit *Create(const ParameterList &parameters); static int ComputePoints(const ParameterList& parameters); static void Init(); Warstomper(); Warstomper(CommandTrait trait, Artefact artefact, FierceLoathing loathing, bool isGeneral); ~Warstomper() override = default; protected: size_t getDamageTableIndex() const; void onWounded() override; void onRestore() override; void onCharged() override; int extraAttacks(const Model *attackingModel, const Weapon *weapon, const Unit *target) const override; Rerolls toHitRerolls(const Weapon *weapon, const Unit *target) const override; int terror(const Unit *unit); void onBeginRound(int battleRound) override; Rerolls toSaveRerolls(const Weapon *weapon, const Unit *attacker) const override; private: Weapon m_grip{Weapon::Type::Melee, "Death Grip", 3, 1, 3, 2, -3, RAND_D6}, m_jump{Weapon::Type::Melee, "Jump Up and Down", 3, 4, 3, 3, -2, RAND_D3}, m_club{Weapon::Type::Melee, "Titanic Boulderclub", 3, 0, 3, 3, -2, 2}; lsignal::slot m_connection; static bool s_registered; }; // // Abilities Implemented // ------------------------------------------- // Almighty Jump Yes // Crushing Charge Yes // Death Grip Yes // Hurled Body TODO // Longshanks TODO // Sons of Behemat TODO // Terror Yes // Timberrrrr! TODO // Titanic Boulderclub TODO // Artefacts // Ironweld Cestus Partial/TODO // Club of the First Oak TODO // Mantle of the Destroyer TODO // } // namespace SonsOfBehemat
28.435897
111
0.58431
[ "model" ]
0e0251612d3ab33facca24314aaa076a47204af4
3,831
h
C
cvt/ml/rdf/RDFClassificationTrainer2D.h
tuxmike/cvt
c6a5df38af4653345e795883b8babd67433746e9
[ "MIT" ]
11
2017-04-04T16:38:31.000Z
2021-08-04T11:31:26.000Z
cvt/ml/rdf/RDFClassificationTrainer2D.h
tuxmike/cvt
c6a5df38af4653345e795883b8babd67433746e9
[ "MIT" ]
null
null
null
cvt/ml/rdf/RDFClassificationTrainer2D.h
tuxmike/cvt
c6a5df38af4653345e795883b8babd67433746e9
[ "MIT" ]
8
2016-04-11T00:58:27.000Z
2022-02-22T07:35:40.000Z
/* The MIT License (MIT) Copyright (c) 2011 - 2013, Philipp Heise and Sebastian Klose 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 CVT_RDFORESTTRAINERCLASSIFICATION2D_H #define CVT_RDFORESTTRAINERCLASSIFICATION2D_H #include <cvt/math/Vector.h> #include <cvt/ml/rdf/RDFClassificationTrainer.h> #include <cvt/gfx/Image.h> #include <cvt/gfx/IMapScoped.h> #include <cvt/ml/rdf/RDFClassifier.h> namespace cvt { class RDFTestLinear2D : public RDFTest<Vector2f> { public: RDFTestLinear2D( const Vector2f& vec, float threshold ) : _norm( vec ), _threshold( threshold ) {} bool operator()( const Vector2f& other ) { return Math::abs( _norm.x * other.x + _norm.y * other.y ) < _threshold; } private: Vector2f _norm; float _threshold; }; class RDFClassificationTrainer2D : public RDFClassificationTrainer<Vector2f,std::vector<Vector3f>,2> { public: RDFClassificationTrainer2D( size_t numberOfClasses ) : _numClasses( numberOfClasses ) { } ~RDFClassificationTrainer2D() { } virtual size_t dataSize( const std::vector<Vector3f>& data ) { return data.size(); } virtual RDFTest<Vector2f>* randomTest() { float x = Math::rand( -1.0f, 1.0f ); float y = Math::sqrt( 1.0f - Math::sqr( x ) ); return new RDFTestLinear2D( Vector2f( x, y ), Math::rand( -10000.0f, 10000.0f ) ); } virtual size_t classLabel( const std::vector<Vector3f>& data, size_t index ) { return ( size_t ) data[ index ].z; } virtual Vector2f& trainingData( const std::vector<Vector3f>& data, size_t index ) { return *( ( Vector2f*) ( &data[ index ] ) ); } static void visualizeClassifier( Image& dst, const RDFClassifier<Vector2f,2>& classifier, const Rectf& range, size_t width, size_t height ); private: size_t _numClasses; }; void RDFClassificationTrainer2D::visualizeClassifier( Image& dst, const RDFClassifier<Vector2f,2>& classifier, const Rectf& rect, size_t width, size_t height ) { dst.reallocate( width, height, IFormat::RGBA_FLOAT ); IMapScoped<float> map( dst ); Vector2f pt; RDFClassHistogram<2> hist; Color ctmp, c, gray( 0.5f ); for( size_t y = 0; y < height; y++ ) { float* ptr = map.ptr(); pt.y = 1.0f - ( float ) y / ( ( float ) height - 1.0f ); pt.y = rect.height * pt.y + rect.y; for( size_t x = 0; x < width; x++ ) { pt.x = ( float ) x / ( ( float ) width - 1.0f ); pt.x = rect.width * pt.x + rect.x; classifier.classify( hist, pt ); ctmp.mix( Color::BLUE, Color::RED, hist.probability( 0 ) ); c.mix( ctmp, gray, hist.entropy() * 0.5 ); *ptr++ = c.red(); *ptr++ = c.green(); *ptr++ = c.blue(); *ptr++ = c.alpha(); } map++; } } } #endif
31.146341
161
0.666667
[ "vector" ]
0e04b2230d12495aef19356be8bb55a221bdaa26
3,731
h
C
src/usvdata/Restrictions.h
AlexandrKedrov/usv-gui
a751032405573e5ffe1bf1da4b54d3539ce7b690
[ "MIT" ]
null
null
null
src/usvdata/Restrictions.h
AlexandrKedrov/usv-gui
a751032405573e5ffe1bf1da4b54d3539ce7b690
[ "MIT" ]
3
2021-12-22T14:00:46.000Z
2021-12-27T10:04:32.000Z
src/usvdata/Restrictions.h
AlexandrKedrov/usv-gui
a751032405573e5ffe1bf1da4b54d3539ce7b690
[ "MIT" ]
2
2021-04-05T13:18:44.000Z
2021-12-25T10:09:59.000Z
#ifndef USV_GUI_RESTRICTIONS_H #define USV_GUI_RESTRICTIONS_H #include "Vector2.h" #include "Frame.h" #include "FeatureCollection.h" #include <vector> #include <deque> namespace USV::Restrictions { typedef std::vector<Vector2> LineString; typedef std::vector<Vector2> ring_type; struct Polygon { std::vector<ring_type> rings; }; class Limitations { public: struct Limitation { struct point_approach_prohibition { Vector2 point; FeatureProperties* _ptr{}; }; struct line_crossing_prohibition { LineString linestring; FeatureProperties* _ptr; }; struct zone_entering_prohibition { Polygon polygon; FeatureProperties* _ptr{}; }; struct zone_leaving_prohibition { Polygon polygon; FeatureProperties* _ptr{}; }; struct movement_parameters_limitation { Polygon polygon; FeatureProperties* _ptr{}; }; }; private: bool empty_{true}; std::vector<Limitation::point_approach_prohibition> point_approach_prohibitions; std::vector<Limitation::line_crossing_prohibition> line_crossing_prohibitions; std::vector<Limitation::zone_entering_prohibition> zone_entering_prohibitions; std::vector<Limitation::zone_leaving_prohibition> zone_leaving_prohibitions; std::vector<Limitation::movement_parameters_limitation> movement_parameters_limitations; public: Limitations() = default; void add_point_approach_prohibition(Vector2 point, FeatureProperties*); void add_line_crossing_prohibition(LineString& linestring, FeatureProperties*); void add_zone_entering_prohibition(Polygon& polygon, FeatureProperties*); void add_zone_leaving_prohibition(Polygon& polygon, FeatureProperties*); void add_movement_parameters_limitation(Polygon& polygon, FeatureProperties* features_ptr); [[nodiscard]] const std::vector<Limitation::point_approach_prohibition>& PointApproachProhibitions() const { return point_approach_prohibitions; } [[nodiscard]] const std::vector<Limitation::line_crossing_prohibition>& LineCrossingProhibitions() const { return line_crossing_prohibitions; } [[nodiscard]] const std::vector<Limitation::zone_entering_prohibition>& ZoneEnteringProhibitions() const { return zone_entering_prohibitions; } [[nodiscard]] const std::vector<Limitation::zone_leaving_prohibition>& ZoneLeavingProhibitions() const { return zone_leaving_prohibitions; } [[nodiscard]] const std::vector<Limitation::movement_parameters_limitation>& MovementParametersLimitations() const { return movement_parameters_limitations; } [[nodiscard]] bool empty() const { return empty_; } }; struct Restrictions { Limitations hard; Limitations soft; std::deque<FeatureProperties> properties{}; Restrictions() = default; explicit Restrictions(const USV::FeatureCollection& feature_collection, const USV::Frame& reference_frame); [[nodiscard]] bool empty() const { return hard.empty() && soft.empty(); } }; Polygon polygonToLocal(const std::vector<std::vector<Vector2>>& polygon, const Frame& frame); LineString lineToLocal(const std::vector<Vector2>& line, const USV::Frame& reference_frame); } #endif //USV_GUI_RESTRICTIONS_H
32.72807
116
0.654248
[ "vector" ]
0e0901b19d45bffffce3adbc0413c112d8a6928e
1,499
c
C
oldstuff/c/old/wordfreq/auxlib.c
bcherry/bcherry
5d2f1144dbdbf35d6284018fa2c9e24ec5cecec6
[ "MIT" ]
3
2016-11-13T09:06:41.000Z
2021-09-11T23:36:19.000Z
oldstuff/c/old/wordfreq/auxlib.c
bcherry/bcherry
5d2f1144dbdbf35d6284018fa2c9e24ec5cecec6
[ "MIT" ]
null
null
null
oldstuff/c/old/wordfreq/auxlib.c
bcherry/bcherry
5d2f1144dbdbf35d6284018fa2c9e24ec5cecec6
[ "MIT" ]
2
2017-04-04T10:03:18.000Z
2021-09-11T23:36:26.000Z
/* $Id: auxlib.c,v 351.1 2005-03-03 14:06:03-08 - - $ */ // Ben Cherry - CMPS012B - Wesley Mackey - Winter 05 - Asg 5 #include <assert.h> #include <errno.h> #include <libgen.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <strings.h> #include "auxlib.h" static constring progname = NULL; static int exitcode = EXIT_SUCCESS; void set_progname( cstring arg0 ){ progname = basename( arg0 ); /* * constring slash = NULL; * assert( arg0 != NULL ); * slash = strrchr( arg0, '/' ); * if( slash == NULL ) progname = arg0; * else progname = slash + 1; */ } void eprintf( constring format, ... ){ va_list args; assert( format != NULL ); xfflush( stdout ); if( strstr( format, "%:" ) == format ){ assert( progname != NULL ); xfprintf( stderr, "%s: ", progname ); format += 2; }; va_start( args, format ); xvfprintf( stderr, format, args ); va_end( args ); xfflush( stderr ); exitcode = EXIT_FAILURE; } void syseprintf( constring object ){ eprintf( "%:%s: %s\n", object, strerror( errno )); } int get_exitcode( void ){ return exitcode; } void __stubprintf( char *file, int line, const char *func, char *format, ... ){ va_list args; assert( progname != NULL ); xfflush( stdout ); xfprintf( stderr, "%s: %s[%d]%s: ", progname, file, line, func ); va_start( args, format ); xvfprintf( stderr, format, args ); va_end( args ); xfflush( stderr ); }
23.421875
68
0.590394
[ "object" ]
0e09c3b9f7ddccdb2a4c4ef0ec40f20311c787f3
11,597
h
C
amd_openvx/openvx/include/VX/vx_import.h
asalmanp/MIVisionX
a964774944331827c8d6e9bb1ffbb2578f335056
[ "MIT" ]
153
2018-12-20T19:33:15.000Z
2022-03-30T03:51:14.000Z
amd_openvx/openvx/include/VX/vx_import.h
asalmanp/MIVisionX
a964774944331827c8d6e9bb1ffbb2578f335056
[ "MIT" ]
484
2019-01-02T23:51:58.000Z
2022-03-31T15:52:43.000Z
amd_openvx/openvx/include/VX/vx_import.h
asalmanp/MIVisionX
a964774944331827c8d6e9bb1ffbb2578f335056
[ "MIT" ]
105
2018-12-21T00:02:38.000Z
2022-03-25T15:44:02.000Z
/* * Copyright (c) 2012-2020 The Khronos Group 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 _OPENVX_IMPORT_H_ #define _OPENVX_IMPORT_H_ #ifdef __cplusplus extern "C" { #endif /*! * \file * \brief The OpenVX Import API * part of the OpenVX Export and Import extension API * and also part of the OpenVX SC deployment feature set. */ /*! \brief An enumeration of export uses. See <tt>\ref vxExportObjectsToMemory</tt> and * <tt>\ref vxImportObjectsFromMemory</tt> * \ingroup vx_enum_e */ #define VX_ENUM_IX_USE 0x18 /*! \brief How to export and import an object * \ingroup group_import */ #define VX_IX_USE_APPLICATION_CREATE (VX_ENUM_BASE(VX_ID_KHRONOS, VX_ENUM_IX_USE) + 0x0) /*!< \brief The application will create the object before import. */ /*! \brief How to export and import an object * \ingroup group_import */ #define VX_IX_USE_EXPORT_VALUES (VX_ENUM_BASE(VX_ID_KHRONOS, VX_ENUM_IX_USE) + 0x1) /*!< \brief Data values are exported and restored upon import. */ /*! \brief How to export and import an object * \ingroup group_import */ #define VX_IX_USE_NO_EXPORT_VALUES (VX_ENUM_BASE(VX_ID_KHRONOS, VX_ENUM_IX_USE) + 0x2) /*!< \brief Data values are not exported. */ /*============================================================================= IMPORT =============================================================================*/ /*! \brief The Import Object. Import is a container of OpenVX objects, which may be retreived * by name * \ingroup group_import */ typedef struct _vx_import *vx_import; /*! \brief The Object Type Enumeration for import. * \ingroup group_import */ #define VX_TYPE_IMPORT 0x814/*!< \brief A <tt>\ref vx_import</tt>. */ /*! \brief Imports objects into a context from a vendor-specific format in memory.\n * * \details This function imports objects from a memory blob previously created using <tt>\ref vxExportObjectsToMemory</tt>[*REQ*].\n * A pointer to memory is given where a list of references is stored, together with the list * of uses which describes how the references are used. The number of references given and the * list of uses must match that given upon export, or this function will not be sucessful[*REQ*].\n * The *uses* array specifies how the objects in the corresponding *refs* array will be imported: * - <tt>\ref VX_IX_USE_APPLICATION_CREATE</tt>\n * The application must create the object and supply the reference; the * meta-data of the object must match exactly the meta-data of the object when it was exported, * except that the name need not match[*REQ*].\n * If the supplied reference has a different name to that stored, the supplied name is used[*REQ*]. * - <tt>\ref VX_IX_USE_EXPORT_VALUES</tt>\n * The implementation will create the object and set the data in it[*REQ*].\n * Any data not defined at the time of export of the object will be set to a default value (zero in the * absence of any other definition) upon import[*REQ*]. * - <tt>\ref VX_IX_USE_NO_EXPORT_VALUES</tt>\n * The implementation will create the object and the importing application will set values as applicable[*REQ*]. * * References are obtained from the import API for those objects whose references were listed at the time of export. * These are not the same objects; they are equivalent objects created by the framework at import time. * The implementation guarantees that references will be available and valid for all objects listed at the time * of export, or the import will fail[*REQ*].\n * The import operation will fail if more than one object whose reference is listed at *refs* * has been given the same non-zero length name (via <tt>\ref vxSetReferenceName</tt>)[*REQ*].\n * The import will be unsuccessful if any of the parameters supplied is NULL[*REQ*].\n * After completion of the function the memory at *ptr* may be deallocated by the application as it will * not be used by any of the created objects[*REQ*].\n * Any delays imported with graphs for which they are registered for auto-aging remain registered * for auto-aging[*REQ*].\n * After import, a graph must execute with exactly the same effect with respect to its visible parameters * as before export[*REQ*]. * \note The *refs* array must be the correct length to hold all references of the import; this will be the same length * that was supplied at the time of export. Only references for objects created by the application, where the * corresponding *uses* entry is <tt>\ref VX_IX_USE_APPLICATION_CREATE</tt> should be filled in by the application; * all other entries will be supplied by the framework and may be initialised by the application to NULL. The *uses* array * must have the identical length and content as given at the time of export, and the value of *numrefs* must also match; * these measures increase confidence that the import contains the correct data. * \note Graph parameters may be changed after import by using the <tt>\ref vxSetGraphParameterByIndex</tt> API, and * images may also be changed by using the <tt>\ref vxSwapImageHandle</tt> API. * When <tt>\ref vxSetGraphParameterByIndex</tt> is used, the framework will check that the new parameter is of the * correct type to run with the graph, which cannot be re-verified. If the reference supplied is not suitable, an error * will be returned, but there may be circumstances where changing graph parameters for unsuitable ones is not detected * and could lead to implementation-dependent behaviour; one such circumstance is when the new parameters are images * corresponding to overlapping regions of interest. The user should avoid these circumstances. * In other words, * - The meta data of the new graph parameter must match the meta data of the graph parameter it replaces [*REQ*]. * - A graph parameter must not be NULL [*REQ*]. * \param [in] context context into which to import objects, must be valid [*REQ*]. * \param [in] numrefs number of references to import, must match export[*REQ*]. * \param [in,out] refs references imported or application-created data which must match * meta-data of the export[*REQ*] * \param [in] uses how to import the references, must match export values[*REQ*] * \param [in] ptr pointer to binary buffer containing a valid binary export[*REQ*] * \param [in] length number of bytes at \*ptr, i.e. the length of the export[*REQ*] * \return A <tt>\ref vx_import</tt>[*REQ*]. * Calling <tt>\ref vxGetStatus</tt> with the vx_import as a parameter will return VX_SUCCESS if the * function was successful[*REQ*].\n * Another value is given to indicate that there was an error[*REQ*].\n * An implementation may provide several different error codes to give useful diagnostic information * in the event of failure to import objects, but these are not required to indicate * possibly recovery mechanisms, and for safety critical use assume errors are not recoverable. * \post <tt>\ref vxReleaseImport</tt> is used to release the import object. * \post Use <tt>\ref vxReleaseReference</tt> or an appropriate specific release function to release * the references in the array refs when they are no longer required. * \ingroup group_import */ VX_API_ENTRY vx_import VX_API_CALL vxImportObjectsFromMemory( vx_context context, vx_size numrefs, vx_reference *refs, const vx_enum * uses, const vx_uint8 * ptr, vx_size length); /*! \brief Releases an import object when no longer required.\n * \details This function releases the reference to the import object [*REQ*].\n * Other objects including those imported at the time of creation of the import object are unaffected[*REQ*].\n * \param [in,out] import The pointer to the reference to the import object[*REQ*]. * \post After returning sucessfully from this function the reference is zeroed[*REQ*]. * \return A <tt>\ref vx_status</tt> value. * \retval VX_SUCCESS If no errors occurred and the import was sucessfully released[*REQ*].\n * An error is indicated when the return value is not VX_SUCCESS[*REQ*].\n * An implementation may provide several different return values to give useful diagnostic * information in the event of failure to export, but these are not required to indicate * possibly recovery mechanisms, and for safety critical use assume errors are not recoverable. * \pre <tt>\ref vxImportObjectsFromMemory</tt> is used to create an import object. * \ingroup group_import */ VX_API_ENTRY vx_status VX_API_CALL vxReleaseImport(vx_import *import); /*! \brief Get a reference from the import object by name.\n * * \details All accessible references of the import object created using <tt>\ref vxImportObjectsFromMemory</tt> are * in the array *refs*, which is populated partly by the application before import, and partly by the * framework. However, it may be more convenient to access the references in the import object without * referring to this array, for example if the import object is passed as a parameter to another function. * In this case, references may be retreived by name, assuming that <tt>\ref vxSetReferenceName</tt> * was called to assign a name to the reference. * This function searches the given import for the given name and returns the associated reference[*REQ*].\n * The reference may have been named either before export or after import[*REQ*].\n * If more than one reference exists in the import with the given name, this is an error[*REQ*].\n * Only references in the array *refs* after calling <tt>\ref vxImportObjectsFromMemory</tt> may be retrieved * using this function[*REQ*].\n * A reference to a named object may be obtained from a valid import object using this API even if all other * references to the object have been released[*REQ*]. * \param [in] import The import object in which to find the name; the function will fail if this parameter * is not valid[*REQ*]. * \param [in] name The name to find, points to a string of at least one and less than VX_MAX_REFERENCE_NAME bytes * followed by a zero byte; the function will fail if this is not valid[*REQ*]. * \return A <tt>\ref vx_reference</tt>[*REQ*].\n * Calling <tt>\ref vxGetStatus</tt> with the reference as a parameter will return VX_SUCCESS if the function * was successful[*REQ*].\n * Another value is given to indicate that there was an error[*REQ*].\n * On success, the reference count of the object in question is incremented[*REQ*].\n * An implementation may provide several different error codes to give useful diagnostic information * in the event of failure to retrieve a reference, but these are not required to indicate * possibly recovery mechanisms, and for safety critical use assume errors are not recoverable. * \pre <tt>\ref vxSetReferenceName</tt> was used to name the reference. * \post use <tt>ref vxReleaseReference</tt> or appropriate specific release function to release a reference * obtained by this method. * \ingroup group_import */ VX_API_ENTRY vx_reference VX_API_CALL vxGetImportReferenceByName(vx_import import, const vx_char *name); #ifdef __cplusplus } #endif #endif
61.036842
157
0.744589
[ "object" ]
0e0deb6bfc1fd0bbfdee3659cb07a7b65442b8fe
1,834
c
C
sched/irq_manager.c
sebastianene07/calypso_os
834c9cd7c482952b3fb2d485ab27a9619be6dd9e
[ "Apache-2.0" ]
5
2020-01-14T13:01:50.000Z
2021-09-01T17:39:30.000Z
sched/irq_manager.c
sebastianene07/calypso_os
834c9cd7c482952b3fb2d485ab27a9619be6dd9e
[ "Apache-2.0" ]
32
2019-10-16T10:41:23.000Z
2021-09-12T18:26:57.000Z
sched/irq_manager.c
sebastianene07/calypso_os
834c9cd7c482952b3fb2d485ab27a9619be6dd9e
[ "Apache-2.0" ]
2
2020-04-17T16:30:09.000Z
2020-06-29T23:47:51.000Z
#include <board.h> #include <irq_manager.h> /**************************************************************************** * Private variables defintion ****************************************************************************/ /* Ram based ISR vector - NUM_IRQS should be defined by the board */ static void (*g_ram_vectors[NUM_IRQS])(void); /**************************************************************************** * Public Methods ****************************************************************************/ /************************************************************************** * Name: * irq_attach * * Description: * Attach an interrupt callback. * * Assumption/Limitations: * Call this function with interrupts disabled. * *************************************************************************/ void irq_attach(int irq_num, irq_cb handler) { g_ram_vectors[irq_num] = handler; } /************************************************************************** * Name: * irq_detach * * Description: * Detach an interrupt callback. * * Assumption/Limitations: * Call this function with interrupts disabled. * *************************************************************************/ void irq_detach(int irq_num) { g_ram_vectors[irq_num] = NULL; } /************************************************************************** * Name: * irq_generic_handler * * Description: * This is the generic interrupt handler for this OS.. * *************************************************************************/ #ifdef INTERRUPT_ATR void INTERRUPT_ATR irq_generic_handler(void) #else void irq_generic_handler(void) #endif { uint8_t isr_num = cpu_getirqnum(); if (isr_num >= NUM_IRQS || g_ram_vectors[isr_num] == NULL) { return; } g_ram_vectors[isr_num](); }
24.783784
78
0.407852
[ "vector" ]
0e0f209a218397bedcbcf28431a556f645bf315d
31,008
c
C
drivers/serial/serial/power.c
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
drivers/serial/serial/power.c
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
drivers/serial/serial/power.c
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (c) 1997 Microsoft Corporation Module Name: power.c Abstract: This module contains the code that handles the power IRPs for the serial driver. Environment: Kernel mode Revision History : --*/ #include "precomp.h" #ifdef ALLOC_PRAGMA #pragma alloc_text(PAGESRP0, SerialGotoPowerState) #pragma alloc_text(PAGESRP0, SerialPowerDispatch) #pragma alloc_text(PAGESRP0, SerialSetPowerD0) #pragma alloc_text(PAGESRP0, SerialSetPowerD3) #pragma alloc_text(PAGESRP0, SerialSaveDeviceState) #pragma alloc_text(PAGESRP0, SerialRestoreDeviceState) #pragma alloc_text(PAGESRP0, SerialSendWaitWake) #endif // ALLOC_PRAGMA VOID SerialSystemPowerCompletion(IN PDEVICE_OBJECT PDevObj, UCHAR MinorFunction, IN POWER_STATE PowerState, IN PVOID Context, PIO_STATUS_BLOCK IoStatus) /*++ Routine Description: This routine is the completion routine for PoRequestPowerIrp calls in this module. Arguments: PDevObj - Pointer to the device object the irp is completing for MinorFunction - IRP_MN_XXXX value requested PowerState - Power state request was made of Context - Event to set or NULL if no setting required IoStatus - Status block from request Return Value: VOID --*/ { if (Context != NULL) { KeSetEvent((PKEVENT)Context, IO_NO_INCREMENT, 0); } return; } VOID SerialSaveDeviceState(IN PSERIAL_DEVICE_EXTENSION PDevExt) /*++ Routine Description: This routine saves the device state of the UART Arguments: PDevExt - Pointer to the device extension for the devobj to save the state for. Return Value: VOID --*/ { PSERIAL_DEVICE_STATE pDevState = &PDevExt->DeviceState; PAGED_CODE(); SerialDbgPrintEx(SERTRACECALLS, "Entering SerialSaveDeviceState\n"); // // Read necessary registers direct // #ifdef _WIN64 pDevState->IER = READ_INTERRUPT_ENABLE(PDevExt->Controller, PDevExt->AddressSpace); pDevState->MCR = READ_MODEM_CONTROL(PDevExt->Controller, PDevExt->AddressSpace); pDevState->LCR = READ_LINE_CONTROL(PDevExt->Controller, PDevExt->AddressSpace); #else pDevState->IER = READ_INTERRUPT_ENABLE(PDevExt->Controller); pDevState->MCR = READ_MODEM_CONTROL(PDevExt->Controller); pDevState->LCR = READ_LINE_CONTROL(PDevExt->Controller); #endif SerialDbgPrintEx(SERTRACECALLS, "Leaving SerialSaveDeviceState\n"); } #ifdef _WIN64 VOID SerialRestoreDeviceState(IN PSERIAL_DEVICE_EXTENSION PDevExt) /*++ Routine Description: This routine restores the device state of the UART Arguments: PDevExt - Pointer to the device extension for the devobj to restore the state for. Return Value: VOID --*/ { PSERIAL_DEVICE_STATE pDevState = &PDevExt->DeviceState; SHORT divisor; SERIAL_IOCTL_SYNC S; KIRQL oldIrql; PAGED_CODE(); SerialDbgPrintEx(SERTRACECALLS, "Enter SerialRestoreDeviceState\n"); SerialDbgPrintEx(SERTRACECALLS, "PDevExt: %x\n", PDevExt); // // Disable interrupts both via OUT2 and IER // WRITE_MODEM_CONTROL(PDevExt->Controller, 0,PDevExt->AddressSpace); DISABLE_ALL_INTERRUPTS(PDevExt->Controller, PDevExt->AddressSpace); // // Set the baud rate // SerialGetDivisorFromBaud(PDevExt->ClockRate, PDevExt->CurrentBaud, &divisor); S.Extension = PDevExt; S.Data = (PVOID)divisor; SerialSetBaud(&S); // // Reset / Re-enable the FIFO's // if (PDevExt->FifoPresent) { WRITE_FIFO_CONTROL(PDevExt->Controller, (UCHAR)0, PDevExt->AddressSpace); READ_RECEIVE_BUFFER(PDevExt->Controller, PDevExt->AddressSpace); WRITE_FIFO_CONTROL(PDevExt->Controller, (UCHAR)(SERIAL_FCR_ENABLE | PDevExt->RxFifoTrigger | SERIAL_FCR_RCVR_RESET | SERIAL_FCR_TXMT_RESET), PDevExt->AddressSpace); } else { WRITE_FIFO_CONTROL(PDevExt->Controller, (UCHAR)0, PDevExt->AddressSpace); } // // In case we are dealing with a bitmasked multiportcard, // that has the mask register enabled, enable the // interrupts. // if (PDevExt->InterruptStatus) { if (PDevExt->Indexed) { WRITE_INTERRUPT_STATUS(PDevExt->InterruptStatus, (UCHAR)0xFF, PDevExt->AddressSpace); } else { // // Either we are standalone or already mapped // if (PDevExt->OurIsrContext == PDevExt) { // // This is a standalone // WRITE_INTERRUPT_STATUS(PDevExt->InterruptStatus, (UCHAR)(1 << (PDevExt->PortIndex - 1)), PDevExt->AddressSpace); } else { // // One of many // WRITE_INTERRUPT_STATUS(PDevExt->InterruptStatus, (UCHAR)((PSERIAL_MULTIPORT_DISPATCH)PDevExt-> OurIsrContext)->UsablePortMask, PDevExt->AddressSpace); } } } // // Restore a couple more registers // WRITE_INTERRUPT_ENABLE(PDevExt->Controller, pDevState->IER, PDevExt->AddressSpace); WRITE_LINE_CONTROL(PDevExt->Controller, pDevState->LCR, PDevExt->AddressSpace); // // Clear out any stale interrupts // READ_INTERRUPT_ID_REG(PDevExt->Controller, PDevExt->AddressSpace); READ_LINE_STATUS(PDevExt->Controller, PDevExt->AddressSpace); READ_MODEM_STATUS(PDevExt->Controller, PDevExt->AddressSpace); if (PDevExt->DeviceState.Reopen == TRUE) { SerialDbgPrintEx(SERPNPPOWER, "Reopening device\n"); SetDeviceIsOpened(PDevExt, TRUE, FALSE); // // This enables interrupts on the device! // WRITE_MODEM_CONTROL(PDevExt->Controller, (UCHAR)(pDevState->MCR | SERIAL_MCR_OUT2), PDevExt->AddressSpace); // // Refire the state machine // DISABLE_ALL_INTERRUPTS(PDevExt->Controller, PDevExt->AddressSpace); ENABLE_ALL_INTERRUPTS(PDevExt->Controller, PDevExt->AddressSpace); } } #else VOID SerialRestoreDeviceState(IN PSERIAL_DEVICE_EXTENSION PDevExt) /*++ Routine Description: This routine restores the device state of the UART Arguments: PDevExt - Pointer to the device extension for the devobj to restore the state for. Return Value: VOID --*/ { PSERIAL_DEVICE_STATE pDevState = &PDevExt->DeviceState; SHORT divisor; SERIAL_IOCTL_SYNC S; KIRQL oldIrql; PAGED_CODE(); SerialDbgPrintEx(SERTRACECALLS, "Enter SerialRestoreDeviceState\n"); SerialDbgPrintEx(SERTRACECALLS, "PDevExt: %x\n", PDevExt); // // Disable interrupts both via OUT2 and IER // WRITE_MODEM_CONTROL(PDevExt->Controller, 0); DISABLE_ALL_INTERRUPTS(PDevExt->Controller); // // Set the baud rate // SerialGetDivisorFromBaud(PDevExt->ClockRate, PDevExt->CurrentBaud, &divisor); S.Extension = PDevExt; S.Data = (PVOID)divisor; SerialSetBaud(&S); // // Reset / Re-enable the FIFO's // if (PDevExt->FifoPresent) { WRITE_FIFO_CONTROL(PDevExt->Controller, (UCHAR)0); READ_RECEIVE_BUFFER(PDevExt->Controller); WRITE_FIFO_CONTROL(PDevExt->Controller, (UCHAR)(SERIAL_FCR_ENABLE | PDevExt->RxFifoTrigger | SERIAL_FCR_RCVR_RESET | SERIAL_FCR_TXMT_RESET)); } else { WRITE_FIFO_CONTROL(PDevExt->Controller, (UCHAR)0); } // // In case we are dealing with a bitmasked multiportcard, // that has the mask register enabled, enable the // interrupts. // if (PDevExt->InterruptStatus) { if (PDevExt->Indexed) { WRITE_PORT_UCHAR(PDevExt->InterruptStatus, (UCHAR)0xFF); } else { // // Either we are standalone or already mapped // if (PDevExt->OurIsrContext == PDevExt) { // // This is a standalone // WRITE_PORT_UCHAR(PDevExt->InterruptStatus, (UCHAR)(1 << (PDevExt->PortIndex - 1))); } else { // // One of many // WRITE_PORT_UCHAR(PDevExt->InterruptStatus, (UCHAR)((PSERIAL_MULTIPORT_DISPATCH)PDevExt-> OurIsrContext)->UsablePortMask); } } } // // Restore a couple more registers // WRITE_INTERRUPT_ENABLE(PDevExt->Controller, pDevState->IER); WRITE_LINE_CONTROL(PDevExt->Controller, pDevState->LCR); // // Clear out any stale interrupts // READ_INTERRUPT_ID_REG(PDevExt->Controller); READ_LINE_STATUS(PDevExt->Controller); READ_MODEM_STATUS(PDevExt->Controller); if (PDevExt->DeviceState.Reopen == TRUE) { SerialDbgPrintEx(SERPNPPOWER, "Reopening device\n"); SetDeviceIsOpened(PDevExt, TRUE, FALSE); // // This enables interrupts on the device! // WRITE_MODEM_CONTROL(PDevExt->Controller, (UCHAR)(pDevState->MCR | SERIAL_MCR_OUT2)); // // Refire the state machine // DISABLE_ALL_INTERRUPTS(PDevExt->Controller); ENABLE_ALL_INTERRUPTS(PDevExt->Controller); } } #endif VOID SerialFinishDevicePower(IN PDEVICE_OBJECT PDevObj, IN UCHAR MinorFunction, IN POWER_STATE State, IN PSERIAL_POWER_COMPLETION_CONTEXT PContext, IN PIO_STATUS_BLOCK PIoStatus) { PSERIAL_DEVICE_EXTENSION pDevExt = PContext->PDevObj->DeviceExtension; PIRP pSIrp = PContext->PSIrp; // // A possible cleaner approach is to not use a proprietary context // and pass the Irp down using our devobj rather than the PDO. // // // Copy status from D request to S request // pSIrp->IoStatus.Status = PIoStatus->Status; ExFreePool(PContext); // // Complete S request // PoStartNextPowerIrp(pSIrp); SerialCompleteRequest(pDevExt, pSIrp, IO_NO_INCREMENT); } NTSTATUS SerialFinishSystemPower(IN PDEVICE_OBJECT PDevObj, IN PIRP PIrp, IN PVOID PContext) /*++ Routine Description: This is the completion routine for the system set power request. Arguments: PDevObj - Pointer to the device object for this device PIrp - Pointer to the IRP for the system set request PContext - Not used Return Value: The function value is the final status of the call --*/ { PSERIAL_DEVICE_EXTENSION pDevExt = PDevObj->DeviceExtension; NTSTATUS status = PIrp->IoStatus.Status; PSERIAL_POWER_COMPLETION_CONTEXT pContext; PIO_STACK_LOCATION pIrpSp; UNREFERENCED_PARAMETER(PContext); // // See if it failed, and if so, just return it. // if (!NT_SUCCESS(status)) { PoStartNextPowerIrp(PIrp); return status; } pContext = (PSERIAL_POWER_COMPLETION_CONTEXT) ExAllocatePool(NonPagedPool, sizeof(SERIAL_POWER_COMPLETION_CONTEXT)); if (pContext == NULL) { status = STATUS_INSUFFICIENT_RESOURCES; goto SerialFinishSystemPowerErrOut; } pIrpSp = IoGetCurrentIrpStackLocation(PIrp); pContext->PDevObj = PDevObj; pContext->PSIrp = PIrp; status = PoRequestPowerIrp(pDevExt->Pdo, pIrpSp->MinorFunction, pDevExt->NewDevicePowerState, SerialFinishDevicePower, pContext, NULL); SerialFinishSystemPowerErrOut: if (!NT_SUCCESS(status)) { if (pContext != NULL) { ExFreePool(pContext); } PoStartNextPowerIrp(PIrp); PIrp->IoStatus.Status = status; SerialCompleteRequest(pDevExt, PIrp, IO_NO_INCREMENT); } return STATUS_MORE_PROCESSING_REQUIRED; } NTSTATUS SerialPowerDispatch(IN PDEVICE_OBJECT PDevObj, IN PIRP PIrp) /*++ Routine Description: This is a dispatch routine for the IRPs that come to the driver with the IRP_MJ_POWER major code (power IRPs). Arguments: PDevObj - Pointer to the device object for this device PIrp - Pointer to the IRP for the current request Return Value: The function value is the final status of the call --*/ { PSERIAL_DEVICE_EXTENSION pDevExt = PDevObj->DeviceExtension; PIO_STACK_LOCATION pIrpStack = IoGetCurrentIrpStackLocation(PIrp); NTSTATUS status; PDEVICE_OBJECT pLowerDevObj = pDevExt->LowerDeviceObject; PDEVICE_OBJECT pPdo = pDevExt->Pdo; BOOLEAN acceptingIRPs; PAGED_CODE(); if ((status = SerialIRPPrologue(PIrp, pDevExt)) != STATUS_SUCCESS) { // // The request may have been queued if we are stopped. If so, // we just return the status. Otherwise, it must be an error // so we complete the power request. // if (status != STATUS_PENDING) { PoStartNextPowerIrp(PIrp); SerialCompleteRequest(pDevExt, PIrp, IO_NO_INCREMENT); } return status; } status = STATUS_SUCCESS; switch (pIrpStack->MinorFunction) { case IRP_MN_WAIT_WAKE: SerialDbgPrintEx(SERPNPPOWER, "Got IRP_MN_WAIT_WAKE Irp\n"); break; case IRP_MN_POWER_SEQUENCE: SerialDbgPrintEx(SERPNPPOWER, "Got IRP_MN_POWER_SEQUENCE Irp\n"); break; case IRP_MN_SET_POWER: SerialDbgPrintEx(SERPNPPOWER, "Got IRP_MN_SET_POWER Irp\n"); // // Perform different ops if it was system or device // switch (pIrpStack->Parameters.Power.Type) { case SystemPowerState: { POWER_STATE powerState; // // They asked for a system power state change // SerialDbgPrintEx(SERPNPPOWER, "SystemPowerState\n"); // // We will only service this if we are policy owner -- we // don't need to lock on this value since we only service // one power request at a time. // if (pDevExt->OwnsPowerPolicy != TRUE) { status = STATUS_SUCCESS; goto PowerExit; } switch (pIrpStack->Parameters.Power.State.SystemState) { case PowerSystemUnspecified: powerState.DeviceState = PowerDeviceUnspecified; break; case PowerSystemWorking: powerState.DeviceState = PowerDeviceD0; break; case PowerSystemSleeping1: case PowerSystemSleeping2: case PowerSystemSleeping3: case PowerSystemHibernate: case PowerSystemShutdown: case PowerSystemMaximum: powerState.DeviceState = pDevExt->DeviceStateMap[pIrpStack-> Parameters.Power.State.SystemState]; break; default: status = STATUS_SUCCESS; goto PowerExit; break; } // // Send IRP to change device state if we should change // // // We only power up the stack if the device is open. This is based // on our policy of keeping the device powered down unless it is // open. // if (((powerState.DeviceState < pDevExt->PowerState) && pDevExt->OpenCount)) { // // Send the request down // // // Mark the IRP as pending // pDevExt->NewDevicePowerState = powerState; IoMarkIrpPending(PIrp); IoCopyCurrentIrpStackLocationToNext(PIrp); IoSetCompletionRoutine(PIrp, SerialFinishSystemPower, NULL, TRUE, TRUE, TRUE); PoCallDriver(pDevExt->LowerDeviceObject, PIrp); return STATUS_PENDING; }else { // // If powering down, we can't go past wake state // if wait-wake pending // if (powerState.DeviceState >= pDevExt->PowerState) { // // Power down -- ensure there is no wake-wait pending OR // we can do down to that level and still wake the machine // if ((pDevExt->PendingWakeIrp == NULL && !pDevExt->SendWaitWake) || powerState.DeviceState <= pDevExt->DeviceWake) { // // Send the request down // // // Mark the IRP as pending // pDevExt->NewDevicePowerState = powerState; IoMarkIrpPending(PIrp); IoCopyCurrentIrpStackLocationToNext(PIrp); IoSetCompletionRoutine(PIrp, SerialFinishSystemPower, NULL, TRUE, TRUE, TRUE); PoCallDriver(pDevExt->LowerDeviceObject, PIrp); return STATUS_PENDING; } else { // // Fail the request // status = STATUS_INVALID_DEVICE_STATE; PIrp->IoStatus.Status = status; PoStartNextPowerIrp(PIrp); SerialCompleteRequest(pDevExt, PIrp, IO_NO_INCREMENT); return status; } } } break; } case DevicePowerState: SerialDbgPrintEx(SERPNPPOWER, "DevicePowerState\n"); break; default: SerialDbgPrintEx(SERPNPPOWER, "UNKNOWN PowerState\n"); status = STATUS_SUCCESS; goto PowerExit; } // // If we are already in the requested state, just pass the IRP down // if (pDevExt->PowerState == pIrpStack->Parameters.Power.State.DeviceState) { SerialDbgPrintEx(SERPNPPOWER, "Already in requested power state\n"); status = STATUS_SUCCESS; break; } switch (pIrpStack->Parameters.Power.State.DeviceState) { case PowerDeviceD0: SerialDbgPrintEx(SERPNPPOWER, "Going to power state D0\n"); return SerialSetPowerD0(PDevObj, PIrp); case PowerDeviceD1: case PowerDeviceD2: case PowerDeviceD3: SerialDbgPrintEx(SERPNPPOWER, "Going to power state D3\n"); return SerialSetPowerD3(PDevObj, PIrp); default: break; } break; case IRP_MN_QUERY_POWER: SerialDbgPrintEx (SERPNPPOWER, "Got IRP_MN_QUERY_POWER Irp\n"); // // Check if we have a wait-wake pending and if so, // ensure we don't power down too far. // if (pDevExt->PendingWakeIrp != NULL || pDevExt->SendWaitWake) { if (pIrpStack->Parameters.Power.Type == DevicePowerState && pIrpStack->Parameters.Power.State.DeviceState > pDevExt->DeviceWake) { status = PIrp->IoStatus.Status = STATUS_INVALID_DEVICE_STATE; PoStartNextPowerIrp(PIrp); SerialCompleteRequest(pDevExt, PIrp, IO_NO_INCREMENT); return status; } } // // If no wait-wake, always successful // PIrp->IoStatus.Status = STATUS_SUCCESS; status = STATUS_SUCCESS; PoStartNextPowerIrp(PIrp); IoSkipCurrentIrpStackLocation(PIrp); return SerialPoCallDriver(pDevExt, pLowerDevObj, PIrp); } // switch (pIrpStack->MinorFunction) PowerExit:; PoStartNextPowerIrp(PIrp); // // Pass to the lower driver // IoSkipCurrentIrpStackLocation(PIrp); status = SerialPoCallDriver(pDevExt, pLowerDevObj, PIrp); return status; } NTSTATUS SerialSetPowerD0(IN PDEVICE_OBJECT PDevObj, IN PIRP PIrp) /*++ Routine Description: This routine Decides if we need to pass the power Irp down the stack or not. It then either sets up a completion handler to finish the initialization or calls the completion handler directly. Arguments: PDevObj - Pointer to the devobj we are changing power state on PIrp - Pointer to the IRP for the current request Return Value: Return status of either PoCallDriver of the call to the initialization routine. --*/ { PSERIAL_DEVICE_EXTENSION pDevExt = PDevObj->DeviceExtension; PIO_STACK_LOCATION pIrpStack = IoGetCurrentIrpStackLocation(PIrp); NTSTATUS status; // PIO_WORKITEM pWorkItem; PAGED_CODE(); SerialDbgPrintEx(SERTRACECALLS, "In SerialSetPowerD0\n"); SerialDbgPrintEx(SERPNPPOWER, "SetPowerD0 has IRP %x\n", PIrp); ASSERT(pDevExt->LowerDeviceObject); // // Set up completion to init device when it is on // KeClearEvent(&pDevExt->PowerD0Event); IoCopyCurrentIrpStackLocationToNext(PIrp); IoSetCompletionRoutine(PIrp, SerialSyncCompletion, &pDevExt->PowerD0Event, TRUE, TRUE, TRUE); SerialDbgPrintEx(SERPNPPOWER, "Calling next driver\n"); status = PoCallDriver(pDevExt->LowerDeviceObject, PIrp); if (status == STATUS_PENDING) { SerialDbgPrintEx(SERPNPPOWER, "Waiting for next driver\n"); KeWaitForSingleObject (&pDevExt->PowerD0Event, Executive, KernelMode, FALSE, NULL); } else { if (!NT_SUCCESS(status)) { PIrp->IoStatus.Status = status; PoStartNextPowerIrp(PIrp); SerialCompleteRequest(pDevExt, PIrp, IO_NO_INCREMENT); // SerialClearAccept(pDevExt,SERIAL_PNPACCEPT_POWER_DOWN); return status; } } if (!NT_SUCCESS(PIrp->IoStatus.Status)) { status = PIrp->IoStatus.Status; PoStartNextPowerIrp(PIrp); SerialCompleteRequest(pDevExt, PIrp, IO_NO_INCREMENT); // SerialClearAccept(pDevExt, SERIAL_PNPACCEPT_POWER_DOWN); return status; } else { status = PIrp->IoStatus.Status; } // // Restore the device // pDevExt->PowerState = PowerDeviceD0; // // Theoretically we could change states in the middle of processing // the restore which would result in a bad PKINTERRUPT being used // in SerialRestoreDeviceState(). // if (pDevExt->PNPState == SERIAL_PNP_STARTED) { SerialRestoreDeviceState(pDevExt); } // // Now that we are powered up, call PoSetPowerState // PoSetPowerState(PDevObj, pIrpStack->Parameters.Power.Type, pIrpStack->Parameters.Power.State); PoStartNextPowerIrp(PIrp); SerialCompleteRequest(pDevExt, PIrp, IO_NO_INCREMENT); // pWorkItem = IoAllocateWorkItem(PDevObj); // IoQueueWorkItem(pWorkItem, SerialPowerD0WorkerRoutine, DelayedWorkQueue, pWorkItem); SerialDbgPrintEx(SERTRACECALLS, "Leaving SerialSetPowerD0\n"); return status; } /*VOID SerialPowerD0WorkerRoutine( IN PDEVICE_OBJECT DeviceObject, IN PVOID pWorkItem) { PSERIAL_DEVICE_EXTENSION pDevExt = DeviceObject->DeviceExtension; SerialUnstallIrps(pDevExt); SerialClearAccept(pDevExt, SERIAL_PNPACCEPT_POWER_DOWN); IoFreeWorkItem(pWorkItem); } */ NTSTATUS SerialGotoPowerState(IN PDEVICE_OBJECT PDevObj, IN PSERIAL_DEVICE_EXTENSION PDevExt, IN DEVICE_POWER_STATE DevPowerState) /*++ Routine Description: This routine causes the driver to request the stack go to a particular power state. Arguments: PDevObj - Pointer to the device object for this device PDevExt - Pointer to the device extension we are working from DevPowerState - the power state we wish to go to Return Value: The function value is the final status of the call --*/ { KEVENT gotoPowEvent; NTSTATUS status; POWER_STATE powerState; PAGED_CODE(); SerialDbgPrintEx(SERTRACECALLS, "In SerialGotoPowerState\n"); powerState.DeviceState = DevPowerState; KeInitializeEvent(&gotoPowEvent, SynchronizationEvent, FALSE); status = PoRequestPowerIrp(PDevObj, IRP_MN_SET_POWER, powerState, SerialSystemPowerCompletion, &gotoPowEvent, NULL); if (status == STATUS_PENDING) { KeWaitForSingleObject(&gotoPowEvent, Executive, KernelMode, FALSE, NULL); status = STATUS_SUCCESS; } #if DBG if (!NT_SUCCESS(status)) { SerialDbgPrintEx(SERPNPPOWER, "SerialGotoPowerState FAILED\n"); } #endif SerialDbgPrintEx(SERTRACECALLS, "Leaving SerialGotoPowerState\n"); return status; } NTSTATUS SerialSetPowerD3(IN PDEVICE_OBJECT PDevObj, IN PIRP PIrp) /*++ Routine Description: This routine handles the SET_POWER minor function. Arguments: PDevObj - Pointer to the device object for this device PIrp - Pointer to the IRP for the current request Return Value: The function value is the final status of the call --*/ { NTSTATUS status = STATUS_SUCCESS; PSERIAL_DEVICE_EXTENSION pDevExt = PDevObj->DeviceExtension; PIO_STACK_LOCATION pIrpStack = IoGetCurrentIrpStackLocation(PIrp); KIRQL oldIrql; PAGED_CODE(); SerialDbgPrintEx(SERDIAG3, "In SerialSetPowerD3\n"); // SerialSetAccept(pDevExt,SERIAL_PNPACCEPT_POWER_DOWN); // // Send the wait wake now, just in time // if (pDevExt->SendWaitWake) { SerialSendWaitWake(pDevExt); } // // Before we power down, call PoSetPowerState // PoSetPowerState(PDevObj, pIrpStack->Parameters.Power.Type, pIrpStack->Parameters.Power.State); // // If the device is not closed, disable interrupts and allow the fifo's // to flush. // if (pDevExt->DeviceIsOpened == TRUE) { LARGE_INTEGER charTime; SetDeviceIsOpened(pDevExt, FALSE, TRUE); charTime.QuadPart = -SerialGetCharTime(pDevExt).QuadPart; // // Shut down the chip // SerialDisableUART(pDevExt); // // Drain the device // SerialDrainUART(pDevExt, &charTime); // // Save the device state // SerialSaveDeviceState(pDevExt); } else { SetDeviceIsOpened(pDevExt, FALSE, FALSE); } // // If the device is not open, we don't need to save the state; // we can just reset the device on power-up // PIrp->IoStatus.Status = STATUS_SUCCESS; pDevExt->PowerState = PowerDeviceD3; // // For what we are doing, we don't need a completion routine // since we don't race on the power requests. // PIrp->IoStatus.Status = STATUS_SUCCESS; PoStartNextPowerIrp(PIrp); IoSkipCurrentIrpStackLocation(PIrp); return SerialPoCallDriver(pDevExt, pDevExt->LowerDeviceObject, PIrp); } NTSTATUS SerialSendWaitWake(PSERIAL_DEVICE_EXTENSION PDevExt) /*++ Routine Description: This routine causes a waitwake IRP to be sent Arguments: PDevExt - Pointer to the device extension for this device Return Value: STATUS_INVALID_DEVICE_STATE if one is already pending, else result of call to PoRequestPowerIrp. --*/ { NTSTATUS status; PIRP pIrp; POWER_STATE powerState; PAGED_CODE(); // // Make sure one isn't pending already -- serial will only handle one at // a time. // if (PDevExt->PendingWakeIrp != NULL) { return STATUS_INVALID_DEVICE_STATE; } // // Make sure we are capable of waking the machine // if (PDevExt->SystemWake <= PowerSystemWorking) { return STATUS_INVALID_DEVICE_STATE; } if (PDevExt->DeviceWake == PowerDeviceUnspecified) { return STATUS_INVALID_DEVICE_STATE; } // // Send IRP to request wait wake and add a pending irp flag // // InterlockedIncrement(&PDevExt->PendingIRPCnt); powerState.SystemState = PDevExt->SystemWake; status = PoRequestPowerIrp(PDevExt->Pdo, IRP_MN_WAIT_WAKE, powerState, SerialWakeCompletion, PDevExt, &pIrp); if (status == STATUS_PENDING) { status = STATUS_SUCCESS; PDevExt->PendingWakeIrp = pIrp; } else if (!NT_SUCCESS(status)) { SerialIRPEpilogue(PDevExt); } return status; } VOID SerialWakeCompletion(IN PDEVICE_OBJECT PDevObj, IN UCHAR MinorFunction, IN POWER_STATE PowerState, IN PVOID Context, IN PIO_STATUS_BLOCK IoStatus) /*++ Routine Description: This routine handles completion of the waitwake IRP. Arguments: PDevObj - Pointer to the device object for this device MinorFunction - Minor function previously supplied to PoRequestPowerIrp PowerState - PowerState previously supplied to PoRequestPowerIrp Context - a pointer to the device extension IoStatus - current/final status of the waitwake IRP Return Value: The function value is the final status of attempting to process the waitwake. --*/ { NTSTATUS status; PSERIAL_DEVICE_EXTENSION pDevExt = (PSERIAL_DEVICE_EXTENSION)Context; POWER_STATE powerState; status = IoStatus->Status; if (NT_SUCCESS(status)) { // // A wakeup has occurred -- powerup our stack // powerState.DeviceState = PowerDeviceD0; PoRequestPowerIrp(pDevExt->Pdo, IRP_MN_SET_POWER, powerState, NULL, NULL, NULL); } pDevExt->PendingWakeIrp = NULL; SerialIRPEpilogue(pDevExt); return; } VOID SetDeviceIsOpened(IN PSERIAL_DEVICE_EXTENSION PDevExt, IN BOOLEAN DeviceIsOpened, IN BOOLEAN Reopen) { KIRQL oldIrql; BOOLEAN currentState; KeAcquireSpinLock(&PDevExt->ControlLock, &oldIrql); PDevExt->DeviceIsOpened = DeviceIsOpened; PDevExt->DeviceState.Reopen = Reopen; KeReleaseSpinLock(&PDevExt->ControlLock, oldIrql); }
25.148418
101
0.610294
[ "object" ]
0e1ae2f3c511dececf5e1f2bae6bc04bcd4b7ef7
824
h
C
RGNetworking/Classes/RGCache.h
ryangomba/RGNetworking
8071b55e1e4b0e5f8452bd92d37406abfea081b3
[ "MIT" ]
null
null
null
RGNetworking/Classes/RGCache.h
ryangomba/RGNetworking
8071b55e1e4b0e5f8452bd92d37406abfea081b3
[ "MIT" ]
null
null
null
RGNetworking/Classes/RGCache.h
ryangomba/RGNetworking
8071b55e1e4b0e5f8452bd92d37406abfea081b3
[ "MIT" ]
null
null
null
// Copyright 2004-present Facebook. All Rights Reserved. @interface RGCache : NSObject /* This class is thread safe. Objects cached in memory are automatically evicted when memory is low. Objects cached on disk are evicted using the LRU scheme when diskCapacity is exceeded. Completion blocks are called on a default priority queue. */ @property (nonatomic, assign) NSUInteger diskCapacity; @property (nonatomic, assign) NSUInteger maxObjectCount; + (instancetype)sharedCache; - (id)objectForKey:(NSString *)key; - (void)objectForKey:(NSString *)key completion:(void(^)(id object))completion; - (void)setObject:(id)object forKey:(NSString *)key; - (void)setObject:(id)object forKey:(NSString *)key completion:(void(^)(void))completion; - (void)removeObjectForKey:(NSString *)key; - (void)removeAllObjects; @end
30.518519
89
0.762136
[ "object" ]
0e2064a97b8a9b8d547e52f1b1f297dd14bcc4d5
12,866
c
C
freebsd4/sys/i386/isa/sound/mad16.c
MarginC/kame
2ef74fe29e4cca9b4a87a1d5041191a9e2e8be30
[ "BSD-3-Clause" ]
91
2015-01-05T15:18:31.000Z
2022-03-11T16:43:28.000Z
freebsd4/sys/i386/isa/sound/mad16.c
MarginC/kame
2ef74fe29e4cca9b4a87a1d5041191a9e2e8be30
[ "BSD-3-Clause" ]
1
2016-02-25T15:57:55.000Z
2016-02-25T16:01:02.000Z
freebsd4/sys/i386/isa/sound/mad16.c
MarginC/kame
2ef74fe29e4cca9b4a87a1d5041191a9e2e8be30
[ "BSD-3-Clause" ]
21
2015-02-07T08:23:07.000Z
2021-12-14T06:01:49.000Z
/* * sound/mad16.c * * Initialization code for OPTi MAD16 compatible audio chips. Including * * OPTi 82C928 MAD16 (replaced by C929) OAK OTI-601D Mozart * OPTi 82C929 MAD16 Pro * * These audio interface chips don't prduce sound themselves. They just connect * some other components (OPL-[234] and a WSS compatible codec) to the PC bus * and perform I/O, DMA and IRQ address decoding. There is also a UART for * the MPU-401 mode (not 82C928/Mozart). The Mozart chip appears to be * compatible with the 82C928 (can anybody confirm this?). * * NOTE! If you want to set CD-ROM address and/or joystick enable, define * MAD16_CONF in local.h as combination of the following bits: * * 0x01 - joystick disabled * * CD-ROM type selection (select just one): 0x00 - none 0x02 - Sony 31A * 0x04 - Mitsumi 0x06 - Panasonic (type "LaserMate", not * "SoundBlaster") 0x08 - Secondary IDE (address 0x170) 0x0a - Primary * IDE (address 0x1F0) * * For example Mitsumi with joystick disabled = 0x04|0x01 = 0x05 For example * LaserMate (for use with sbpcd) plus joystick = 0x06 * * MAD16_CDSEL: This defaults to CD I/O 0x340, no IRQ and DMA3 (DMA5 with * Mitsumi or IDE). If you like to change these, define MAD16_CDSEL with the * following bits: * * CD-ROM port: 0x00=340, 0x40=330, 0x80=360 or 0xc0=320 OPL4 select: 0x20=OPL4, * 0x00=OPL3 CD-ROM irq: 0x00=disabled, 0x04=IRQ5, 0x08=IRQ7, 0x0a=IRQ3, * 0x10=IRQ9, 0x14=IRQ10 and 0x18=IRQ11. * * CD-ROM DMA (Sony or Panasonic): 0x00=DMA3, 0x01=DMA2, 0x02=DMA1 or * 0x03=disabled or CD-ROM DMA (Mitsumi or IDE): 0x00=DMA5, 0x01=DMA6, * 0x02=DMA7 or 0x03=disabled * * For use with sbpcd, address 0x340, set MAD16_CDSEL to 0x03 or 0x23. * * Copyright by Hannu Savolainen 1995 * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. 2. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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 <i386/isa/sound/sound_config.h> #if defined(CONFIG_MAD16) static int already_initialized = 0; #define C928 1 #define MOZART 2 #define C929 3 /* * Registers * * The MAD16 occupies I/O ports 0xf8d to 0xf93 (fixed locations). All ports are * inactive by default. They can be activated by writing 0xE2 or 0xE3 to the * password register. The password is valid only until the next I/O read or * write. */ #define MC1_PORT 0xf8d /* SB address, CDROM interface type, joystick */ #define MC2_PORT 0xf8e /* CDROM address, IRQ, DMA, plus OPL4 bit */ #define MC3_PORT 0xf8f #define PASSWD_REG 0xf8f #define MC4_PORT 0xf90 #define MC5_PORT 0xf91 #define MC6_PORT 0xf92 #define MC7_PORT 0xf93 static int board_type = C928; static sound_os_info *mad16_osp; #ifndef DDB #define DDB(x) #endif static unsigned char mad_read(int port) { unsigned long flags; unsigned char tmp; flags = splhigh(); switch (board_type) { /* Output password */ case C928: case MOZART: outb(PASSWD_REG, 0xE2); break; case C929: outb(PASSWD_REG, 0xE3); break; } tmp = inb(port); splx(flags); return tmp; } static void mad_write(int port, int value) { unsigned long flags; flags = splhigh(); switch (board_type) { /* Output password */ case C928: case MOZART: outb(PASSWD_REG, 0xE2); break; case C929: outb(PASSWD_REG, 0xE3); break; } outb(port, (unsigned char) (value & 0xff)); splx(flags); } static int detect_mad16(void) { unsigned char tmp, tmp2; /* * Check that reading a register doesn't return bus float (0xff) when * the card is accessed using password. This may fail in case the * card is in low power mode. Normally at least the power saving mode * bit should be 0. */ if ((tmp = mad_read(MC1_PORT)) == 0xff) { DDB(printf("MC1_PORT returned 0xff\n")); return 0; } /* * Now check that the gate is closed on first I/O after writing the * password. (This is how a MAD16 compatible card works). */ if ((tmp2 = inb(MC1_PORT)) == tmp) { /* It didn't close */ DDB(printf("MC1_PORT didn't close after read (0x%02x)\n", tmp2)); return 0; } mad_write(MC1_PORT, tmp ^ 0x80); /* Togge a bit */ if ((tmp2 = mad_read(MC1_PORT)) != (tmp ^ 0x80)) { /* Compare the bit */ mad_write(MC1_PORT, tmp); /* Restore */ DDB(printf("Bit revert test failed (0x%02x, 0x%02x)\n", tmp, tmp2)); return 0; } mad_write(MC1_PORT, tmp); /* Restore */ return 1; /* Bingo */ } int probe_mad16(struct address_info * hw_config) { int i; static int valid_ports[] = {0x530, 0xe80, 0xf40, 0x604}; unsigned char tmp; unsigned char cs4231_mode = 0; int ad_flags = 0; if (already_initialized) return 0; mad16_osp = hw_config->osp; /* * Check that all ports return 0xff (bus float) when no password is * written to the password register. */ DDB(printf("--- Detecting MAD16 / Mozart ---\n")); /* * Then try to detect with the old password */ board_type = C928; DDB(printf("Detect using password = 0xE2\n")); if (!detect_mad16()) { /* No luck. Try different model */ board_type = C929; DDB(printf("Detect using password = 0xE3\n")); if (!detect_mad16()) return 0; DDB(printf("mad16.c: 82C929 detected\n")); } else { unsigned char model; if (((model = mad_read(MC3_PORT)) & 0x03) == 0x03) { DDB(printf("mad16.c: Mozart detected\n")); board_type = MOZART; } else { DDB(printf("mad16.c: 82C928 detected???\n")); board_type = C928; } } for (i = 0xf8d; i <= 0xf93; i++) DDB(printf("port %03x = %03x\n", i, mad_read(i))); /* * Set the WSS address */ tmp = 0x80; /* Enable WSS, Disable SB */ for (i = 0; i < 5; i++) { if (i > 3) { /* Not a valid port */ printf("MAD16/Mozart: Bad WSS base address 0x%x\n", hw_config->io_base); return 0; } if (valid_ports[i] == hw_config->io_base) { tmp |= i << 4; /* WSS port select bits */ break; } } /* * Set optional CD-ROM and joystick settings. */ #ifdef MAD16_CONF tmp |= ((MAD16_CONF) & 0x0f); /* CD-ROM and joystick bits */ #endif mad_write(MC1_PORT, tmp); #if defined(MAD16_CONF) && defined(MAD16_CDSEL) tmp = MAD16_CDSEL; #else tmp = 0x03; #endif #ifdef MAD16_OPL4 tmp |= 0x20; /* Enable OPL4 access */ #endif mad_write(MC2_PORT, tmp); mad_write(MC3_PORT, 0xf0); /* Disable SB */ if (!ad1848_detect(hw_config->io_base + 4, &ad_flags, mad16_osp)) return 0; if (ad_flags & (AD_F_CS4231 | AD_F_CS4248)) cs4231_mode = 0x02; /* CS4248/CS4231 sync delay switch */ if (board_type == C929) { mad_write(MC4_PORT, 0xa2); mad_write(MC5_PORT, 0xA5 | cs4231_mode); mad_write(MC6_PORT, 0x03); /* Disable MPU401 */ } else { mad_write(MC4_PORT, 0x02); mad_write(MC5_PORT, 0x30 | cs4231_mode); } for (i = 0xf8d; i <= 0xf93; i++) DDB(printf("port %03x after init = %03x\n", i, mad_read(i))); /* * Verify the WSS parameters */ if (0) { printf("MSS: I/O port conflict\n"); return 0; } /* * Check if the IO port returns valid signature. The original MS * Sound system returns 0x04 while some cards (AudioTriX Pro for * example) return 0x00. */ if ((inb(hw_config->io_base + 3) & 0x3f) != 0x04 && (inb(hw_config->io_base + 3) & 0x3f) != 0x00) { DDB(printf("No MSS signature detected on port 0x%x (0x%x)\n", hw_config->io_base, inb(hw_config->io_base + 3))); return 0; } if (hw_config->irq > 11) { printf("MSS: Bad IRQ %d\n", hw_config->irq); return 0; } if (hw_config->dma != 0 && hw_config->dma != 1 && hw_config->dma != 3) { printf("MSS: Bad DMA %d\n", hw_config->dma); return 0; } /* * Check that DMA0 is not in use with a 8 bit board. */ if (hw_config->dma == 0 && inb(hw_config->io_base + 3) & 0x80) { printf("MSS: Can't use DMA0 with a 8 bit card/slot\n"); return 0; } if (hw_config->irq > 7 && hw_config->irq != 9 && inb(hw_config->io_base + 3) & 0x80) { printf("MSS: Can't use IRQ%d with a 8 bit card/slot\n", hw_config->irq); return 0; } return 1; } void attach_mad16(struct address_info * hw_config) { static char interrupt_bits[12] = { -1, -1, -1, -1, -1, -1, -1, 0x08, -1, 0x10, 0x18, 0x20 }; char bits; static char dma_bits[4] = { 1, 2, 0, 3 }; int config_port = hw_config->io_base + 0, version_port = hw_config->io_base + 3; int ad_flags = 0, dma = hw_config->dma, dma2 = hw_config->dma2; unsigned char dma2_bit = 0; already_initialized = 1; if (!ad1848_detect(hw_config->io_base + 4, &ad_flags, mad16_osp)) return; /* * Set the IRQ and DMA addresses. */ bits = interrupt_bits[hw_config->irq]; if (bits == -1) return; outb(config_port, bits | 0x40); if ((inb(version_port) & 0x40) == 0) printf("[IRQ Conflict?]"); /* * Handle the capture DMA channel */ if (ad_flags & AD_F_CS4231 && dma2 != -1 && dma2 != dma) { if ((dma == 0 && dma2 == 1) || (dma == 1 && dma2 == 0) || (dma == 3 && dma2 == 0)) { dma2_bit = 0x04; /* Enable capture DMA */ } else { printf("MAD16: Invalid capture DMA\n"); dma2 = dma; } } else dma2 = dma; outb(config_port, bits | dma_bits[dma] | dma2_bit); /* Write IRQ+DMA setup */ ad1848_init("MAD16 WSS", hw_config->io_base + 4, hw_config->irq, dma, dma2, 0, hw_config->osp); } void attach_mad16_mpu(struct address_info * hw_config) { if (board_type < C929) {/* Early chip. No MPU support. Just SB MIDI */ #ifdef CONFIG_MIDI if (mad_read(MC1_PORT) & 0x20) hw_config->io_base = 0x240; else hw_config->io_base = 0x220; return mad16_sb_dsp_init(hw_config); #else return 0; #endif } #if (defined(CONFIG_MPU401) || defined(CONFIG_MPU_EMU)) && defined(CONFIG_MIDI) if (!already_initialized) return; attach_mpu401(hw_config); #endif } int probe_mad16_mpu(struct address_info * hw_config) { #if (defined(CONFIG_MPU401) || defined(CONFIG_MPU_EMU)) && defined(CONFIG_MIDI) static int mpu_attached = 0; static int valid_ports[] = {0x330, 0x320, 0x310, 0x300}; static short valid_irqs[] = {9, 10, 5, 7}; unsigned char tmp; int i; /* A variable with secret power */ if (!already_initialized) /* The MSS port must be initialized * first */ return 0; if (mpu_attached) /* Don't let them call this twice */ return 0; mpu_attached = 1; if (board_type < C929) {/* Early chip. No MPU support. Just SB MIDI */ #ifdef CONFIG_MIDI unsigned char tmp; tmp = mad_read(MC3_PORT); /* * MAD16 SB base is defined by the WSS base. It cannot be * changed alone. Ignore configured I/O base. Use the active * setting. */ if (mad_read(MC1_PORT) & 0x20) hw_config->io_base = 0x240; else hw_config->io_base = 0x220; switch (hw_config->irq) { case 5: tmp = (tmp & 0x3f) | 0x80; break; case 7: tmp = (tmp & 0x3f); break; case 11: tmp = (tmp & 0x3f) | 0x40; break; default: printf("mad16/Mozart: Invalid MIDI IRQ\n"); return 0; } mad_write(MC3_PORT, tmp | 0x04); return mad16_sb_dsp_detect(hw_config); #else return 0; #endif } tmp = 0x83; /* MPU-401 enable */ /* * Set the MPU base bits */ for (i = 0; i < 5; i++) { if (i > 3) { /* Out of array bounds */ printf("MAD16 / Mozart: Invalid MIDI port 0x%x\n", hw_config->io_base); return 0; } if (valid_ports[i] == hw_config->io_base) { tmp |= i << 5; break; } } /* * Set the MPU IRQ bits */ for (i = 0; i < 5; i++) { if (i > 3) { /* Out of array bounds */ printf("MAD16 / Mozart: Invalid MIDI IRQ %d\n", hw_config->irq); return 0; } if (valid_irqs[i] == hw_config->irq) { tmp |= i << 3; break; } } mad_write(MC6_PORT, tmp); /* Write MPU401 config */ return probe_mpu401(hw_config); #else return 0; #endif } /* That's all folks */ #endif
24.506667
93
0.651718
[ "model" ]
0e27e8a0b83423743aff6d0781605a7009d95795
12,501
h
C
RecoHI/HiEvtPlaneAlgos/interface/HiEvtPlaneFlatten.h
SWuchterl/cmssw
769b4a7ef81796579af7d626da6039dfa0347b8e
[ "Apache-2.0" ]
6
2017-09-08T14:12:56.000Z
2022-03-09T23:57:01.000Z
RecoHI/HiEvtPlaneAlgos/interface/HiEvtPlaneFlatten.h
SWuchterl/cmssw
769b4a7ef81796579af7d626da6039dfa0347b8e
[ "Apache-2.0" ]
545
2017-09-19T17:10:19.000Z
2022-03-07T16:55:27.000Z
RecoHI/HiEvtPlaneAlgos/interface/HiEvtPlaneFlatten.h
SWuchterl/cmssw
769b4a7ef81796579af7d626da6039dfa0347b8e
[ "Apache-2.0" ]
14
2017-10-04T09:47:21.000Z
2019-10-23T18:04:45.000Z
#ifndef __HiEvtPlaneFlatten__ #define __HiEvtPlaneFlatten__ #include <memory> #include <iostream> #include <string> #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/EDProducer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "DataFormats/Common/interface/Handle.h" #include "FWCore/Framework/interface/ESHandle.h" #include "DataFormats/HeavyIonEvent/interface/EvtPlane.h" #include <vector> #include <cmath> // // class declaration // class HiEvtPlaneFlatten { public: explicit HiEvtPlaneFlatten() { hbins_ = 1; hOrder_ = 9; vorder_ = 2; //sets default order of event plane } void init(int order, int nbins, std::string tag, int vord) { hOrder_ = order; //order of flattening vorder_ = vord; //1(v1), 2(v2), 3(v3), 4(v4) caloCentRefMinBin_ = -1; caloCentRefMaxBin_ = -1; hbins_ = nbins * nvtxbins_ * hOrder_; obins_ = nbins * nvtxbins_; if (hbins_ > MAXCUT) { hbins_ = 1; hOrder_ = 9; } for (int i = 0; i < hbins_; i++) { flatX_[i] = 0; flatY_[i] = 0; flatXDB_[i] = 0; flatYDB_[i] = 0; flatCnt_[i] = 0; } for (int i = 0; i < obins_; i++) { xoff_[i] = 0; yoff_[i] = 0; xoffDB_[i] = 0; yoffDB_[i] = 0; xyoffcnt_[i] = 0; xyoffmult_[i] = 0; pt_[i] = 0; pt2_[i] = 0; ptDB_[i] = 0; pt2DB_[i] = 0; ptcnt_[i] = 0; } } int getCutIndx(int centbin, double vtx, int iord) const { int cut; if (centbin < 0) return -1; int ibin = centbin; int ivtx = (vtx - minvtx_) / delvtx_; if (vtx < minvtx_ || ivtx >= nvtxbins_) return -1; cut = hOrder_ * nvtxbins_ * ibin + hOrder_ * ivtx + iord; if (cut < 0 || cut >= hbins_) return -1; return cut; } int getOffsetIndx(int centbin, double vtx) const { int cut; if (centbin < 0) return -1; int ibin = centbin; int ivtx = (vtx - minvtx_) / delvtx_; if (ivtx < 0 || ivtx > nvtxbins_) return -1; cut = nvtxbins_ * ibin + ivtx; if (cut < 0 || cut > hbins_) return -1; return cut; } void fill(double psi, double vtx, int centbin) { if (fabs(psi) > 4) return; for (int k = 0; k < hOrder_; k++) { double fsin = sin(vorder_ * (k + 1) * psi); double fcos = cos(vorder_ * (k + 1) * psi); int indx = getCutIndx(centbin, vtx, k); if (indx >= 0) { flatX_[indx] += fcos; flatY_[indx] += fsin; ++flatCnt_[indx]; } } } void fillOffset(double s, double c, uint m, double vtx, int centbin) { int indx = getOffsetIndx(centbin, vtx); if (indx >= 0) { xoff_[indx] += c; yoff_[indx] += s; xyoffmult_[indx] += m; ++xyoffcnt_[indx]; } } void fillPt(double ptval, double vtx, int centbin) { int indx = getOffsetIndx(centbin, vtx); if (indx >= 0) { pt_[indx] += ptval; pt2_[indx] += ptval * ptval; ++ptcnt_[indx]; } } void setCaloCentRefBins(const int caloCentRefMinBin, const int caloCentRefMaxBin) { caloCentRefMinBin_ = caloCentRefMinBin; caloCentRefMaxBin_ = caloCentRefMaxBin; } double getEtScale(double vtx, int centbin) const { int refmin = getOffsetIndx(caloCentRefMinBin_, vtx); int refmax = getOffsetIndx(caloCentRefMaxBin_, vtx); double caloCentRefVal_ = 0; for (int i = refmin; i <= refmax; i++) { caloCentRefVal_ += getPtDB(i); } caloCentRefVal_ /= refmax - refmin + 1.; if (caloCentRefMinBin_ < 0) return 1.; int indx = getOffsetIndx(centbin, vtx); if (indx < 0 || caloCentRefVal_ == 0 || getPtDB(indx) == 0) return 1.; return caloCentRefVal_ / getPtDB(indx); } double getW(double pt, double vtx, int centbin) const { int indx = getOffsetIndx(centbin, vtx); if (indx >= 0) { double scale = getEtScale(vtx, centbin); double ptval = getPtDB(indx) * scale; double pt2val = getPt2DB(indx) * pow(scale, 2); if (ptval > 0) return pt * scale - pt2val / ptval; } return 0.; } double getFlatPsi(double psi, double vtx, int centbin) const { double correction = 0; for (int k = 0; k < hOrder_; k++) { int indx = getCutIndx(centbin, vtx, k); if (indx >= 0) correction += (2. / (double)((k + 1) * vorder_)) * (flatXDB_[indx] * sin(vorder_ * (k + 1) * psi) - flatYDB_[indx] * cos(vorder_ * (k + 1) * psi)); } psi += correction; psi = bounds(psi); psi = bounds2(psi); return psi; } double getSoffset(double s, double vtx, int centbin) const { int indx = getOffsetIndx(centbin, vtx); if (indx >= 0) return s - yoffDB_[indx]; else return s; } double getCoffset(double c, double vtx, int centbin) const { int indx = getOffsetIndx(centbin, vtx); if (indx >= 0) return c - xoffDB_[indx]; else return c; } double getOffsetPsi(double s, double c) const { double psi = atan2(s, c) / vorder_; if ((fabs(s) < 1e-4) && (fabs(c) < 1e-4)) psi = 0.; psi = bounds(psi); psi = bounds2(psi); return psi; } ~HiEvtPlaneFlatten() {} int getHBins() const { return hbins_; } int getOBins() const { return obins_; } int getNvtx() const { return nvtxbins_; } double getVtxMin() const { return minvtx_; } double getVtxMax() const { return minvtx_ + nvtxbins_ * delvtx_; } int getNcent() const { return hbins_; } double getX(unsigned int bin) const { return flatX_[bin]; } double getY(unsigned int bin) const { return flatY_[bin]; } double getXoff(unsigned int bin) const { return xoff_[bin]; } double getYoff(unsigned int bin) const { return yoff_[bin]; } double getXoffDB(unsigned int bin) const { return xoffDB_[bin]; } double getYoffDB(unsigned int bin) const { return yoffDB_[bin]; } double getXYoffcnt(unsigned int bin) const { return xyoffcnt_[bin]; } double getXYoffmult(unsigned int bin) const { return xyoffmult_[bin]; } double getPt(unsigned int bin) const { return pt_[bin]; } double getPt2(unsigned int bin) const { return pt2_[bin]; } double getPtDB(unsigned int bin) const { if (bin < MAXCUTOFF) { return ptDB_[bin]; } else { return 0.; } } double getPt2DB(unsigned int bin) const { if (bin < MAXCUTOFF) { return pt2DB_[bin]; } else { return 0.; } } double getPtcnt(unsigned int bin) const { return ptcnt_[bin]; } double getXDB(unsigned int bin) const { return flatXDB_[bin]; } double getYDB(unsigned int bin) const { return flatYDB_[bin]; } double getCnt(unsigned int bin) const { return flatCnt_[bin]; } void setXDB(unsigned int indx, double val) { flatXDB_[indx] = val; } void setYDB(unsigned int indx, double val) { flatYDB_[indx] = val; } void setXoffDB(unsigned int indx, double val) { xoffDB_[indx] = val; } void setYoffDB(unsigned int indx, double val) { yoffDB_[indx] = val; } void setPtDB(unsigned int indx, double val) { ptDB_[indx] = val; } void setPt2DB(unsigned int indx, double val) { pt2DB_[indx] = val; } double bounds(double ang) const { if (ang < -M_PI) ang += 2. * M_PI; if (ang > M_PI) ang -= 2. * M_PI; return ang; } double bounds2(double ang) const { double range = M_PI / (double)vorder_; while (ang < -range) { ang += 2 * range; } while (ang > range) { ang -= 2 * range; } return ang; } void setCentRes1(unsigned int bin, double res, double err) { if (bin < 100) { centRes1_[bin] = res; centResErr1_[bin] = err; } } void setCentRes2(unsigned int bin, double res, double err) { if (bin < 50) { centRes2_[bin] = res; centResErr2_[bin] = err; } } void setCentRes5(unsigned int bin, double res, double err) { if (bin < 20) { centRes5_[bin] = res; centResErr5_[bin] = err; } } void setCentRes10(unsigned int bin, double res, double err) { if (bin < 10) { centRes10_[bin] = res; centResErr10_[bin] = err; } } void setCentRes20(unsigned int bin, double res, double err) { if (bin < 5) { centRes20_[bin] = res; centResErr20_[bin] = err; } } void setCentRes25(unsigned int bin, double res, double err) { if (bin < 4) { centRes25_[bin] = res; centResErr25_[bin] = err; } } void setCentRes30(unsigned int bin, double res, double err) { if (bin < 3) { centRes30_[bin] = res; centResErr30_[bin] = err; } } void setCentRes40(unsigned int bin, double res, double err) { if (bin < 2) { centRes40_[bin] = res; centResErr40_[bin] = err; } } double getCentRes1(unsigned int bin) const { if (bin < 100) { return centRes1_[bin]; } else { return 0.; } } double getCentRes2(unsigned int bin) const { if (bin < 50) { return centRes2_[bin]; } else { return 0.; } } double getCentRes5(unsigned int bin) const { if (bin < 20) { return centRes5_[bin]; } else { return 0.; } } double getCentRes10(unsigned int bin) const { if (bin < 10) { return centRes10_[bin]; } else { return 0.; } } double getCentRes20(unsigned int bin) const { if (bin < 5) { return centRes20_[bin]; } else { return 0.; } } double getCentRes25(unsigned int bin) const { if (bin < 4) { return centRes25_[bin]; } else { return 0.; } } double getCentRes30(unsigned int bin) const { if (bin < 3) { return centRes30_[bin]; } else { return 0.; } } double getCentRes40(unsigned int bin) const { if (bin < 2) { return centRes40_[bin]; } else { return 0.; } } double getCentResErr1(unsigned int bin) const { if (bin < 100) { return centResErr1_[bin]; } else { return 0.; } } double getCentResErr2(unsigned int bin) const { if (bin < 50) { return centResErr2_[bin]; } else { return 0.; } } double getCentResErr5(unsigned int bin) const { if (bin < 20) { return centResErr5_[bin]; } else { return 0.; } } double getCentResErr10(unsigned int bin) const { if (bin < 10) { return centResErr10_[bin]; } else { return 0.; } } double getCentResErr20(unsigned int bin) const { if (bin < 5) { return centResErr20_[bin]; } else { return 0.; } } double getCentResErr25(unsigned int bin) const { if (bin < 4) { return centResErr25_[bin]; } else { return 0.; } } double getCentResErr30(unsigned int bin) const { if (bin < 3) { return centResErr30_[bin]; } else { return 0.; } } double getCentResErr40(unsigned int bin) const { if (bin < 2) { return centResErr40_[bin]; } else { return 0.; } } private: static constexpr int nvtxbins_ = 10; static constexpr double minvtx_ = -25.; static constexpr double delvtx_ = 5.; static const int MAXCUT = 10000; static const int MAXCUTOFF = 1000; double flatX_[MAXCUT]; double flatY_[MAXCUT]; double flatXDB_[MAXCUT]; double flatYDB_[MAXCUT]; double flatCnt_[MAXCUT]; double xoff_[MAXCUTOFF]; double yoff_[MAXCUTOFF]; double xoffDB_[MAXCUTOFF]; double yoffDB_[MAXCUTOFF]; double xyoffcnt_[MAXCUTOFF]; uint xyoffmult_[MAXCUTOFF]; double pt_[MAXCUTOFF]; double pt2_[MAXCUTOFF]; double ptDB_[MAXCUTOFF]; double pt2DB_[MAXCUTOFF]; double ptcnt_[MAXCUTOFF]; double centRes1_[100]; double centResErr1_[100]; double centRes2_[50]; double centResErr2_[50]; double centRes5_[20]; double centResErr5_[20]; double centRes10_[10]; double centResErr10_[10]; double centRes20_[5]; double centResErr20_[5]; double centRes25_[4]; double centResErr25_[4]; double centRes30_[3]; double centResErr30_[3]; double centRes40_[2]; double centResErr40_[2]; int hOrder_; //flattening order int hbins_; //number of bins needed for flattening int obins_; //number of (x,y) offset bins int vorder_; //order of flattened event plane int caloCentRefMinBin_; //min ref centrality bin for calo weight scale int caloCentRefMaxBin_; //max ref centrality bin for calo weight scale }; #endif
25.935685
118
0.601952
[ "vector" ]
0e31290eb3da424f602d0f87956fa517b247194c
13,032
h
C
Project/Temp/StagingArea/Data/il2cppOutput/mscorlib_System_Collections_ObjectModel_ReadOnlyCo4005162163MethodDeclarations.h
Yuunagi-Yu/NumberDisk
f1cf414dbfe8d0094d3ef11b37839f6caf58ae9f
[ "MIT" ]
null
null
null
Project/Temp/StagingArea/Data/il2cppOutput/mscorlib_System_Collections_ObjectModel_ReadOnlyCo4005162163MethodDeclarations.h
Yuunagi-Yu/NumberDisk
f1cf414dbfe8d0094d3ef11b37839f6caf58ae9f
[ "MIT" ]
null
null
null
Project/Temp/StagingArea/Data/il2cppOutput/mscorlib_System_Collections_ObjectModel_ReadOnlyCo4005162163MethodDeclarations.h
Yuunagi-Yu/NumberDisk
f1cf414dbfe8d0094d3ef11b37839f6caf58ae9f
[ "MIT" ]
null
null
null
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include <assert.h> #include <exception> #include "codegen/il2cpp-codegen.h" #include "mscorlib_System_Collections_ObjectModel_ReadOnlyCo2875234987MethodDeclarations.h" // System.Void System.Collections.ObjectModel.ReadOnlyCollection`1<UnityEngine.Component>::.ctor(System.Collections.Generic.IList`1<T>) #define ReadOnlyCollection_1__ctor_m1084399902(__this, ___list0, method) (( void (*) (ReadOnlyCollection_1_t4005162163 *, Il2CppObject*, const MethodInfo*))ReadOnlyCollection_1__ctor_m3671019970_gshared)(__this, ___list0, method) // System.Void System.Collections.ObjectModel.ReadOnlyCollection`1<UnityEngine.Component>::System.Collections.Generic.ICollection<T>.Add(T) #define ReadOnlyCollection_1_System_Collections_Generic_ICollectionU3CTU3E_Add_m1184767334(__this, ___item0, method) (( void (*) (ReadOnlyCollection_1_t4005162163 *, Component_t3819376471 *, const MethodInfo*))ReadOnlyCollection_1_System_Collections_Generic_ICollectionU3CTU3E_Add_m2989589458_gshared)(__this, ___item0, method) // System.Void System.Collections.ObjectModel.ReadOnlyCollection`1<UnityEngine.Component>::System.Collections.Generic.ICollection<T>.Clear() #define ReadOnlyCollection_1_System_Collections_Generic_ICollectionU3CTU3E_Clear_m3200661762(__this, method) (( void (*) (ReadOnlyCollection_1_t4005162163 *, const MethodInfo*))ReadOnlyCollection_1_System_Collections_Generic_ICollectionU3CTU3E_Clear_m454937302_gshared)(__this, method) // System.Void System.Collections.ObjectModel.ReadOnlyCollection`1<UnityEngine.Component>::System.Collections.Generic.IList<T>.Insert(System.Int32,T) #define ReadOnlyCollection_1_System_Collections_Generic_IListU3CTU3E_Insert_m466654313(__this, ___index0, ___item1, method) (( void (*) (ReadOnlyCollection_1_t4005162163 *, int32_t, Component_t3819376471 *, const MethodInfo*))ReadOnlyCollection_1_System_Collections_Generic_IListU3CTU3E_Insert_m4272763307_gshared)(__this, ___index0, ___item1, method) // System.Boolean System.Collections.ObjectModel.ReadOnlyCollection`1<UnityEngine.Component>::System.Collections.Generic.ICollection<T>.Remove(T) #define ReadOnlyCollection_1_System_Collections_Generic_ICollectionU3CTU3E_Remove_m295331897(__this, ___item0, method) (( bool (*) (ReadOnlyCollection_1_t4005162163 *, Component_t3819376471 *, const MethodInfo*))ReadOnlyCollection_1_System_Collections_Generic_ICollectionU3CTU3E_Remove_m3199809075_gshared)(__this, ___item0, method) // System.Void System.Collections.ObjectModel.ReadOnlyCollection`1<UnityEngine.Component>::System.Collections.Generic.IList<T>.RemoveAt(System.Int32) #define ReadOnlyCollection_1_System_Collections_Generic_IListU3CTU3E_RemoveAt_m955327341(__this, ___index0, method) (( void (*) (ReadOnlyCollection_1_t4005162163 *, int32_t, const MethodInfo*))ReadOnlyCollection_1_System_Collections_Generic_IListU3CTU3E_RemoveAt_m962041751_gshared)(__this, ___index0, method) // T System.Collections.ObjectModel.ReadOnlyCollection`1<UnityEngine.Component>::System.Collections.Generic.IList<T>.get_Item(System.Int32) #define ReadOnlyCollection_1_System_Collections_Generic_IListU3CTU3E_get_Item_m1004125849(__this, ___index0, method) (( Component_t3819376471 * (*) (ReadOnlyCollection_1_t4005162163 *, int32_t, const MethodInfo*))ReadOnlyCollection_1_System_Collections_Generic_IListU3CTU3E_get_Item_m70085287_gshared)(__this, ___index0, method) // System.Void System.Collections.ObjectModel.ReadOnlyCollection`1<UnityEngine.Component>::System.Collections.Generic.IList<T>.set_Item(System.Int32,T) #define ReadOnlyCollection_1_System_Collections_Generic_IListU3CTU3E_set_Item_m3817427724(__this, ___index0, ___value1, method) (( void (*) (ReadOnlyCollection_1_t4005162163 *, int32_t, Component_t3819376471 *, const MethodInfo*))ReadOnlyCollection_1_System_Collections_Generic_IListU3CTU3E_set_Item_m1547026160_gshared)(__this, ___index0, ___value1, method) // System.Boolean System.Collections.ObjectModel.ReadOnlyCollection`1<UnityEngine.Component>::System.Collections.Generic.ICollection<T>.get_IsReadOnly() #define ReadOnlyCollection_1_System_Collections_Generic_ICollectionU3CTU3E_get_IsReadOnly_m1583843580(__this, method) (( bool (*) (ReadOnlyCollection_1_t4005162163 *, const MethodInfo*))ReadOnlyCollection_1_System_Collections_Generic_ICollectionU3CTU3E_get_IsReadOnly_m4041967064_gshared)(__this, method) // System.Void System.Collections.ObjectModel.ReadOnlyCollection`1<UnityEngine.Component>::System.Collections.ICollection.CopyTo(System.Array,System.Int32) #define ReadOnlyCollection_1_System_Collections_ICollection_CopyTo_m3185566035(__this, ___array0, ___index1, method) (( void (*) (ReadOnlyCollection_1_t4005162163 *, Il2CppArray *, int32_t, const MethodInfo*))ReadOnlyCollection_1_System_Collections_ICollection_CopyTo_m3664791405_gshared)(__this, ___array0, ___index1, method) // System.Collections.IEnumerator System.Collections.ObjectModel.ReadOnlyCollection`1<UnityEngine.Component>::System.Collections.IEnumerable.GetEnumerator() #define ReadOnlyCollection_1_System_Collections_IEnumerable_GetEnumerator_m3303869368(__this, method) (( Il2CppObject * (*) (ReadOnlyCollection_1_t4005162163 *, const MethodInfo*))ReadOnlyCollection_1_System_Collections_IEnumerable_GetEnumerator_m531171980_gshared)(__this, method) // System.Int32 System.Collections.ObjectModel.ReadOnlyCollection`1<UnityEngine.Component>::System.Collections.IList.Add(System.Object) #define ReadOnlyCollection_1_System_Collections_IList_Add_m3969170939(__this, ___value0, method) (( int32_t (*) (ReadOnlyCollection_1_t4005162163 *, Il2CppObject *, const MethodInfo*))ReadOnlyCollection_1_System_Collections_IList_Add_m3780136817_gshared)(__this, ___value0, method) // System.Void System.Collections.ObjectModel.ReadOnlyCollection`1<UnityEngine.Component>::System.Collections.IList.Clear() #define ReadOnlyCollection_1_System_Collections_IList_Clear_m1293000091(__this, method) (( void (*) (ReadOnlyCollection_1_t4005162163 *, const MethodInfo*))ReadOnlyCollection_1_System_Collections_IList_Clear_m3983677501_gshared)(__this, method) // System.Boolean System.Collections.ObjectModel.ReadOnlyCollection`1<UnityEngine.Component>::System.Collections.IList.Contains(System.Object) #define ReadOnlyCollection_1_System_Collections_IList_Contains_m2568400699(__this, ___value0, method) (( bool (*) (ReadOnlyCollection_1_t4005162163 *, Il2CppObject *, const MethodInfo*))ReadOnlyCollection_1_System_Collections_IList_Contains_m1990607517_gshared)(__this, ___value0, method) // System.Int32 System.Collections.ObjectModel.ReadOnlyCollection`1<UnityEngine.Component>::System.Collections.IList.IndexOf(System.Object) #define ReadOnlyCollection_1_System_Collections_IList_IndexOf_m3330195617(__this, ___value0, method) (( int32_t (*) (ReadOnlyCollection_1_t4005162163 *, Il2CppObject *, const MethodInfo*))ReadOnlyCollection_1_System_Collections_IList_IndexOf_m606942423_gshared)(__this, ___value0, method) // System.Void System.Collections.ObjectModel.ReadOnlyCollection`1<UnityEngine.Component>::System.Collections.IList.Insert(System.Int32,System.Object) #define ReadOnlyCollection_1_System_Collections_IList_Insert_m3230331490(__this, ___index0, ___value1, method) (( void (*) (ReadOnlyCollection_1_t4005162163 *, int32_t, Il2CppObject *, const MethodInfo*))ReadOnlyCollection_1_System_Collections_IList_Insert_m691705570_gshared)(__this, ___index0, ___value1, method) // System.Void System.Collections.ObjectModel.ReadOnlyCollection`1<UnityEngine.Component>::System.Collections.IList.Remove(System.Object) #define ReadOnlyCollection_1_System_Collections_IList_Remove_m1116041508(__this, ___value0, method) (( void (*) (ReadOnlyCollection_1_t4005162163 *, Il2CppObject *, const MethodInfo*))ReadOnlyCollection_1_System_Collections_IList_Remove_m3182494192_gshared)(__this, ___value0, method) // System.Void System.Collections.ObjectModel.ReadOnlyCollection`1<UnityEngine.Component>::System.Collections.IList.RemoveAt(System.Int32) #define ReadOnlyCollection_1_System_Collections_IList_RemoveAt_m2975154628(__this, ___index0, method) (( void (*) (ReadOnlyCollection_1_t4005162163 *, int32_t, const MethodInfo*))ReadOnlyCollection_1_System_Collections_IList_RemoveAt_m572840272_gshared)(__this, ___index0, method) // System.Boolean System.Collections.ObjectModel.ReadOnlyCollection`1<UnityEngine.Component>::System.Collections.ICollection.get_IsSynchronized() #define ReadOnlyCollection_1_System_Collections_ICollection_get_IsSynchronized_m2572957083(__this, method) (( bool (*) (ReadOnlyCollection_1_t4005162163 *, const MethodInfo*))ReadOnlyCollection_1_System_Collections_ICollection_get_IsSynchronized_m2871048729_gshared)(__this, method) // System.Object System.Collections.ObjectModel.ReadOnlyCollection`1<UnityEngine.Component>::System.Collections.ICollection.get_SyncRoot() #define ReadOnlyCollection_1_System_Collections_ICollection_get_SyncRoot_m2229789939(__this, method) (( Il2CppObject * (*) (ReadOnlyCollection_1_t4005162163 *, const MethodInfo*))ReadOnlyCollection_1_System_Collections_ICollection_get_SyncRoot_m769863805_gshared)(__this, method) // System.Boolean System.Collections.ObjectModel.ReadOnlyCollection`1<UnityEngine.Component>::System.Collections.IList.get_IsFixedSize() #define ReadOnlyCollection_1_System_Collections_IList_get_IsFixedSize_m2453603270(__this, method) (( bool (*) (ReadOnlyCollection_1_t4005162163 *, const MethodInfo*))ReadOnlyCollection_1_System_Collections_IList_get_IsFixedSize_m942145650_gshared)(__this, method) // System.Boolean System.Collections.ObjectModel.ReadOnlyCollection`1<UnityEngine.Component>::System.Collections.IList.get_IsReadOnly() #define ReadOnlyCollection_1_System_Collections_IList_get_IsReadOnly_m58323911(__this, method) (( bool (*) (ReadOnlyCollection_1_t4005162163 *, const MethodInfo*))ReadOnlyCollection_1_System_Collections_IList_get_IsReadOnly_m1367736517_gshared)(__this, method) // System.Object System.Collections.ObjectModel.ReadOnlyCollection`1<UnityEngine.Component>::System.Collections.IList.get_Item(System.Int32) #define ReadOnlyCollection_1_System_Collections_IList_get_Item_m2613484842(__this, ___index0, method) (( Il2CppObject * (*) (ReadOnlyCollection_1_t4005162163 *, int32_t, const MethodInfo*))ReadOnlyCollection_1_System_Collections_IList_get_Item_m3336878134_gshared)(__this, ___index0, method) // System.Void System.Collections.ObjectModel.ReadOnlyCollection`1<UnityEngine.Component>::System.Collections.IList.set_Item(System.Int32,System.Object) #define ReadOnlyCollection_1_System_Collections_IList_set_Item_m46032121(__this, ___index0, ___value1, method) (( void (*) (ReadOnlyCollection_1_t4005162163 *, int32_t, Il2CppObject *, const MethodInfo*))ReadOnlyCollection_1_System_Collections_IList_set_Item_m1799572719_gshared)(__this, ___index0, ___value1, method) // System.Boolean System.Collections.ObjectModel.ReadOnlyCollection`1<UnityEngine.Component>::Contains(T) #define ReadOnlyCollection_1_Contains_m1299584476(__this, ___value0, method) (( bool (*) (ReadOnlyCollection_1_t4005162163 *, Component_t3819376471 *, const MethodInfo*))ReadOnlyCollection_1_Contains_m1227826160_gshared)(__this, ___value0, method) // System.Void System.Collections.ObjectModel.ReadOnlyCollection`1<UnityEngine.Component>::CopyTo(T[],System.Int32) #define ReadOnlyCollection_1_CopyTo_m3227834514(__this, ___array0, ___index1, method) (( void (*) (ReadOnlyCollection_1_t4005162163 *, ComponentU5BU5D_t4136971630*, int32_t, const MethodInfo*))ReadOnlyCollection_1_CopyTo_m4257276542_gshared)(__this, ___array0, ___index1, method) // System.Collections.Generic.IEnumerator`1<T> System.Collections.ObjectModel.ReadOnlyCollection`1<UnityEngine.Component>::GetEnumerator() #define ReadOnlyCollection_1_GetEnumerator_m2693820243(__this, method) (( Il2CppObject* (*) (ReadOnlyCollection_1_t4005162163 *, const MethodInfo*))ReadOnlyCollection_1_GetEnumerator_m1627519329_gshared)(__this, method) // System.Int32 System.Collections.ObjectModel.ReadOnlyCollection`1<UnityEngine.Component>::IndexOf(T) #define ReadOnlyCollection_1_IndexOf_m2128612316(__this, ___value0, method) (( int32_t (*) (ReadOnlyCollection_1_t4005162163 *, Component_t3819376471 *, const MethodInfo*))ReadOnlyCollection_1_IndexOf_m1981423404_gshared)(__this, ___value0, method) // System.Int32 System.Collections.ObjectModel.ReadOnlyCollection`1<UnityEngine.Component>::get_Count() #define ReadOnlyCollection_1_get_Count_m4277622971(__this, method) (( int32_t (*) (ReadOnlyCollection_1_t4005162163 *, const MethodInfo*))ReadOnlyCollection_1_get_Count_m2562379905_gshared)(__this, method) // T System.Collections.ObjectModel.ReadOnlyCollection`1<UnityEngine.Component>::get_Item(System.Int32) #define ReadOnlyCollection_1_get_Item_m1487616837(__this, ___index0, method) (( Component_t3819376471 * (*) (ReadOnlyCollection_1_t4005162163 *, int32_t, const MethodInfo*))ReadOnlyCollection_1_get_Item_m191392387_gshared)(__this, ___index0, method)
164.962025
359
0.859269
[ "object" ]
0e349f1cf00e5732a0232930ed631fdceafa07b2
48,847
c
C
3rdparty/gnsstk/gps.c
eglrp/otSim
24b5773536856847bfaa90a47e331ccf9475bb9b
[ "MIT" ]
2
2021-12-29T16:21:31.000Z
2022-01-09T11:29:11.000Z
3rdparty/gnsstk/gps.c
eglrp/otSim
24b5773536856847bfaa90a47e331ccf9475bb9b
[ "MIT" ]
null
null
null
3rdparty/gnsstk/gps.c
eglrp/otSim
24b5773536856847bfaa90a47e331ccf9475bb9b
[ "MIT" ]
2
2021-04-09T12:46:15.000Z
2022-01-09T11:29:21.000Z
/** \file gps.c \brief GNSS core 'c' function library: GPS specific functions. \author Glenn D. MacGougan (GDM) \date 2005-08-14 \since 2005-07-31 \b "LICENSE INFORMATION" \n Copyright (c) 2007, refer to 'author' doxygen tags \n All rights reserved. \n Redistribution and use in source and binary forms, with or without modification, are permitted provided the following conditions are met: \n - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. \n - 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. \n - The name(s) of the contributor(s) may not be used to endorse or promote products derived from this software without specific prior written permission. \n THIS SOFTWARE IS PROVIDED BY THE 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 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 <math.h> #include "gnss_error.h" #include "gps.h" #include "constants.h" #include "geodesy.h" /*************************************************************************************************/ // local preprocessor constant definitions, any related enumerations and descriptors #ifndef GPS_CLOCK_CORRECTION_RELATIVISTIC_CONSTANT_F #define GPS_CLOCK_CORRECTION_RELATIVISTIC_CONSTANT_F (-4.442807633e-10) //!< combined constant defined in ICD-GPS-200C p. 88 [s]/[sqrt(m)] #endif #ifndef GPS_UNIVERSAL_GRAVITY_CONSTANT #define GPS_UNIVERSAL_GRAVITY_CONSTANT (3.986005e14) //!< gravity constant defined on ICD-GPS-200C p. 98 [m^3/s^2] #endif #ifndef GPS_RATIO_OF_SQUARED_FREQUENCIES_L1_OVER_L2 #define GPS_RATIO_OF_SQUARED_FREQUENCIES_L1_OVER_L2 (1.6469444444444444444444444444444) //!< (f_L1/f_L2)^2 = (1575.42/1227.6)^2 = (77/60)^2 #endif #ifndef GPS_WGS84_EARTH_ROTATION_RATE #define GPS_WGS84_EARTH_ROTATION_RATE (7.2921151467e-05) //!< constant defined on ICD-GPS-200C p. 98 [rad/s] #endif #define TWO_TO_THE_POWER_OF_55 (36028797018963968.0) #define TWO_TO_THE_POWER_OF_43 (8796093022208.0) #define TWO_TO_THE_POWER_OF_33 (8589934592.0) #define TWO_TO_THE_POWER_OF_31 (2147483648.0) #define TWO_TO_THE_POWER_OF_29 (536870912.0) #define TWO_TO_THE_POWER_OF_19 (524288.0) // /*************************************************************************************************/ void GPS_ComputeSatelliteClockCorrectionAndDrift( const unsigned short transmission_gpsweek, //!< GPS week when signal was transmit (0-1024+) [weeks] const double transmission_gpstow, //!< GPS time of week when signal was transmit [s] const unsigned short ephem_week, //!< ephemeris: GPS week (0-1024+) [weeks] const unsigned toe, //!< ephemeris: time of week [s] const unsigned toc, //!< ephemeris: clock reference time of week [s] const double af0, //!< ephemeris: polynomial clock correction coefficient [s], Note: parameters from ephemeris preferred vs almanac (22 vs 11 bits) const double af1, //!< ephemeris: polynomial clock correction coefficient [s/s], Note: parameters from ephemeris preferred vs almanac (16 vs 11 bits) const double af2, //!< ephemeris: polynomial clock correction coefficient [s/s^2] const double ecc, //!< ephemeris: eccentricity of satellite orbit [] const double sqrta, //!< ephemeris: square root of the semi-major axis of orbit [m^(1/2)] const double delta_n, //!< ephemeris: mean motion difference from computed value [rad] const double m0, //!< ephemeris: mean anomaly at reference time [rad] const double tgd, //!< ephemeris: group delay differential between L1 and L2 [s] const unsigned char mode, //!< 0=L1 only, 1=L2 only (see p. 90, ICD-GPS-200C) double* clock_correction, //!< satellite clock correction [m] double* clock_drift //!< satellite clock drift correction [m/s] ) { unsigned char i; // counter double tot; // time of transmission (including gps week) [s] double tk; // time from ephemeris reference epoch [s] double tc; // time from clock reference epoch [s] double d_tr; // relativistic correction term [s] double d_tsv; // SV PRN code phase time offset [s] double a; // semi-major axis of orbit [m] double n; // corrected mean motion [rad/s] double M; // mean anomaly, [rad] (Kepler's equation for eccentric anomaly, solved by iteration) double E; // eccentric anomaly [rad] // compute the times from the reference epochs // By including the week in the calculation, week rollover and old ephmeris bugs are mitigated // The result should be between -302400 and 302400 if the ephemeris is within one week of transmission tot = transmission_gpsweek*SECONDS_IN_WEEK + transmission_gpstow; tk = tot - (ephem_week*SECONDS_IN_WEEK + toe); tc = tot - (ephem_week*SECONDS_IN_WEEK + toc); // compute the corrected mean motion term a = sqrta*sqrta; n = sqrt(GPS_UNIVERSAL_GRAVITY_CONSTANT / (a*a*a)); // computed mean motion n += delta_n; // corrected mean motion // Kepler's equation for eccentric anomaly M = m0 + n*tk; // mean anomaly E = M; for (i = 0; i < 7; i++) { E = M + ecc * sin(E); } // relativistic correction d_tr = GPS_CLOCK_CORRECTION_RELATIVISTIC_CONSTANT_F * ecc * sqrta * sin(E); // [s] d_tr *= LIGHTSPEED; // clock correcton d_tsv = af0 + af1*tc + af2*tc*tc; // [s] if (mode == 0) { // L1 only d_tsv -= tgd; // [s] } else if (mode == 1) { // L2 only d_tsv -= tgd*GPS_RATIO_OF_SQUARED_FREQUENCIES_L1_OVER_L2; // [s] } // clock correction *clock_correction = d_tsv*LIGHTSPEED + d_tr; // [m] // clock drift *clock_drift = (af1 + 2.0*af2*tc) * LIGHTSPEED; // [m/s] } void GPS_ComputeSatellitePositionAndVelocity( const unsigned short transmission_gpsweek, //!< GPS week when signal was transmit (0-1024+) [weeks] const double transmission_gpstow, //!< GPS time of week when signal was transmit [s] const unsigned short ephem_week, //!< ephemeris: GPS week (0-1024+) [weeks] const unsigned toe, //!< ephemeris: time of week [s] const double m0, //!< ephemeris: mean anomaly at reference time [rad] const double delta_n, //!< ephemeris: mean motion difference from computed value [rad] const double ecc, //!< ephemeris: eccentricity [] const double sqrta, //!< ephemeris: square root of the semi-major axis [m^(1/2)] const double omega0, //!< ephemeris: longitude of ascending node of orbit plane at weekly epoch [rad] const double i0, //!< ephemeris: inclination angle at reference time [rad] const double w, //!< ephemeris: argument of perigee [rad] const double omegadot, //!< ephemeris: rate of right ascension [rad/s] const double idot, //!< ephemeris: rate of inclination angle [rad/s] const double cuc, //!< ephemeris: amplitude of the cosine harmonic correction term to the argument of latitude [rad] const double cus, //!< ephemeris: amplitude of the sine harmonic correction term to the argument of latitude [rad] const double crc, //!< ephemeris: amplitude of the cosine harmonic correction term to the orbit radius [m] const double crs, //!< ephemeris: amplitude of the sine harmonic correction term to the orbit radius [m] const double cic, //!< ephemeris: amplitude of the cosine harmonic correction term to the angle of inclination [rad] const double cis, //!< ephemeris: amplitude of the sine harmonic correction term to the angle of inclination [rad] const double estimateOfTrueRange, //!< best estimate of the signal propagation time (in m) for Sagnac effect compensation [m] const double estimteOfRangeRate, //!< best estimate of the true signal Doppler (in m/s) for Sagnac effect compensation [m/s] double* x, //!< satellite x [m] double* y, //!< satellite y [m] double* z, //!< satellite z [m] double* vx, //!< satellite velocity x [m/s] double* vy, //!< satellite velocity y [m/s] double* vz //!< satellite velocity z [m/s] ) { unsigned char j; // counter double tot; // time of transmission (including gps week) [s] double tk; // time from ephemeris reference epoch [s] double a; // semi-major axis of orbit [m] double n; // corrected mean motion [rad/s] double M; // mean anomaly, [rad] (Kepler's equation for eccentric anomaly, solved by iteration) double E; // eccentric anomaly [rad] double v; // true anomaly [rad] double u; // argument of latitude, corrected [rad] double r; // radius in the orbital plane [m] double i; // orbital inclination [rad] double cos2u; // cos(2*u) [] double sin2u; // sin(2*u) [] double d_u; // argument of latitude correction [rad] double d_r; // radius correction [m] double d_i; // inclination correction [rad] double x_op; // x position in the orbital plane [m] double y_op; // y position in the orbital plane [m] double omegak; // corrected longitude of the ascending node [rad] double cos_omegak; // cos(omegak) double sin_omegak; // sin(omegak) double cosu; // cos(u) double sinu; // sin(u) double cosi; // cos(i) double sini; // sin(i) double cosE; // cos(E) double sinE; // sin(E) double omegadotk; // corrected rate of right ascension [rad/s] double edot; // edot = n/(1.0 - ecc*cos(E)), [rad/s] double vdot; // d/dt of true anomaly [rad/s] double udot; // d/dt of argument of latitude [rad/s] double idotdot; // d/dt of the rate of the inclination angle [rad/s^2] double rdot; // d/dt of the radius in the orbital plane [m/s] double tmpa; // temp double tmpb; // temp double vx_op; // x velocity in the orbital plane [m/s] double vy_op; // y velocity in the orbital plane [m/s] // compute the times from the reference epochs // By including the week in the calculation, week rollover and older ephemeris bugs are mitigated // The result should be between -302400 and 302400 if the ephemeris is within one week of transmission tot = transmission_gpsweek*SECONDS_IN_WEEK + transmission_gpstow; tk = tot - (ephem_week*SECONDS_IN_WEEK + toe); // compute the corrected mean motion term a = sqrta*sqrta; n = sqrt(GPS_UNIVERSAL_GRAVITY_CONSTANT / (a*a*a)); // computed mean motion n += delta_n; // corrected mean motion // Kepler's equation for eccentric anomaly M = m0 + n*tk; // mean anomaly E = M; for (j = 0; j < 7; j++) { E = M + ecc * sin(E); } cosE = cos(E); sinE = sin(E); // true anomaly v = atan2((sqrt(1.0 - ecc*ecc)*sinE), (cosE - ecc)); // argument of latitude u = v + w; // radius in orbital plane r = a * (1.0 - ecc * cos(E)); // orbital inclination i = i0; // second harmonic perturbations // cos2u = cos(2.0*u); sin2u = sin(2.0*u); // argument of latitude correction d_u = cuc * cos2u + cus * sin2u; // radius correction d_r = crc * cos2u + crs * sin2u; // correction to inclination d_i = cic * cos2u + cis * sin2u; // corrected argument of latitude u += d_u; // corrected radius r += d_r; // corrected inclination i += d_i + idot * tk; // positions in orbital plane cosu = cos(u); sinu = sin(u); x_op = r * cosu; y_op = r * sinu; // compute the corrected longitude of the ascending node // This equation deviates from that in Table 20-IV p. 100 GPSICD200C with the inclusion of the // signal propagation time (estimateOfTrueRange/LIGHTSPEED) term. This compensates for the Sagnac effect. // The omegak term is thus sensitive to the estimateOfTrueRange term which is usually unknown without // prior information. The average signal propagation time/range (70ms * c) can be used on first use // and this function must be called again to iterate this term. The sensitivity of the omegak term // typically requires N iterations - GDM_DEBUG{find out how many iterations are needed, how sensitive to the position?} omegak = omega0 + (omegadot - GPS_WGS84_EARTH_ROTATION_RATE)*tk - GPS_WGS84_EARTH_ROTATION_RATE*(toe + estimateOfTrueRange / LIGHTSPEED); // compute the WGS84 ECEF coordinates, // vector r with components x & y is now rotated using, R3(-omegak)*R1(-i) cos_omegak = cos(omegak); sin_omegak = sin(omegak); cosi = cos(i); sini = sin(i); *x = x_op * cos_omegak - y_op * sin_omegak * cosi; *y = x_op * sin_omegak + y_op * cos_omegak * cosi; *z = y_op * sini; // Satellite Velocity Computations are below // see Reference // Remodi, B. M (2004). GPS Tool Box: Computing satellite velocities using the broadcast ephemeris. // GPS Solutions. Volume 8(3), 2004. pp. 181-183 // // example source code was available at [http://www.ngs.noaa.gov/gps-toolbox/bc_velo/bc_velo.c] // recomputed the cos and sin of the corrected argument of latitude cos2u = cos(2.0*u); sin2u = sin(2.0*u); edot = n / (1.0 - ecc*cosE); vdot = sinE*edot*(1.0 + ecc*cos(v)) / (sin(v)*(1.0 - ecc*cosE)); udot = vdot + 2.0*(cus*cos2u - cuc*sin2u)*vdot; rdot = a*ecc*sinE*n / (1.0 - ecc*cosE) + 2.0*(crs*cos2u - crc*sin2u)*vdot; idotdot = idot + (cis*cos2u - cic*sin2u)*2.0*vdot; vx_op = rdot*cosu - y_op*udot; vy_op = rdot*sinu + x_op*udot; // corrected rate of right ascension including similarily as above, for omegak, // compensation for the Sagnac effect omegadotk = omegadot - GPS_WGS84_EARTH_ROTATION_RATE*(1.0 + estimteOfRangeRate / LIGHTSPEED); tmpa = vx_op - y_op*cosi*omegadotk; tmpb = x_op*omegadotk + vy_op*cosi - y_op*sini*idotdot; *vx = tmpa * cos_omegak - tmpb * sin_omegak; *vy = tmpa * sin_omegak + tmpb * cos_omegak; *vz = vy_op*sini + y_op*cosi*idotdot; } void GPS_ComputeUserToSatelliteRange( const double userX, //!< user X position WGS84 ECEF [m] const double userY, //!< user Y position WGS84 ECEF [m] const double userZ, //!< user Z position WGS84 ECEF [m] const double satX, //!< satellite X position WGS84 ECEF [m] const double satY, //!< satellite Y positoin WGS84 ECEF [m] const double satZ, //!< satellite Z position WGS84 ECEF [m] double* range //!< user to satellite range [m] ) { double dx; double dy; double dz; dx = satX - userX; dy = satY - userY; dz = satZ - userZ; // compute the range *range = sqrt(dx*dx + dy*dy + dz*dz); } void GPS_ComputeUserToSatelliteRangeAndRangeRate( const double userX, //!< user X position WGS84 ECEF [m] const double userY, //!< user Y position WGS84 ECEF [m] const double userZ, //!< user Z position WGS84 ECEF [m] const double userVx, //!< user X velocity WGS84 ECEF [m/s] const double userVy, //!< user Y velocity WGS84 ECEF [m/s] const double userVz, //!< user Z velocity WGS84 ECEF [m/s] const double satX, //!< satellite X position WGS84 ECEF [m] const double satY, //!< satellite Y positoin WGS84 ECEF [m] const double satZ, //!< satellite Z position WGS84 ECEF [m] const double satVx, //!< satellite X velocity WGS84 ECEF [m/s] const double satVy, //!< satellite Y velocity WGS84 ECEF [m/s] const double satVz, //!< satellite Z velocity WGS84 ECEF [m/s] double* range, //!< user to satellite range [m] double* range_rate //!< user to satellite range rate [m/s] ) { double dx; double dy; double dz; dx = satX - userX; dy = satY - userY; dz = satZ - userZ; // compute the range *range = sqrt(dx*dx + dy*dy + dz*dz); // compute the range rate // this method uses the NovAtel style sign convention! *range_rate = (userVx - satVx)*dx + (userVy - satVy)*dy + (userVz - satVz)*dz; *range_rate /= *range; } void GPS_ComputeSatellitePositionVelocityAzimuthElevationDoppler_BasedOnAlmanacData( const double userX, //!< user X position WGS84 ECEF [m] const double userY, //!< user Y position WGS84 ECEF [m] const double userZ, //!< user Z position WGS84 ECEF [m] const unsigned short gpsweek, //!< user gps week (0-1024+) [week] const double gpstow, //!< user time of week [s] const double toa, //!< time of applicability [s] const unsigned short almanac_week, //!< gps week of almanac (0-1024+) [week] const unsigned short prn, //!< GPS prn number [] const double ecc, //!< eccentricity [] const double i0, //!< orbital inclination at reference time [rad] const double omegadot, //!< rate of right ascension [rad/s] const double sqrta, //!< square root of the semi-major axis [m^(1/2)] const double omega0, //!< longitude of ascending node of orbit plane at weekly epoch [rad] const double w, //!< argument of perigee [rad] const double m0, //!< mean anomaly at reference time [rad] const double af0, //!< polynomial clock correction coefficient (clock bias) [s], Note: parameters from ephemeris preferred vs almanac (22 vs 11 bits) const double af1, //!< polynomial clock correction coefficient (clock drift) [s/s], Note: parameters from ephemeris preferred vs almanac (16 vs 11 bits) double* clock_correction, //!< clock correction for this satellite for this epoch [m] double* clock_drift, //!< clock drift correction for this satellite for this epoch [m/s] double* satX, //!< satellite X position WGS84 ECEF [m] double* satY, //!< satellite Y position WGS84 ECEF [m] double* satZ, //!< satellite Z position WGS84 ECEF [m] double* satVx, //!< satellite X velocity WGS84 ECEF [m/s] double* satVy, //!< satellite Y velocity WGS84 ECEF [m/s] double* satVz, //!< satellite Z velocity WGS84 ECEF [m/s] double* azimuth, //!< satelilte azimuth [rad] double* elevation, //!< satelilte elevation [rad] double* doppler //!< satellite doppler with respect to the user position [m/s], Note: User must convert to Hz ) { double tow; // user time of week adjusted with the clock corrections [s] double range; // range estimate between user and satellite [m] double range_rate; // range_rate esimate between user and satellite [m/s] double x; // sat X position [m] double y; // sat Y position [m] double z; // sat Z position [m] double vx; // sat X velocity [m/s] double vy; // sat Y velocity [m/s] double vz; // sat Z velocity [m/s] unsigned short week; // user week adjusted with the clock correction if needed [week] unsigned char i; // counter i = (unsigned char)prn; // get rid of a debug msg :) // initialize to zero x = y = z = vx = vy = vz = 0.0; GPS_ComputeSatelliteClockCorrectionAndDrift( gpsweek, gpstow, almanac_week, (unsigned)toa, (unsigned)toa, af0, af1, 0.0, ecc, sqrta, 0.0, m0, 0.0, 0, clock_correction, clock_drift); // adjust for week rollover week = gpsweek; tow = gpstow + (*clock_correction) / LIGHTSPEED; if (tow < 0.0) { tow += SECONDS_IN_WEEK; week--; } if (tow > 604800.0) { tow -= SECONDS_IN_WEEK; week++; } // iterate to include the Sagnac correction // since the range is unknown, an approximate of 70 ms is good enough // to start the iterations so that 2 iterations are enough range = 0.070*LIGHTSPEED; range_rate = 0.0; for (i = 0; i < 2; i++) { GPS_ComputeSatellitePositionAndVelocity( week, tow, almanac_week, (unsigned)toa, m0, 0.0, ecc, sqrta, omega0, i0, w, omegadot, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, range, range_rate, &x, &y, &z, &vx, &vy, &vz); GPS_ComputeUserToSatelliteRangeAndRangeRate( userX, userY, userZ, 0.0, 0.0, 0.0, x, y, z, vx, vy, vz, &range, &range_rate); } GEODESY_ComputeAzimuthAndElevationAnglesBetweenToPointsInTheEarthFixedFrame( GEODESY_REFERENCE_ELLIPSE_WGS84, userX, userY, userZ, x, y, z, elevation, // sets the elevation azimuth); // sets the azimuth *satX = x; *satY = y; *satZ = z; *satVx = vx; *satVy = vy; *satVz = vz; *doppler = range_rate; } void GPS_ComputeSatellitePositionVelocityAzimuthElevationDoppler_BasedOnEphmerisData( const double userX, //!< user X position WGS84 ECEF [m] const double userY, //!< user Y position WGS84 ECEF [m] const double userZ, //!< user Z position WGS84 ECEF [m] const unsigned short gpsweek, //!< gps week of signal transmission (0-1024+) [week] const double gpstow, //!< time of week of signal transmission (gpstow-psr/c) [s] const unsigned short ephem_week, //!< ephemeris: GPS week (0-1024+) [weeks] const unsigned toe, //!< ephemeris: time of week [s] const unsigned toc, //!< ephemeris: clock reference time of week [s] const double af0, //!< ephemeris: polynomial clock correction coefficient [s], Note: parameters from ephemeris preferred vs almanac (22 vs 11 bits) const double af1, //!< ephemeris: polynomial clock correction coefficient [s/s], Note: parameters from ephemeris preferred vs almanac (16 vs 11 bits) const double af2, //!< ephemeris: polynomial clock correction coefficient [s/s^2] const double tgd, //!< ephemeris: group delay differential between L1 and L2 [s] const double m0, //!< ephemeris: mean anomaly at reference time [rad] const double delta_n, //!< ephemeris: mean motion difference from computed value [rad/s] const double ecc, //!< ephemeris: eccentricity [] const double sqrta, //!< ephemeris: square root of the semi-major axis [m^(1/2)] const double omega0, //!< ephemeris: longitude of ascending node of orbit plane at weekly epoch [rad] const double i0, //!< ephemeris: inclination angle at reference time [rad] const double w, //!< ephemeris: argument of perigee [rad] const double omegadot, //!< ephemeris: rate of right ascension [rad/s] const double idot, //!< ephemeris: rate of inclination angle [rad/s] const double cuc, //!< ephemeris: amplitude of the cosine harmonic correction term to the argument of latitude [rad] const double cus, //!< ephemeris: amplitude of the sine harmonic correction term to the argument of latitude [rad] const double crc, //!< ephemeris: amplitude of the cosine harmonic correction term to the orbit radius [m] const double crs, //!< ephemeris: amplitude of the sine harmonic correction term to the orbit radius [m] const double cic, //!< ephemeris: amplitude of the cosine harmonic correction term to the angle of inclination [rad] const double cis, //!< ephemeris: amplitude of the sine harmonic correction term to the angle of inclination [rad] double* clock_correction, //!< clock correction for this satellite for this epoch [m] double* clock_drift, //!< clock drift correction for this satellite for this epoch [m/s] double* satX, //!< satellite X position WGS84 ECEF [m] double* satY, //!< satellite Y position WGS84 ECEF [m] double* satZ, //!< satellite Z position WGS84 ECEF [m] double* satVx, //!< satellite X velocity WGS84 ECEF [m/s] double* satVy, //!< satellite Y velocity WGS84 ECEF [m/s] double* satVz, //!< satellite Z velocity WGS84 ECEF [m/s] double* azimuth, //!< satelilte azimuth [rad] double* elevation, //!< satelilte elevation [rad] double* doppler //!< satellite doppler with respect to the user position [m/s], Note: User must convert to Hz ) { double tow; // user time of week adjusted with the clock corrections [s] double range; // range estimate between user and satellite [m] double range_rate; // range_rate esimate between user and satellite [m/s] double x; // sat X position [m] double y; // sat Y position [m] double z; // sat Z position [m] double vx; // sat X velocity [m/s] double vy; // sat Y velocity [m/s] double vz; // sat Z velocity [m/s] unsigned short week; // user week adjusted with the clock correction if needed [week] unsigned char i; // counter // initialize to zero x = y = z = vx = vy = vz = 0.0; GPS_ComputeSatelliteClockCorrectionAndDrift( gpsweek, gpstow, ephem_week, toe, toc, af0, af1, af2, ecc, sqrta, delta_n, m0, tgd, 0, clock_correction, clock_drift); // adjust for week rollover week = gpsweek; tow = gpstow + (*clock_correction) / LIGHTSPEED; if (tow < 0.0) { tow += SECONDS_IN_WEEK; week--; } if (tow > 604800.0) { tow -= SECONDS_IN_WEEK; week++; } // iterate to include the Sagnac correction // since the range is unknown, an approximate of 70 ms is good enough to start // the iterations so that 2 iterations are enough for sub mm accuracy range = 0.070*LIGHTSPEED; range_rate = 0.0; for (i = 0; i < 2; i++) { GPS_ComputeSatellitePositionAndVelocity( week, tow, ephem_week, toe, m0, delta_n, ecc, sqrta, omega0, i0, w, omegadot, idot, cuc, cus, crc, crs, cic, cis, range, range_rate, &x, &y, &z, &vx, &vy, &vz); GPS_ComputeUserToSatelliteRangeAndRangeRate( userX, userY, userZ, 0.0, 0.0, 0.0, x, y, z, vx, vy, vz, &range, &range_rate); } GEODESY_ComputeAzimuthAndElevationAnglesBetweenToPointsInTheEarthFixedFrame( GEODESY_REFERENCE_ELLIPSE_WGS84, userX, userY, userZ, x, y, z, elevation, // sets the elevation azimuth); // sets the azimuth *satX = x; *satY = y; *satZ = z; *satVx = vx; *satVy = vy; *satVz = vz; *doppler = range_rate; } BOOL GPS_DecodeRawGPSEphemeris( const unsigned char subframe1[30], //!< subframe 1 data, 30 bytes * 8bits/byte = 240 bits, thus parity bits have been removed const unsigned char subframe2[30], //!< subframe 2 data, 30 bytes * 8bits/byte = 240 bits, thus parity bits have been removed const unsigned char subframe3[30], //!< subframe 3 data, 30 bytes * 8bits/byte = 240 bits, thus parity bits have been removed unsigned short prn, //!< GPS PRN number (helps with debugging) unsigned* tow, //!< time of week in subframe1, the time of the leading bit edge of subframe 2 [s] unsigned short* iodc, //!< 10 bit issue of data (clock), 8 LSB bits will match the iode [] unsigned char* iode, //!< 8 bit issue of data (ephemeris) [] unsigned* toe, //!< reference time ephemeris (0-604800) [s] unsigned* toc, //!< reference time (clock) (0-604800) [s] unsigned short* week, //!< 10 bit gps week 0-1023 (user must account for week rollover ) [week] unsigned char* health, //!< 6 bit health parameter, 0 if healthy, unhealth othersize [0=healthy] unsigned char* alert_flag, //!< 1 = URA may be worse than indicated [0,1] unsigned char* anti_spoof, //!< anti-spoof flag from 0=off, 1=on [0,1] unsigned char* code_on_L2, //!< 0=reserved, 1=P code on L2, 2=C/A on L2 [0,1,2] unsigned char* ura, //!< User Range Accuracy lookup code, 0 is excellent, 15 is use at own risk [0-15], see p. 83 GPSICD200C unsigned char* L2_P_data_flag, //!< flag indicating if P is on L2 1=true [0,1] unsigned char* fit_interval_flag, //!< fit interval flag (four hour interval or longer) 0=4 fours, 1=greater [0,1] unsigned short* age_of_data_offset, //!< age of data offset [s] double* tgd, //!< group delay [s] double* af2, //!< polynomial clock correction coefficient (rate of clock drift) [s/s^2] double* af1, //!< polynomial clock correction coefficient (clock drift) [s/s] double* af0, //!< polynomial clock correction coefficient (clock bias) [s] double* m0, //!< mean anomaly at reference time [rad] double* delta_n, //!< mean motion difference from computed value [rad/s] double* ecc, //!< eccentricity [] double* sqrta, //!< square root of the semi-major axis [m^(1/2)] double* omega0, //!< longitude of ascending node of orbit plane at weekly epoch [rad] double* i0, //!< inclination angle at reference time [rad] double* w, //!< argument of perigee [rad] double* omegadot, //!< rate of right ascension [rad/s] double* idot, //!< rate of inclination angle [rad/s] double* cuc, //!< amplitude of the cosine harmonic correction term to the argument of latitude [rad] double* cus, //!< amplitude of the sine harmonic correction term to the argument of latitude [rad] double* crc, //!< amplitude of the cosine harmonic correction term to the orbit radius [m] double* crs, //!< amplitude of the sine harmonic correction term to the orbit radius [m] double* cic, //!< amplitude of the cosine harmonic correction term to the angle of inclination [rad] double* cis //!< amplitude of the sine harmonic correction term to the angle of inclination [rad] ) { /* ------------------------------------------------------------------ SUBFRAME1 ------------------------------------------------------------------ TERM, NR BITS, BITS NO PARITY, BITS WITH PARITY preamble, 8, 1-8, 1-8, TLM, 14, 9-22, 9-22 reserved, 2, 23-24, 23-24 --PARITY-- 6, ----- 25-30 TOW, 17, 25-41, 31-47 alert_flag, 1, 42, 48 anti_spoof_flag, 1, 43, 49 subframeID, 3, 44-46, 50-52 parity_related, 2, 47-48, 53-54 --PARITY-- 6, ----- 25-30 week, 10, 49-58, 61-70 code_on_L2, 2, 59,60, 71-72 ura, 4, 61-64, 73-76 health, 6, 65-70, 77-82 iodc_MSB, 2, 71-72, 83-84 --PARITY-- 6, ----- 85-90 L2_P_data_flag, 1, 73, 91 reserved, 23, 74-96, 92-114 --PARITY-- 6, ----- 115-120 reserved, 24, 97-120, 121-144 --PARITY-- 6, ----- 25-30 reserved, 24, 121-144, 151-174 --PARITY-- 6, ----- 25-30 reserved, 16, 145-160, 181-196 tgd, 8, 161-168, 197-204 --PARITY-- 6, ----- 205-210 iodc_LSB, 8, 169-176, 211-218 toc, 16, 177-192, 219-234 --PARITY-- 6, ----- 235-240 af2, 8, 193-200, 241-248 af1, 16, 201-216, 249-264 --PARITY-- 6, ----- 265-270 af0, 22, 217-238, 271-292 parity_related, 2, 239-240, 293-294 --PARITY-- 6, ----- 295-300 ------------------------------------------------------------------ SUBFRAME2 ------------------------------------------------------------------ TERM, NR BITS, BITS NO PARITY, BITS WITH PARITY preamble, 8, 1-8, 1-8, TLM, 14, 9-22, 9-22 reserved, 2, 23-24, 23-24 --PARITY-- 6, ----- 25-30 TOW, 17, 25-41, 31-47 alert_flag, 1, 42, 48 anti_spoof_flag, 1, 43, 49 subframeID, 3, 44-46, 50-52 parity_related, 2, 47-48, 53-54 --PARITY-- 6, ----- 25-30 iode, 8, 49-56, 61-68 crs, 16, 57-72, 69-84 --PARITY-- 6, ----- 95-90 delta_n, 16, 73-88, 91-106 m0_MSB, 8, 89-96, 107-114 --PARITY-- 6, ----- 115-120 m0_LSB, 24, 97-120, 121-144 --PARITY-- 6, ----- 145-150 cuc, 16, 121-136, 151-166 ecc_MSB, 8, 137-144, 167-174 --PARITY-- 6, ----- 175-180 ecc_LSB, 24, 145-168, 181-204 --PARITY-- 6, ----- 205-210 cus, 16, 169-184, 211-226 sqrta_MSB, 8, 185-192, 227-234 --PARITY-- 6, ----- 235-240 sqrta_LSB, 24, 193-216, 241-264 --PARITY-- 6, ----- 265-270 toe, 16, 217-232, 271-286 fit_interval_flag, 1, 233, 287 age_of_data_offset, 5, 234-238, 288-292 parity_related, 2, 239-240, 293-294 --PARITY-- 6, ----- 295-300 ------------------------------------------------------------------ SUBFRAME3 ------------------------------------------------------------------ TERM, NR BITS, BITS NO PARITY, BITS WITH PARITY preamble, 8, 1-8, 1-8, TLM, 14, 9-22, 9-22 reserved, 2, 23-24, 23-24 --PARITY-- 6, ----- 25-30 TOW, 17, 25-41, 31-47 alert_flag, 1, 42, 48 anti_spoof_flag, 1, 43, 49 subframeID, 3, 44-46, 50-52 parity_related, 2, 47-48, 53-54 --PARITY-- 6, ----- 25-30 cic, 16, 49-64, 61-76 omega0_MSB, 8, 65-72, 77-84 --PARITY-- 6, ----- 85-90 omega0_LSB, 24, 73-96, 91-114 --PARITY-- 6, ----- 115-120 cis, 16, 97-112, 121-136 i0_MSB, 8, 113-120, 137-144 --PARITY-- 6, ----- 145-150 i0_LSB, 24, 121-144, 151-174 --PARITY-- 6, ----- 175-180 crc, 16, 145-160, 181-196 w_MSB, 8, 161-168, 197-204 --PARITY-- 6, ----- 205-210 w_LSB, 24, 169-192, 211-234 --PARITY-- 6, ----- 235-240 omegadot, 24, 193-216, 241-264 --PARITY-- 6, ----- 265-270 iode, 8, 217-224, 271-278 idot, 14, 225-238, 279-292 parity_related, 2, 239-240, 293-294 ------------------------------------------------------------------ */ unsigned char subframe_id; // subrame id unsigned char iode_subframe1; // 8 LSB bits of the iodc in subframe 1 unsigned char iode_subframe2; // subframe2 iode unsigned char iode_subframe3; // subframe3 iode // temporary variables of different size char s8; short s16; int s32; unsigned short u16a, u16b; unsigned u32a, u32b, u32c, u32d; u16a = prn; // gets rid of a debug msg :) //------------------------------------------------------------------ // SUBFRAME1 //------------------------------------------------------------------ // time of week, actually a 19 bit value, 17 MSBs are available, 2 LSB bits are always zero u32a = subframe1[3] << 11; u32b = subframe1[4] << 3; u32c = (subframe1[5] & 0x80) >> 5; *tow = (u32a | u32b | u32c); // [z-count 1.5s intervals] *tow = (*tow * 3) / 2; // converted to [s] // alert_flag *alert_flag = (unsigned char)((subframe1[5] & 0x40) >> 6); // anti-spoof *anti_spoof = (unsigned char)((subframe1[5] & 0x20) >> 5); // confirm that this is subframe 1 subframe_id = (unsigned char)((subframe1[5] & 0x1C) >> 2); if (subframe_id != 1) { GNSS_ERROR_MSG("if( subframe_id != 1 )"); return FALSE; } // GPS Week u16a = (unsigned short)(subframe1[6] << 2); u16b = (unsigned short)(subframe1[7] >> 6); *week = (unsigned short)(u16a | u16b); /// code_on_L2 *code_on_L2 = (unsigned char)((subframe1[7] & 0x30) >> 4); // ura *ura = (unsigned char)((subframe1[7] & 0x0F)); // health *health = (unsigned char)(subframe1[8] >> 2); // issue of data clock u16a = (unsigned short)((subframe1[8] & 0x03) << 8); u16b = (unsigned short)(subframe1[21]); *iodc = (unsigned short)(u16a | u16b); // [] // iode subframe1 for consistency checking iode_subframe1 = subframe1[21]; // L2_P_data_flag *L2_P_data_flag = (unsigned char)((subframe1[9] & 0x80) >> 7); // tgd s8 = subframe1[20]; // signed *tgd = s8 / TWO_TO_THE_POWER_OF_31; // toc u16a = (unsigned short)(subframe1[22] << 8); u16b = (unsigned short)(subframe1[23]); *toc = (unsigned)((u16a | u16b)) * 16; // af2 s8 = subframe1[24]; // signed *af2 = s8; *af2 /= TWO_TO_THE_POWER_OF_55; // af1 u16a = (unsigned short)(subframe1[25] << 8); u16b = subframe1[26]; s16 = (unsigned short)(u16a | u16b); // signed value *af1 = s16; *af1 /= TWO_TO_THE_POWER_OF_43; // af0 u32a = subframe1[27] << 24; u32b = subframe1[28] << 16; u32c = subframe1[29] & 0xFC; u32c <<= 8; // align to the sign bit (two's complement integer) u32d = (u32a | u32b | u32c); s32 = (int)(u32d); s32 >>= 10; // 22 bit value *af0 = s32; *af0 /= TWO_TO_THE_POWER_OF_31; //------------------------------------------------------------------ // SUBFRAME2 //------------------------------------------------------------------ // confirm that this is subframe 2 subframe_id = (unsigned char)((subframe2[5] & 0x1C) >> 2); if (subframe_id != 2) { GNSS_ERROR_MSG("if( subframe_id != 2 )"); return FALSE; } // iode subframe2 iode_subframe2 = subframe2[6]; // crs u16a = (unsigned short)(subframe2[7] << 8); u16b = subframe2[8]; s16 = (unsigned short)(u16a | u16b); // signed value *crs = s16; *crs /= 32.0; // [m] // delta_n u16a = (unsigned short)(subframe2[9] << 8); u16b = subframe2[10]; s16 = (short)(u16a | u16b); // signed value *delta_n = s16; *delta_n *= PI / TWO_TO_THE_POWER_OF_43; // [rad/s] // m0 u32a = subframe2[11] << 24; u32b = subframe2[12] << 16; u32c = subframe2[13] << 8; u32d = subframe2[14]; s32 = (u32a | u32b | u32c | u32d); // signed value *m0 = s32; *m0 *= PI / TWO_TO_THE_POWER_OF_31; // [rad] // cuc u16a = (unsigned short)(subframe2[15] << 8); u16b = subframe2[16]; s16 = (short)(u16a | u16b); // signed value *cuc = s16; *cuc /= TWO_TO_THE_POWER_OF_29; // [rad] // ecc u32a = subframe2[17] << 24; u32b = subframe2[18] << 16; u32c = subframe2[19] << 8; u32d = subframe2[20]; *ecc = u32a | u32b | u32c | u32d; *ecc /= TWO_TO_THE_POWER_OF_33; // [] // cus u16a = (unsigned short)(subframe2[21] << 8); u16b = subframe2[22]; s16 = (short)(u16a | u16b); *cus = s16; *cus /= TWO_TO_THE_POWER_OF_29; // [rad] // sqrta u32a = subframe2[23] << 24; u32b = subframe2[24] << 16; u32c = subframe2[25] << 8; u32d = subframe2[26]; *sqrta = u32a | u32b | u32c | u32d; *sqrta /= TWO_TO_THE_POWER_OF_19; // [sqrt(m)] // toe u16a = (unsigned short)(subframe2[27] << 8); u16b = subframe2[28]; *toe = (unsigned)((u16a | u16b)) * 16; // [s] // fit_interval_flag *fit_interval_flag = (unsigned char)(subframe2[29] >> 7); // age_of_data_offset *age_of_data_offset = (unsigned short)((subframe2[29] & 0x74) >> 2); *age_of_data_offset *= 900; // [s] //------------------------------------------------------------------ // SUBFRAME3 //------------------------------------------------------------------ // confirm that this is subframe 3 subframe_id = (unsigned char)((subframe3[5] & 0x1C) >> 2); if (subframe_id != 3) { GNSS_ERROR_MSG("if( subframe_id != 3 )"); return FALSE; } // cic u16a = (unsigned short)(subframe3[6] << 8); u16b = subframe3[7]; s16 = (short)(u16a | u16b); // signed value *cic = s16; *cic /= TWO_TO_THE_POWER_OF_29; // [rad] // omego0 u32a = subframe3[8] << 24; u32b = subframe3[9] << 16; u32c = subframe3[10] << 8; u32d = subframe3[11]; s32 = u32a | u32b | u32c | u32d; // signed value *omega0 = s32; *omega0 *= PI / TWO_TO_THE_POWER_OF_31; // [rad] // cis u16a = (unsigned short)(subframe3[12] << 8); u16b = subframe3[13]; s16 = (short)(u16a | u16b); // signed value *cis = s16; *cis /= TWO_TO_THE_POWER_OF_29; // [rad] // i0 u32a = subframe3[14] << 24; u32b = subframe3[15] << 16; u32c = subframe3[16] << 8; u32d = subframe3[17]; s32 = u32a | u32b | u32c | u32d; *i0 = s32; *i0 *= PI / TWO_TO_THE_POWER_OF_31; // [rad] // crc u16a = (unsigned short)(subframe3[18] << 8); u16b = subframe3[19]; s16 = (short)(u16a | u16b); // signed value *crc = s16; *crc /= 32.0; // [m] // w u32a = subframe3[20] << 24; u32b = subframe3[21] << 16; u32c = subframe3[22] << 8; u32d = subframe3[23]; s32 = u32a | u32b | u32c | u32d; // signed value *w = s32; *w *= PI / TWO_TO_THE_POWER_OF_31; // [rad] // omegadot u32a = subframe3[24] << 24; u32b = subframe3[25] << 16; u32c = subframe3[26] << 8; s32 = u32a | u32b | u32c; // signed value s32 = s32 >> 8; *omegadot = s32; *omegadot *= PI / TWO_TO_THE_POWER_OF_43; // [rad/s] // iode subframe3 iode_subframe3 = subframe3[27]; // idot u16a = (unsigned short)(subframe3[28] << 8); u16b = (unsigned short)(subframe3[29] & 0xFC); s16 = (short)(u16a | u16b); // signed value s16 = (short)(s16 >> 2); *idot = s16; *idot *= PI / TWO_TO_THE_POWER_OF_43; // [rad/s] // check that the IODE values match for all three subframes if ((iode_subframe1 == iode_subframe2) && (iode_subframe1 == iode_subframe3)) { *iode = iode_subframe1; return TRUE; } else { *iode = 0; GNSS_ERROR_MSG("inconsistent subframe dataset"); return FALSE; // inconsistent subframe dataset } }
42.92355
187
0.521752
[ "vector" ]
0e364492696dd84cd791ca77595f549d52f973d0
638
h
C
node.h
5cript/lyne-solver
a30ae9aaf70d08f4895e94d9cb85749a9d7d73c3
[ "MIT" ]
1
2019-07-01T14:33:44.000Z
2019-07-01T14:33:44.000Z
node.h
5cript/lyne-solver
a30ae9aaf70d08f4895e94d9cb85749a9d7d73c3
[ "MIT" ]
null
null
null
node.h
5cript/lyne-solver
a30ae9aaf70d08f4895e94d9cb85749a9d7d73c3
[ "MIT" ]
null
null
null
#ifndef NODE_H_INCLUDED #define NODE_H_INCLUDED #include <opencv2/core/core.hpp> #include <vector> enum class NodeShape { Nothing = 0x0, Triangle = 0xA8DBA8, Diamond = 0x86863B, Square = 0x5C78C2, Pentagon = 0x1, Hexagon = 0x2, ValenceRestricted = 0xD8DBA7 }; cv::Vec4b ShapeToVector(NodeShape shape); NodeShape ShapeFromVector(cv::Vec4b const& vect); struct Node { cv::Point position = {}; NodeShape shape = NodeShape::Nothing; int requiredValence = 0; int valence = 0; std::vector <std::pair <Node*, NodeShape> > connections; }; #endif // NODE_H_INCLUDED
21.266667
61
0.655172
[ "shape", "vector" ]
0e39b286399c3a46db2b3e7e4b4254b2091ccc2b
13,441
c
C
src/fusion-c/examples/psg-sound2.c
SaffronCR/msx-rpg
5bb63e2f545b0a3c82bbda3f9ec399da6c485b0e
[ "BSD-3-Clause" ]
40
2019-07-19T17:27:10.000Z
2022-02-21T17:49:11.000Z
src/fusion-c/examples/psg-sound2.c
SaffronCR/msx-rpg
5bb63e2f545b0a3c82bbda3f9ec399da6c485b0e
[ "BSD-3-Clause" ]
2
2020-07-05T19:21:27.000Z
2020-07-05T19:31:02.000Z
src/fusion-c/examples/psg-sound2.c
SaffronCR/msx-rpg
5bb63e2f545b0a3c82bbda3f9ec399da6c485b0e
[ "BSD-3-Clause" ]
3
2019-07-23T10:27:32.000Z
2020-10-28T18:35:27.000Z
/* ============================================================================= SDCC AY-3-8910 PlayFX Lib Test Version: 1.0 Date: 17/06/2018 Author: mvac7/303bcn Architecture: MSX Format: C Object (SDCC .rel) Programming language: C WEB: mail: mvac7303b@gmail.com Description: Test the functions of the library PSG_AY38910. ### 4.1 Envelope shapes The header file defines envelope shapes in case you prefer to use it instead of the numerical form: * ENV_LowerBeat 0 * ENV_Upper 4 * ENV_LeftSaw 8 * ENV_LowerTriangle 10 * ENV_LowerHold 11 * ENV_RightSaw 12 * ENV_UpperHold 13 * ENV_UpperTriangle 14 ### 4.2 FX struct - [boolean] isTone enable tone - [boolean] isNoise enable noise - [unsigned int] Tone Tone period (0 - 4095) - [char] Noise Noise period (0 - 31) - [unsigned int] Period Envelope Period (0 - 65535) - [char] Shape Envelope shape (0-15) ## 5 Functions * Sound(register, value) - Write into a register of PSG * PlayFX(channel, soundat) - Play FX * SetChannel(channel, isTone, isNoise) - Mixer. Enable/disable Tone and Noise channels. * SilencePSG() - Silence the three PSG channels. ## 6 How to use This library provides functions to play simple effects (using the hardware), designed for to be used in videogames. In our program we can include all the effects we need using the FX structure, which is defined in the library. This allows us to indicate a tone value, the noise, the state of these channels, an envelope period and a type of wave envelope. To play an FX, we must use the PlayFX function. It allows us to select one of the three available channels, but because it is based on sounds produced by the wave envelope hardware and the AY-3-8910 can only play one at the same time, it is recommended to always send them through the same chanel to avoid generating unwanted sounds. If an FX is played without having finished the previous one, this last one will have priority over the previous one since it will overwrite the PSG registers. If you want to take advantage of the other channels to include music using one of the existing AY players (PT3, WYZ, Arkos, ...), these functions will probably not work since the music players use a buffer that is modified every time it is executed and it is dumped directly to PSG on every VBLANK interruption. In order to get this working, this library should be modified so that instead of writing directly to the registers, it does it over the player's buffer. ============================================================================= */ #include "fusion-c/header/vars_msxSystem.h" #include "fusion-c/header/vars_msxBios.h" #include "fusion-c/header/vars_msxDos.h" #include "fusion-c/header/msx_fusion.h" #include "fusion-c/header/psg.h" #define HALT __asm halt __endasm //wait for the next interrupt #define PAUSE_TIME 30 // Function Declarations ------------------------------------------------------- void test1(); // test SOUND void test2(); // test SetTonePeriod void test3(); // test SetNoisePeriod void test4(); // test SetVolume void test5(); // test SetEnvelopePeriod void test6(); // test PlayEnvelope and SetChannel void setEnv(char envType); void PrintChannel(char chan, boolean stateTone, boolean stateNoise); void WAIT(int cicles); boolean NOT(boolean value); // constants ------------------------------------------------------------------ const char text01[] = "Test SDCC PSG Lib"; const char text02[] = "v1.2 (18/06/2018)"; // global variable definition -------------------------------------------------- char _lastEnv; // Functions ------------------------------------------------------------------- // void main(void) { SetColors(BLACK,GRAY,DARK_BLUE); Screen(1); Width(32); test1(); // test SOUND test2(); // test SetTonePeriod test3(); // test SetNoisePeriod test4(); // test SetVolume test5(); // test SetEnvelopePeriod test6(); // test PlayEnvelope and SetChannel //EXIT MSXDOS /* screen(0); __asm ld b,4(ix) ld c,#0x62 call 5 __endasm;*/ //end EXIT return; } // Generates a pause in the execution of n interruptions. // PAL: 50=1second. ; NTSC: 60=1second. void WAIT(int cicles) { int i; for(i=0;i<cicles;i++) HALT; return; } boolean NOT(boolean value) { if (value) return false; return true; } // test SOUND void test1() { Cls(); Locate(0,0); Print(text01); Locate(0,1); Print(text02); Locate(0,4); Print(">Test SOUND function"); Locate(0,6); Print(" Press a key to stop sound"); Sound(0,100);//tone period channel A (2B) Sound(1,10); Sound(6,100); //noise Sound(7,0B00110110); //Mixer Sound(8,16); //channel A envelope on Sound(11,100);//envelope period (2B) Sound(12,10); // Sound(13,14); //envelope wave type WaitKey(); Sound(8,0); //silencia Sound(13,0); WAIT(PAUSE_TIME); } // test SetTonePeriod void test2() { int period=0; Cls(); Locate(0,0); Print(text01); Locate(0,1); Print(text02); Locate(0,4); Print(">Test SetTonePeriod function"); Locate(0,6); Print(" Press space to end"); Locate(0,8); Print(" Tone Period A:"); Sound(7,0B00111110); //Mixer Sound(8,12); while(1) { HALT; if (GetKeyMatrix(8)!=255) break; Locate(16,8); PrintNumber(period); SetTonePeriod(0, period++); if (period>4094) period=0; } Sound(8,10); WAIT(PAUSE_TIME); Locate(0,9); Print(" Tone Period B:"); period = 0; Sound(7,0B00111100); //Mixer Sound(9,12); while(1) { HALT; if (GetKeyMatrix(8)!=255) break; Locate(16,9); PrintNumber(period); SetTonePeriod(1, period++); if (period>4094) period=0; } Sound(9,10); WAIT(PAUSE_TIME); Locate(0,10); Print(" Tone Period C:"); period = 0; Sound(7,0B00111000); //Mixer Sound(10,12); while(1) { HALT; if (GetKeyMatrix(8)!=255) break; Locate(16,10); PrintNumber(period); SetTonePeriod(2, period++); if (period>4094) period=0; } WAIT(PAUSE_TIME); Sound(8,0); Sound(9,0); Sound(10,0); } // Test SetNoisePeriod void test3() { char noise=0; Cls(); Locate(0,0); Print(text01); Locate(0,1); Print(text02); Locate(0,4); Print(">Test SetNoisePeriod function"); Locate(0,6); Print(" Press space to end"); Locate(0,8); Print(" Noise Period:"); Sound(7,0B00110111); //Mixer Sound(8,11); while(1) { if (GetKeyMatrix(8)!=255) break; Locate(14,8); PrintNumber(noise); SetNoisePeriod(noise++); if (noise>31) noise=0; WAIT(4); } WAIT(PAUSE_TIME); Sound(8,0); Sound(9,0); Sound(10,0); } // Test SetVolume void test4() { char amp=0; Cls(); Locate(0,0); Print(text01); Locate(0,1); Print(text02); Locate(0,4); Print(">Test SetVolume function"); Locate(0,6); Print(" Press space to end"); Locate(0,8); Print(" Volume A:"); Sound(0,100); Sound(1,10); //tone period Sound(7,0B11110110); //Mixer > Test write to 7 AY register while(1) { if (GetKeyMatrix(8)!=255) break; Locate(10,8); PrintNumber(amp); SetVolume(0,amp++); if (amp>15) amp=0; WAIT(5); } WAIT(PAUSE_TIME); Locate(0,9); Print(" Volume B:"); amp=0; Sound(2,300); Sound(3,10); //tone period Sound(7,0B00101101); //Mixer > Test write to 7 AY register while(1) { if (GetKeyMatrix(8)!=255) break; Locate(10,9); PrintNumber(amp); SetVolume(1,amp++); if (amp>15) amp=0; WAIT(5); } WAIT(PAUSE_TIME); Locate(0,10); Print(" Volume C:"); amp=0; Sound(4,600); Sound(5,10); //tone period Sound(7,0B00011011); //Mixer > Test write to 7 AY register while(1) { if (GetKeyMatrix(8)!=255) break; Locate(10,10); PrintNumber(amp); SetVolume(2,amp++); if (amp>15) amp=0; WAIT(5); } WAIT(PAUSE_TIME); Sound(8,0);//enjoy the silence Sound(9,0); Sound(10,0); } // Test SetEnvelopePeriod void test5() { int period=0; char i; boolean isEnd=false; Cls(); Locate(0,0); Print(text01); Locate(0,1); Print(text02); Locate(0,4); Print(">Test SetEnvelopePeriod function"); Locate(0,6); Print(" Press space to end"); Locate(0,8); Print(" Env Period:"); Sound(0,100); Sound(1,10); //tone period Sound(7,0B00111110); //Mixer Sound(8,16); Sound(13,14); while(!isEnd) { Locate(12,8); PrintNumber(period); SetEnvelopePeriod(period++); if (period>65533) period=0; for(i=0;i<20;i++) { HALT; if (GetKeyMatrix(8)!=255){isEnd=true;break;} } //if (joytrig(0)) break; } Sound(8,0); WAIT(PAUSE_TIME); } // Test PlayEnvelope and SetChannel void test6() { char pressKey; boolean chanA = true; boolean chanB = true; boolean chanC = true; boolean noiseA = false; boolean noiseB = false; boolean noiseC = false; boolean keyB0semaphore = false; boolean keyB1semaphore = false; boolean keyB3semaphore = false; boolean keyB6semaphore = false; _lastEnv=0; Cls(); Locate(0,0); Print(text01); Locate(0,1); Print(text02); Locate(0,4); Print(">Test PlayEnvelope function"); Locate(0,6); Print("Press 0-7 to fire Envelope"); Locate(0,8); Print(" A B C "); Print(" -------- -------- --------"); Locate(0,10); Print("Tone :"); Locate(0,11); Print("Noise:"); Locate(0,14); Print(" 1 - \\_____\n"); Print(" 2 - /|____\n"); Print(" 3 - |\\|\\|\\ \n"); Print(" 4 - \\/\\/\\/\n"); Print(" 5 - \\|----\n"); Print(" 6 - /|/|/|\n"); Print(" 7 - /-----\n"); Print(" 8 - /\\/\\/\\ \n"); SetTonePeriod(0, 1000); SetTonePeriod(1, 1100); SetTonePeriod(2, 1200); SetVolume(0,16); SetVolume(1,16); SetVolume(2,16); SetEnvelopePeriod(7000); setEnv(7); PrintChannel(0, chanA,noiseA); PrintChannel(1, chanB,noiseB); PrintChannel(2, chanC,noiseC); while(1) //bucle infinito { HALT; pressKey = GetKeyMatrix(0); if (pressKey!=255) { if (!keyB0semaphore) { keyB0semaphore = true; //if (pressKey==0b11111110) //0 if (pressKey==0b11111101) setEnv(0); //1 if (pressKey==0b11111011) setEnv(1); //2 if (pressKey==0b11110111) setEnv(2); //3 if (pressKey==0b11101111) setEnv(3); //4 if (pressKey==0b11011111) setEnv(4); //5 if (pressKey==0b10111111) setEnv(5); //6 if (pressKey==0b01111111) setEnv(6); //7 } }else keyB0semaphore=false; pressKey = GetKeyMatrix(1); if (pressKey!=255) { if (!keyB1semaphore) { keyB1semaphore = true; if (pressKey==0b11111110) setEnv(7); //8 } }else keyB1semaphore=false; pressKey = GetKeyMatrix(3); if (pressKey!=255) { if (!keyB3semaphore) { keyB3semaphore = true; if (pressKey==0b11111101){ noiseA=NOT(noiseA);PrintChannel(0, chanA,noiseA);} // D if (pressKey==0b11110111){ noiseB=NOT(noiseB);PrintChannel(1, chanB,noiseB);} //F if (pressKey==0b11101111){ noiseC=NOT(noiseC);PrintChannel(2, chanC,noiseC);} //G } }else keyB3semaphore=false; pressKey = GetKeyMatrix(6); if (pressKey!=255) { if (!keyB6semaphore) { keyB6semaphore = true; if (pressKey==0b11011111){ chanA=NOT(chanA);PrintChannel(0, chanA,noiseA);} //F1 if (pressKey==0b10111111){ chanB=NOT(chanB);PrintChannel(1, chanB,noiseB);} //F2 if (pressKey==0b01111111){ chanC=NOT(chanC);PrintChannel(2, chanC,noiseC);} //F3 } }else keyB6semaphore=false; } //END while } void setEnv(char envType) { Locate(0,14+_lastEnv); Print(" "); _lastEnv = envType; Locate(0,14+envType); Print(">"); switch (envType) { case 0: PlayEnvelope(ENV_LowerBeat); break; case 1: PlayEnvelope(ENV_Upper); break; case 2: PlayEnvelope(ENV_LeftSaw); break; case 3: PlayEnvelope(ENV_LowerTriangle); break; case 4: PlayEnvelope(ENV_LowerHold); break; case 5: PlayEnvelope(ENV_RightSaw); break; case 6: PlayEnvelope(ENV_UpperHold); break; case 7: PlayEnvelope(ENV_UpperTriangle); break; } } void PrintChannel(char chan, boolean stateTone, boolean stateNoise) { char posx = (chan*9)+6; SetChannel(chan, stateTone, stateNoise); Locate(posx,10); switch (chan) { case 1: Print("[F2] "); break; case 2: Print("[F3] "); break; default: Print("[F1] "); break; } if (stateTone) Print("On "); else Print("Off"); Locate(posx,11); switch (chan) { case 1: Print("[F] "); break; case 2: Print("[G] "); break; default: Print("[D] "); break; } if (stateNoise) Print("On "); else Print("Off"); return; }
19.708211
90
0.576296
[ "object", "shape" ]
0e39ddc6c5aea84992da43c7315486949760482d
3,468
h
C
include/cli.h
hrandib/waked
e7a0d1532204c422a16ed51697483e9b50fcaeae
[ "MIT" ]
null
null
null
include/cli.h
hrandib/waked
e7a0d1532204c422a16ed51697483e9b50fcaeae
[ "MIT" ]
null
null
null
include/cli.h
hrandib/waked
e7a0d1532204c422a16ed51697483e9b50fcaeae
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include "cli_options.h" #include "sleep.h" namespace Wk { class Cli { private: constexpr static uint32_t TIMEOUT = 50; Packet_t params_; std::vector<uint8_t> addressGroup_; Wake& wake_; void PrintRaw(const Packet_t& params) { using namespace std; cout << setw(4) << (uint32_t)params.addr << setw(4) << (uint32_t)params.cmd << setw(4) << (uint32_t)params.n; for(uint8_t i = 0; i != params.n; ++i) { cout << setw(4) << (uint32_t)params.payload[i]; } cout << endl; } void PrintOperatingTime(uint8_t* data) { uint32_t uptime = ((*(uint32_t*)data & 0xFFFFFF) * 10); //In minutes uint32_t years = uptime / (365 * 24 * 60); uptime -= years * 365 * 24 * 60; uint32_t months = uptime / (30 * 24 * 60); uptime -= months * 30 * 24 * 60; uint32_t days = uptime / (24 * 60); uptime -= days * 24 * 60; uint32_t hours = uptime / 60; uint32_t minutes = uptime - hours * 60; cout << "Operating Time: " << years << " years " << months << " months " << days << " days " << hours << " hours " << minutes << " minutes" << endl; } public: Cli(Wake& wake, CliOpts& options) : wake_{wake} { options.GetParams(addressGroup_, params_); } bool OpenConnection() { for(uint32_t n = 0; n < 10; ++n) { if(wake_.OpenConnection()) { return true; } else { sleep_ms(TIMEOUT); } } std::cerr << "Port is busy (or absent)"; return false; } static bool IsMulticast(size_t addr) { return addr > 79 && addr < 96; } void Process() { using std::setw; for(auto addr : addressGroup_) { Packet_t paramsTemp = params_; paramsTemp.addr = addr; if(C_GETINFO == paramsTemp.cmd) { cout << ">>> Device address: " << (size_t)addr << "\r\n"; wake_.GetInfo(paramsTemp); continue; } else if(IsMulticast(paramsTemp.addr)) { wake_.Request(paramsTemp, 10); continue; } else if(!wake_.Request(paramsTemp)) { std::cerr << "!!! Request failed, address: " << (size_t)paramsTemp.addr << endl; continue; } if(paramsTemp.payload[0] && paramsTemp.cmd > C_ECHO) { cout << "!!! Error: " << GetErrorString((Err)paramsTemp.payload[0]) << "\r\n"; return; } switch(paramsTemp.cmd) { case C_GETOPTIME: PrintOperatingTime(&paramsTemp.payload[1]); break; case C_SETGROUPADDRESS: cout << "Group address: " << (size_t)paramsTemp.payload[1] << "\r\n"; break; default: PrintRaw(paramsTemp); } } } }; }//WakeCli
33.346154
100
0.433679
[ "vector" ]
0e3f57dd6fd9bacc4a0754bd06b3020b4649a8be
4,178
c
C
tests/api/test-to-object.c
wenq1/duktape
5ed3eee19b291f3b3de0b212cc62c0aba0ab4ecb
[ "MIT" ]
4,268
2015-01-01T17:33:40.000Z
2022-03-31T17:53:31.000Z
tests/api/test-to-object.c
GyonGyon/duktape
3f732345c745059d1d7307b17b5b8d070e9609e9
[ "MIT" ]
1,667
2015-01-01T22:43:03.000Z
2022-02-23T22:27:19.000Z
tests/api/test-to-object.c
GyonGyon/duktape
3f732345c745059d1d7307b17b5b8d070e9609e9
[ "MIT" ]
565
2015-01-08T14:15:28.000Z
2022-03-31T16:29:31.000Z
/*=== *** test_1 (duk_safe_call) top: 10 index 0, type: 6, string coerced: true index 1, type: 6, string coerced: false index 2, type: 6, string coerced: 0 index 3, type: 6, string coerced: 1 index 4, type: 6, string coerced: NaN index 5, type: 6, string coerced: Infinity index 6, type: 6, string coerced: index 7, type: 6, string coerced: foo index 8, type: 6, string coerced: [object Object] index 9, type: 6, string coerced: [object Thread] ==> rc=0, result='undefined' *** test_2a (duk_safe_call) ==> rc=1, result='TypeError: not object coercible' *** test_2b (duk_safe_call) ==> rc=1, result='TypeError: not object coercible' *** test_2c (duk_safe_call) index 0 OK ==> rc=0, result='undefined' *** test_2d (duk_safe_call) index 0 OK ==> rc=0, result='undefined' *** test_2e (duk_safe_call) index 0 OK ==> rc=0, result='undefined' *** test_2f (duk_safe_call) index 0 OK ==> rc=0, result='undefined' *** test_2g (duk_safe_call) index 0 OK ==> rc=0, result='undefined' *** test_2h (duk_safe_call) index 0 OK ==> rc=0, result='undefined' *** test_3 (duk_safe_call) ==> rc=1, result='RangeError: invalid stack index 3' *** test_4 (duk_safe_call) ==> rc=1, result='RangeError: invalid stack index -2147483648' ===*/ static duk_ret_t test_1(duk_context *ctx, void *udata) { duk_idx_t i, n; (void) udata; duk_set_top(ctx, 0); duk_push_true(ctx); duk_push_false(ctx); duk_push_int(ctx, 0); duk_push_int(ctx, 1); duk_push_nan(ctx); duk_push_number(ctx, INFINITY); duk_push_string(ctx, ""); duk_push_string(ctx, "foo"); duk_push_object(ctx); duk_push_thread(ctx); n = duk_get_top(ctx); printf("top: %ld\n", (long) n); for (i = 0; i < n; i++) { duk_int_t t; const char *p; duk_to_object(ctx, i); t = duk_get_type(ctx, i); p = duk_to_string(ctx, i); printf("index %ld, type: %ld, string coerced:%s%s\n", (long) i, (long) t, (strlen(p) == 0 ? "" : " "), p); } return 0; } /* Non-coercible types */ static duk_ret_t test_2a(duk_context *ctx, void *udata) { (void) udata; duk_set_top(ctx, 0); duk_push_undefined(ctx); duk_to_object(ctx, 0); printf("index 0 OK\n"); return 0; } static duk_ret_t test_2b(duk_context *ctx, void *udata) { (void) udata; duk_set_top(ctx, 0); duk_push_null(ctx); duk_to_object(ctx, 0); printf("index 0 OK\n"); return 0; } /* Buffers and pointers are coercible */ static duk_ret_t test_2c(duk_context *ctx, void *udata) { (void) udata; duk_set_top(ctx, 0); duk_push_fixed_buffer(ctx, 0); duk_to_object(ctx, 0); printf("index 0 OK\n"); return 0; } static duk_ret_t test_2d(duk_context *ctx, void *udata) { (void) udata; duk_set_top(ctx, 0); duk_push_fixed_buffer(ctx, 1024); duk_to_object(ctx, 0); printf("index 0 OK\n"); return 0; } static duk_ret_t test_2e(duk_context *ctx, void *udata) { (void) udata; duk_set_top(ctx, 0); duk_push_dynamic_buffer(ctx, 0); duk_to_object(ctx, 0); printf("index 0 OK\n"); return 0; } static duk_ret_t test_2f(duk_context *ctx, void *udata) { (void) udata; duk_set_top(ctx, 0); duk_push_dynamic_buffer(ctx, 1024); duk_to_object(ctx, 0); printf("index 0 OK\n"); return 0; } static duk_ret_t test_2g(duk_context *ctx, void *udata) { (void) udata; duk_set_top(ctx, 0); duk_push_pointer(ctx, (void *) NULL); duk_to_object(ctx, 0); printf("index 0 OK\n"); return 0; } static duk_ret_t test_2h(duk_context *ctx, void *udata) { (void) udata; duk_set_top(ctx, 0); duk_push_pointer(ctx, (void *) 0xdeadbeefUL); duk_to_object(ctx, 0); printf("index 0 OK\n"); return 0; } static duk_ret_t test_3(duk_context *ctx, void *udata) { (void) udata; duk_set_top(ctx, 0); duk_to_boolean(ctx, 3); printf("index 3 OK\n"); return 0; } static duk_ret_t test_4(duk_context *ctx, void *udata) { (void) udata; duk_set_top(ctx, 0); duk_to_boolean(ctx, DUK_INVALID_INDEX); printf("index DUK_INVALID_INDEX OK\n"); return 0; } void test(duk_context *ctx) { TEST_SAFE_CALL(test_1); TEST_SAFE_CALL(test_2a); TEST_SAFE_CALL(test_2b); TEST_SAFE_CALL(test_2c); TEST_SAFE_CALL(test_2d); TEST_SAFE_CALL(test_2e); TEST_SAFE_CALL(test_2f); TEST_SAFE_CALL(test_2g); TEST_SAFE_CALL(test_2h); TEST_SAFE_CALL(test_3); TEST_SAFE_CALL(test_4); }
22.956044
62
0.691958
[ "object" ]
0e43ea289518d9fd3782d91d257dfb051e0cee7b
6,013
h
C
source/ccsp/components/include/ccsp_ifo_ccd.h
lgirdk/ccsp-common-library
8d912984e96f960df6dadb4b0e6bc76c76376776
[ "Apache-2.0" ]
4
2018-02-26T05:41:14.000Z
2019-12-20T07:31:39.000Z
source/ccsp/components/include/ccsp_ifo_ccd.h
rdkcmf/rdkb-CcspCommonLibrary
3eba76685bbf5eb6656f45eb4b57fdb5c269c2a1
[ "Apache-2.0" ]
null
null
null
source/ccsp/components/include/ccsp_ifo_ccd.h
rdkcmf/rdkb-CcspCommonLibrary
3eba76685bbf5eb6656f45eb4b57fdb5c269c2a1
[ "Apache-2.0" ]
3
2017-07-30T15:35:16.000Z
2020-08-18T20:44:08.000Z
/* * If not stated otherwise in this file or this component's Licenses.txt file the * following copyright and licenses apply: * * Copyright 2015 RDK Management * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /********************************************************************** Copyright [2014] [Cisco Systems, 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. **********************************************************************/ /********************************************************************** module: ccsp_ifo_ccd.h For CCSP Common Components --------------------------------------------------------------- description: This wrapper file defines the base class data structure and interface for the component common data model. --------------------------------------------------------------- environment: platform independent --------------------------------------------------------------- author: Tom Chang --------------------------------------------------------------- revision: 06/14/11 initial revision. **********************************************************************/ #ifndef _CCSP_IFO_CCD_ #define _CCSP_IFO_CCD_ /* * This object is derived a virtual base object defined by the underlying framework. We include the * interface header files of the base object here to shield other objects from knowing the derived * relationship between this object and its base class. */ #include "ansc_ifo_interface.h" /************************************************************** CCSP COMPONENT COMMON DATA MODEL INTERFACE OBJECT DEFINITION **************************************************************/ /* * Define some const values that will be used in the os wrapper object definition. */ #define CCSP_CCD_INTERFACE_NAME "CcspComponentCommonDatamodelIf" #define CCSP_CCD_INTERFACE_ID 0x00000002 /* * Since we write all kernel modules in C (due to better performance and lack of compiler support), we * have to simulate the C++ object by encapsulating a set of functions inside a data structure. */ typedef BOOL (*PFN_CCSPCCDM_GET_VALUE_BOOL) ( ANSC_HANDLE hThisObject ); typedef ANSC_STATUS (*PFN_CCSPCCDM_SET_VALUE_BOOL) ( ANSC_HANDLE hThisObject, BOOL bValue ); typedef ULONG (*PFN_CCSPCCDM_GET_VALUE_ULONG) ( ANSC_HANDLE hThisObject ); typedef ANSC_STATUS (*PFN_CCSPCCDM_SET_VALUE_ULONG) ( ANSC_HANDLE hThisObject, ULONG ulValue ); typedef char* (*PFN_CCSPCCDM_GET_VALUE_STRING) ( ANSC_HANDLE hThisObject ); typedef ANSC_STATUS (*PFN_CCSPCCDM_APPLY_CHANGES) ( ANSC_HANDLE hThisObject ); /* * The Interface exposed for component common data model. */ #define CCSP_CCD_INTERFACE_CLASS_CONTENT \ /* duplication of the base object class content */ \ ANSCIFO_CLASS_CONTENT \ /* start of object class content */ \ PFN_CCSPCCDM_GET_VALUE_STRING GetComponentName; \ PFN_CCSPCCDM_GET_VALUE_ULONG GetComponentVersion; \ PFN_CCSPCCDM_GET_VALUE_STRING GetComponentAuthor; \ PFN_CCSPCCDM_GET_VALUE_ULONG GetComponentHealth; \ PFN_CCSPCCDM_GET_VALUE_ULONG GetComponentState; \ PFN_CCSPCCDM_GET_VALUE_BOOL GetLoggingEnabled; \ PFN_CCSPCCDM_SET_VALUE_BOOL SetLoggingEnabled; \ PFN_CCSPCCDM_GET_VALUE_ULONG GetLoggingLevel; \ PFN_CCSPCCDM_SET_VALUE_ULONG SetLoggingLevel; \ PFN_CCSPCCDM_GET_VALUE_ULONG GetMemMaxUsage; \ PFN_CCSPCCDM_GET_VALUE_ULONG GetMemMinUsage; \ PFN_CCSPCCDM_GET_VALUE_ULONG GetMemConsumed; \ PFN_CCSPCCDM_APPLY_CHANGES ApplyChanges; \ /* end of object class content */ \ typedef struct _CCSP_CCD_INTERFACE { CCSP_CCD_INTERFACE_CLASS_CONTENT } CCSP_CCD_INTERFACE, *PCCSP_CCD_INTERFACE; #define ACCESS_CCSP_CCD_INTERFACE(p) \ ACCESS_CONTAINER(p, CCSP_CCD_INTERFACE, Linkage) #endif
35.791667
102
0.529187
[ "object", "model" ]
0e44bd1fc623db6670f57ea3daabef4f4bce1dec
2,619
h
C
source/common/upstream/load_balancer_impl.h
dio/piotr-envoy
46da71aa83d8d969c5d2c822820b2b88a4421655
[ "Apache-2.0" ]
1
2018-10-31T20:20:01.000Z
2018-10-31T20:20:01.000Z
source/common/upstream/load_balancer_impl.h
dio/piotr-envoy
46da71aa83d8d969c5d2c822820b2b88a4421655
[ "Apache-2.0" ]
1
2020-11-04T16:24:38.000Z
2020-11-04T16:24:38.000Z
source/common/upstream/load_balancer_impl.h
PiotrSikora/envoy
46da71aa83d8d969c5d2c822820b2b88a4421655
[ "Apache-2.0" ]
null
null
null
#pragma once #include "envoy/runtime/runtime.h" #include "envoy/upstream/load_balancer.h" #include "envoy/upstream/upstream.h" namespace Upstream { /** * Base class for all LB implementations. */ class LoadBalancerBase { protected: LoadBalancerBase(const HostSet& host_set, ClusterStats& stats, Runtime::Loader& runtime) : stats_(stats), runtime_(runtime), host_set_(host_set) {} /** * Pick the host list to use (healthy or all depending on how many in the set are not healthy). */ const std::vector<HostPtr>& hostsToUse(); ClusterStats& stats_; Runtime::Loader& runtime_; private: const HostSet& host_set_; }; /** * Implementation of LoadBalancer that performs RR selection across the hosts in the cluster. */ class RoundRobinLoadBalancer : public LoadBalancer, LoadBalancerBase { public: RoundRobinLoadBalancer(const HostSet& host_set, ClusterStats& stats, Runtime::Loader& runtime) : LoadBalancerBase(host_set, stats, runtime) {} // Upstream::LoadBalancer ConstHostPtr chooseHost() override; private: size_t rr_index_{}; }; /** * Weighted Least Request load balancer. * * In a normal setup when all hosts have the same weight of 1 it randomly picks up two healthy hosts * and compares number of active requests. * Technique is based on http://www.eecs.harvard.edu/~michaelm/postscripts/mythesis.pdf * * When any of the hosts have non 1 weight, apply random weighted balancing. * Randomly pickup the host and send 'weight' number of requests to it. * This technique is acceptable for load testing but * will not work well in situations where requests take a long time. * In that case a different algorithm using a full scan will be required. */ class LeastRequestLoadBalancer : public LoadBalancer, LoadBalancerBase { public: LeastRequestLoadBalancer(const HostSet& host_set, ClusterStats& stats, Runtime::Loader& runtime, Runtime::RandomGenerator& random); // Upstream::LoadBalancer ConstHostPtr chooseHost() override; private: Runtime::RandomGenerator& random_; HostPtr last_host_; uint32_t hits_left_{}; }; /** * Random load balancer that picks a random host out of all hosts. */ class RandomLoadBalancer : public LoadBalancer, LoadBalancerBase { public: RandomLoadBalancer(const HostSet& host_set, ClusterStats& stats, Runtime::Loader& runtime, Runtime::RandomGenerator& random) : LoadBalancerBase(host_set, stats, runtime), random_(random) {} // Upstream::LoadBalancer ConstHostPtr chooseHost() override; private: Runtime::RandomGenerator& random_; }; } // Upstream
29.761364
100
0.737304
[ "vector" ]