text
stringlengths
4
5.48M
meta
stringlengths
14
6.54k
/********************************************************************** * $Id$ lpc177x_8x_can.h 2011-06-02 *//** * @file lpc177x_8x_can.h * @brief Contains all macro definitions and function prototypes * support for CAN firmware library on LPC177x_8x * @version 1.0 * @date 02. June. 2011 * @author NXP MCU SW Application Team * * Copyright(C) 2011, NXP Semiconductor * All rights reserved. * *********************************************************************** * Software that is described herein is for illustrative purposes only * which provides customers with programming information regarding the * products. This software is supplied "AS IS" without any warranties. * NXP Semiconductors assumes no responsibility or liability for the * use of the software, conveys no license or title under any patent, * copyright, or mask work right to the product. NXP Semiconductors * reserves the right to make changes in the software without * notification. NXP Semiconductors also make no representation or * warranty that such application will be suitable for the specified * use without further testing or modification. * Permission to use, copy, modify, and distribute this software and its * documentation is hereby granted, under NXP Semiconductors' * relevant copyright in the software, without fee, provided that it * is used in conjunction with NXP Semiconductors microcontrollers. This * copyright, permission, and disclaimer notice must appear in all copies of * this code. **********************************************************************/ /* Peripheral group ----------------------------------------------------------- */ /** @defgroup CAN CAN (Controller Area Network) * @ingroup LPC177x_8xCMSIS_FwLib_Drivers * @{ */ #ifndef __LPC177X_8X_CAN_H_ #define __LPC177X_8X_CAN_H_ /* Includes ------------------------------------------------------------------- */ #include "LPC177x_8x.h" #include "lpc_types.h" #ifdef __cplusplus extern "C" { #endif /* Public Types --------------------------------------------------------------- */ /** @defgroup CAN_Public_Macros CAN Public Macros * @{ */ /** Controller ID for CAN1 */ #define CAN1_CTRL ((uint8_t)(0)) /** Controller ID for CAN2 */ #define CAN2_CTRL ((uint8_t)(1)) /** Message(s) Acceptance is enabled */ #define MSG_ENABLE ((uint8_t)(0)) /** Message(s) Acceptance is disabled */ #define MSG_DISABLE ((uint8_t)(1)) /** * @} */ /* Private Macros ------------------------------------------------------------- */ /** @defgroup CAN_Private_Macros CAN Private Macros * @{ */ /* --------------------- BIT DEFINITIONS -------------------------------------- */ /*********************************************************************//** * Macro defines for CAN Mode Register **********************************************************************/ /** CAN Reset mode */ #define CAN_MOD_RM ((uint32_t)(1<<0)) /** CAN Listen Only Mode */ #define CAN_MOD_LOM ((uint32_t)(1<<1)) /** CAN Self Test mode */ #define CAN_MOD_STM ((uint32_t)(1<<2)) /** CAN Transmit Priority mode */ #define CAN_MOD_TPM ((uint32_t)(1<<3)) /** CAN Sleep mode */ #define CAN_MOD_SM ((uint32_t)(1<<4)) /** CAN Receive Polarity mode */ #define CAN_MOD_RPM ((uint32_t)(1<<5)) /** CAN Test mode */ #define CAN_MOD_TM ((uint32_t)(1<<7)) /*********************************************************************//** * Macro defines for CAN Command Register **********************************************************************/ /** CAN Transmission Request */ #define CAN_CMR_TR ((uint32_t)(1)) /** CAN Abort Transmission */ #define CAN_CMR_AT ((uint32_t)(1<<1)) /** CAN Release Receive Buffer */ #define CAN_CMR_RRB ((uint32_t)(1<<2)) /** CAN Clear Data Overrun */ #define CAN_CMR_CDO ((uint32_t)(1<<3)) /** CAN Self Reception Request */ #define CAN_CMR_SRR ((uint32_t)(1<<4)) /** CAN Select Tx Buffer 1 */ #define CAN_CMR_STB1 ((uint32_t)(1<<5)) /** CAN Select Tx Buffer 2 */ #define CAN_CMR_STB2 ((uint32_t)(1<<6)) /** CAN Select Tx Buffer 3 */ #define CAN_CMR_STB3 ((uint32_t)(1<<7)) /*********************************************************************//** * Macro defines for CAN Global Status Register **********************************************************************/ /** CAN Receive Buffer Status */ #define CAN_GSR_RBS ((uint32_t)(1)) /** CAN Data Overrun Status */ #define CAN_GSR_DOS ((uint32_t)(1<<1)) /** CAN Transmit Buffer Status */ #define CAN_GSR_TBS ((uint32_t)(1<<2)) /** CAN Transmit Complete Status */ #define CAN_GSR_TCS ((uint32_t)(1<<3)) /** CAN Receive Status */ #define CAN_GSR_RS ((uint32_t)(1<<4)) /** CAN Transmit Status */ #define CAN_GSR_TS ((uint32_t)(1<<5)) /** CAN Error Status */ #define CAN_GSR_ES ((uint32_t)(1<<6)) /** CAN Bus Status */ #define CAN_GSR_BS ((uint32_t)(1<<7)) /** CAN Current value of the Rx Error Counter */ #define CAN_GSR_RXERR(n) ((uint32_t)((n&0xFF)<<16)) /** CAN Current value of the Tx Error Counter */ #define CAN_GSR_TXERR(n) ((uint32_t)(n&0xFF)<<24)) /*********************************************************************//** * Macro defines for CAN Interrupt and Capture Register **********************************************************************/ /** CAN Receive Interrupt */ #define CAN_ICR_RI ((uint32_t)(1)) /** CAN Transmit Interrupt 1 */ #define CAN_ICR_TI1 ((uint32_t)(1<<1)) /** CAN Error Warning Interrupt */ #define CAN_ICR_EI ((uint32_t)(1<<2)) /** CAN Data Overrun Interrupt */ #define CAN_ICR_DOI ((uint32_t)(1<<3)) /** CAN Wake-Up Interrupt */ #define CAN_ICR_WUI ((uint32_t)(1<<4)) /** CAN Error Passive Interrupt */ #define CAN_ICR_EPI ((uint32_t)(1<<5)) /** CAN Arbitration Lost Interrupt */ #define CAN_ICR_ALI ((uint32_t)(1<<6)) /** CAN Bus Error Interrupt */ #define CAN_ICR_BEI ((uint32_t)(1<<7)) /** CAN ID Ready Interrupt */ #define CAN_ICR_IDI ((uint32_t)(1<<8)) /** CAN Transmit Interrupt 2 */ #define CAN_ICR_TI2 ((uint32_t)(1<<9)) /** CAN Transmit Interrupt 3 */ #define CAN_ICR_TI3 ((uint32_t)(1<<10)) /** CAN Error Code Capture */ #define CAN_ICR_ERRBIT(n) ((uint32_t)((n&0x1F)<<16)) /** CAN Error Direction */ #define CAN_ICR_ERRDIR ((uint32_t)(1<<21)) /** CAN Error Capture */ #define CAN_ICR_ERRC(n) ((uint32_t)((n&0x3)<<22)) /** CAN Arbitration Lost Capture */ #define CAN_ICR_ALCBIT(n) ((uint32_t)((n&0xFF)<<24)) /*********************************************************************//** * Macro defines for CAN Interrupt Enable Register **********************************************************************/ /** CAN Receive Interrupt Enable */ #define CAN_IER_RIE ((uint32_t)(1)) /** CAN Transmit Interrupt Enable for buffer 1 */ #define CAN_IER_TIE1 ((uint32_t)(1<<1)) /** CAN Error Warning Interrupt Enable */ #define CAN_IER_EIE ((uint32_t)(1<<2)) /** CAN Data Overrun Interrupt Enable */ #define CAN_IER_DOIE ((uint32_t)(1<<3)) /** CAN Wake-Up Interrupt Enable */ #define CAN_IER_WUIE ((uint32_t)(1<<4)) /** CAN Error Passive Interrupt Enable */ #define CAN_IER_EPIE ((uint32_t)(1<<5)) /** CAN Arbitration Lost Interrupt Enable */ #define CAN_IER_ALIE ((uint32_t)(1<<6)) /** CAN Bus Error Interrupt Enable */ #define CAN_IER_BEIE ((uint32_t)(1<<7)) /** CAN ID Ready Interrupt Enable */ #define CAN_IER_IDIE ((uint32_t)(1<<8)) /** CAN Transmit Enable Interrupt for Buffer 2 */ #define CAN_IER_TIE2 ((uint32_t)(1<<9)) /** CAN Transmit Enable Interrupt for Buffer 3 */ #define CAN_IER_TIE3 ((uint32_t)(1<<10)) /*********************************************************************//** * Macro defines for CAN Bus Timing Register **********************************************************************/ /** CAN Baudrate Prescaler */ #define CAN_BTR_BRP(n) ((uint32_t)(n&0x3FF)) /** CAN Synchronization Jump Width */ #define CAN_BTR_SJM(n) ((uint32_t)((n&0x3)<<14)) /** CAN Time Segment 1 */ #define CAN_BTR_TESG1(n) ((uint32_t)(n&0xF)<<16)) /** CAN Time Segment 2 */ #define CAN_BTR_TESG2(n) ((uint32_t)(n&0xF)<<20)) /** CAN Sampling */ #define CAN_BTR_SAM(n) ((uint32_t)(1<<23)) /*********************************************************************//** * Macro defines for CAN Error Warning Limit Register **********************************************************************/ /** CAN Error Warning Limit */ #define CAN_EWL_EWL(n) ((uint32_t)(n&0xFF)) /*********************************************************************//** * Macro defines for CAN Status Register **********************************************************************/ /** CAN Receive Buffer Status */ #define CAN_SR_RBS ((uint32_t)(1)) /** CAN Data Overrun Status */ #define CAN_SR_DOS ((uint32_t)(1<<1)) /** CAN Transmit Buffer Status 1 */ #define CAN_SR_TBS1 ((uint32_t)(1<<2)) /** CAN Transmission Complete Status of Buffer 1 */ #define CAN_SR_TCS1 ((uint32_t)(1<<3)) /** CAN Receive Status */ #define CAN_SR_RS ((uint32_t)(1<<4)) /** CAN Transmit Status 1 */ #define CAN_SR_TS1 ((uint32_t)(1<<5)) /** CAN Error Status */ #define CAN_SR_ES ((uint32_t)(1<<6)) /** CAN Bus Status */ #define CAN_SR_BS ((uint32_t)(1<<7)) /** CAN Transmit Buffer Status 2 */ #define CAN_SR_TBS2 ((uint32_t)(1<<10)) /** CAN Transmission Complete Status of Buffer 2 */ #define CAN_SR_TCS2 ((uint32_t)(1<<11)) /** CAN Transmit Status 2 */ #define CAN_SR_TS2 ((uint32_t)(1<<13)) /** CAN Transmit Buffer Status 2 */ #define CAN_SR_TBS3 ((uint32_t)(1<<18)) /** CAN Transmission Complete Status of Buffer 2 */ #define CAN_SR_TCS3 ((uint32_t)(1<<19)) /** CAN Transmit Status 2 */ #define CAN_SR_TS3 ((uint32_t)(1<<21)) /*********************************************************************//** * Macro defines for CAN Receive Frame Status Register **********************************************************************/ /** CAN ID Index */ #define CAN_RFS_ID_INDEX(n) ((uint32_t)(n&0x3FF)) /** CAN Bypass */ #define CAN_RFS_BP ((uint32_t)(1<<10)) /** CAN Data Length Code */ #define CAN_RFS_DLC(n) ((uint32_t)((n&0xF)<<16) /** CAN Remote Transmission Request */ #define CAN_RFS_RTR ((uint32_t)(1<<30)) /** CAN control 11 bit or 29 bit Identifier */ #define CAN_RFS_FF ((uint32_t)(1<<31)) /*********************************************************************//** * Macro defines for CAN Receive Identifier Register **********************************************************************/ /** CAN 11 bit Identifier */ #define CAN_RID_ID_11(n) ((uint32_t)(n&0x7FF)) /** CAN 29 bit Identifier */ #define CAN_RID_ID_29(n) ((uint32_t)(n&0x1FFFFFFF)) /*********************************************************************//** * Macro defines for CAN Receive Data A Register **********************************************************************/ /** CAN Receive Data 1 */ #define CAN_RDA_DATA1(n) ((uint32_t)(n&0xFF)) /** CAN Receive Data 2 */ #define CAN_RDA_DATA2(n) ((uint32_t)((n&0xFF)<<8)) /** CAN Receive Data 3 */ #define CAN_RDA_DATA3(n) ((uint32_t)((n&0xFF)<<16)) /** CAN Receive Data 4 */ #define CAN_RDA_DATA4(n) ((uint32_t)((n&0xFF)<<24)) /*********************************************************************//** * Macro defines for CAN Receive Data B Register **********************************************************************/ /** CAN Receive Data 5 */ #define CAN_RDB_DATA5(n) ((uint32_t)(n&0xFF)) /** CAN Receive Data 6 */ #define CAN_RDB_DATA6(n) ((uint32_t)((n&0xFF)<<8)) /** CAN Receive Data 7 */ #define CAN_RDB_DATA7(n) ((uint32_t)((n&0xFF)<<16)) /** CAN Receive Data 8 */ #define CAN_RDB_DATA8(n) ((uint32_t)((n&0xFF)<<24)) /*********************************************************************//** * Macro defines for CAN Transmit Frame Information Register **********************************************************************/ /** CAN Priority */ #define CAN_TFI_PRIO(n) ((uint32_t)(n&0xFF)) /** CAN Data Length Code */ #define CAN_TFI_DLC(n) ((uint32_t)((n&0xF)<<16)) /** CAN Remote Frame Transmission */ #define CAN_TFI_RTR ((uint32_t)(1<<30)) /** CAN control 11-bit or 29-bit Identifier */ #define CAN_TFI_FF ((uint32_t)(1<<31)) /*********************************************************************//** * Macro defines for CAN Transmit Identifier Register **********************************************************************/ /** CAN 11-bit Identifier */ #define CAN_TID_ID11(n) ((uint32_t)(n&0x7FF)) /** CAN 11-bit Identifier */ #define CAN_TID_ID29(n) ((uint32_t)(n&0x1FFFFFFF)) /*********************************************************************//** * Macro defines for CAN Transmit Data A Register **********************************************************************/ /** CAN Transmit Data 1 */ #define CAN_TDA_DATA1(n) ((uint32_t)(n&0xFF)) /** CAN Transmit Data 2 */ #define CAN_TDA_DATA2(n) ((uint32_t)((n&0xFF)<<8)) /** CAN Transmit Data 3 */ #define CAN_TDA_DATA3(n) ((uint32_t)((n&0xFF)<<16)) /** CAN Transmit Data 4 */ #define CAN_TDA_DATA4(n) ((uint32_t)((n&0xFF)<<24)) /*********************************************************************//** * Macro defines for CAN Transmit Data B Register **********************************************************************/ /** CAN Transmit Data 5 */ #define CAN_TDA_DATA5(n) ((uint32_t)(n&0xFF)) /** CAN Transmit Data 6 */ #define CAN_TDA_DATA6(n) ((uint32_t)((n&0xFF)<<8)) /** CAN Transmit Data 7 */ #define CAN_TDA_DATA7(n) ((uint32_t)((n&0xFF)<<16)) /** CAN Transmit Data 8 */ #define CAN_TDA_DATA8(n) ((uint32_t)((n&0xFF)<<24)) /*********************************************************************//** * Macro defines for CAN Sleep Clear Register **********************************************************************/ /** CAN1 Sleep mode */ #define CAN1SLEEPCLR ((uint32_t)(1<<1)) /** CAN2 Sleep Mode */ #define CAN2SLEEPCLR ((uint32_t)(1<<2)) /*********************************************************************//** * Macro defines for CAN Wake up Flags Register **********************************************************************/ /** CAN1 Sleep mode */ #define CAN_WAKEFLAGES_CAN1WAKE ((uint32_t)(1<<1)) /** CAN2 Sleep Mode */ #define CAN_WAKEFLAGES_CAN2WAKE ((uint32_t)(1<<2)) /*********************************************************************//** * Macro defines for Central transmit Status Register **********************************************************************/ /** CAN Transmit 1 */ #define CAN_TSR_TS1 ((uint32_t)(1)) /** CAN Transmit 2 */ #define CAN_TSR_TS2 ((uint32_t)(1<<1)) /** CAN Transmit Buffer Status 1 */ #define CAN_TSR_TBS1 ((uint32_t)(1<<8)) /** CAN Transmit Buffer Status 2 */ #define CAN_TSR_TBS2 ((uint32_t)(1<<9)) /** CAN Transmission Complete Status 1 */ #define CAN_TSR_TCS1 ((uint32_t)(1<<16)) /** CAN Transmission Complete Status 2 */ #define CAN_TSR_TCS2 ((uint32_t)(1<<17)) /*********************************************************************//** * Macro defines for Central Receive Status Register **********************************************************************/ /** CAN Receive Status 1 */ #define CAN_RSR_RS1 ((uint32_t)(1)) /** CAN Receive Status 1 */ #define CAN_RSR_RS2 ((uint32_t)(1<<1)) /** CAN Receive Buffer Status 1*/ #define CAN_RSR_RB1 ((uint32_t)(1<<8)) /** CAN Receive Buffer Status 2*/ #define CAN_RSR_RB2 ((uint32_t)(1<<9)) /** CAN Data Overrun Status 1 */ #define CAN_RSR_DOS1 ((uint32_t)(1<<16)) /** CAN Data Overrun Status 1 */ #define CAN_RSR_DOS2 ((uint32_t)(1<<17)) /*********************************************************************//** * Macro defines for Central Miscellaneous Status Register **********************************************************************/ /** Same CAN Error Status in CAN1GSR */ #define CAN_MSR_E1 ((uint32_t)(1)) /** Same CAN Error Status in CAN2GSR */ #define CAN_MSR_E2 ((uint32_t)(1<<1)) /** Same CAN Bus Status in CAN1GSR */ #define CAN_MSR_BS1 ((uint32_t)(1<<8)) /** Same CAN Bus Status in CAN2GSR */ #define CAN_MSR_BS2 ((uint32_t)(1<<9)) /*********************************************************************//** * Macro defines for Acceptance Filter Mode Register **********************************************************************/ /** CAN Acceptance Filter Off mode */ #define CAN_AFMR_AccOff ((uint32_t)(1)) /** CAN Acceptance File Bypass mode */ #define CAN_AFMR_AccBP ((uint32_t)(1<<1)) /** FullCAN Mode Enhancements */ #define CAN_AFMR_eFCAN ((uint32_t)(1<<2)) /*********************************************************************//** * Macro defines for Standard Frame Individual Start Address Register **********************************************************************/ /** The start address of the table of individual Standard Identifier */ #define CAN_STT_sa(n) ((uint32_t)((n&1FF)<<2)) /*********************************************************************//** * Macro defines for Standard Frame Group Start Address Register **********************************************************************/ /** The start address of the table of grouped Standard Identifier */ #define CAN_SFF_GRP_sa(n) ((uint32_t)((n&3FF)<<2)) /*********************************************************************//** * Macro defines for Extended Frame Start Address Register **********************************************************************/ /** The start address of the table of individual Extended Identifier */ #define CAN_EFF_sa(n) ((uint32_t)((n&1FF)<<2)) /*********************************************************************//** * Macro defines for Extended Frame Group Start Address Register **********************************************************************/ /** The start address of the table of grouped Extended Identifier */ #define CAN_Eff_GRP_sa(n) ((uint32_t)((n&3FF)<<2)) /*********************************************************************//** * Macro defines for End Of AF Table Register **********************************************************************/ /** The End of Table of AF LookUp Table */ #define CAN_EndofTable(n) ((uint32_t)((n&3FF)<<2)) /*********************************************************************//** * Macro defines for LUT Error Address Register **********************************************************************/ /** CAN Look-Up Table Error Address */ #define CAN_LUTerrAd(n) ((uint32_t)((n&1FF)<<2)) /*********************************************************************//** * Macro defines for LUT Error Register **********************************************************************/ /** CAN Look-Up Table Error */ #define CAN_LUTerr ((uint32_t)(1)) /*********************************************************************//** * Macro defines for Global FullCANInterrupt Enable Register **********************************************************************/ /** Global FullCANInterrupt Enable */ #define CAN_FCANIE ((uint32_t)(1)) /*********************************************************************//** * Macro defines for FullCAN Interrupt and Capture Register 0 **********************************************************************/ /** FullCAN Interrupt and Capture (0-31)*/ #define CAN_FCANIC0_IntPnd(n) ((uint32_t)(1<<n)) /*********************************************************************//** * Macro defines for FullCAN Interrupt and Capture Register 1 **********************************************************************/ /** FullCAN Interrupt and Capture (0-31)*/ #define CAN_FCANIC1_IntPnd(n) ((uint32_t)(1<<(n-32))) /* ---------------- CHECK PARAMETER DEFINITIONS ---------------------------- */ /** Macro to determine if it is valid CAN peripheral or not */ #define PARAM_CANx(x) ((((uint32_t*)x)==((uint32_t *)LPC_CAN1)) \ ||(((uint32_t*)x)==((uint32_t *)LPC_CAN2))) /* Macro to determine if it is valid CANAF or not*/ #define PARAM_CANAFx(x) (((uint32_t*)x)== ((uint32_t*)LPC_CANAF)) /* Macro to determine if it is valid CANAF RAM or not*/ #define PARAM_CANAFRAMx(x) (((uint32_t*)x)== (uint32_t*)LPC_CANAF_RAM) /* Macro to determine if it is valid CANCR or not*/ #define PARAM_CANCRx(x) (((uint32_t*)x)==((uint32_t*)LPC_CANCR)) /** Macro to check Data to send valid */ #define PARAM_I2S_DATA(data) ((data>=0)&&(data <= 0xFFFFFFFF)) /** Macro to check frequency value */ #define PRAM_I2S_FREQ(freq) ((freq>=16000)&&(freq <= 96000)) /** Macro to check Frame Identifier */ #define PARAM_ID_11(n) ((n>>11)==0) /*-- 11 bit --*/ #define PARAM_ID_29(n) ((n>>29)==0) /*-- 29 bit --*/ /** Macro to check DLC value */ #define PARAM_DLC(n) ((n>>4)==0) /*-- 4 bit --*/ /** Macro to check ID format type */ #define PARAM_ID_FORMAT(n) ((n==STD_ID_FORMAT)||(n==EXT_ID_FORMAT)) /** Macro to check Group identifier */ #define PARAM_GRP_ID(x, y) ((x<=y)) /** Macro to check Frame type */ #define PARAM_FRAME_TYPE(n) ((n==DATA_FRAME)||(n==REMOTE_FRAME)) /** Macro to check Control/Central Status type parameter */ #define PARAM_CTRL_STS_TYPE(n) ((n==CANCTRL_GLOBAL_STS)||(n==CANCTRL_INT_CAP) \ ||(n==CANCTRL_ERR_WRN)||(n==CANCTRL_STS)) /** Macro to check CR status type */ #define PARAM_CR_STS_TYPE(n) ((n==CANCR_TX_STS)||(n==CANCR_RX_STS) \ ||(n==CANCR_MS)) /** Macro to check AF Mode type parameter */ #define PARAM_AFMODE_TYPE(n) ((n==CAN_NORMAL)||(n==CAN_ACC_OFF) \ ||(n==CAN_ACC_BP)||(n==CAN_EFCAN)) /** Macro to check Operation Mode */ #define PARAM_MODE_TYPE(n) ((n==CAN_OPERATING_MODE)||(n==CAN_RESET_MODE) \ ||(n==CAN_LISTENONLY_MODE)||(n==CAN_SELFTEST_MODE) \ ||(n==CAN_TXPRIORITY_MODE)||(n==CAN_SLEEP_MODE) \ ||(n==CAN_RXPOLARITY_MODE)||(n==CAN_TEST_MODE)) /** Macro define for struct AF_Section parameter */ #define PARAM_CTRL(n) ((n==CAN1_CTRL)|(n==CAN2_CTRL)) /** Macro define for struct AF_Section parameter */ #define PARAM_MSG_DISABLE(n) ((n==MSG_ENABLE)|(n==MSG_DISABLE)) /**Macro to check Interrupt Type parameter */ #define PARAM_INT_EN_TYPE(n) ((n==CANINT_RIE)||(n==CANINT_TIE1) \ ||(n==CANINT_EIE)||(n==CANINT_DOIE) \ ||(n==CANINT_WUIE)||(n==CANINT_EPIE) \ ||(n==CANINT_ALIE)||(n==CANINT_BEIE) \ ||(n==CANINT_IDIE)||(n==CANINT_TIE2) \ ||(n==CANINT_TIE3)||(n==CANINT_FCE)) /** Macro to check AFLUT Entry type */ #define PARAM_AFLUT_ENTRY_TYPE(n) ((n==FULLCAN_ENTRY)||(n==EXPLICIT_STANDARD_ENTRY)\ ||(n==GROUP_STANDARD_ENTRY)||(n==EXPLICIT_EXTEND_ENTRY) \ ||(n==GROUP_EXTEND_ENTRY)) /** Macro to check position */ #define PARAM_POSITION(n) ((n>=0)&&(n<512)) /** * @} */ /* Public Types --------------------------------------------------------------- */ /** @defgroup CAN_Public_Types CAN Public Types * @{ */ /*********************************************************************** * CAN device configuration commands (IOCTL commands and arguments) **********************************************************************/ /** CAN peripheral ID 0 */ #define CAN_1 0 /** CAN peripheral ID 1 */ #define CAN_2 1 /** * @brief CAN peripheral ID no */ typedef enum { CAN_ID_1 = CAN_1, CAN_ID_2 = CAN_2 } en_CAN_unitId; /** * @brief CAN ID format definition */ typedef enum { STD_ID_FORMAT = 0, /**< Use standard ID format (11 bit ID) */ EXT_ID_FORMAT = 1 /**< Use extended ID format (29 bit ID) */ } CAN_ID_FORMAT_Type; /** * @brief AFLUT Entry type definition */ typedef enum { FULLCAN_ENTRY = 0, EXPLICIT_STANDARD_ENTRY, GROUP_STANDARD_ENTRY, EXPLICIT_EXTEND_ENTRY, GROUP_EXTEND_ENTRY, } AFLUT_ENTRY_Type; /** * @brief Symbolic names for type of CAN message */ typedef enum { DATA_FRAME = 0, /**< Data frame */ REMOTE_FRAME = 1 /**< Remote frame */ } CAN_FRAME_Type; /** * @brief CAN Control status definition */ typedef enum { CANCTRL_GLOBAL_STS = 0, /**< CAN Global Status */ CANCTRL_INT_CAP, /**< CAN Interrupt and Capture */ CANCTRL_ERR_WRN, /**< CAN Error Warning Limit */ CANCTRL_STS /**< CAN Control Status */ } CAN_CTRL_STS_Type; /** * @brief Central CAN status type definition */ typedef enum { CANCR_TX_STS = 0, /**< Central CAN Tx Status */ CANCR_RX_STS, /**< Central CAN Rx Status */ CANCR_MS /**< Central CAN Miscellaneous Status */ } CAN_CR_STS_Type; /** * @brief FullCAN Interrupt Capture type definition */ typedef enum { FULLCAN_IC0, /**< FullCAN Interrupt and Capture 0 */ FULLCAN_IC1 /**< FullCAN Interrupt and Capture 1 */ }FullCAN_IC_Type; /** * @brief CAN interrupt enable type definition */ typedef enum { CANINT_RIE = 0, /**< CAN Receiver Interrupt Enable */ CANINT_TIE1, /**< CAN Transmit Interrupt Enable */ CANINT_EIE, /**< CAN Error Warning Interrupt Enable */ CANINT_DOIE, /**< CAN Data Overrun Interrupt Enable */ CANINT_WUIE, /**< CAN Wake-Up Interrupt Enable */ CANINT_EPIE, /**< CAN Error Passive Interrupt Enable */ CANINT_ALIE, /**< CAN Arbitration Lost Interrupt Enable */ CANINT_BEIE, /**< CAN Bus Error Inter rupt Enable */ CANINT_IDIE, /**< CAN ID Ready Interrupt Enable */ CANINT_TIE2, /**< CAN Transmit Interrupt Enable for Buffer2 */ CANINT_TIE3, /**< CAN Transmit Interrupt Enable for Buffer3 */ CANINT_FCE /**< FullCAN Interrupt Enable */ } CAN_INT_EN_Type; /** * @brief Acceptance Filter Mode type definition */ typedef enum { CAN_NORMAL = 0, /**< Normal Mode */ CAN_ACC_OFF, /**< Acceptance Filter Off Mode */ CAN_ACC_BP, /**< Acceptance Fileter Bypass Mode */ CAN_EFCAN /**< FullCAN Mode Enhancement */ } CAN_AFMODE_Type; /** * @brief CAN Mode Type definition */ typedef enum { CAN_OPERATING_MODE = 0, /**< Operating Mode */ CAN_RESET_MODE, /**< Reset Mode */ CAN_LISTENONLY_MODE, /**< Listen Only Mode */ CAN_SELFTEST_MODE, /**< Seft Test Mode */ CAN_TXPRIORITY_MODE, /**< Transmit Priority Mode */ CAN_SLEEP_MODE, /**< Sleep Mode */ CAN_RXPOLARITY_MODE, /**< Receive Polarity Mode */ CAN_TEST_MODE /**< Test Mode */ } CAN_MODE_Type; /** * @brief Error values that functions can return */ typedef enum { CAN_OK = 1, /**< No error */ CAN_OBJECTS_FULL_ERROR, /**< No more rx or tx objects available */ CAN_FULL_OBJ_NOT_RCV, /**< Full CAN object not received */ CAN_NO_RECEIVE_DATA, /**< No have receive data available */ CAN_AF_ENTRY_ERROR, /**< Entry load in AFLUT is unvalid */ CAN_CONFLICT_ID_ERROR, /**< Conflict ID occur */ CAN_ENTRY_NOT_EXIT_ERROR /**< Entry remove outo AFLUT is not exit */ } CAN_ERROR; /** * @brief Pin Configuration structure */ typedef struct { uint8_t RD; /**< Serial Inputs, from CAN transceivers, should be: ** For CAN1: - CAN_RD1_P0_0: RD pin is on P0.0 - CAN_RD1_P0_21 : RD pin is on P0.21 ** For CAN2: - CAN_RD2_P0_4: RD pin is on P0.4 - CAN_RD2_P2_7: RD pin is on P2.7 */ uint8_t TD; /**< Serial Outputs, To CAN transceivers, should be: ** For CAN1: - CAN_TD1_P0_1: TD pin is on P0.1 - CAN_TD1_P0_22: TD pin is on P0.22 ** For CAN2: - CAN_TD2_P0_5: TD pin is on P0.5 - CAN_TD2_P2_8: TD pin is on P2.8 */ } CAN_PinCFG_Type; /** * @brief CAN message object structure */ typedef struct { uint32_t id; /**< 29 bit identifier, it depend on "format" value - if format = STD_ID_FORMAT, id should be 11 bit identifier - if format = EXT_ID_FORMAT, id should be 29 bit identifier */ uint8_t dataA[4]; /**< Data field A */ uint8_t dataB[4]; /**< Data field B */ uint8_t len; /**< Length of data field in bytes, should be: - 0000b-0111b: 0-7 bytes - 1xxxb: 8 bytes */ uint8_t format; /**< Identifier Format, should be: - STD_ID_FORMAT: Standard ID - 11 bit format - EXT_ID_FORMAT: Extended ID - 29 bit format */ uint8_t type; /**< Remote Frame transmission, should be: - DATA_FRAME: the number of data bytes called out by the DLC field are send from the CANxTDA and CANxTDB registers - REMOTE_FRAME: Remote Frame is sent */ } CAN_MSG_Type; /** * @brief FullCAN Entry structure */ typedef struct { uint8_t controller; /**< CAN Controller, should be: - CAN1_CTRL: CAN1 Controller - CAN2_CTRL: CAN2 Controller */ uint8_t disable; /**< Disable bit, should be: - MSG_ENABLE: disable bit = 0 - MSG_DISABLE: disable bit = 1 */ uint16_t id_11; /**< Standard ID, should be 11-bit value */ } FullCAN_Entry; /** * @brief Standard ID Frame Format Entry structure */ typedef struct { uint8_t controller; /**< CAN Controller, should be: - CAN1_CTRL: CAN1 Controller - CAN2_CTRL: CAN2 Controller */ uint8_t disable; /**< Disable bit, should be: - MSG_ENABLE: disable bit = 0 - MSG_DISABLE: disable bit = 1 */ uint16_t id_11; /**< Standard ID, should be 11-bit value */ } SFF_Entry; /** * @brief Group of Standard ID Frame Format Entry structure */ typedef struct { uint8_t controller1; /**< First CAN Controller, should be: - CAN1_CTRL: CAN1 Controller - CAN2_CTRL: CAN2 Controller */ uint8_t disable1; /**< First Disable bit, should be: - MSG_ENABLE: disable bit = 0) - MSG_DISABLE: disable bit = 1 */ uint16_t lowerID; /**< ID lower bound, should be 11-bit value */ uint8_t controller2; /**< Second CAN Controller, should be: - CAN1_CTRL: CAN1 Controller - CAN2_CTRL: CAN2 Controller */ uint8_t disable2; /**< Second Disable bit, should be: - MSG_ENABLE: disable bit = 0 - MSG_DISABLE: disable bit = 1 */ uint16_t upperID; /**< ID upper bound, should be 11-bit value and equal or greater than lowerID */ } SFF_GPR_Entry; /** * @brief Extended ID Frame Format Entry structure */ typedef struct { uint8_t controller; /**< CAN Controller, should be: - CAN1_CTRL: CAN1 Controller - CAN2_CTRL: CAN2 Controller */ uint32_t ID_29; /**< Extend ID, shoud be 29-bit value */ } EFF_Entry; /** * @brief Group of Extended ID Frame Format Entry structure */ typedef struct { uint8_t controller1; /**< First CAN Controller, should be: - CAN1_CTRL: CAN1 Controller - CAN2_CTRL: CAN2 Controller */ uint8_t controller2; /**< Second Disable bit, should be: - MSG_ENABLE: disable bit = 0(default) - MSG_DISABLE: disable bit = 1 */ uint32_t lowerEID; /**< Extended ID lower bound, should be 29-bit value */ uint32_t upperEID; /**< Extended ID upper bound, should be 29-bit value */ } EFF_GPR_Entry; /** * @brief Acceptance Filter Section Table structure */ typedef struct { FullCAN_Entry* FullCAN_Sec; /**< The pointer point to FullCAN_Entry */ uint8_t FC_NumEntry; /**< FullCAN Entry Number */ SFF_Entry* SFF_Sec; /**< The pointer point to SFF_Entry */ uint8_t SFF_NumEntry; /**< Standard ID Entry Number */ SFF_GPR_Entry* SFF_GPR_Sec; /**< The pointer point to SFF_GPR_Entry */ uint8_t SFF_GPR_NumEntry; /**< Group Standard ID Entry Number */ EFF_Entry* EFF_Sec; /**< The pointer point to EFF_Entry */ uint8_t EFF_NumEntry; /**< Extended ID Entry Number */ EFF_GPR_Entry* EFF_GPR_Sec; /**< The pointer point to EFF_GPR_Entry */ uint8_t EFF_GPR_NumEntry; /**< Group Extended ID Entry Number */ } AF_SectionDef; /** * @} */ /* Public Functions ----------------------------------------------------------- */ /** @defgroup CAN_Public_Functions CAN Public Functions * @{ */ /* Init/DeInit CAN peripheral -----------*/ void CAN_Init(uint8_t canId, uint32_t baudrate); void CAN_DeInit(uint8_t canId); /* CAN messages functions ---------------*/ Status CAN_SendMsg(uint8_t canId, CAN_MSG_Type *CAN_Msg); Status CAN_ReceiveMsg(uint8_t canId, CAN_MSG_Type *CAN_Msg); CAN_ERROR FCAN_ReadObj(CAN_MSG_Type *CAN_Msg); /* CAN configure functions ---------------*/ void CAN_ModeConfig(uint8_t canId, CAN_MODE_Type mode, FunctionalState NewState); void CAN_SetAFMode(CAN_AFMODE_Type AFmode); void CAN_SetCommand(uint8_t canId, uint32_t CMRType); /* AFLUT functions ---------------------- */ CAN_ERROR CAN_SetupAFLUT(AF_SectionDef* AFSection); CAN_ERROR CAN_LoadFullCANEntry(uint8_t canId, uint16_t ID); CAN_ERROR CAN_LoadExplicitEntry(uint8_t canId, uint32_t ID, CAN_ID_FORMAT_Type format); CAN_ERROR CAN_LoadGroupEntry(uint8_t canId, uint32_t lowerID, uint32_t upperID, CAN_ID_FORMAT_Type format); CAN_ERROR CAN_RemoveEntry(AFLUT_ENTRY_Type EntryType, uint16_t position); /* CAN interrupt functions -----------------*/ void CAN_IRQCmd(uint8_t canId, CAN_INT_EN_Type arg, FunctionalState NewState); uint32_t CAN_IntGetStatus(uint8_t canId); /* CAN get status functions ----------------*/ IntStatus CAN_FullCANIntGetStatus (void); uint32_t CAN_FullCANPendGetStatus (FullCAN_IC_Type type); uint32_t CAN_GetCTRLStatus(uint8_t canId, CAN_CTRL_STS_Type arg); uint32_t CAN_GetCRStatus(CAN_CR_STS_Type arg); /** * @} */ #ifdef __cplusplus } #endif #endif /* LPC177X_8X_CAN_H_ */ /** * @} */ /* --------------------------------- End Of File ------------------------------ */
{'content_hash': '3946b6cd00c15ff1bd4bd510d30b4291', 'timestamp': '', 'source': 'github', 'line_count': 1014, 'max_line_length': 97, 'avg_line_length': 36.146942800788956, 'alnum_prop': 0.47895124546421847, 'repo_name': 'dbtayl/Runner-s-GPS', 'id': 'd7aff2d84e169be103fc6ba8eb3ab6f4d362dd85', 'size': '36653', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'software/Drivers/include/lpc177x_8x_can.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Assembly', 'bytes': '10352'}, {'name': 'C', 'bytes': '3554196'}, {'name': 'C++', 'bytes': '69446'}, {'name': 'Eagle', 'bytes': '34459'}, {'name': 'Makefile', 'bytes': '4140'}, {'name': 'Shell', 'bytes': '607'}]}
// // UAASSetDesiredCapacityRequest.m // AWS iOS SDK // // Copyright © Unsigned Apps 2014. See License file. // Created by Rob Amos. // // #import "UAASSetDesiredCapacityRequest.h" #import "UAAWSAdditionalAccessors.h" #import "UAASSetDesiredCapacityResponse.h" @interface UAASSetDesiredCapacityRequest () @property (nonatomic, copy) NSString *action; @property (nonatomic, copy) NSString *version; @end #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wincomplete-implementation" @implementation UAASSetDesiredCapacityRequest @synthesize action=_action, version=_version, autoScalingGroupName=_autoScalingGroupName, desiredCapacity=_desiredCapacity, honorCooldown=_honorCooldown; - (id)init { if (self = [super init]) { [self setAction:@"SetDesiredCapacity"]; [self setVersion:@"2011-01-01"]; } return self; } - (Class)UA_ResponseClass { return [UAASSetDesiredCapacityResponse class]; } + (NSDictionary *)queryStringKeyPathsByPropertyKey { // Start with super's key paths (if there are any) NSMutableDictionary *keyPaths = [[UAASRequest queryStringKeyPathsByPropertyKey] mutableCopy]; [keyPaths addEntriesFromDictionary: @{ @"action": @"Action", @"version": @"Version", @"autoScalingGroupName": @"AutoScalingGroupName", @"desiredCapacity": @"DesiredCapacity", @"honorCooldown": @"HonorCooldown" }]; return [keyPaths copy]; } + (NSValueTransformer *)honorCooldownQueryStringTransformer { return [UAMTLValueTransformer UA_JSONTransformerForBooleanString]; } /*#pragma mark - Invocation - (void)invokeWithOwner:(id)owner completionBlock:(UAASSetDesiredCapacityRequestCompletionBlock)completionBlock { [self setUA_Owner:owner]; [self setUA_RequestCompletionBlock:completionBlock]; [self invoke]; } - (void)waitWithOwner:(id)owner shouldContinueWaitingBlock:(UAASSetDesiredCapacityRequestShouldContinueWaitingBlock)shouldContinueWaitingBlock completionBlock:(UAASSetDesiredCapacityRequestCompletionBlock)completionBlock { [self setUA_Owner:owner]; [self setUA_ShouldContinueWaiting:shouldContinueWaitingBlock]; [self setUA_RequestCompletionBlock:completionBlock]; [self invoke]; } - (void)waitWithOwner:(id)owner untilValueAtKeyPath:(NSString *)keyPath isInArray:(NSArray *)array completionBlock:(UAASSetDesiredCapacityRequestCompletionBlock)completionBlock { [self setUA_Owner:self]; [self setUA_ShouldContinueWaiting:[UAAWSRequest UA_ShouldContinueWaitingBlockUntilValueAtKeyPath:keyPath isInArray:array]]; [self setUA_RequestCompletionBlock:completionBlock]; [self invoke]; } */ @end #pragma clang diagnostic pop
{'content_hash': 'da4555607c75debb7414c5c9e6e04414', 'timestamp': '', 'source': 'github', 'line_count': 93, 'max_line_length': 220, 'avg_line_length': 28.752688172043012, 'alnum_prop': 0.7662677636499626, 'repo_name': 'unsignedapps/ua-aws-sdk-ios', 'id': '542cb28a2ea244af5597beaad4dfbf8ae6d75388', 'size': '2675', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'AWS iOS SDK/AS/Requests/UAASSetDesiredCapacityRequest.m', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '42359'}, {'name': 'Objective-C', 'bytes': '4812683'}, {'name': 'Ruby', 'bytes': '1520'}]}
'use strict'; const { expect } = require('chai'); const info_window_middleware = require('../src/components/info_window/middleware'); const uuid = require('uuid'); describe('.interface.components.info_window.middleware', function() { let store; let next; let action; beforeEach(function() { store = { dispatch: this.sinon.spy(), }; next = this.sinon.spy(); action = { type: "FAKE_ACTION", payload: {}, }; this.sinon.stub(uuid, 'v4').returns('fake-uuid'); }); it('passes the action through', function() { info_window_middleware(store)(next)(action); expect(next).to.have.been.calledOnce; expect(next.args[0][0]).to.deep.equal(action); }); context('when the action is CHANGE_STAT_FAILURE', function() { let error; beforeEach(function() { error = 'fake-error'; action.payload = error; action.type = 'CHANGE_STAT_FAILURE'; }); it('dispatches an error action with an unique id', function() { info_window_middleware(store)(next)(action); expect(store.dispatch).to.have.been.calledOnce; expect(store.dispatch.args[0][0]).to.deep.equal({ type: 'INFO_WINDOW_ALERT', payload: { id: 'fake-uuid', message: 'fake-error', type: 'CHANGE_STAT_FAILURE', category: 'error', }, }); }); }); context('When the action is a LOAD_FILE_FULFILLED.', function() { beforeEach(function() { action = { type: "LOAD_FILE_FULFILLED", payload: { filename: 'fake-filename', }, }; }); it('dispatches an info action with an unique id and clears errors', function() { info_window_middleware(store)(next)(action); expect(store.dispatch).to.have.been.calledTwicw; expect(store.dispatch.args[0][0]).to.deep.equal({ type: 'INFO_WINDOW_ALERT', payload: { id: 'fake-uuid', message: 'successfully loaded fake-filename', type: 'LOAD_FILE_FULFILLED', category: 'info', }, }); expect(store.dispatch.args[1][0]).to.deep.equal({ type: 'INFO_WINDOW_CLEAR_TYPE', payload: { type: 'LOAD_FILE_REJECTED', }, }); }); }); context('when the action is LOAD_FILE_REJECTED', function() { beforeEach(function() { action = { type: "LOAD_FILE_REJECTED", payload: new Error('fake-error'), }; }); it('dispatches an error action with an unique id', function() { info_window_middleware(store)(next)(action); expect(store.dispatch).to.have.been.calledOnce; expect(store.dispatch.args[0][0]).to.deep.equal({ type: 'INFO_WINDOW_ALERT', payload: { id: 'fake-uuid', message: 'fake-error', type: 'LOAD_FILE_REJECTED', category: 'error', }, }); }); }); context('When the action is a SAVE_FILE_FULFILLED.', function() { beforeEach(function() { action = { type: "SAVE_FILE_FULFILLED", payload: { filename: 'fake-filename', }, }; }); it('dispatches an info action with an unique id and clears errors', function() { info_window_middleware(store)(next)(action); expect(store.dispatch).to.have.been.calledTwice; expect(store.dispatch.args[0][0]).to.deep.equal({ type: 'INFO_WINDOW_ALERT', payload: { id: 'fake-uuid', message: 'successfully saved fake-filename', type: 'SAVE_FILE_FULFILLED', category: 'info', }, }); expect(store.dispatch.args[1][0]).to.deep.equal({ type: 'INFO_WINDOW_CLEAR_TYPE', payload: { type: 'SAVE_FILE_REJECTED', }, }); }); }); context('when the action is SAVE_FILE_REJECTED', function() { beforeEach(function() { action = { type: "SAVE_FILE_REJECTED", payload: new Error('fake-error'), }; }); it('dispatches an error action with an unique id', function() { info_window_middleware(store)(next)(action); expect(store.dispatch).to.have.been.calledOnce; expect(store.dispatch.args[0][0]).to.deep.equal({ type: 'INFO_WINDOW_ALERT', payload: { id: 'fake-uuid', message: 'fake-error', type: 'SAVE_FILE_REJECTED', category: 'error', }, }); }); }); context('when an error action is dispatched', function() { let error; beforeEach(function() { error = new Error('fake-error'); action.payload = error; action.type = 'LOAD_FILE_REJECTED'; }); it('dispatches a INFO_WINDOW_CLEAR_ID action after 15 seconds', function() { var clock = this.sinon.useFakeTimers(); info_window_middleware(store)(next)(action); expect(store.dispatch).to.have.been.calledOnce; clock.tick(14000); expect(store.dispatch).to.have.been.calledOnce; clock.tick(1000); expect(store.dispatch).to.have.been.calledTwice; expect(store.dispatch.args[1][0]).to.deep.equal({ type: 'INFO_WINDOW_CLEAR_ID', payload: { id: 'fake-uuid', }, }); clock.restore(); }); }); });
{'content_hash': 'aa53eec8f9812b3cb3106136db92748a', 'timestamp': '', 'source': 'github', 'line_count': 212, 'max_line_length': 84, 'avg_line_length': 25.712264150943398, 'alnum_prop': 0.5483397541735462, 'repo_name': 'bkovacevich/poe-companion-editor', 'id': '0c4024e76598be7f41002e5e896702bc5bc50d6d', 'size': '5451', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'interface/tests/components.info_window.middleware.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '296811'}, {'name': 'HTML', 'bytes': '644'}, {'name': 'JavaScript', 'bytes': '101725'}]}
from __future__ import absolute_import, unicode_literals, division import datetime import json import logging import re import os from vld.constants import DATA_DIR from vld.ingredient import IngredientMap from vld.serialization import load_ingredients from vld.parse import parse_log_data, ParseError from vld.objects import CantConvert, LogData, NutritionalValue from vld.utils import base_argument_parser logger = logging.getLogger(__name__) # pylint: disable=invalid-name def get_argument_parser(): parser = base_argument_parser() parser.add_argument( 'data', nargs='+', help=('Ingredients to count in format <ingredient>, <amount> <unit>. ' 'Multiple ingredients must be separated with "+"')) return parser def main(options): parts = ' '.join(options.data).split('+') ingredients = load_ingredients(os.path.join(DATA_DIR, 'ingredients')) ingredient_map = IngredientMap(ingredients) _update_stock(STOCK_DIR, STOCK_CACHE_DIR, ingredient_map) with open(os.path.join(STOCK_CACHE_DIR, datetime.date.today().strftime('%F'))) as fin: prices = json.load(fin) datas = [make_log_data(p, ingredient_map, n) for n, p in enumerate(parts)] total = 0 for data in datas: print data.name, log_line = data.log_line if log_line and log_line.ingredient: ingredient = log_line.ingredient price = prices[ingredient.name] * ingredient.convert( log_line.amount, log_line.unit, ingredient.sample_unit) print " $", price total += price else: print "BAD LINE" print print "TOTAL: $", total def make_log_data(line, ingredient_map, part_num): try: return parse_log_data(line, ingredient_map) except ParseError as err: logging.warning("%s (Part #%s)", err, part_num + 1) return LogData(name=line.strip(), nutritional_value=NutritionalValue.UNKNOWN) STOCK_DIR = 'data/stock' STOCK_CACHE_DIR = '/tmp/stock' def _update_stock(stock_dir, cache_dir, ingredients): if not os.path.isdir(cache_dir): os.makedirs(cache_dir) stock_files = os.listdir(stock_dir) if not stock_files: logger.info('No stock files to process') start = datetime.datetime.strptime(sorted(stock_files)[0], '%Y-%m-%d').date() end = datetime.date.today() date = start values = {} while date <= end: date_str = date.strftime('%Y-%m-%d') stock_file = os.path.join(stock_dir, date_str) if os.path.isfile(stock_file): values.update(_get_price_values(stock_file, ingredients)) with open(os.path.join(cache_dir, date_str), 'w') as fout: json.dump(values, fout, indent=1, sort_keys=True) date += datetime.timedelta(days=1) def _get_price_values(filename, ingredients): prices = {} with open(filename) as fin: for line in fin: line = line.strip() logger.debug("Getting prices from line: '%s'", line) if not line or line.startswith('#'): continue if ':' not in line: continue log_line, data = line.split(':', 1) if re.match('[+-]', log_line): log_line = log_line[1:] try: parsed = parse_log_data(log_line, ingredients) except ParseError as err: # TODO: handle error logger.debug("ERRRRRRROOOOOOOORRRRR %s", err) continue parsed_line = parsed.log_line logger.debug('Parsed line: "%s"', parsed_line) ingredient = parsed_line.ingredient data_values = _get_data_values(data) logger.debug('DataValues: %s', data_values) for key, value in data_values.items(): if key.startswith("$/"): unit = key[2:] amount = 1 break else: try: value = data_values['$'] except KeyError: continue amount = parsed_line.amount unit = parsed_line.unit try: prices[ingredient.name] = value / ingredient.convert( amount, unit, ingredient.sample_unit) except CantConvert as err: pass # TODO: handl error return prices RE_KEY_VALUE = r'(?P<key>[^\d.]+)\s*(?P<value>[\d.]+)' RE_VALUE_KEY = r'(?P<value>[\d.]+)\s*(?P<key>[^\d.]+)' def _get_data_values(data): values = {} for data_bit in data.split(','): data_bit = data_bit.strip() mobj = (re.search(RE_KEY_VALUE, data_bit) or re.search(RE_VALUE_KEY, data_bit)) if not mobj: continue try: values[mobj.group('key').strip()] = float(mobj.group('value')) except ValueError: continue return values
{'content_hash': '6f99fef4858b6c46505ef4265a00ca22', 'timestamp': '', 'source': 'github', 'line_count': 158, 'max_line_length': 78, 'avg_line_length': 32.28481012658228, 'alnum_prop': 0.5618506175259753, 'repo_name': 'pignacio/vld', 'id': 'ac394521f41b96cf6ee211819be604c4c228c0a3', 'size': '5147', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'vld/commands/price.py', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Makefile', 'bytes': '2573'}, {'name': 'Python', 'bytes': '45660'}]}
// 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. package org.chromium.chrome.browser.locale; import org.chromium.base.annotations.NativeMethods; /** * A loader class for changes of template url in a given special locale. This is a JNI bridge and * it owns the native object. Make sure to call destroy() after this object is not used anymore. */ public class LocaleTemplateUrlLoader { private final String mLocaleId; private long mNativeLocaleTemplateUrlLoader; private boolean mAddedToService; /** * Creates a {@link LocaleTemplateUrlLoader} that handles changes for the given locale. * @param localeId Country id of the locale. Should be 2 characters long. */ public LocaleTemplateUrlLoader(String localeId) { assert localeId.length() == 2; mLocaleId = localeId; mNativeLocaleTemplateUrlLoader = LocaleTemplateUrlLoaderJni.get().init(localeId); } /** * This *must* be called after the {@link LocaleTemplateUrlLoader} is not used anymore. */ public void destroy() { assert mNativeLocaleTemplateUrlLoader != 0; LocaleTemplateUrlLoaderJni.get().destroy(mNativeLocaleTemplateUrlLoader); mNativeLocaleTemplateUrlLoader = 0; } /** * Loads the template urls for this locale, and adds it to template url service. If the device * was initialized in the given special locale, no-op here. * @return Whether loading is needed. */ public boolean loadTemplateUrls() { assert mNativeLocaleTemplateUrlLoader != 0; // If the locale is the same as the one set at install time, there is no need to load the // search engines, as they are already cached in the template url service. mAddedToService = LocaleTemplateUrlLoaderJni.get().loadTemplateUrls(mNativeLocaleTemplateUrlLoader); return mAddedToService; } /** * Removes the template urls that was added by {@link #loadTemplateUrls()}. No-op if * {@link #loadTemplateUrls()} returned false. */ public void removeTemplateUrls() { assert mNativeLocaleTemplateUrlLoader != 0; if (mAddedToService) { LocaleTemplateUrlLoaderJni.get().removeTemplateUrls(mNativeLocaleTemplateUrlLoader); } } /** * Overrides the default search provider in special locale. */ public void overrideDefaultSearchProvider() { assert mNativeLocaleTemplateUrlLoader != 0; LocaleTemplateUrlLoaderJni.get().overrideDefaultSearchProvider( mNativeLocaleTemplateUrlLoader); } /** * Sets the default search provider back to Google. */ public void setGoogleAsDefaultSearch() { assert mNativeLocaleTemplateUrlLoader != 0; LocaleTemplateUrlLoaderJni.get().setGoogleAsDefaultSearch(mNativeLocaleTemplateUrlLoader); } @NativeMethods interface Natives { long init(String localeId); void destroy(long nativeLocaleTemplateUrlLoader); boolean loadTemplateUrls(long nativeLocaleTemplateUrlLoader); void removeTemplateUrls(long nativeLocaleTemplateUrlLoader); void overrideDefaultSearchProvider(long nativeLocaleTemplateUrlLoader); void setGoogleAsDefaultSearch(long nativeLocaleTemplateUrlLoader); } }
{'content_hash': 'b610962d0735b833f1e870cb18dcd9eb', 'timestamp': '', 'source': 'github', 'line_count': 87, 'max_line_length': 98, 'avg_line_length': 39.41379310344828, 'alnum_prop': 0.7063283756197142, 'repo_name': 'endlessm/chromium-browser', 'id': '85e8503b342da8f1eae3997f6e81a1620dac6a7f', 'size': '3429', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'chrome/android/java/src/org/chromium/chrome/browser/locale/LocaleTemplateUrlLoader.java', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []}
title: "How do you paint so smoothly with the brush tool?" type: paper date: 2014-12-07 modified: 2015-09-23T14:59:42-04:00 order: 5 --- A smooth gradient can be achieved layering many washes of watercolor on top of each other. Speed and pressure play an important role in how clean of a tone you end up with. My [Paper Basics guide]({{ site.url }}{% post_url 2014-02-09-basics %}) explains all of the nuances of the watercolor brush and several techniques for using it. #### Here's a quick video showing the basics: <iframe width="853" height="480" src="https://www.youtube-nocookie.com/embed/AjJVrFFaCck?rel=0&amp;controls=0&amp;showinfo=0" frameborder="0" allowfullscreen></iframe>
{'content_hash': 'a8d31188dc290c4cddbf4fbc2968932b', 'timestamp': '', 'source': 'github', 'line_count': 12, 'max_line_length': 333, 'avg_line_length': 57.333333333333336, 'alnum_prop': 0.75, 'repo_name': 'blogtips/blogtips.github.io', 'id': '183f1c9733f96d055eff02c51b20dd94c1ddde10', 'size': '692', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/_faqs/paint-smooth.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '39588'}, {'name': 'HTML', 'bytes': '18093'}, {'name': 'JavaScript', 'bytes': '2333'}, {'name': 'Shell', 'bytes': '356'}]}
/* * GlobalGTest.cpp * * Created on: 03.06.2013 * Author: cls */ #ifndef NOGTEST #include "GlobalGTest.h" #include "../ClusteringCoefficient.h" #include "../../generators/ErdosRenyiGenerator.h" namespace NetworKit { GlobalGTest::GlobalGTest() { } GlobalGTest::~GlobalGTest() { } TEST_F(GlobalGTest, testClusteringCoefficient) { ErdosRenyiGenerator graphGen(10, 1.0); Graph G = graphGen.generate(); ClusteringCoefficient clusteringCoefficient; double cc = clusteringCoefficient.avgLocal(G); EXPECT_EQ(1.0, cc); } TEST_F(GlobalGTest, testGlobalClusteringCoefficient) { Graph G(6); G.addEdge(0, 1); G.addEdge(1, 2); G.addEdge(1, 3); G.addEdge(1, 4); G.addEdge(2, 3); G.addEdge(2, 4); G.addEdge(2, 5); G.addEdge(3, 5); double ccg = ClusteringCoefficient::exactGlobal(G); EXPECT_NEAR(ccg, 18.0 / 34.0, 1e-9); } } /* namespace NetworKit */ #endif /*NOGTEST*/
{'content_hash': '4a91d7451c884bd9e81c5db05b35943b', 'timestamp': '', 'source': 'github', 'line_count': 61, 'max_line_length': 54, 'avg_line_length': 14.819672131147541, 'alnum_prop': 0.6792035398230089, 'repo_name': 'fmaschler/networkit', 'id': '3a402e2143e9f9d6d63fd8a00c53b2c58d3f56a3', 'size': '904', 'binary': False, 'copies': '2', 'ref': 'refs/heads/SCD-weighted', 'path': 'networkit/cpp/global/test/GlobalGTest.cpp', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '10112'}, {'name': 'C++', 'bytes': '2589116'}, {'name': 'CSS', 'bytes': '16109'}, {'name': 'HTML', 'bytes': '10110'}, {'name': 'JavaScript', 'bytes': '4583'}, {'name': 'Jupyter Notebook', 'bytes': '35441'}, {'name': 'Matlab', 'bytes': '238'}, {'name': 'Python', 'bytes': '606841'}, {'name': 'Shell', 'bytes': '846'}, {'name': 'TeX', 'bytes': '5547'}]}
package com.anrisoftware.globalpom.projects.appproject; import java.beans.PropertyVetoException; import com.anrisoftware.globalpom.projects.appexceptions.AppException; @SuppressWarnings("serial") public class ProjectCreateException extends AppException { private static final String MESSAGE = "Error create default project"; public ProjectCreateException(PropertyVetoException e) { super(MESSAGE, e); } }
{'content_hash': '0d3a8785955439857fb573c75862f829', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 73, 'avg_line_length': 25.41176470588235, 'alnum_prop': 0.7893518518518519, 'repo_name': 'devent/globalpom-utils', 'id': '02bc0d99cef4080a346caec4d29429506a1918e1', 'size': '1079', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'globalpomutils-projects/src/main/java/com/anrisoftware/globalpom/projects/appproject/ProjectCreateException.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '26266'}, {'name': 'Groovy', 'bytes': '337502'}, {'name': 'Java', 'bytes': '1207947'}, {'name': 'Makefile', 'bytes': '5023'}, {'name': 'Shell', 'bytes': '502'}]}
/* global NexT, CONFIG */ HTMLElement.prototype.wrap = function(wrapper) { this.parentNode.insertBefore(wrapper, this); this.parentNode.removeChild(this); wrapper.appendChild(this); }; // https://caniuse.com/mdn-api_element_classlist_replace if (typeof DOMTokenList.prototype.replace !== 'function') { DOMTokenList.prototype.replace = function(remove, add) { this.remove(remove); this.add(add); }; } (function() { const onPageLoaded = () => document.dispatchEvent( new Event('page:loaded', { bubbles: true }) ); if (document.readyState === 'loading') { document.addEventListener('readystatechange', onPageLoaded, {once: true}); } else { onPageLoaded(); } document.addEventListener('pjax:success', onPageLoaded); })(); NexT.utils = { /** * Wrap images with fancybox. */ wrapImageWithFancyBox: function() { document.querySelectorAll('.post-body :not(a) > img, .post-body > img').forEach(element => { const $image = $(element); const imageLink = $image.attr('data-src') || $image.attr('src'); const $imageWrapLink = $image.wrap(`<a class="fancybox fancybox.image" href="${imageLink}" itemscope itemtype="http://schema.org/ImageObject" itemprop="url"></a>`).parent('a'); if ($image.is('.post-gallery img')) { $imageWrapLink.attr('data-fancybox', 'gallery').attr('rel', 'gallery'); } else if ($image.is('.group-picture img')) { $imageWrapLink.attr('data-fancybox', 'group').attr('rel', 'group'); } else { $imageWrapLink.attr('data-fancybox', 'default').attr('rel', 'default'); } const imageTitle = $image.attr('title') || $image.attr('alt'); if (imageTitle) { $imageWrapLink.append(`<p class="image-caption">${imageTitle}</p>`); // Make sure img title tag will show correctly in fancybox $imageWrapLink.attr('title', imageTitle).attr('data-caption', imageTitle); } }); $.fancybox.defaults.hash = false; $('.fancybox').fancybox({ loop : true, helpers: { overlay: { locked: false } } }); }, registerExtURL: function() { document.querySelectorAll('span.exturl').forEach(element => { const link = document.createElement('a'); // https://stackoverflow.com/questions/30106476/using-javascripts-atob-to-decode-base64-doesnt-properly-decode-utf-8-strings link.href = decodeURIComponent(atob(element.dataset.url).split('').map(c => { return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); }).join('')); link.rel = 'noopener external nofollow noreferrer'; link.target = '_blank'; link.className = element.className; link.title = element.title; link.innerHTML = element.innerHTML; element.parentNode.replaceChild(link, element); }); }, /** * One-click copy code support. */ registerCopyCode: function() { let figure = document.querySelectorAll('figure.highlight'); if (figure.length === 0) figure = document.querySelectorAll('pre:not(.mermaid)'); figure.forEach(element => { element.querySelectorAll('.code .line span').forEach(span => { span.classList.forEach(name => { span.classList.replace(name, `hljs-${name}`); }); }); if (!CONFIG.copycode) return; element.insertAdjacentHTML('beforeend', '<div class="copy-btn"><i class="fa fa-copy fa-fw"></i></div>'); const button = element.querySelector('.copy-btn'); button.addEventListener('click', () => { const lines = element.querySelector('.code') || element.querySelector('code'); const code = lines.innerText; if (navigator.clipboard) { // https://caniuse.com/mdn-api_clipboard_writetext navigator.clipboard.writeText(code).then(() => { button.querySelector('i').className = 'fa fa-check-circle fa-fw'; }, () => { button.querySelector('i').className = 'fa fa-times-circle fa-fw'; }); } else { const ta = document.createElement('textarea'); ta.style.top = window.scrollY + 'px'; // Prevent page scrolling ta.style.position = 'absolute'; ta.style.opacity = '0'; ta.readOnly = true; ta.value = code; document.body.append(ta); ta.select(); ta.setSelectionRange(0, code.length); ta.readOnly = false; const result = document.execCommand('copy'); button.querySelector('i').className = result ? 'fa fa-check-circle fa-fw' : 'fa fa-times-circle fa-fw'; ta.blur(); // For iOS button.blur(); document.body.removeChild(ta); } }); element.addEventListener('mouseleave', () => { setTimeout(() => { button.querySelector('i').className = 'fa fa-copy fa-fw'; }, 300); }); }); }, wrapTableWithBox: function() { document.querySelectorAll('table').forEach(element => { const box = document.createElement('div'); box.className = 'table-container'; element.wrap(box); }); }, registerVideoIframe: function() { document.querySelectorAll('iframe').forEach(element => { const supported = [ 'www.youtube.com', 'player.vimeo.com', 'player.youku.com', 'player.bilibili.com', 'www.tudou.com' ].some(host => element.src.includes(host)); if (supported && !element.parentNode.matches('.video-container')) { const box = document.createElement('div'); box.className = 'video-container'; element.wrap(box); const width = Number(element.width); const height = Number(element.height); if (width && height) { box.style.paddingTop = (height / width * 100) + '%'; } } }); }, registerScrollPercent: function() { const backToTop = document.querySelector('.back-to-top'); const readingProgressBar = document.querySelector('.reading-progress-bar'); // For init back to top in sidebar if page was scrolled after page refresh. window.addEventListener('scroll', () => { if (backToTop || readingProgressBar) { const contentHeight = document.body.scrollHeight - window.innerHeight; const scrollPercent = contentHeight > 0 ? Math.min(100 * window.scrollY / contentHeight, 100) : 0; if (backToTop) { backToTop.classList.toggle('back-to-top-on', Math.round(scrollPercent) >= 5); backToTop.querySelector('span').innerText = Math.round(scrollPercent) + '%'; } if (readingProgressBar) { readingProgressBar.style.setProperty('--progress', scrollPercent.toFixed(2) + '%'); } } if (!Array.isArray(NexT.utils.sections)) return; let index = NexT.utils.sections.findIndex(element => { return element && element.getBoundingClientRect().top > 0; }); if (index === -1) { index = NexT.utils.sections.length - 1; } else if (index > 0) { index--; } this.activateNavByIndex(index); }); backToTop && backToTop.addEventListener('click', () => { window.anime({ targets : document.scrollingElement, duration : 500, easing : 'linear', scrollTop: 0 }); }); }, /** * Tabs tag listener (without twitter bootstrap). */ registerTabsTag: function() { // Binding `nav-tabs` & `tab-content` by real time permalink changing. document.querySelectorAll('.tabs ul.nav-tabs .tab').forEach(element => { element.addEventListener('click', event => { event.preventDefault(); // Prevent selected tab to select again. if (element.classList.contains('active')) return; // Add & Remove active class on `nav-tabs` & `tab-content`. [...element.parentNode.children].forEach(target => { target.classList.toggle('active', target === element); }); // https://stackoverflow.com/questions/20306204/using-queryselector-with-ids-that-are-numbers const tActive = document.getElementById(element.querySelector('a').getAttribute('href').replace('#', '')); [...tActive.parentNode.children].forEach(target => { target.classList.toggle('active', target === tActive); }); // Trigger event tActive.dispatchEvent(new Event('tabs:click', { bubbles: true })); }); }); window.dispatchEvent(new Event('tabs:register')); }, registerCanIUseTag: function() { // Get responsive height passed from iframe. window.addEventListener('message', ({ data }) => { if (typeof data === 'string' && data.includes('ciu_embed')) { const featureID = data.split(':')[1]; const height = data.split(':')[2]; document.querySelector(`iframe[data-feature=${featureID}]`).style.height = parseInt(height, 10) + 5 + 'px'; } }, false); }, registerActiveMenuItem: function() { document.querySelectorAll('.menu-item a[href]').forEach(target => { const isSamePath = target.pathname === location.pathname || target.pathname === location.pathname.replace('index.html', ''); const isSubPath = !CONFIG.root.startsWith(target.pathname) && location.pathname.startsWith(target.pathname); target.classList.toggle('menu-item-active', target.hostname === location.hostname && (isSamePath || isSubPath)); }); }, registerLangSelect: function() { const selects = document.querySelectorAll('.lang-select'); selects.forEach(sel => { sel.value = CONFIG.page.lang; sel.addEventListener('change', () => { const target = sel.options[sel.selectedIndex]; document.querySelectorAll('.lang-select-label span').forEach(span => { span.innerText = target.text; }); // Disable Pjax to force refresh translation of menu item window.location.href = target.dataset.href; }); }); }, registerSidebarTOC: function() { this.sections = [...document.querySelectorAll('.post-toc li a.nav-link')].map(element => { const target = document.getElementById(decodeURI(element.getAttribute('href')).replace('#', '')); // TOC item animation navigate. element.addEventListener('click', event => { event.preventDefault(); const offset = target.getBoundingClientRect().top + window.scrollY; window.anime({ targets : document.scrollingElement, duration : 500, easing : 'linear', scrollTop: offset + 10 }); }); return target; }); }, activateNavByIndex: function(index) { const target = document.querySelectorAll('.post-toc li a.nav-link')[index]; if (!target || target.classList.contains('active-current')) return; document.querySelectorAll('.post-toc .active').forEach(element => { element.classList.remove('active', 'active-current'); }); target.classList.add('active', 'active-current'); let parent = target.parentNode; while (!parent.matches('.post-toc')) { if (parent.matches('li')) parent.classList.add('active'); parent = parent.parentNode; } // Scrolling to center active TOC element if TOC content is taller then viewport. const tocElement = document.querySelector('.sidebar-panel-container'); window.anime({ targets : tocElement, duration : 200, easing : 'linear', scrollTop: tocElement.scrollTop - (tocElement.offsetHeight / 2) + target.getBoundingClientRect().top - tocElement.getBoundingClientRect().top }); }, /** * Init Sidebar & TOC inner dimensions on all pages and for all schemes. * Need for Sidebar/TOC inner scrolling if content taller then viewport. */ initSidebarDimension: function() { const sidebarNav = document.querySelector('.sidebar-nav'); const sidebarb2t = document.querySelector('.sidebar-inner .back-to-top'); const sidebarNavHeight = sidebarNav ? sidebarNav.offsetHeight : 0; const sidebarb2tHeight = sidebarb2t ? sidebarb2t.offsetHeight : 0; const sidebarOffset = CONFIG.sidebar.offset || 12; let sidebarSchemePadding = (CONFIG.sidebar.padding * 2) + sidebarNavHeight + sidebarb2tHeight; if (CONFIG.scheme === 'Pisces' || CONFIG.scheme === 'Gemini') sidebarSchemePadding += sidebarOffset * 2; // Initialize Sidebar & TOC Height. const sidebarWrapperHeight = document.body.offsetHeight - sidebarSchemePadding + 'px'; document.documentElement.style.setProperty('--sidebar-wrapper-height', sidebarWrapperHeight); }, updateSidebarPosition: function() { NexT.utils.initSidebarDimension(); if (window.innerWidth < 992 || CONFIG.scheme === 'Pisces' || CONFIG.scheme === 'Gemini') return; // Expand sidebar on post detail page by default, when post has a toc. const hasTOC = document.querySelector('.post-toc'); let display = CONFIG.page.sidebar; if (typeof display !== 'boolean') { // There's no definition sidebar in the page front-matter. display = CONFIG.sidebar.display === 'always' || (CONFIG.sidebar.display === 'post' && hasTOC); } if (display) { window.dispatchEvent(new Event('sidebar:show')); } }, getScript: function(url, options = {}, legacyCondition) { if (typeof options === 'function') { return this.getScript(url, { condition: legacyCondition }).then(options); } const { condition = false, attributes: { id = '', async = false, defer = false, crossOrigin = '', dataset = {}, ...otherAttributes } = {}, parentNode = null } = options; return new Promise((resolve, reject) => { if (condition) { resolve(); } else { const script = document.createElement('script'); if (id) script.id = id; if (crossOrigin) script.crossOrigin = crossOrigin; script.async = async; script.defer = defer; Object.assign(script.dataset, dataset); Object.entries(otherAttributes).forEach(([name, value]) => { script.setAttribute(name, String(value)); }); script.onload = resolve; script.onerror = reject; script.src = url; (parentNode || document.head).appendChild(script); } }); }, loadComments: function(selector, legacyCallback) { if (legacyCallback) { return this.loadComments(selector).then(legacyCallback); } return new Promise((resolve) => { const element = document.querySelector(selector); if (!CONFIG.comments.lazyload || !element) { resolve(); return; } const intersectionObserver = new IntersectionObserver((entries, observer) => { const entry = entries[0]; if (!entry.isIntersecting) return; resolve(); observer.disconnect(); }); intersectionObserver.observe(element); }); } };
{'content_hash': 'acee9cf0445fa3d9adb97ff6ff7fff65', 'timestamp': '', 'source': 'github', 'line_count': 402, 'max_line_length': 182, 'avg_line_length': 37.3681592039801, 'alnum_prop': 0.615630408733857, 'repo_name': 'cdnjs/cdnjs', 'id': 'c4b33f87642681211cfef028c9f970c37627c2b2', 'size': '15022', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'ajax/libs/hexo-theme-next/8.4.0/utils.js', 'mode': '33188', 'license': 'mit', 'language': []}
package sand import ( "bytes" "encoding/json" "errors" "fmt" "io/ioutil" "net/http" "time" log "github.com/sirupsen/logrus" ) const ( iso8601 = "2006-01-02T15:04:05.999999999Z07:00" serviceCacheKey = "service-access-token" ) var notAllowedResponse = map[string]interface{}{ "allowed": false, } //Service can be used to verify a token with SAND type Service struct { Client //The default resource name that this Service will check the token against. Resource string //Default context Context map[string]interface{} //The URL of the token verification endpoint, e.g., "https://oauth.example.com/warden/token/allowed" TokenVerifyURL string //The default expiry time for cache for invalid tokens and also valid tokens without expiry times //Default value is 3599 seconds //Only services need this because client tokens will always give expiry time DefaultExpDuration time.Duration //The scopes required for the service to access the token verification endpoint Scopes []string } // VerificationOption affects how tokens are verified type VerificationOption struct { TargetScopes []string Resource string Action string Context map[string]interface{} NumRetry *int SkipCachedToken bool Timeout time.Duration } //NewService returns a Service struct. func NewService(id, secret, tokenURL, resource, verifyURL string, scopes []string) (service *Service, err error) { client, err := NewClient(id, secret, tokenURL) if err != nil || resource == "" || verifyURL == "" { err = errors.New("NewService: missing required argument(s)") return } client.cacheType = "service" service = &Service{ Client: *client, Resource: resource, Context: map[string]interface{}{}, TokenVerifyURL: verifyURL, Scopes: scopes, DefaultExpDuration: defaultExpiryTime, } return } //CheckRequest checks the bearer token of an incoming HTTP request and return response with 'allowed' true/false field. //If the error is of type sand.ConnectionError, the service should respond with //HTTP status code 502. Otherwise the client would perform unnecessary retries. //Example with Gin: // func(c *gin.Context) { // response, err := sandService.CheckRequest(c.Request, []string{"scope1", "scope2"}, "action") // if err != nil || response["allowed"] != true { // c.JSON(sandService.ErrorCode(err), err) //This would set 502 on ConnectionError // } // } func (s *Service) CheckRequest(r *http.Request, targetScopes []string, action string) (map[string]interface{}, error) { return s.CheckRequestWithCustomRetry(r, targetScopes, action, s.DefaultRetryCount) } //CheckRequestWithCustomRetry allows specifying a positive number as number of retries to //use instead of using DefaultRetryCount on a per-request basis. //Using a negative number for numRetry is equivalent to the "Request" function func (s *Service) CheckRequestWithCustomRetry(r *http.Request, targetScopes []string, action string, numRetry int) (map[string]interface{}, error) { return s.VerifyRequest(r, &VerificationOption{TargetScopes: targetScopes, Action: action, NumRetry: &numRetry}) } //VerifyRequest takes the token in a request and verifies with SAND //Remember to set a reasonable NumRetry value (>= 0) for the VerificationOption func (s *Service) VerifyRequest(r *http.Request, opt *VerificationOption) (map[string]interface{}, error) { token := ExtractToken(r.Header.Get("Authorization")) rv, err := s.VerifyTokenWithCache(token, opt) if err != nil { log.Error(err) } return rv, err } //ErrorCode gets the HTTP error code based on the error type. By default it is //401 unauthorized; if the error is connection error, then it returns 502 func (s *Service) ErrorCode(err error) int { if err != nil { //Return 502 on error return http.StatusBadGateway } return http.StatusUnauthorized } //VerifyTokenWithCache tries to get the result for this token from the cache first. //If not found in cache, if will make a token verification request with Sand. func (s *Service) VerifyTokenWithCache(token string, opt *VerificationOption) (map[string]interface{}, error) { s.buildOption(opt) if token == "" || opt.Resource == "" { return notAllowedResponse, nil } var ckey string if theCache != nil { //Calculate cache key for use later ckey = s.cacheKey(token, opt.TargetScopes, opt.Resource) //Read from cache result := theCache.Read(ckey, 0) response, ok := result.(map[string]interface{}) if ok { return response, nil } } resp, err := s.verifyToken(token, opt) if err != nil { switch err.(type) { case ExpiredTokenError: log.Infof("(%s) Service was unauthorized (401) to access Sand's token verification endpoint. Retry once by getting a new service token.", s.ClientID) option := *opt option.SkipCachedToken = true if resp, err = s.verifyToken(token, &option); err != nil { return notAllowedResponse, err } default: return notAllowedResponse, err } } if resp == nil { log.Warnf("(%s) Service getting nil token verification response.", s.ClientID) return notAllowedResponse, err } if theCache != nil { //Write to cache if resp["allowed"] == true { exp := s.DefaultExpDuration if resp["exp"] != nil { expTime, ok := resp["exp"].(string) if ok { exp = s.expirationTime(expTime) } } else { log.Warnf("(%s) Token verification result missing 'exp' field. Use default expiration time.", s.ClientID) } theCache.Write(ckey, resp, exp) } else { theCache.Write(ckey, notAllowedResponse, s.DefaultExpDuration) } } return resp, nil } //verifyToken verifies with SAND to see if the token is allowed to access this service. //When returned error is nil and the map return value is nil or {"allowed":false}, //VerifyTokenWithCache will return notAllowedResponse, so the service will respond //to the client with 401. func (s *Service) verifyToken(token string, opt *VerificationOption) (map[string]interface{}, error) { if token == "" || opt.Resource == "" { return nil, nil } s.buildNumRetry(opt) numRetry := *opt.NumRetry if numRetry < 1 { numRetry = 1 } accessToken, err := s.Token(serviceCacheKey, s.Scopes, &tokenOption{NumRetry: numRetry, Timeout: opt.Timeout}) if err != nil { return nil, err } transport := http.DefaultTransport.(*http.Transport).Clone() transport.TLSClientConfig.MinVersion = s.SSLMinVersion client := &http.Client{ Transport: transport, Timeout: getTimeout(opt.Timeout, s.Timeout), } data := map[string]interface{}{ "scopes": opt.TargetScopes, "token": token, "resource": opt.Resource, "action": opt.Action, "context": opt.Context, } dBytes, err := json.Marshal(data) if err != nil { return nil, fmt.Errorf("(%s) Service failed to marshal json data: %v", s.ClientID, err) } var body []byte for retryCount := 0; retryCount <= *opt.NumRetry; retryCount++ { req, err := http.NewRequest("POST", s.TokenVerifyURL, bytes.NewBuffer(dBytes)) if err != nil { return nil, fmt.Errorf("(%s) Service failed to create token verification request: %v", s.ClientID, err) } req.Header.Add("Authorization", "Bearer "+accessToken) resp, err := client.Do(req) if err != nil { if retryCount < *opt.NumRetry { sleep := ExponentialRetryDuration(retryCount) log.Warnf("(%s) Service failed to verify the token. Retrying in %s. Error: %v", s.ClientID, sleep, err) time.Sleep(sleep) continue } return nil, InternalServerError{SandError{ fmt.Sprintf("(%s) Service failed to verify the token: %v", s.ClientID, err), }} } defer resp.Body.Close() body, _ = ioutil.ReadAll(resp.Body) if resp.StatusCode != http.StatusOK { str := fmt.Sprintf("(%s) Error response from the authentication service: %d - %s", s.ClientID, resp.StatusCode, body) log.Warn(str) switch resp.StatusCode { case http.StatusInternalServerError: //When the response is 500, the client's token may be expired. So let the client retry //and return 401 by returning nil, so that the result is not cached. return nil, nil case http.StatusUnauthorized: return nil, ExpiredTokenError{SandError{ fmt.Sprintf("(%s) Service cannot access the token verification endpoint at this time with the current service token", s.ClientID), }} case http.StatusForbidden: return nil, PermissionDeniedError{SandError{ fmt.Sprintf("(%s) Service is denied access to the token verification endpoint", s.ClientID), }} default: if retryCount < *opt.NumRetry { sleep := ExponentialRetryDuration(retryCount) log.Warnf("(%s) Service failed to verify the token. Retrying in %s. Status code was: %d", s.ClientID, sleep, resp.StatusCode) time.Sleep(sleep) continue } if resp.StatusCode == http.StatusTooManyRequests { return nil, TooManyRequestsError{SandError{ fmt.Sprintf("(%s) Service cannot verify a token due to rate limiting", s.ClientID), }} } return nil, InternalServerError{SandError{fmt.Sprintf("(%s) %s", s.ClientID, str)}} } } } var result map[string]interface{} err = json.Unmarshal(body, &result) return result, err } //Set the defaults for values that are not given. func (s *Service) buildOption(opt *VerificationOption) { if opt.Resource == "" { opt.Resource = s.Resource } if len(opt.Context) == 0 { opt.Context = s.Context } if len(opt.TargetScopes) == 0 { opt.TargetScopes = []string{} } } func (s *Service) buildNumRetry(opt *VerificationOption) { retry := s.DefaultRetryCount if opt.NumRetry != nil { retry = *opt.NumRetry } retry = s.tokenRequestRetryCount(retry) opt.NumRetry = &retry } //expirationTime computes the expiry time given the expiry time as a string //Example time returned by SAND: {"exp":"2021-08-26T05:33:27.107035237Z"} func (s *Service) expirationTime(expTime string) time.Duration { if expTime == "" { log.Warnf("(%s) 'exp' field is empty from the token verification result. Use default expiration time.", s.ClientID) return s.DefaultExpDuration } t, err := time.Parse(iso8601, expTime) if err != nil { log.Warnf("(%s) Error parsing the token expiration time: %s. Use default expiration time: %v", s.ClientID, expTime, err) return s.DefaultExpDuration } return t.Sub(time.Now()) }
{'content_hash': '6168eef137c317dcd8b81a877cffca9d', 'timestamp': '', 'source': 'github', 'line_count': 306, 'max_line_length': 152, 'avg_line_length': 33.8235294117647, 'alnum_prop': 0.703768115942029, 'repo_name': 'coupa/sand-go', 'id': '7e9085d52431a16bc6ee8477f14daffef82621fa', 'size': '10350', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'service.go', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Go', 'bytes': '63396'}]}
package io.selendroid.nativetests; import static org.junit.Assert.assertEquals; import io.selendroid.ScreenBrightness; import io.selendroid.support.BaseAndroidTest; import org.junit.Before; import org.junit.Test; public class BrightnessTest extends BaseAndroidTest { @Before public void openApp() throws Exception { openStartActivity(); } @Test public void shouldBeAbleToGetAndSetBrightness() throws InterruptedException { ScreenBrightness brightness = (ScreenBrightness) driver(); brightness.setBrightness(0); int seen = brightness.getBrightness(); assertEquals(0, seen); brightness.setBrightness(50); seen = brightness.getBrightness(); assertEquals(50, seen); brightness.setBrightness(100); seen = brightness.getBrightness(); assertEquals(100, seen); } }
{'content_hash': 'ef881d018e26c3bc2603de457fe65548', 'timestamp': '', 'source': 'github', 'line_count': 35, 'max_line_length': 79, 'avg_line_length': 23.514285714285716, 'alnum_prop': 0.7484811664641555, 'repo_name': 'DominikDary/selendroid', 'id': 'e253ec0846b2e337fc3f658e780ecbf4de58d537', 'size': '1455', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'selendroid-test-app/test/io/selendroid/nativetests/BrightnessTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '15838'}, {'name': 'Java', 'bytes': '2089824'}, {'name': 'JavaScript', 'bytes': '765202'}, {'name': 'Shell', 'bytes': '2508'}]}
typedef NS_ENUM(unsigned int, RCTSRReadyState) { RCTSR_CONNECTING = 0, RCTSR_OPEN = 1, RCTSR_CLOSING = 2, RCTSR_CLOSED = 3, }; typedef NS_ENUM(NSInteger, RCTSRStatusCode) { RCTSRStatusCodeNormal = 1000, RCTSRStatusCodeGoingAway = 1001, RCTSRStatusCodeProtocolError = 1002, RCTSRStatusCodeUnhandledType = 1003, // 1004 reserved. RCTSRStatusNoStatusReceived = 1005, // 1004-1006 reserved. RCTSRStatusCodeInvalidUTF8 = 1007, RCTSRStatusCodePolicyViolated = 1008, RCTSRStatusCodeMessageTooBig = 1009, }; @class RCTSRWebSocket; extern NSString *const RCTSRWebSocketErrorDomain; extern NSString *const RCTSRHTTPResponseErrorKey; #pragma mark - RCTSRWebSocketDelegate @protocol RCTSRWebSocketDelegate; #pragma mark - RCTSRWebSocket @interface RCTSRWebSocket : NSObject <NSStreamDelegate> @property (nonatomic, weak) id<RCTSRWebSocketDelegate> delegate; @property (nonatomic, readonly) RCTSRReadyState readyState; @property (nonatomic, readonly, strong) NSURL *url; // This returns the negotiated protocol. // It will be nil until after the handshake completes. @property (nonatomic, readonly, copy) NSString *protocol; // Protocols should be an array of strings that turn into Sec-WebSocket-Protocol. - (instancetype)initWithURLRequest:(NSURLRequest *)request protocols:(NSArray<NSString *> *)protocols NS_DESIGNATED_INITIALIZER; - (instancetype)initWithURLRequest:(NSURLRequest *)request; // Some helper constructors. - (instancetype)initWithURL:(NSURL *)url protocols:(NSArray<NSString *> *)protocols; - (instancetype)initWithURL:(NSURL *)url; // Delegate queue will be dispatch_main_queue by default. // You cannot set both OperationQueue and dispatch_queue. - (void)setDelegateOperationQueue:(NSOperationQueue*) queue; - (void)setDelegateDispatchQueue:(dispatch_queue_t) queue; // By default, it will schedule itself on +[NSRunLoop RCTSR_networkRunLoop] using defaultModes. - (void)scheduleInRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode; - (void)unscheduleFromRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode; // RCTSRWebSockets are intended for one-time-use only. Open should be called once and only once. - (void)open; - (void)close; - (void)closeWithCode:(NSInteger)code reason:(NSString *)reason; // Send a UTF8 String or Data. - (void)send:(id)data; // Send Data (can be nil) in a ping message. - (void)sendPing:(NSData *)data; @end #pragma mark - RCTSRWebSocketDelegate @protocol RCTSRWebSocketDelegate <NSObject> // message will either be an NSString if the server is using text // or NSData if the server is using binary. - (void)webSocket:(RCTSRWebSocket *)webSocket didReceiveMessage:(id)message; @optional - (void)webSocketDidOpen:(RCTSRWebSocket *)webSocket; - (void)webSocket:(RCTSRWebSocket *)webSocket didFailWithError:(NSError *)error; - (void)webSocket:(RCTSRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean; - (void)webSocket:(RCTSRWebSocket *)webSocket didReceivePong:(NSData *)pongPayload; @end #pragma mark - NSURLRequest (CertificateAdditions) @interface NSURLRequest (CertificateAdditions) @property (nonatomic, readonly, copy) NSArray *RCTSR_SSLPinnedCertificates; @end #pragma mark - NSMutableURLRequest (CertificateAdditions) @interface NSMutableURLRequest (CertificateAdditions) @property (nonatomic, copy) NSArray *RCTSR_SSLPinnedCertificates; @end #pragma mark - NSRunLoop (RCTSRWebSocket) @interface NSRunLoop (RCTSRWebSocket) + (NSRunLoop *)RCTSR_networkRunLoop; @end
{'content_hash': '6ace6b9b03a68a423c32241f2178cee7', 'timestamp': '', 'source': 'github', 'line_count': 113, 'max_line_length': 129, 'avg_line_length': 31.707964601769913, 'alnum_prop': 0.7683505442366731, 'repo_name': 'adamkrell/react-native', 'id': '0c209c21cebb8e97007dea48d8bc7c17acebb5f3', 'size': '4269', 'binary': False, 'copies': '34', 'ref': 'refs/heads/master', 'path': 'Libraries/WebSocket/RCTSRWebSocket.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Assembly', 'bytes': '15255'}, {'name': 'Awk', 'bytes': '121'}, {'name': 'Batchfile', 'bytes': '301'}, {'name': 'C', 'bytes': '65156'}, {'name': 'C++', 'bytes': '320088'}, {'name': 'CSS', 'bytes': '20807'}, {'name': 'HTML', 'bytes': '28752'}, {'name': 'IDL', 'bytes': '617'}, {'name': 'Java', 'bytes': '1344142'}, {'name': 'JavaScript', 'bytes': '1475664'}, {'name': 'Makefile', 'bytes': '4167'}, {'name': 'Objective-C', 'bytes': '1134279'}, {'name': 'Objective-C++', 'bytes': '8138'}, {'name': 'Prolog', 'bytes': '311'}, {'name': 'Python', 'bytes': '32195'}, {'name': 'Ruby', 'bytes': '4450'}, {'name': 'Shell', 'bytes': '18449'}]}
""" Provide functionality to interact with Cast devices on the network. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/media_player.cast/ """ # pylint: disable=import-error import logging import voluptuous as vol from homeassistant.components.media_player import ( MEDIA_TYPE_MUSIC, MEDIA_TYPE_TVSHOW, MEDIA_TYPE_VIDEO, SUPPORT_NEXT_TRACK, SUPPORT_PAUSE, SUPPORT_PLAY_MEDIA, SUPPORT_PREVIOUS_TRACK, SUPPORT_TURN_OFF, SUPPORT_TURN_ON, SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_SET, SUPPORT_STOP, MediaPlayerDevice, PLATFORM_SCHEMA) from homeassistant.const import ( CONF_HOST, STATE_IDLE, STATE_OFF, STATE_PAUSED, STATE_PLAYING, STATE_UNKNOWN) import homeassistant.helpers.config_validation as cv import homeassistant.util.dt as dt_util REQUIREMENTS = ['pychromecast==0.7.6'] _LOGGER = logging.getLogger(__name__) CONF_IGNORE_CEC = 'ignore_cec' CAST_SPLASH = 'https://home-assistant.io/images/cast/splash.png' DEFAULT_PORT = 8009 SUPPORT_CAST = SUPPORT_PAUSE | SUPPORT_VOLUME_SET | SUPPORT_VOLUME_MUTE | \ SUPPORT_TURN_ON | SUPPORT_TURN_OFF | SUPPORT_PREVIOUS_TRACK | \ SUPPORT_NEXT_TRACK | SUPPORT_PLAY_MEDIA | SUPPORT_STOP KNOWN_HOSTS = [] PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_HOST): cv.string, }) # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): """Setup the cast platform.""" import pychromecast # import CEC IGNORE attributes ignore_cec = config.get(CONF_IGNORE_CEC, []) if isinstance(ignore_cec, list): pychromecast.IGNORE_CEC += ignore_cec else: _LOGGER.error('CEC config "%s" must be a list.', CONF_IGNORE_CEC) hosts = [] if discovery_info and discovery_info in KNOWN_HOSTS: return elif discovery_info: hosts = [discovery_info] elif CONF_HOST in config: hosts = [(config.get(CONF_HOST), DEFAULT_PORT)] else: hosts = [tuple(dev[:2]) for dev in pychromecast.discover_chromecasts() if tuple(dev[:2]) not in KNOWN_HOSTS] casts = [] # get_chromecasts() returns Chromecast objects # with the correct friendly name for grouped devices all_chromecasts = pychromecast.get_chromecasts() for host in hosts: found = [device for device in all_chromecasts if (device.host, device.port) == host] if found: try: casts.append(CastDevice(found[0])) KNOWN_HOSTS.append(host) except pychromecast.ChromecastConnectionError: pass else: try: # add the device anyway, get_chromecasts couldn't find it casts.append(CastDevice(pychromecast.Chromecast(*host))) KNOWN_HOSTS.append(host) except pychromecast.ChromecastConnectionError: pass add_devices(casts) class CastDevice(MediaPlayerDevice): """Representation of a Cast device on the network.""" def __init__(self, chromecast): """Initialize the Cast device.""" self.cast = chromecast self.cast.socket_client.receiver_controller.register_status_listener( self) self.cast.socket_client.media_controller.register_status_listener(self) self.cast_status = self.cast.status self.media_status = self.cast.media_controller.status self.media_status_received = None @property def should_poll(self): """No polling needed.""" return False @property def name(self): """Return the name of the device.""" return self.cast.device.friendly_name # MediaPlayerDevice properties and methods @property def state(self): """Return the state of the player.""" if self.media_status is None: return STATE_UNKNOWN elif self.media_status.player_is_playing: return STATE_PLAYING elif self.media_status.player_is_paused: return STATE_PAUSED elif self.media_status.player_is_idle: return STATE_IDLE elif self.cast.is_idle: return STATE_OFF else: return STATE_UNKNOWN @property def volume_level(self): """Volume level of the media player (0..1).""" return self.cast_status.volume_level if self.cast_status else None @property def is_volume_muted(self): """Boolean if volume is currently muted.""" return self.cast_status.volume_muted if self.cast_status else None @property def media_content_id(self): """Content ID of current playing media.""" return self.media_status.content_id if self.media_status else None @property def media_content_type(self): """Content type of current playing media.""" if self.media_status is None: return None elif self.media_status.media_is_tvshow: return MEDIA_TYPE_TVSHOW elif self.media_status.media_is_movie: return MEDIA_TYPE_VIDEO elif self.media_status.media_is_musictrack: return MEDIA_TYPE_MUSIC return None @property def media_duration(self): """Duration of current playing media in seconds.""" return self.media_status.duration if self.media_status else None @property def media_image_url(self): """Image url of current playing media.""" if self.media_status is None: return None images = self.media_status.images return images[0].url if images else None @property def media_title(self): """Title of current playing media.""" return self.media_status.title if self.media_status else None @property def media_artist(self): """Artist of current playing media (Music track only).""" return self.media_status.artist if self.media_status else None @property def media_album(self): """Album of current playing media (Music track only).""" return self.media_status.album_name if self.media_status else None @property def media_album_artist(self): """Album arist of current playing media (Music track only).""" return self.media_status.album_artist if self.media_status else None @property def media_track(self): """Track number of current playing media (Music track only).""" return self.media_status.track if self.media_status else None @property def media_series_title(self): """The title of the series of current playing media (TV Show only).""" return self.media_status.series_title if self.media_status else None @property def media_season(self): """Season of current playing media (TV Show only).""" return self.media_status.season if self.media_status else None @property def media_episode(self): """Episode of current playing media (TV Show only).""" return self.media_status.episode if self.media_status else None @property def app_id(self): """Return the ID of the current running app.""" return self.cast.app_id @property def app_name(self): """Name of the current running app.""" return self.cast.app_display_name @property def supported_media_commands(self): """Flag of media commands that are supported.""" return SUPPORT_CAST @property def media_position(self): """Position of current playing media in seconds.""" if self.media_status is None or self.media_status_received is None or \ not (self.media_status.player_is_playing or self.media_status.player_is_idle): return None position = self.media_status.current_time if self.media_status.player_is_playing: position += (dt_util.utcnow() - self.media_status_received).total_seconds() return position @property def media_position_updated_at(self): """When was the position of the current playing media valid. Returns value from homeassistant.util.dt.utcnow(). """ return self.media_status_received def turn_on(self): """Turn on the ChromeCast.""" # The only way we can turn the Chromecast is on is by launching an app if not self.cast.status or not self.cast.status.is_active_input: import pychromecast if self.cast.app_id: self.cast.quit_app() self.cast.play_media( CAST_SPLASH, pychromecast.STREAM_TYPE_BUFFERED) def turn_off(self): """Turn Chromecast off.""" self.cast.quit_app() def mute_volume(self, mute): """Mute the volume.""" self.cast.set_volume_muted(mute) def set_volume_level(self, volume): """Set volume level, range 0..1.""" self.cast.set_volume(volume) def media_play(self): """Send play commmand.""" self.cast.media_controller.play() def media_pause(self): """Send pause command.""" self.cast.media_controller.pause() def media_stop(self): """Send stop command.""" self.cast.media_controller.stop() def media_previous_track(self): """Send previous track command.""" self.cast.media_controller.rewind() def media_next_track(self): """Send next track command.""" self.cast.media_controller.skip() def media_seek(self, position): """Seek the media to a specific location.""" self.cast.media_controller.seek(position) def play_media(self, media_type, media_id, **kwargs): """Play media from a URL.""" self.cast.media_controller.play_media(media_id, media_type) # Implementation of chromecast status_listener methods def new_cast_status(self, status): """Called when a new cast status is received.""" self.cast_status = status self.schedule_update_ha_state() def new_media_status(self, status): """Called when a new media status is received.""" self.media_status = status self.media_status_received = dt_util.utcnow() self.schedule_update_ha_state()
{'content_hash': '7aa2e04375ebee0d39f38ea88534a3fd', 'timestamp': '', 'source': 'github', 'line_count': 322, 'max_line_length': 79, 'avg_line_length': 32.161490683229815, 'alnum_prop': 0.6360563924295095, 'repo_name': 'ma314smith/home-assistant', 'id': '7e96e0dbed6c74d0bec70deec84c793c89e310b4', 'size': '10356', 'binary': False, 'copies': '3', 'ref': 'refs/heads/dev', 'path': 'homeassistant/components/media_player/cast.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '1436909'}, {'name': 'Python', 'bytes': '4511947'}, {'name': 'Ruby', 'bytes': '379'}, {'name': 'Shell', 'bytes': '4460'}]}
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>higman-cf: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.5.1 / higman-cf - 8.9.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> higman-cf <small> 8.9.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-10-25 16:48:06 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-10-25 16:48:06 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 2 Virtual package relying on perl coq 8.5.1 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.04.2 The OCaml compiler (virtual package) ocaml-base-compiler 4.04.2 Official 4.04.2 release ocaml-config 1 OCaml Switch Configuration # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;[email protected]&quot; homepage: &quot;https://github.com/coq-contribs/higman-cf&quot; license: &quot;LGPL 2.1&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/HigmanCF&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.9&quot; &amp; &lt; &quot;8.10~&quot;} ] tags: [ &quot;keyword: Higman&#39;s lemma&quot; &quot;keyword: extraction&quot; &quot;category: Mathematics/Combinatorics and Graph Theory&quot; &quot;category: Miscellaneous/Extracted Programs/Combinatorics&quot; ] authors: [ &quot;Stefan Berghofer&quot; ] bug-reports: &quot;https://github.com/coq-contribs/higman-cf/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/higman-cf.git&quot; synopsis: &quot;A direct constructive proof of Higman&#39;s Lemma&quot; description: &quot;&quot;&quot; This development formalizes in Coq the Coquand-Friedlender proof of Higman&#39;s lemma for a two-letter alphabet. An efficient program can be extracted from the proof.&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/higman-cf/archive/v8.9.0.tar.gz&quot; checksum: &quot;md5=1ce02b6135e92838aaf98fc5932274bf&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-higman-cf.8.9.0 coq.8.5.1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.5.1). The following dependencies couldn&#39;t be met: - coq-higman-cf -&gt; coq &gt;= 8.9 -&gt; ocaml &gt;= 4.05.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-higman-cf.8.9.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{'content_hash': 'c0fd2ed50220753b624e9b8f48f47c11', 'timestamp': '', 'source': 'github', 'line_count': 174, 'max_line_length': 159, 'avg_line_length': 40.735632183908045, 'alnum_prop': 0.5457110609480813, 'repo_name': 'coq-bench/coq-bench.github.io', 'id': 'e6849150a7fa8aebf74b90de40ea7420981c4272', 'size': '7113', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'clean/Linux-x86_64-4.04.2-2.0.5/released/8.5.1/higman-cf/8.9.0.html', 'mode': '33188', 'license': 'mit', 'language': []}
FROM postgres:9.4 # create directory in container RUN mkdir -p docker-entrypoint-initdb.d # copy table creation scripts COPY create-voting-db.sql /docker-entrypoint-initdb.d/
{'content_hash': '7a672fcbaaa1c35c846eb62f52a3b17a', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 54, 'avg_line_length': 25.285714285714285, 'alnum_prop': 0.7909604519774012, 'repo_name': 'mwellner/voting', 'id': '193b306844a1c694ccd88d4c2bc933a10ee587d9', 'size': '177', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'db/Dockerfile', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '400'}, {'name': 'HTML', 'bytes': '4009'}, {'name': 'JavaScript', 'bytes': '8727'}, {'name': 'Nginx', 'bytes': '387'}, {'name': 'Python', 'bytes': '2123'}, {'name': 'Shell', 'bytes': '202'}]}
module Azure # Armrest namespace module Armrest # Base class for managing virtual machines class VirtualMachineService < ResourceGroupBasedService # Create and return a new VirtualMachineService instance. Most # methods for a VirtualMachineService instance will return one or more # VirtualMachine instances. # # This subclass accepts the additional :provider option as well. The # default is 'Microsoft.Compute'. You may need to set this to # 'Microsoft.ClassicCompute' for your purposes. # def initialize(configuration, options = {}) super(configuration, 'virtualMachines', 'Microsoft.Compute', options) end # Return a list of virtual machines for the given +location+. # def list_by_location(location, options = {}) url = url_with_api_version(api_version, base_url, 'providers', provider, 'locations', location, service_name) response = rest_get(url) get_all_results(response, options[:skip_accessors_definition]) end # Return a list of available VM series (aka sizes, flavors, etc), such # as "Basic_A1", though other information is included as well. # def series(location) namespace = 'microsoft.compute' version = configuration.provider_default_api_version(namespace, 'locations/vmsizes') unless version raise ArgumentError, "Unable to find resources for #{namespace}" end url = url_with_api_version( version, base_url, 'providers', provider, 'locations', location, 'vmSizes' ) JSON.parse(rest_get(url))['value'].map{ |hash| VirtualMachineSize.new(hash) } end alias sizes series # Captures the +vmname+ and associated disks into a reusable CSM template. # The 3rd argument is a hash of options that supports the following keys: # # * vhdPrefix - The prefix in the name of the blobs. # * destinationContainerName - The name of the container inside which the image will reside. # * overwriteVhds - Boolean that indicates whether or not to overwrite any VHD's # with the same prefix. The default is false. # def capture(vmname, options, group = configuration.resource_group) vm_operate('capture', vmname, group, options) end # Stop the VM +vmname+ in +group+ and deallocate the tenant in Fabric. # def deallocate(vmname, group = configuration.resource_group) vm_operate('deallocate', vmname, group) end # Sets the OSState for the +vmname+ in +group+ to 'Generalized'. # def generalize(vmname, group = configuration.resource_group) vm_operate('generalize', vmname, group) end # Retrieves the settings of the VM named +vmname+ in resource group # +group+, which will default to the same as the name of the VM. # # You can also specify any query options. At this time only the # :expand => 'instanceView' option is supported, but others could # be added over time. # # For backwards compatibility, the third argument may also be a boolean # which will retrieve the model view by default. Set to false if you only # want the instance view. # # Examples: # # vms = VirtualMachineService.new(credentials) # # # Standard call, get just the model view # vms.get('some_name', 'some_group') # vms.get('some_name', 'some_group', true) # same # # # Get the instance view only # vms.get('some_name', 'some_group', false) # # # Get the instance view merged with the model view # vms.get('some_name', 'some_group', :expand => 'instanceView') # def get(vmname, group = configuration.resource_group, options = {}) if options.kind_of?(Hash) url = build_url(group, vmname, options) response = rest_get(url) VirtualMachineInstance.new(response) else options ? super(vmname, group) : get_instance_view(vmname, group) end end # Convenient wrapper around the get method that retrieves the model view # for +vmname+ in resource_group +group+ without the instance view # information. # def get_model_view(vmname, group = configuration.resource_group) get(vmname, group) end # Convenient wrapper around the get method that retrieves only the # instance view for +vmname+ in resource_group +group+. # def get_instance_view(vmname, group = configuration.resource_group) raise ArgumentError, "must specify resource group" unless group raise ArgumentError, "must specify name of the resource" unless vmname url = build_url(group, vmname, 'instanceView') response = rest_get(url) VirtualMachineInstance.new(response) end # Restart the VM +vmname+ for the given +group+, which will default # to the same as the vmname. # # This is an asynchronous operation that returns a response object # which you can inspect, such as response.code or response.headers. # def restart(vmname, group = configuration.resource_group) vm_operate('restart', vmname, group) end # Start the VM +vmname+ for the given +group+, which will default # to the same as the vmname. # # This is an asynchronous operation that returns a response object # which you can inspect, such as response.code or response.headers. # def start(vmname, group = configuration.resource_group) vm_operate('start', vmname, group) end # Stop the VM +vmname+ for the given +group+ gracefully. However, # a forced shutdown will occur after 15 minutes. # # This is an asynchronous operation that returns a response object # which you can inspect, such as response.code or response.headers. # def stop(vmname, group = configuration.resource_group) vm_operate('powerOff', vmname, group) end # Delete the VM and associated resources. By default, this will # delete the VM, its NIC, the associated IP address, and the # image files (.vhd and .status) for the VM. # # If you want to delete other associated resources, such as any # attached disks, the VM's underlying storage account, or associated # network security groups you must explicitly specify them as an option. # # An attempt to delete a resource that cannot be deleted because it's # still associated with some other resource will be logged and skipped. # # If the :verbose option is set to true, then additional messages are # sent to your configuration log, or stdout if no log was specified. # # Note that if all of your related resources are in a self-contained # resource group, you do not necessarily need this method. You could # just delete the resource group itself, which would automatically # delete all of its resources. # def delete_associated_resources(vmname, vmgroup, options = {}) options = { :network_interfaces => true, :ip_addresses => true, :os_disk => true, :data_disks => false, :network_security_groups => false, :storage_account => false, :verbose => false }.merge(options) Azure::Armrest::Configuration.log ||= STDOUT if options[:verbose] vm = get(vmname, vmgroup) delete_and_wait(self, vmname, vmgroup, options) # Must delete network interfaces first if you want to delete # IP addresses or network security groups. if options[:network_interfaces] || options[:ip_addresses] || options[:network_security_groups] delete_associated_nics(vm, options) end if options[:os_disk] || options[:storage_account] delete_associated_disk(vm, options) end if options[:data_disks] delete_associated_data_disks(vm, options) end end def model_class VirtualMachineModel end private # Deletes any NIC's associated with the VM, and optionally any public IP addresses # and network security groups. # def delete_associated_nics(vm, options) nis = Azure::Armrest::Network::NetworkInterfaceService.new(configuration) nics = vm.properties.network_profile.network_interfaces.map(&:id) if options[:ip_addresses] ips = Azure::Armrest::Network::IpAddressService.new(configuration) end if options[:network_security_groups] nsgs = Azure::Armrest::Network::NetworkSecurityGroupService.new(configuration) end nics.each do |nic_id_string| nic = get_by_id(nic_id_string) delete_and_wait(nis, nic.name, nic.resource_group, options) if options[:ip_addresses] nic.properties.ip_configurations.each do |ipconfig| address = ipconfig.properties.try(:public_ip_address) if address ip = get_by_id(address.id) delete_and_wait(ips, ip.name, ip.resource_group, options) end end end if options[:network_security_groups] if nic.properties.respond_to?(:network_security_group) nsg = get_by_id(nic.properties.network_security_group.id) delete_and_wait(nsgs, nsg.name, nsg.resource_group, options) end end end end # This deletes the OS disk from the storage account that's backing the # virtual machine, along with the .status file. This does NOT delete # copies of the disk. # # If the option to delete the entire storage account was selected, then # it will not bother with deleting invidual files from the storage # account first. # def delete_associated_disk(vm, options) if vm.managed_disk? delete_managed_storage(vm, options) else delete_unmanaged_storage(vm, options) end end # This deletes any attached data disks that are associated with the # virtual machine. Note that this should only happen after the VM # has been deleted. # def delete_associated_data_disks(vm, options) sds = Azure::Armrest::Storage::DiskService.new(configuration) data_disks = vm.properties.storage_profile.try(:data_disks) data_disks&.each do |data_disk| disk = sds.get_by_id(data_disk.managed_disk.id) delete_and_wait(sds, disk.name, disk.resource_group, options) end end def delete_managed_storage(vm, options) sds = Azure::Armrest::Storage::DiskService.new(configuration) disk = sds.get_by_id(vm.properties.storage_profile.os_disk.managed_disk.id) delete_and_wait(sds, disk.name, disk.resource_group, options) end def delete_unmanaged_storage(vm, options) sas = Azure::Armrest::StorageAccountService.new(configuration) storage_account = sas.get_from_vm(vm) # Deleting the storage account does not require deleting the disks # first, so skip that if deletion of the storage account was requested. if options[:storage_account] delete_and_wait(sas, storage_account.name, storage_account.resource_group, options) else keys = sas.list_account_keys(storage_account.name, storage_account.resource_group) key = keys['key1'] || keys['key2'] disk = sas.get_os_disk(vm) # There's a short delay between deleting the VM and unlocking the underlying # .vhd file by Azure. Therefore we sleep up to two minutes while checking. if disk.x_ms_lease_status.casecmp('unlocked') != 0 sleep_time = 0 while sleep_time < 120 sleep 10 sleep_time += 10 disk = sas.get_os_disk(vm) break if disk.x_ms_lease_status.casecmp('unlocked') != 0 end # In the unlikely event it did not unlock, just log and skip. if disk.x_ms_lease_status.casecmp('unlocked') != 0 log('warn', "Unable to delete disk #{disk.container}/#{disk.name}") return end end storage_account.delete_blob(disk.container, disk.name, key) log("Deleted blob #{disk.container}/#{disk.name}") if options[:verbose] begin status_file = File.basename(disk.name, '.vhd') + '.status' storage_account.delete_blob(disk.container, status_file, key) rescue Azure::Armrest::NotFoundException # Ignore, does not always exist. else log("Deleted blob #{disk.container}/#{status_file}") if options[:verbose] end end end # Delete a +service+ type resource using its name and resource group, # and wait for the operation to complete before returning. # # If the operation fails because a dependent resource is still attached, # then the error is logged (in verbose mode) and ignored. # def delete_and_wait(service, name, group, options) resource_type = service.class.to_s.sub('Service', '').split('::').last log("Deleting #{resource_type} #{name}/#{group}") if options[:verbose] wait(service.delete(name, group), 0) log("Deleted #{resource_type} #{name}/#{group}") if options[:verbose] rescue Azure::Armrest::BadRequestException, Azure::Armrest::PreconditionFailedException => err if options[:verbose] msg = "Unable to delete #{resource_type} #{name}/#{group}, skipping. Message: #{err.message}" log('warn', msg) end end def vm_operate(action, vmname, group, options = {}) raise ArgumentError, "must specify resource group" unless group raise ArgumentError, "must specify name of the vm" unless vmname url = build_url(group, vmname, action) response = rest_post(url, options.to_json) Azure::Armrest::ResponseHeaders.new(response.headers).tap do |headers| headers.response_code = response.code end end end end end
{'content_hash': '5970e69e177f07237a91188b5b6107ce', 'timestamp': '', 'source': 'github', 'line_count': 368, 'max_line_length': 117, 'avg_line_length': 39.54891304347826, 'alnum_prop': 0.6264257248866291, 'repo_name': 'djberg96/azure-armrest', 'id': '8410e7077de8c1be2fb8dccd122ea95cfbc278c1', 'size': '14572', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'lib/azure/armrest/virtual_machine_service.rb', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Ruby', 'bytes': '348033'}]}
package network import ( "fmt" "net" "strings" "golang.org/x/net/context" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/network" "github.com/docker/docker/cli" "github.com/docker/docker/cli/command" "github.com/docker/docker/opts" runconfigopts "github.com/docker/docker/runconfig/opts" "github.com/spf13/cobra" ) type createOptions struct { name string driver string driverOpts opts.MapOpts labels []string internal bool ipv6 bool attachable bool ipamDriver string ipamSubnet []string ipamIPRange []string ipamGateway []string ipamAux opts.MapOpts ipamOpt opts.MapOpts } func newCreateCommand(dockerCli *command.DockerCli) *cobra.Command { opts := createOptions{ driverOpts: *opts.NewMapOpts(nil, nil), ipamAux: *opts.NewMapOpts(nil, nil), ipamOpt: *opts.NewMapOpts(nil, nil), } cmd := &cobra.Command{ Use: "create [OPTIONS] NETWORK", Short: "Create a network", Args: cli.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.name = args[0] return runCreate(dockerCli, opts) }, } flags := cmd.Flags() flags.StringVarP(&opts.driver, "driver", "d", "bridge", "Driver to manage the Network") flags.VarP(&opts.driverOpts, "opt", "o", "Set driver specific options") flags.StringSliceVar(&opts.labels, "label", []string{}, "Set metadata on a network") flags.BoolVar(&opts.internal, "internal", false, "Restrict external access to the network") flags.BoolVar(&opts.ipv6, "ipv6", false, "Enable IPv6 networking") flags.BoolVar(&opts.attachable, "attachable", false, "Enable manual container attachment") flags.StringVar(&opts.ipamDriver, "ipam-driver", "default", "IP Address Management Driver") flags.StringSliceVar(&opts.ipamSubnet, "subnet", []string{}, "Subnet in CIDR format that represents a network segment") flags.StringSliceVar(&opts.ipamIPRange, "ip-range", []string{}, "Allocate container ip from a sub-range") flags.StringSliceVar(&opts.ipamGateway, "gateway", []string{}, "IPv4 or IPv6 Gateway for the master subnet") flags.Var(&opts.ipamAux, "aux-address", "Auxiliary IPv4 or IPv6 addresses used by Network driver") flags.Var(&opts.ipamOpt, "ipam-opt", "Set IPAM driver specific options") return cmd } func runCreate(dockerCli *command.DockerCli, opts createOptions) error { client := dockerCli.Client() ipamCfg, err := consolidateIpam(opts.ipamSubnet, opts.ipamIPRange, opts.ipamGateway, opts.ipamAux.GetAll()) if err != nil { return err } // Construct network create request body nc := types.NetworkCreate{ Driver: opts.driver, Options: opts.driverOpts.GetAll(), IPAM: &network.IPAM{ Driver: opts.ipamDriver, Config: ipamCfg, Options: opts.ipamOpt.GetAll(), }, CheckDuplicate: true, Internal: opts.internal, EnableIPv6: opts.ipv6, Attachable: opts.attachable, Labels: runconfigopts.ConvertKVStringsToMap(opts.labels), } resp, err := client.NetworkCreate(context.Background(), opts.name, nc) if err != nil { return err } fmt.Fprintf(dockerCli.Out(), "%s\n", resp.ID) return nil } // Consolidates the ipam configuration as a group from different related configurations // user can configure network with multiple non-overlapping subnets and hence it is // possible to correlate the various related parameters and consolidate them. // consoidateIpam consolidates subnets, ip-ranges, gateways and auxiliary addresses into // structured ipam data. func consolidateIpam(subnets, ranges, gateways []string, auxaddrs map[string]string) ([]network.IPAMConfig, error) { if len(subnets) < len(ranges) || len(subnets) < len(gateways) { return nil, fmt.Errorf("every ip-range or gateway must have a corresponding subnet") } iData := map[string]*network.IPAMConfig{} // Populate non-overlapping subnets into consolidation map for _, s := range subnets { for k := range iData { ok1, err := subnetMatches(s, k) if err != nil { return nil, err } ok2, err := subnetMatches(k, s) if err != nil { return nil, err } if ok1 || ok2 { return nil, fmt.Errorf("multiple overlapping subnet configuration is not supported") } } iData[s] = &network.IPAMConfig{Subnet: s, AuxAddress: map[string]string{}} } // Validate and add valid ip ranges for _, r := range ranges { match := false for _, s := range subnets { ok, err := subnetMatches(s, r) if err != nil { return nil, err } if !ok { continue } if iData[s].IPRange != "" { return nil, fmt.Errorf("cannot configure multiple ranges (%s, %s) on the same subnet (%s)", r, iData[s].IPRange, s) } d := iData[s] d.IPRange = r match = true } if !match { return nil, fmt.Errorf("no matching subnet for range %s", r) } } // Validate and add valid gateways for _, g := range gateways { match := false for _, s := range subnets { ok, err := subnetMatches(s, g) if err != nil { return nil, err } if !ok { continue } if iData[s].Gateway != "" { return nil, fmt.Errorf("cannot configure multiple gateways (%s, %s) for the same subnet (%s)", g, iData[s].Gateway, s) } d := iData[s] d.Gateway = g match = true } if !match { return nil, fmt.Errorf("no matching subnet for gateway %s", g) } } // Validate and add aux-addresses for key, aa := range auxaddrs { match := false for _, s := range subnets { ok, err := subnetMatches(s, aa) if err != nil { return nil, err } if !ok { continue } iData[s].AuxAddress[key] = aa match = true } if !match { return nil, fmt.Errorf("no matching subnet for aux-address %s", aa) } } idl := []network.IPAMConfig{} for _, v := range iData { idl = append(idl, *v) } return idl, nil } func subnetMatches(subnet, data string) (bool, error) { var ( ip net.IP ) _, s, err := net.ParseCIDR(subnet) if err != nil { return false, fmt.Errorf("Invalid subnet %s : %v", s, err) } if strings.Contains(data, "/") { ip, _, err = net.ParseCIDR(data) if err != nil { return false, fmt.Errorf("Invalid cidr %s : %v", data, err) } } else { ip = net.ParseIP(data) } return s.Contains(ip), nil }
{'content_hash': 'c549af26e128c50d83d110db875dc16b', 'timestamp': '', 'source': 'github', 'line_count': 225, 'max_line_length': 122, 'avg_line_length': 27.58222222222222, 'alnum_prop': 0.6696745085401224, 'repo_name': 'xiaods/docker', 'id': '2ffd80548b8ad666dcc013874e8a3cf668a1a3ed', 'size': '6206', 'binary': False, 'copies': '11', 'ref': 'refs/heads/master', 'path': 'cli/command/network/create.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '81'}, {'name': 'C', 'bytes': '3809'}, {'name': 'Go', 'bytes': '6003850'}, {'name': 'Makefile', 'bytes': '9751'}, {'name': 'PowerShell', 'bytes': '5978'}, {'name': 'Shell', 'bytes': '400897'}, {'name': 'VimL', 'bytes': '1350'}]}
 CKEDITOR.plugins.setLang( 'codemirror', 'ar', { toolbar: 'المصدر', autoFormat: 'Format Selection', commentSelectedRange: 'Comment Selection', uncommentSelectedRange: 'Uncomment Selection' });
{'content_hash': 'f7f3ac43da2e95551c9ad01168b9958f', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 47, 'avg_line_length': 29.285714285714285, 'alnum_prop': 0.7219512195121951, 'repo_name': 'emencia/emencia_paste_djangocms_3', 'id': 'e6c2de97ebba05c3e855a465656a42c9ff35f212', 'size': '360', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'emencia_paste_djangocms_3/django_buildout/project/mods_available/ckeditor/static/ckeditor/ckeditor/plugins/codemirror/lang/ar.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1288333'}, {'name': 'HTML', 'bytes': '110757'}, {'name': 'JavaScript', 'bytes': '464712'}, {'name': 'Makefile', 'bytes': '1885'}, {'name': 'Python', 'bytes': '123058'}, {'name': 'Ruby', 'bytes': '2904'}]}
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" tools:deviceIds="wear_square"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <LinearLayout android:layout_weight="1" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="0dp"> <Button android:id="@+id/btn1" android:layout_weight="1" android:layout_width="0dp" android:layout_height="match_parent" android:background="@drawable/play_btn" android:layout_margin="2dp" /> <Button android:id="@+id/btn2" android:layout_weight="1" android:layout_width="0dp" android:layout_height="match_parent" android:background="@drawable/play_btn" android:layout_margin="2dp" /> <Button android:id="@+id/btn3" android:layout_weight="1" android:layout_width="0dp" android:layout_height="match_parent" android:background="@drawable/play_btn" android:layout_margin="2dp" /> </LinearLayout> <LinearLayout android:layout_weight="1" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="0dp"> <Button android:id="@+id/btn4" android:layout_weight="1" android:layout_width="0dp" android:layout_height="match_parent" android:background="@drawable/play_btn" android:layout_margin="2dp" /> <Button android:id="@+id/btn5" android:layout_weight="1" android:layout_width="0dp" android:layout_height="match_parent" android:background="@drawable/play_btn" android:layout_margin="2dp" /> <Button android:id="@+id/btn6" android:layout_weight="1" android:layout_width="0dp" android:layout_height="match_parent" android:background="@drawable/play_btn" android:layout_margin="2dp" /> </LinearLayout> <LinearLayout android:layout_weight="1" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="0dp"> <Button android:id="@+id/btn7" android:layout_weight="1" android:layout_width="0dp" android:layout_height="match_parent" android:background="@drawable/play_btn" android:layout_margin="2dp" /> <Button android:id="@+id/btn8" android:layout_weight="1" android:layout_width="0dp" android:layout_height="match_parent" android:background="@drawable/play_btn" android:layout_margin="2dp" /> <Button android:id="@+id/btn9" android:layout_weight="1" android:layout_width="0dp" android:layout_height="match_parent" android:background="@drawable/play_btn" android:layout_margin="2dp" /> </LinearLayout> </LinearLayout> <include layout="@layout/include_count"/> </RelativeLayout>
{'content_hash': 'b8cfbd9e5a25326ab99c34da11f02dce', 'timestamp': '', 'source': 'github', 'line_count': 111, 'max_line_length': 62, 'avg_line_length': 36.52252252252252, 'alnum_prop': 0.5091267883571781, 'repo_name': 'gotokatsuya/TouchLight', 'id': 'daab4934e1b8492f9197df140b818a5046cc9d02', 'size': '4054', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/src/main/res/layout/rect_activity_main.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Groovy', 'bytes': '1380'}, {'name': 'Java', 'bytes': '7242'}]}
 #include <aws/pinpoint/model/ActivitiesResponse.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace Pinpoint { namespace Model { ActivitiesResponse::ActivitiesResponse() : m_itemHasBeenSet(false) { } ActivitiesResponse::ActivitiesResponse(const JsonValue& jsonValue) : m_itemHasBeenSet(false) { *this = jsonValue; } ActivitiesResponse& ActivitiesResponse::operator =(const JsonValue& jsonValue) { if(jsonValue.ValueExists("Item")) { Array<JsonValue> itemJsonList = jsonValue.GetArray("Item"); for(unsigned itemIndex = 0; itemIndex < itemJsonList.GetLength(); ++itemIndex) { m_item.push_back(itemJsonList[itemIndex].AsObject()); } m_itemHasBeenSet = true; } return *this; } JsonValue ActivitiesResponse::Jsonize() const { JsonValue payload; if(m_itemHasBeenSet) { Array<JsonValue> itemJsonList(m_item.size()); for(unsigned itemIndex = 0; itemIndex < itemJsonList.GetLength(); ++itemIndex) { itemJsonList[itemIndex].AsObject(m_item[itemIndex].Jsonize()); } payload.WithArray("Item", std::move(itemJsonList)); } return payload; } } // namespace Model } // namespace Pinpoint } // namespace Aws
{'content_hash': '12a2055504475fec00f3370b593987f1', 'timestamp': '', 'source': 'github', 'line_count': 64, 'max_line_length': 82, 'avg_line_length': 20.109375, 'alnum_prop': 0.7117327117327117, 'repo_name': 'svagionitis/aws-sdk-cpp', 'id': 'cd58419a460cd6b8f73e0fb8a5d172c9fcff983e', 'size': '1860', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'aws-cpp-sdk-pinpoint/source/model/ActivitiesResponse.cpp', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '2313'}, {'name': 'C++', 'bytes': '104799778'}, {'name': 'CMake', 'bytes': '455533'}, {'name': 'HTML', 'bytes': '4471'}, {'name': 'Java', 'bytes': '243075'}, {'name': 'Python', 'bytes': '72896'}, {'name': 'Shell', 'bytes': '2803'}]}
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.o3dr.android.dp.wear"> <uses-permission android:name="android.permission.BLUETOOTH"/> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/> <application android:allowBackup="true" android:label="@string/app_name" android:icon="@drawable/ic_launcher" android:theme="@style/AppTheme"> <activity android:name=".activities.PreferencesActivity" android:launchMode="singleTop"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <receiver android:name=".receivers.GCSEventsReceiver" android:exported="true"> <intent-filter> <action android:name="com.o3dr.services.android.lib.gcs.event.action.VEHICLE_CONNECTION" /> <action android:name="com.o3dr.services.android.lib.gcs.event.action.VEHICLE_DISCONNECTION" /> </intent-filter> </receiver> <service android:name=".services.DroneService" /> <service android:name=".services.WearListenerService"> <intent-filter> <action android:name="com.google.android.gms.wearable.BIND_LISTENER" /> </intent-filter> </service> </application> </manifest>
{'content_hash': 'e306beb603d0b21e2235302067a92618', 'timestamp': '', 'source': 'github', 'line_count': 38, 'max_line_length': 110, 'avg_line_length': 40.18421052631579, 'alnum_prop': 0.6077275703994761, 'repo_name': 'ne0fhyk/DP-Wear', 'id': '6bf5f761ee31c60b47f07eb1ff0c3b73c5648447', 'size': '1527', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'mobile/src/main/AndroidManifest.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '164644'}]}
<?xml version="1.0" encoding="UTF-8"?> <!-- Copyright 2013 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources> <string name="app_name">BasicAndroidKeyStore</string> <string name="intro_message"> <![CDATA[ Welcome to the <b>Basic Android Key Store</b> sample!\n\n This sample demonstrates how to use the Android Key Store to safely create and store encryption keys that only your application can access. You can also sign data using those keys.\n\n To create a new KeyPair, click \"Create\".\n\n To sign some data using a KeyPair, click \"Sign\".\n\n To verify the data using the signature provided, click \"Verify\".\n\n ]]> </string> </resources>
{'content_hash': '2a92cf327e3c7a65fae97049d1b3c2ee', 'timestamp': '', 'source': 'github', 'line_count': 36, 'max_line_length': 100, 'avg_line_length': 37.94444444444444, 'alnum_prop': 0.650805270863836, 'repo_name': 'efortuna/AndroidSDKClone', 'id': '0699a4aee73b9b01074c499a5f2731bd13df0d41', 'size': '1366', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'sdk/samples/android-20/security/BasicAndroidKeyStore/BasicAndroidKeyStoreSample/src/main/res/values/base-strings.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'AppleScript', 'bytes': '0'}, {'name': 'Assembly', 'bytes': '79928'}, {'name': 'Awk', 'bytes': '101642'}, {'name': 'C', 'bytes': '110780727'}, {'name': 'C++', 'bytes': '62609188'}, {'name': 'CSS', 'bytes': '318944'}, {'name': 'Component Pascal', 'bytes': '220'}, {'name': 'Emacs Lisp', 'bytes': '4737'}, {'name': 'Groovy', 'bytes': '82931'}, {'name': 'IDL', 'bytes': '31867'}, {'name': 'Java', 'bytes': '102919416'}, {'name': 'JavaScript', 'bytes': '44616'}, {'name': 'Objective-C', 'bytes': '196166'}, {'name': 'Perl', 'bytes': '45617403'}, {'name': 'Prolog', 'bytes': '1828886'}, {'name': 'Python', 'bytes': '34997242'}, {'name': 'Rust', 'bytes': '17781'}, {'name': 'Shell', 'bytes': '1585527'}, {'name': 'Visual Basic', 'bytes': '962'}, {'name': 'XC', 'bytes': '802542'}]}
// Copyright 2005, 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. // Low-level types and utilities for porting Google Test to various // platforms. All macros ending with _ and symbols defined in an // internal namespace are subject to change without notice. Code // outside Google Test MUST NOT USE THEM DIRECTLY. Macros that don't // end with _ are part of Google Test's public API and can be used by // code outside Google Test. // // This file is fundamental to Google Test. All other Google Test source // files are expected to #include this. Therefore, it cannot #include // any other Google Test header. // IWYU pragma: private, include "gtest/gtest.h" // IWYU pragma: friend gtest/.* // IWYU pragma: friend gmock/.* #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_ #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_ // Environment-describing macros // ----------------------------- // // Google Test can be used in many different environments. Macros in // this section tell Google Test what kind of environment it is being // used in, such that Google Test can provide environment-specific // features and implementations. // // Google Test tries to automatically detect the properties of its // environment, so users usually don't need to worry about these // macros. However, the automatic detection is not perfect. // Sometimes it's necessary for a user to define some of the following // macros in the build script to override Google Test's decisions. // // If the user doesn't define a macro in the list, Google Test will // provide a default definition. After this header is #included, all // macros in this list will be defined to either 1 or 0. // // Notes to maintainers: // - Each macro here is a user-tweakable knob; do not grow the list // lightly. // - Use #if to key off these macros. Don't use #ifdef or "#if // defined(...)", which will not work as these macros are ALWAYS // defined. // // GTEST_HAS_CLONE - Define it to 1/0 to indicate that clone(2) // is/isn't available. // GTEST_HAS_EXCEPTIONS - Define it to 1/0 to indicate that exceptions // are enabled. // GTEST_HAS_POSIX_RE - Define it to 1/0 to indicate that POSIX regular // expressions are/aren't available. // GTEST_HAS_PTHREAD - Define it to 1/0 to indicate that <pthread.h> // is/isn't available. // GTEST_HAS_RTTI - Define it to 1/0 to indicate that RTTI is/isn't // enabled. // GTEST_HAS_STD_WSTRING - Define it to 1/0 to indicate that // std::wstring does/doesn't work (Google Test can // be used where std::wstring is unavailable). // GTEST_HAS_SEH - Define it to 1/0 to indicate whether the // compiler supports Microsoft's "Structured // Exception Handling". // GTEST_HAS_STREAM_REDIRECTION // - Define it to 1/0 to indicate whether the // platform supports I/O stream redirection using // dup() and dup2(). // GTEST_LINKED_AS_SHARED_LIBRARY // - Define to 1 when compiling tests that use // Google Test as a shared library (known as // DLL on Windows). // GTEST_CREATE_SHARED_LIBRARY // - Define to 1 when compiling Google Test itself // as a shared library. // GTEST_DEFAULT_DEATH_TEST_STYLE // - The default value of --gtest_death_test_style. // The legacy default has been "fast" in the open // source version since 2008. The recommended value // is "threadsafe", and can be set in // custom/gtest-port.h. // Platform-indicating macros // -------------------------- // // Macros indicating the platform on which Google Test is being used // (a macro is defined to 1 if compiled on the given platform; // otherwise UNDEFINED -- it's never defined to 0.). Google Test // defines these macros automatically. Code outside Google Test MUST // NOT define them. // // GTEST_OS_AIX - IBM AIX // GTEST_OS_CYGWIN - Cygwin // GTEST_OS_DRAGONFLY - DragonFlyBSD // GTEST_OS_FREEBSD - FreeBSD // GTEST_OS_FUCHSIA - Fuchsia // GTEST_OS_GNU_HURD - GNU/Hurd // GTEST_OS_GNU_KFREEBSD - GNU/kFreeBSD // GTEST_OS_HAIKU - Haiku // GTEST_OS_HPUX - HP-UX // GTEST_OS_LINUX - Linux // GTEST_OS_LINUX_ANDROID - Google Android // GTEST_OS_MAC - Mac OS X // GTEST_OS_IOS - iOS // GTEST_OS_NACL - Google Native Client (NaCl) // GTEST_OS_NETBSD - NetBSD // GTEST_OS_OPENBSD - OpenBSD // GTEST_OS_OS2 - OS/2 // GTEST_OS_QNX - QNX // GTEST_OS_SOLARIS - Sun Solaris // GTEST_OS_WINDOWS - Windows (Desktop, MinGW, or Mobile) // GTEST_OS_WINDOWS_DESKTOP - Windows Desktop // GTEST_OS_WINDOWS_MINGW - MinGW // GTEST_OS_WINDOWS_MOBILE - Windows Mobile // GTEST_OS_WINDOWS_PHONE - Windows Phone // GTEST_OS_WINDOWS_RT - Windows Store App/WinRT // GTEST_OS_ZOS - z/OS // // Among the platforms, Cygwin, Linux, Mac OS X, and Windows have the // most stable support. Since core members of the Google Test project // don't have access to other platforms, support for them may be less // stable. If you notice any problems on your platform, please notify // [email protected] (patches for fixing them are // even more welcome!). // // It is possible that none of the GTEST_OS_* macros are defined. // Feature-indicating macros // ------------------------- // // Macros indicating which Google Test features are available (a macro // is defined to 1 if the corresponding feature is supported; // otherwise UNDEFINED -- it's never defined to 0.). Google Test // defines these macros automatically. Code outside Google Test MUST // NOT define them. // // These macros are public so that portable tests can be written. // Such tests typically surround code using a feature with an #if // which controls that code. For example: // // #if GTEST_HAS_DEATH_TEST // EXPECT_DEATH(DoSomethingDeadly()); // #endif // // GTEST_HAS_DEATH_TEST - death tests // GTEST_HAS_TYPED_TEST - typed tests // GTEST_HAS_TYPED_TEST_P - type-parameterized tests // GTEST_IS_THREADSAFE - Google Test is thread-safe. // GTEST_USES_RE2 - the RE2 regular expression library is used // GTEST_USES_POSIX_RE - enhanced POSIX regex is used. Do not confuse with // GTEST_HAS_POSIX_RE (see above) which users can // define themselves. // GTEST_USES_SIMPLE_RE - our own simple regex is used; // the above RE\b(s) are mutually exclusive. // Misc public macros // ------------------ // // GTEST_FLAG(flag_name) - references the variable corresponding to // the given Google Test flag. // Internal utilities // ------------------ // // The following macros and utilities are for Google Test's INTERNAL // use only. Code outside Google Test MUST NOT USE THEM DIRECTLY. // // Macros for basic C++ coding: // GTEST_AMBIGUOUS_ELSE_BLOCKER_ - for disabling a gcc warning. // GTEST_ATTRIBUTE_UNUSED_ - declares that a class' instances or a // variable don't have to be used. // GTEST_MUST_USE_RESULT_ - declares that a function's result must be used. // GTEST_INTENTIONAL_CONST_COND_PUSH_ - start code section where MSVC C4127 is // suppressed (constant conditional). // GTEST_INTENTIONAL_CONST_COND_POP_ - finish code section where MSVC C4127 // is suppressed. // GTEST_INTERNAL_HAS_ANY - for enabling UniversalPrinter<std::any> or // UniversalPrinter<absl::any> specializations. // GTEST_INTERNAL_HAS_OPTIONAL - for enabling UniversalPrinter<std::optional> // or // UniversalPrinter<absl::optional> // specializations. // GTEST_INTERNAL_HAS_STRING_VIEW - for enabling Matcher<std::string_view> or // Matcher<absl::string_view> // specializations. // GTEST_INTERNAL_HAS_VARIANT - for enabling UniversalPrinter<std::variant> or // UniversalPrinter<absl::variant> // specializations. // // Synchronization: // Mutex, MutexLock, ThreadLocal, GetThreadCount() // - synchronization primitives. // // Regular expressions: // RE - a simple regular expression class using // 1) the RE2 syntax on all platforms when built with RE2 // and Abseil as dependencies // 2) the POSIX Extended Regular Expression syntax on // UNIX-like platforms, // 3) A reduced regular exception syntax on other platforms, // including Windows. // Logging: // GTEST_LOG_() - logs messages at the specified severity level. // LogToStderr() - directs all log messages to stderr. // FlushInfoLog() - flushes informational log messages. // // Stdout and stderr capturing: // CaptureStdout() - starts capturing stdout. // GetCapturedStdout() - stops capturing stdout and returns the captured // string. // CaptureStderr() - starts capturing stderr. // GetCapturedStderr() - stops capturing stderr and returns the captured // string. // // Integer types: // TypeWithSize - maps an integer to a int type. // TimeInMillis - integers of known sizes. // BiggestInt - the biggest signed integer type. // // Command-line utilities: // GetInjectableArgvs() - returns the command line as a vector of strings. // // Environment variable utilities: // GetEnv() - gets the value of an environment variable. // BoolFromGTestEnv() - parses a bool environment variable. // Int32FromGTestEnv() - parses an int32_t environment variable. // StringFromGTestEnv() - parses a string environment variable. // // Deprecation warnings: // GTEST_INTERNAL_DEPRECATED(message) - attribute marking a function as // deprecated; calling a marked function // should generate a compiler warning #include <ctype.h> // for isspace, etc #include <stddef.h> // for ptrdiff_t #include <stdio.h> #include <stdlib.h> #include <string.h> #include <cerrno> // #include <condition_variable> // Guarded by GTEST_IS_THREADSAFE below #include <cstdint> #include <iostream> #include <limits> #include <locale> #include <memory> #include <string> // #include <mutex> // Guarded by GTEST_IS_THREADSAFE below #include <tuple> #include <type_traits> #include <vector> #ifndef _WIN32_WCE #include <sys/stat.h> #include <sys/types.h> #endif // !_WIN32_WCE #if defined __APPLE__ #include <AvailabilityMacros.h> #include <TargetConditionals.h> #endif #include "gtest/internal/custom/gtest-port.h" #include "gtest/internal/gtest-port-arch.h" #if GTEST_HAS_ABSL #include "absl/flags/declare.h" #include "absl/flags/flag.h" #include "absl/flags/reflection.h" #endif #if !defined(GTEST_DEV_EMAIL_) #define GTEST_DEV_EMAIL_ "googletestframework@@googlegroups.com" #define GTEST_FLAG_PREFIX_ "gtest_" #define GTEST_FLAG_PREFIX_DASH_ "gtest-" #define GTEST_FLAG_PREFIX_UPPER_ "GTEST_" #define GTEST_NAME_ "Google Test" #define GTEST_PROJECT_URL_ "https://github.com/google/googletest/" #endif // !defined(GTEST_DEV_EMAIL_) #if !defined(GTEST_INIT_GOOGLE_TEST_NAME_) #define GTEST_INIT_GOOGLE_TEST_NAME_ "testing::InitGoogleTest" #endif // !defined(GTEST_INIT_GOOGLE_TEST_NAME_) // Determines the version of gcc that is used to compile this. #ifdef __GNUC__ // 40302 means version 4.3.2. #define GTEST_GCC_VER_ \ (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) #endif // __GNUC__ // Macros for disabling Microsoft Visual C++ warnings. // // GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 4385) // /* code that triggers warnings C4800 and C4385 */ // GTEST_DISABLE_MSC_WARNINGS_POP_() #if defined(_MSC_VER) #define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings) \ __pragma(warning(push)) __pragma(warning(disable : warnings)) #define GTEST_DISABLE_MSC_WARNINGS_POP_() __pragma(warning(pop)) #else // Not all compilers are MSVC #define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings) #define GTEST_DISABLE_MSC_WARNINGS_POP_() #endif // Clang on Windows does not understand MSVC's pragma warning. // We need clang-specific way to disable function deprecation warning. #ifdef __clang__ #define GTEST_DISABLE_MSC_DEPRECATED_PUSH_() \ _Pragma("clang diagnostic push") \ _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"") \ _Pragma("clang diagnostic ignored \"-Wdeprecated-implementations\"") #define GTEST_DISABLE_MSC_DEPRECATED_POP_() _Pragma("clang diagnostic pop") #else #define GTEST_DISABLE_MSC_DEPRECATED_PUSH_() \ GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996) #define GTEST_DISABLE_MSC_DEPRECATED_POP_() GTEST_DISABLE_MSC_WARNINGS_POP_() #endif // Brings in definitions for functions used in the testing::internal::posix // namespace (read, write, close, chdir, isatty, stat). We do not currently // use them on Windows Mobile. #if GTEST_OS_WINDOWS #if !GTEST_OS_WINDOWS_MOBILE #include <direct.h> #include <io.h> #endif // In order to avoid having to include <windows.h>, use forward declaration #if GTEST_OS_WINDOWS_MINGW && !defined(__MINGW64_VERSION_MAJOR) // MinGW defined _CRITICAL_SECTION and _RTL_CRITICAL_SECTION as two // separate (equivalent) structs, instead of using typedef typedef struct _CRITICAL_SECTION GTEST_CRITICAL_SECTION; #else // Assume CRITICAL_SECTION is a typedef of _RTL_CRITICAL_SECTION. // This assumption is verified by // WindowsTypesTest.CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION. typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; #endif #elif GTEST_OS_XTENSA #include <unistd.h> // Xtensa toolchains define strcasecmp in the string.h header instead of // strings.h. string.h is already included. #else // This assumes that non-Windows OSes provide unistd.h. For OSes where this // is not the case, we need to include headers that provide the functions // mentioned above. #include <strings.h> #include <unistd.h> #endif // GTEST_OS_WINDOWS #if GTEST_OS_LINUX_ANDROID // Used to define __ANDROID_API__ matching the target NDK API level. #include <android/api-level.h> // NOLINT #endif // Defines this to true if and only if Google Test can use POSIX regular // expressions. #ifndef GTEST_HAS_POSIX_RE #if GTEST_OS_LINUX_ANDROID // On Android, <regex.h> is only available starting with Gingerbread. #define GTEST_HAS_POSIX_RE (__ANDROID_API__ >= 9) #else #define GTEST_HAS_POSIX_RE (!GTEST_OS_WINDOWS && !GTEST_OS_XTENSA) #endif #endif // Select the regular expression implementation. #if GTEST_HAS_ABSL // When using Abseil, RE2 is required. #include "absl/strings/string_view.h" #include "re2/re2.h" #define GTEST_USES_RE2 1 #elif GTEST_HAS_POSIX_RE #include <regex.h> // NOLINT #define GTEST_USES_POSIX_RE 1 #else // Use our own simple regex implementation. #define GTEST_USES_SIMPLE_RE 1 #endif #ifndef GTEST_HAS_EXCEPTIONS // The user didn't tell us whether exceptions are enabled, so we need // to figure it out. #if defined(_MSC_VER) && defined(_CPPUNWIND) // MSVC defines _CPPUNWIND to 1 if and only if exceptions are enabled. #define GTEST_HAS_EXCEPTIONS 1 #elif defined(__BORLANDC__) // C++Builder's implementation of the STL uses the _HAS_EXCEPTIONS // macro to enable exceptions, so we'll do the same. // Assumes that exceptions are enabled by default. #ifndef _HAS_EXCEPTIONS #define _HAS_EXCEPTIONS 1 #endif // _HAS_EXCEPTIONS #define GTEST_HAS_EXCEPTIONS _HAS_EXCEPTIONS #elif defined(__clang__) // clang defines __EXCEPTIONS if and only if exceptions are enabled before clang // 220714, but if and only if cleanups are enabled after that. In Obj-C++ files, // there can be cleanups for ObjC exceptions which also need cleanups, even if // C++ exceptions are disabled. clang has __has_feature(cxx_exceptions) which // checks for C++ exceptions starting at clang r206352, but which checked for // cleanups prior to that. To reliably check for C++ exception availability with // clang, check for // __EXCEPTIONS && __has_feature(cxx_exceptions). #define GTEST_HAS_EXCEPTIONS (__EXCEPTIONS && __has_feature(cxx_exceptions)) #elif defined(__GNUC__) && __EXCEPTIONS // gcc defines __EXCEPTIONS to 1 if and only if exceptions are enabled. #define GTEST_HAS_EXCEPTIONS 1 #elif defined(__SUNPRO_CC) // Sun Pro CC supports exceptions. However, there is no compile-time way of // detecting whether they are enabled or not. Therefore, we assume that // they are enabled unless the user tells us otherwise. #define GTEST_HAS_EXCEPTIONS 1 #elif defined(__IBMCPP__) && __EXCEPTIONS // xlC defines __EXCEPTIONS to 1 if and only if exceptions are enabled. #define GTEST_HAS_EXCEPTIONS 1 #elif defined(__HP_aCC) // Exception handling is in effect by default in HP aCC compiler. It has to // be turned of by +noeh compiler option if desired. #define GTEST_HAS_EXCEPTIONS 1 #else // For other compilers, we assume exceptions are disabled to be // conservative. #define GTEST_HAS_EXCEPTIONS 0 #endif // defined(_MSC_VER) || defined(__BORLANDC__) #endif // GTEST_HAS_EXCEPTIONS #ifndef GTEST_HAS_STD_WSTRING // The user didn't tell us whether ::std::wstring is available, so we need // to figure it out. // Cygwin 1.7 and below doesn't support ::std::wstring. // Solaris' libc++ doesn't support it either. Android has // no support for it at least as recent as Froyo (2.2). #define GTEST_HAS_STD_WSTRING \ (!(GTEST_OS_LINUX_ANDROID || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \ GTEST_OS_HAIKU || GTEST_OS_ESP32 || GTEST_OS_ESP8266 || GTEST_OS_XTENSA)) #endif // GTEST_HAS_STD_WSTRING // Determines whether RTTI is available. #ifndef GTEST_HAS_RTTI // The user didn't tell us whether RTTI is enabled, so we need to // figure it out. #ifdef _MSC_VER #ifdef _CPPRTTI // MSVC defines this macro if and only if RTTI is enabled. #define GTEST_HAS_RTTI 1 #else #define GTEST_HAS_RTTI 0 #endif // Starting with version 4.3.2, gcc defines __GXX_RTTI if and only if RTTI is // enabled. #elif defined(__GNUC__) #ifdef __GXX_RTTI // When building against STLport with the Android NDK and with // -frtti -fno-exceptions, the build fails at link time with undefined // references to __cxa_bad_typeid. Note sure if STL or toolchain bug, // so disable RTTI when detected. #if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR) && !defined(__EXCEPTIONS) #define GTEST_HAS_RTTI 0 #else #define GTEST_HAS_RTTI 1 #endif // GTEST_OS_LINUX_ANDROID && __STLPORT_MAJOR && !__EXCEPTIONS #else #define GTEST_HAS_RTTI 0 #endif // __GXX_RTTI // Clang defines __GXX_RTTI starting with version 3.0, but its manual recommends // using has_feature instead. has_feature(cxx_rtti) is supported since 2.7, the // first version with C++ support. #elif defined(__clang__) #define GTEST_HAS_RTTI __has_feature(cxx_rtti) // Starting with version 9.0 IBM Visual Age defines __RTTI_ALL__ to 1 if // both the typeid and dynamic_cast features are present. #elif defined(__IBMCPP__) && (__IBMCPP__ >= 900) #ifdef __RTTI_ALL__ #define GTEST_HAS_RTTI 1 #else #define GTEST_HAS_RTTI 0 #endif #else // For all other compilers, we assume RTTI is enabled. #define GTEST_HAS_RTTI 1 #endif // _MSC_VER #endif // GTEST_HAS_RTTI // It's this header's responsibility to #include <typeinfo> when RTTI // is enabled. #if GTEST_HAS_RTTI #include <typeinfo> #endif // Determines whether Google Test can use the pthreads library. #ifndef GTEST_HAS_PTHREAD // The user didn't tell us explicitly, so we make reasonable assumptions about // which platforms have pthreads support. // // To disable threading support in Google Test, add -DGTEST_HAS_PTHREAD=0 // to your compiler flags. #define GTEST_HAS_PTHREAD \ (GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_HPUX || GTEST_OS_QNX || \ GTEST_OS_FREEBSD || GTEST_OS_NACL || GTEST_OS_NETBSD || GTEST_OS_FUCHSIA || \ GTEST_OS_DRAGONFLY || GTEST_OS_GNU_KFREEBSD || GTEST_OS_OPENBSD || \ GTEST_OS_HAIKU || GTEST_OS_GNU_HURD) #endif // GTEST_HAS_PTHREAD #if GTEST_HAS_PTHREAD // gtest-port.h guarantees to #include <pthread.h> when GTEST_HAS_PTHREAD is // true. #include <pthread.h> // NOLINT // For timespec and nanosleep, used below. #include <time.h> // NOLINT #endif // Determines whether clone(2) is supported. // Usually it will only be available on Linux, excluding // Linux on the Itanium architecture. // Also see http://linux.die.net/man/2/clone. #ifndef GTEST_HAS_CLONE // The user didn't tell us, so we need to figure it out. #if GTEST_OS_LINUX && !defined(__ia64__) #if GTEST_OS_LINUX_ANDROID // On Android, clone() became available at different API levels for each 32-bit // architecture. #if defined(__LP64__) || (defined(__arm__) && __ANDROID_API__ >= 9) || \ (defined(__mips__) && __ANDROID_API__ >= 12) || \ (defined(__i386__) && __ANDROID_API__ >= 17) #define GTEST_HAS_CLONE 1 #else #define GTEST_HAS_CLONE 0 #endif #else #define GTEST_HAS_CLONE 1 #endif #else #define GTEST_HAS_CLONE 0 #endif // GTEST_OS_LINUX && !defined(__ia64__) #endif // GTEST_HAS_CLONE // Determines whether to support stream redirection. This is used to test // output correctness and to implement death tests. #ifndef GTEST_HAS_STREAM_REDIRECTION // By default, we assume that stream redirection is supported on all // platforms except known mobile ones. #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \ GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266 || GTEST_OS_XTENSA #define GTEST_HAS_STREAM_REDIRECTION 0 #else #define GTEST_HAS_STREAM_REDIRECTION 1 #endif // !GTEST_OS_WINDOWS_MOBILE #endif // GTEST_HAS_STREAM_REDIRECTION // Determines whether to support death tests. // pops up a dialog window that cannot be suppressed programmatically. #if (GTEST_OS_LINUX || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \ (GTEST_OS_MAC && !GTEST_OS_IOS) || \ (GTEST_OS_WINDOWS_DESKTOP && _MSC_VER) || GTEST_OS_WINDOWS_MINGW || \ GTEST_OS_AIX || GTEST_OS_HPUX || GTEST_OS_OPENBSD || GTEST_OS_QNX || \ GTEST_OS_FREEBSD || GTEST_OS_NETBSD || GTEST_OS_FUCHSIA || \ GTEST_OS_DRAGONFLY || GTEST_OS_GNU_KFREEBSD || GTEST_OS_HAIKU || \ GTEST_OS_GNU_HURD) #define GTEST_HAS_DEATH_TEST 1 #endif // Determines whether to support type-driven tests. // Typed tests need <typeinfo> and variadic macros, which GCC, VC++ 8.0, // Sun Pro CC, IBM Visual Age, and HP aCC support. #if defined(__GNUC__) || defined(_MSC_VER) || defined(__SUNPRO_CC) || \ defined(__IBMCPP__) || defined(__HP_aCC) #define GTEST_HAS_TYPED_TEST 1 #define GTEST_HAS_TYPED_TEST_P 1 #endif // Determines whether the system compiler uses UTF-16 for encoding wide strings. #define GTEST_WIDE_STRING_USES_UTF16_ \ (GTEST_OS_WINDOWS || GTEST_OS_CYGWIN || GTEST_OS_AIX || GTEST_OS_OS2) // Determines whether test results can be streamed to a socket. #if GTEST_OS_LINUX || GTEST_OS_GNU_KFREEBSD || GTEST_OS_DRAGONFLY || \ GTEST_OS_FREEBSD || GTEST_OS_NETBSD || GTEST_OS_OPENBSD || \ GTEST_OS_GNU_HURD #define GTEST_CAN_STREAM_RESULTS_ 1 #endif // Defines some utility macros. // The GNU compiler emits a warning if nested "if" statements are followed by // an "else" statement and braces are not used to explicitly disambiguate the // "else" binding. This leads to problems with code like: // // if (gate) // ASSERT_*(condition) << "Some message"; // // The "switch (0) case 0:" idiom is used to suppress this. #ifdef __INTEL_COMPILER #define GTEST_AMBIGUOUS_ELSE_BLOCKER_ #else #define GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ switch (0) \ case 0: \ default: // NOLINT #endif // Use this annotation at the end of a struct/class definition to // prevent the compiler from optimizing away instances that are never // used. This is useful when all interesting logic happens inside the // c'tor and / or d'tor. Example: // // struct Foo { // Foo() { ... } // } GTEST_ATTRIBUTE_UNUSED_; // // Also use it after a variable or parameter declaration to tell the // compiler the variable/parameter does not have to be used. #if defined(__GNUC__) && !defined(COMPILER_ICC) #define GTEST_ATTRIBUTE_UNUSED_ __attribute__((unused)) #elif defined(__clang__) #if __has_attribute(unused) #define GTEST_ATTRIBUTE_UNUSED_ __attribute__((unused)) #endif #endif #ifndef GTEST_ATTRIBUTE_UNUSED_ #define GTEST_ATTRIBUTE_UNUSED_ #endif // Use this annotation before a function that takes a printf format string. #if (defined(__GNUC__) || defined(__clang__)) && !defined(COMPILER_ICC) #if defined(__MINGW_PRINTF_FORMAT) // MinGW has two different printf implementations. Ensure the format macro // matches the selected implementation. See // https://sourceforge.net/p/mingw-w64/wiki2/gnu%20printf/. #define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) \ __attribute__(( \ __format__(__MINGW_PRINTF_FORMAT, string_index, first_to_check))) #else #define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) \ __attribute__((__format__(__printf__, string_index, first_to_check))) #endif #else #define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) #endif // Tell the compiler to warn about unused return values for functions declared // with this macro. The macro should be used on function declarations // following the argument list: // // Sprocket* AllocateSprocket() GTEST_MUST_USE_RESULT_; #if defined(__GNUC__) && !defined(COMPILER_ICC) #define GTEST_MUST_USE_RESULT_ __attribute__((warn_unused_result)) #else #define GTEST_MUST_USE_RESULT_ #endif // __GNUC__ && !COMPILER_ICC // MS C++ compiler emits warning when a conditional expression is compile time // constant. In some contexts this warning is false positive and needs to be // suppressed. Use the following two macros in such cases: // // GTEST_INTENTIONAL_CONST_COND_PUSH_() // while (true) { // GTEST_INTENTIONAL_CONST_COND_POP_() // } #define GTEST_INTENTIONAL_CONST_COND_PUSH_() \ GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127) #define GTEST_INTENTIONAL_CONST_COND_POP_() GTEST_DISABLE_MSC_WARNINGS_POP_() // Determine whether the compiler supports Microsoft's Structured Exception // Handling. This is supported by several Windows compilers but generally // does not exist on any other system. #ifndef GTEST_HAS_SEH // The user didn't tell us, so we need to figure it out. #if defined(_MSC_VER) || defined(__BORLANDC__) // These two compilers are known to support SEH. #define GTEST_HAS_SEH 1 #else // Assume no SEH. #define GTEST_HAS_SEH 0 #endif #endif // GTEST_HAS_SEH #ifndef GTEST_IS_THREADSAFE #define GTEST_IS_THREADSAFE \ (GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ || \ (GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT) || \ GTEST_HAS_PTHREAD) #endif // GTEST_IS_THREADSAFE #if GTEST_IS_THREADSAFE // Some platforms don't support including these threading related headers. #include <condition_variable> // NOLINT #include <mutex> // NOLINT #endif // GTEST_IS_THREADSAFE // GTEST_API_ qualifies all symbols that must be exported. The definitions below // are guarded by #ifndef to give embedders a chance to define GTEST_API_ in // gtest/internal/custom/gtest-port.h #ifndef GTEST_API_ #ifdef _MSC_VER #if GTEST_LINKED_AS_SHARED_LIBRARY #define GTEST_API_ __declspec(dllimport) #elif GTEST_CREATE_SHARED_LIBRARY #define GTEST_API_ __declspec(dllexport) #endif #elif __GNUC__ >= 4 || defined(__clang__) #define GTEST_API_ __attribute__((visibility("default"))) #endif // _MSC_VER #endif // GTEST_API_ #ifndef GTEST_API_ #define GTEST_API_ #endif // GTEST_API_ #ifndef GTEST_DEFAULT_DEATH_TEST_STYLE #define GTEST_DEFAULT_DEATH_TEST_STYLE "fast" #endif // GTEST_DEFAULT_DEATH_TEST_STYLE #ifdef __GNUC__ // Ask the compiler to never inline a given function. #define GTEST_NO_INLINE_ __attribute__((noinline)) #else #define GTEST_NO_INLINE_ #endif #if defined(__clang__) // Nested ifs to avoid triggering MSVC warning. #if __has_attribute(disable_tail_calls) // Ask the compiler not to perform tail call optimization inside // the marked function. #define GTEST_NO_TAIL_CALL_ __attribute__((disable_tail_calls)) #endif #elif __GNUC__ #define GTEST_NO_TAIL_CALL_ \ __attribute__((optimize("no-optimize-sibling-calls"))) #else #define GTEST_NO_TAIL_CALL_ #endif // _LIBCPP_VERSION is defined by the libc++ library from the LLVM project. #if !defined(GTEST_HAS_CXXABI_H_) #if defined(__GLIBCXX__) || (defined(_LIBCPP_VERSION) && !defined(_MSC_VER)) #define GTEST_HAS_CXXABI_H_ 1 #else #define GTEST_HAS_CXXABI_H_ 0 #endif #endif // A function level attribute to disable checking for use of uninitialized // memory when built with MemorySanitizer. #if defined(__clang__) #if __has_feature(memory_sanitizer) #define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ __attribute__((no_sanitize_memory)) #else #define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ #endif // __has_feature(memory_sanitizer) #else #define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ #endif // __clang__ // A function level attribute to disable AddressSanitizer instrumentation. #if defined(__clang__) #if __has_feature(address_sanitizer) #define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ \ __attribute__((no_sanitize_address)) #else #define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ #endif // __has_feature(address_sanitizer) #else #define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ #endif // __clang__ // A function level attribute to disable HWAddressSanitizer instrumentation. #if defined(__clang__) #if __has_feature(hwaddress_sanitizer) #define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ \ __attribute__((no_sanitize("hwaddress"))) #else #define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ #endif // __has_feature(hwaddress_sanitizer) #else #define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ #endif // __clang__ // A function level attribute to disable ThreadSanitizer instrumentation. #if defined(__clang__) #if __has_feature(thread_sanitizer) #define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ __attribute__((no_sanitize_thread)) #else #define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ #endif // __has_feature(thread_sanitizer) #else #define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ #endif // __clang__ namespace testing { class Message; // Legacy imports for backwards compatibility. // New code should use std:: names directly. using std::get; using std::make_tuple; using std::tuple; using std::tuple_element; using std::tuple_size; namespace internal { // A secret type that Google Test users don't know about. It has no // definition on purpose. Therefore it's impossible to create a // Secret object, which is what we want. class Secret; // A helper for suppressing warnings on constant condition. It just // returns 'condition'. GTEST_API_ bool IsTrue(bool condition); // Defines RE. #if GTEST_USES_RE2 // This is almost `using RE = ::RE2`, except it is copy-constructible, and it // needs to disambiguate the `std::string`, `absl::string_view`, and `const // char*` constructors. class GTEST_API_ RE { public: RE(absl::string_view regex) : regex_(regex) {} // NOLINT RE(const char* regex) : RE(absl::string_view(regex)) {} // NOLINT RE(const std::string& regex) : RE(absl::string_view(regex)) {} // NOLINT RE(const RE& other) : RE(other.pattern()) {} const std::string& pattern() const { return regex_.pattern(); } static bool FullMatch(absl::string_view str, const RE& re) { return RE2::FullMatch(str, re.regex_); } static bool PartialMatch(absl::string_view str, const RE& re) { return RE2::PartialMatch(str, re.regex_); } private: RE2 regex_; }; #elif GTEST_USES_POSIX_RE || GTEST_USES_SIMPLE_RE // A simple C++ wrapper for <regex.h>. It uses the POSIX Extended // Regular Expression syntax. class GTEST_API_ RE { public: // A copy constructor is required by the Standard to initialize object // references from r-values. RE(const RE& other) { Init(other.pattern()); } // Constructs an RE from a string. RE(const ::std::string& regex) { Init(regex.c_str()); } // NOLINT RE(const char* regex) { Init(regex); } // NOLINT ~RE(); // Returns the string representation of the regex. const char* pattern() const { return pattern_; } // FullMatch(str, re) returns true if and only if regular expression re // matches the entire str. // PartialMatch(str, re) returns true if and only if regular expression re // matches a substring of str (including str itself). static bool FullMatch(const ::std::string& str, const RE& re) { return FullMatch(str.c_str(), re); } static bool PartialMatch(const ::std::string& str, const RE& re) { return PartialMatch(str.c_str(), re); } static bool FullMatch(const char* str, const RE& re); static bool PartialMatch(const char* str, const RE& re); private: void Init(const char* regex); const char* pattern_; bool is_valid_; #if GTEST_USES_POSIX_RE regex_t full_regex_; // For FullMatch(). regex_t partial_regex_; // For PartialMatch(). #else // GTEST_USES_SIMPLE_RE const char* full_pattern_; // For FullMatch(); #endif }; #endif // ::testing::internal::RE implementation // Formats a source file path and a line number as they would appear // in an error message from the compiler used to compile this code. GTEST_API_ ::std::string FormatFileLocation(const char* file, int line); // Formats a file location for compiler-independent XML output. // Although this function is not platform dependent, we put it next to // FormatFileLocation in order to contrast the two functions. GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char* file, int line); // Defines logging utilities: // GTEST_LOG_(severity) - logs messages at the specified severity level. The // message itself is streamed into the macro. // LogToStderr() - directs all log messages to stderr. // FlushInfoLog() - flushes informational log messages. enum GTestLogSeverity { GTEST_INFO, GTEST_WARNING, GTEST_ERROR, GTEST_FATAL }; // Formats log entry severity, provides a stream object for streaming the // log message, and terminates the message with a newline when going out of // scope. class GTEST_API_ GTestLog { public: GTestLog(GTestLogSeverity severity, const char* file, int line); // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program. ~GTestLog(); ::std::ostream& GetStream() { return ::std::cerr; } private: const GTestLogSeverity severity_; GTestLog(const GTestLog&) = delete; GTestLog& operator=(const GTestLog&) = delete; }; #if !defined(GTEST_LOG_) #define GTEST_LOG_(severity) \ ::testing::internal::GTestLog(::testing::internal::GTEST_##severity, \ __FILE__, __LINE__) \ .GetStream() inline void LogToStderr() {} inline void FlushInfoLog() { fflush(nullptr); } #endif // !defined(GTEST_LOG_) #if !defined(GTEST_CHECK_) // INTERNAL IMPLEMENTATION - DO NOT USE. // // GTEST_CHECK_ is an all-mode assert. It aborts the program if the condition // is not satisfied. // Synopsis: // GTEST_CHECK_(boolean_condition); // or // GTEST_CHECK_(boolean_condition) << "Additional message"; // // This checks the condition and if the condition is not satisfied // it prints message about the condition violation, including the // condition itself, plus additional message streamed into it, if any, // and then it aborts the program. It aborts the program irrespective of // whether it is built in the debug mode or not. #define GTEST_CHECK_(condition) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ if (::testing::internal::IsTrue(condition)) \ ; \ else \ GTEST_LOG_(FATAL) << "Condition " #condition " failed. " #endif // !defined(GTEST_CHECK_) // An all-mode assert to verify that the given POSIX-style function // call returns 0 (indicating success). Known limitation: this // doesn't expand to a balanced 'if' statement, so enclose the macro // in {} if you need to use it as the only statement in an 'if' // branch. #define GTEST_CHECK_POSIX_SUCCESS_(posix_call) \ if (const int gtest_error = (posix_call)) \ GTEST_LOG_(FATAL) << #posix_call << "failed with error " << gtest_error // Transforms "T" into "const T&" according to standard reference collapsing // rules (this is only needed as a backport for C++98 compilers that do not // support reference collapsing). Specifically, it transforms: // // char ==> const char& // const char ==> const char& // char& ==> char& // const char& ==> const char& // // Note that the non-const reference will not have "const" added. This is // standard, and necessary so that "T" can always bind to "const T&". template <typename T> struct ConstRef { typedef const T& type; }; template <typename T> struct ConstRef<T&> { typedef T& type; }; // The argument T must depend on some template parameters. #define GTEST_REFERENCE_TO_CONST_(T) \ typename ::testing::internal::ConstRef<T>::type // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Use ImplicitCast_ as a safe version of static_cast for upcasting in // the type hierarchy (e.g. casting a Foo* to a SuperclassOfFoo* or a // const Foo*). When you use ImplicitCast_, the compiler checks that // the cast is safe. Such explicit ImplicitCast_s are necessary in // surprisingly many situations where C++ demands an exact type match // instead of an argument type convertible to a target type. // // The syntax for using ImplicitCast_ is the same as for static_cast: // // ImplicitCast_<ToType>(expr) // // ImplicitCast_ would have been part of the C++ standard library, // but the proposal was submitted too late. It will probably make // its way into the language in the future. // // This relatively ugly name is intentional. It prevents clashes with // similar functions users may have (e.g., implicit_cast). The internal // namespace alone is not enough because the function can be found by ADL. template <typename To> inline To ImplicitCast_(To x) { return x; } // When you upcast (that is, cast a pointer from type Foo to type // SuperclassOfFoo), it's fine to use ImplicitCast_<>, since upcasts // always succeed. When you downcast (that is, cast a pointer from // type Foo to type SubclassOfFoo), static_cast<> isn't safe, because // how do you know the pointer is really of type SubclassOfFoo? It // could be a bare Foo, or of type DifferentSubclassOfFoo. Thus, // when you downcast, you should use this macro. In debug mode, we // use dynamic_cast<> to double-check the downcast is legal (we die // if it's not). In normal mode, we do the efficient static_cast<> // instead. Thus, it's important to test in debug mode to make sure // the cast is legal! // This is the only place in the code we should use dynamic_cast<>. // In particular, you SHOULDN'T be using dynamic_cast<> in order to // do RTTI (eg code like this: // if (dynamic_cast<Subclass1>(foo)) HandleASubclass1Object(foo); // if (dynamic_cast<Subclass2>(foo)) HandleASubclass2Object(foo); // You should design the code some other way not to need this. // // This relatively ugly name is intentional. It prevents clashes with // similar functions users may have (e.g., down_cast). The internal // namespace alone is not enough because the function can be found by ADL. template <typename To, typename From> // use like this: DownCast_<T*>(foo); inline To DownCast_(From* f) { // so we only accept pointers // Ensures that To is a sub-type of From *. This test is here only // for compile-time type checking, and has no overhead in an // optimized build at run-time, as it will be optimized away // completely. GTEST_INTENTIONAL_CONST_COND_PUSH_() if (false) { GTEST_INTENTIONAL_CONST_COND_POP_() const To to = nullptr; ::testing::internal::ImplicitCast_<From*>(to); } #if GTEST_HAS_RTTI // RTTI: debug mode only! GTEST_CHECK_(f == nullptr || dynamic_cast<To>(f) != nullptr); #endif return static_cast<To>(f); } // Downcasts the pointer of type Base to Derived. // Derived must be a subclass of Base. The parameter MUST // point to a class of type Derived, not any subclass of it. // When RTTI is available, the function performs a runtime // check to enforce this. template <class Derived, class Base> Derived* CheckedDowncastToActualType(Base* base) { #if GTEST_HAS_RTTI GTEST_CHECK_(typeid(*base) == typeid(Derived)); #endif #if GTEST_HAS_DOWNCAST_ return ::down_cast<Derived*>(base); #elif GTEST_HAS_RTTI return dynamic_cast<Derived*>(base); // NOLINT #else return static_cast<Derived*>(base); // Poor man's downcast. #endif } #if GTEST_HAS_STREAM_REDIRECTION // Defines the stderr capturer: // CaptureStdout - starts capturing stdout. // GetCapturedStdout - stops capturing stdout and returns the captured string. // CaptureStderr - starts capturing stderr. // GetCapturedStderr - stops capturing stderr and returns the captured string. // GTEST_API_ void CaptureStdout(); GTEST_API_ std::string GetCapturedStdout(); GTEST_API_ void CaptureStderr(); GTEST_API_ std::string GetCapturedStderr(); #endif // GTEST_HAS_STREAM_REDIRECTION // Returns the size (in bytes) of a file. GTEST_API_ size_t GetFileSize(FILE* file); // Reads the entire content of a file as a string. GTEST_API_ std::string ReadEntireFile(FILE* file); // All command line arguments. GTEST_API_ std::vector<std::string> GetArgvs(); #if GTEST_HAS_DEATH_TEST std::vector<std::string> GetInjectableArgvs(); // Deprecated: pass the args vector by value instead. void SetInjectableArgvs(const std::vector<std::string>* new_argvs); void SetInjectableArgvs(const std::vector<std::string>& new_argvs); void ClearInjectableArgvs(); #endif // GTEST_HAS_DEATH_TEST // Defines synchronization primitives. #if GTEST_IS_THREADSAFE #if GTEST_OS_WINDOWS // Provides leak-safe Windows kernel handle ownership. // Used in death tests and in threading support. class GTEST_API_ AutoHandle { public: // Assume that Win32 HANDLE type is equivalent to void*. Doing so allows us to // avoid including <windows.h> in this header file. Including <windows.h> is // undesirable because it defines a lot of symbols and macros that tend to // conflict with client code. This assumption is verified by // WindowsTypesTest.HANDLEIsVoidStar. typedef void* Handle; AutoHandle(); explicit AutoHandle(Handle handle); ~AutoHandle(); Handle Get() const; void Reset(); void Reset(Handle handle); private: // Returns true if and only if the handle is a valid handle object that can be // closed. bool IsCloseable() const; Handle handle_; AutoHandle(const AutoHandle&) = delete; AutoHandle& operator=(const AutoHandle&) = delete; }; #endif #if GTEST_HAS_NOTIFICATION_ // Notification has already been imported into the namespace. // Nothing to do here. #else GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ /* class A needs to have dll-interface to be used by clients of class B */) // Allows a controller thread to pause execution of newly created // threads until notified. Instances of this class must be created // and destroyed in the controller thread. // // This class is only for testing Google Test's own constructs. Do not // use it in user tests, either directly or indirectly. // TODO(b/203539622): Replace unconditionally with absl::Notification. class GTEST_API_ Notification { public: Notification() : notified_(false) {} Notification(const Notification&) = delete; Notification& operator=(const Notification&) = delete; // Notifies all threads created with this notification to start. Must // be called from the controller thread. void Notify() { std::lock_guard<std::mutex> lock(mu_); notified_ = true; cv_.notify_all(); } // Blocks until the controller thread notifies. Must be called from a test // thread. void WaitForNotification() { std::unique_lock<std::mutex> lock(mu_); cv_.wait(lock, [this]() { return notified_; }); } private: std::mutex mu_; std::condition_variable cv_; bool notified_; }; GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 #endif // GTEST_HAS_NOTIFICATION_ // On MinGW, we can have both GTEST_OS_WINDOWS and GTEST_HAS_PTHREAD // defined, but we don't want to use MinGW's pthreads implementation, which // has conformance problems with some versions of the POSIX standard. #if GTEST_HAS_PTHREAD && !GTEST_OS_WINDOWS_MINGW // As a C-function, ThreadFuncWithCLinkage cannot be templated itself. // Consequently, it cannot select a correct instantiation of ThreadWithParam // in order to call its Run(). Introducing ThreadWithParamBase as a // non-templated base class for ThreadWithParam allows us to bypass this // problem. class ThreadWithParamBase { public: virtual ~ThreadWithParamBase() {} virtual void Run() = 0; }; // pthread_create() accepts a pointer to a function type with the C linkage. // According to the Standard (7.5/1), function types with different linkages // are different even if they are otherwise identical. Some compilers (for // example, SunStudio) treat them as different types. Since class methods // cannot be defined with C-linkage we need to define a free C-function to // pass into pthread_create(). extern "C" inline void* ThreadFuncWithCLinkage(void* thread) { static_cast<ThreadWithParamBase*>(thread)->Run(); return nullptr; } // Helper class for testing Google Test's multi-threading constructs. // To use it, write: // // void ThreadFunc(int param) { /* Do things with param */ } // Notification thread_can_start; // ... // // The thread_can_start parameter is optional; you can supply NULL. // ThreadWithParam<int> thread(&ThreadFunc, 5, &thread_can_start); // thread_can_start.Notify(); // // These classes are only for testing Google Test's own constructs. Do // not use them in user tests, either directly or indirectly. template <typename T> class ThreadWithParam : public ThreadWithParamBase { public: typedef void UserThreadFunc(T); ThreadWithParam(UserThreadFunc* func, T param, Notification* thread_can_start) : func_(func), param_(param), thread_can_start_(thread_can_start), finished_(false) { ThreadWithParamBase* const base = this; // The thread can be created only after all fields except thread_ // have been initialized. GTEST_CHECK_POSIX_SUCCESS_( pthread_create(&thread_, nullptr, &ThreadFuncWithCLinkage, base)); } ~ThreadWithParam() override { Join(); } void Join() { if (!finished_) { GTEST_CHECK_POSIX_SUCCESS_(pthread_join(thread_, nullptr)); finished_ = true; } } void Run() override { if (thread_can_start_ != nullptr) thread_can_start_->WaitForNotification(); func_(param_); } private: UserThreadFunc* const func_; // User-supplied thread function. const T param_; // User-supplied parameter to the thread function. // When non-NULL, used to block execution until the controller thread // notifies. Notification* const thread_can_start_; bool finished_; // true if and only if we know that the thread function has // finished. pthread_t thread_; // The native thread object. ThreadWithParam(const ThreadWithParam&) = delete; ThreadWithParam& operator=(const ThreadWithParam&) = delete; }; #endif // !GTEST_OS_WINDOWS && GTEST_HAS_PTHREAD || // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ #if GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ // Mutex and ThreadLocal have already been imported into the namespace. // Nothing to do here. #elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT // Mutex implements mutex on Windows platforms. It is used in conjunction // with class MutexLock: // // Mutex mutex; // ... // MutexLock lock(&mutex); // Acquires the mutex and releases it at the // // end of the current scope. // // A static Mutex *must* be defined or declared using one of the following // macros: // GTEST_DEFINE_STATIC_MUTEX_(g_some_mutex); // GTEST_DECLARE_STATIC_MUTEX_(g_some_mutex); // // (A non-static Mutex is defined/declared in the usual way). class GTEST_API_ Mutex { public: enum MutexType { kStatic = 0, kDynamic = 1 }; // We rely on kStaticMutex being 0 as it is to what the linker initializes // type_ in static mutexes. critical_section_ will be initialized lazily // in ThreadSafeLazyInit(). enum StaticConstructorSelector { kStaticMutex = 0 }; // This constructor intentionally does nothing. It relies on type_ being // statically initialized to 0 (effectively setting it to kStatic) and on // ThreadSafeLazyInit() to lazily initialize the rest of the members. explicit Mutex(StaticConstructorSelector /*dummy*/) {} Mutex(); ~Mutex(); void Lock(); void Unlock(); // Does nothing if the current thread holds the mutex. Otherwise, crashes // with high probability. void AssertHeld(); private: // Initializes owner_thread_id_ and critical_section_ in static mutexes. void ThreadSafeLazyInit(); // Per https://blogs.msdn.microsoft.com/oldnewthing/20040223-00/?p=40503, // we assume that 0 is an invalid value for thread IDs. unsigned int owner_thread_id_; // For static mutexes, we rely on these members being initialized to zeros // by the linker. MutexType type_; long critical_section_init_phase_; // NOLINT GTEST_CRITICAL_SECTION* critical_section_; Mutex(const Mutex&) = delete; Mutex& operator=(const Mutex&) = delete; }; #define GTEST_DECLARE_STATIC_MUTEX_(mutex) \ extern ::testing::internal::Mutex mutex #define GTEST_DEFINE_STATIC_MUTEX_(mutex) \ ::testing::internal::Mutex mutex(::testing::internal::Mutex::kStaticMutex) // We cannot name this class MutexLock because the ctor declaration would // conflict with a macro named MutexLock, which is defined on some // platforms. That macro is used as a defensive measure to prevent against // inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than // "MutexLock l(&mu)". Hence the typedef trick below. class GTestMutexLock { public: explicit GTestMutexLock(Mutex* mutex) : mutex_(mutex) { mutex_->Lock(); } ~GTestMutexLock() { mutex_->Unlock(); } private: Mutex* const mutex_; GTestMutexLock(const GTestMutexLock&) = delete; GTestMutexLock& operator=(const GTestMutexLock&) = delete; }; typedef GTestMutexLock MutexLock; // Base class for ValueHolder<T>. Allows a caller to hold and delete a value // without knowing its type. class ThreadLocalValueHolderBase { public: virtual ~ThreadLocalValueHolderBase() {} }; // Provides a way for a thread to send notifications to a ThreadLocal // regardless of its parameter type. class ThreadLocalBase { public: // Creates a new ValueHolder<T> object holding a default value passed to // this ThreadLocal<T>'s constructor and returns it. It is the caller's // responsibility not to call this when the ThreadLocal<T> instance already // has a value on the current thread. virtual ThreadLocalValueHolderBase* NewValueForCurrentThread() const = 0; protected: ThreadLocalBase() {} virtual ~ThreadLocalBase() {} private: ThreadLocalBase(const ThreadLocalBase&) = delete; ThreadLocalBase& operator=(const ThreadLocalBase&) = delete; }; // Maps a thread to a set of ThreadLocals that have values instantiated on that // thread and notifies them when the thread exits. A ThreadLocal instance is // expected to persist until all threads it has values on have terminated. class GTEST_API_ ThreadLocalRegistry { public: // Registers thread_local_instance as having value on the current thread. // Returns a value that can be used to identify the thread from other threads. static ThreadLocalValueHolderBase* GetValueOnCurrentThread( const ThreadLocalBase* thread_local_instance); // Invoked when a ThreadLocal instance is destroyed. static void OnThreadLocalDestroyed( const ThreadLocalBase* thread_local_instance); }; class GTEST_API_ ThreadWithParamBase { public: void Join(); protected: class Runnable { public: virtual ~Runnable() {} virtual void Run() = 0; }; ThreadWithParamBase(Runnable* runnable, Notification* thread_can_start); virtual ~ThreadWithParamBase(); private: AutoHandle thread_; }; // Helper class for testing Google Test's multi-threading constructs. template <typename T> class ThreadWithParam : public ThreadWithParamBase { public: typedef void UserThreadFunc(T); ThreadWithParam(UserThreadFunc* func, T param, Notification* thread_can_start) : ThreadWithParamBase(new RunnableImpl(func, param), thread_can_start) {} virtual ~ThreadWithParam() {} private: class RunnableImpl : public Runnable { public: RunnableImpl(UserThreadFunc* func, T param) : func_(func), param_(param) {} virtual ~RunnableImpl() {} virtual void Run() { func_(param_); } private: UserThreadFunc* const func_; const T param_; RunnableImpl(const RunnableImpl&) = delete; RunnableImpl& operator=(const RunnableImpl&) = delete; }; ThreadWithParam(const ThreadWithParam&) = delete; ThreadWithParam& operator=(const ThreadWithParam&) = delete; }; // Implements thread-local storage on Windows systems. // // // Thread 1 // ThreadLocal<int> tl(100); // 100 is the default value for each thread. // // // Thread 2 // tl.set(150); // Changes the value for thread 2 only. // EXPECT_EQ(150, tl.get()); // // // Thread 1 // EXPECT_EQ(100, tl.get()); // In thread 1, tl has the original value. // tl.set(200); // EXPECT_EQ(200, tl.get()); // // The template type argument T must have a public copy constructor. // In addition, the default ThreadLocal constructor requires T to have // a public default constructor. // // The users of a TheadLocal instance have to make sure that all but one // threads (including the main one) using that instance have exited before // destroying it. Otherwise, the per-thread objects managed for them by the // ThreadLocal instance are not guaranteed to be destroyed on all platforms. // // Google Test only uses global ThreadLocal objects. That means they // will die after main() has returned. Therefore, no per-thread // object managed by Google Test will be leaked as long as all threads // using Google Test have exited when main() returns. template <typename T> class ThreadLocal : public ThreadLocalBase { public: ThreadLocal() : default_factory_(new DefaultValueHolderFactory()) {} explicit ThreadLocal(const T& value) : default_factory_(new InstanceValueHolderFactory(value)) {} ~ThreadLocal() override { ThreadLocalRegistry::OnThreadLocalDestroyed(this); } T* pointer() { return GetOrCreateValue(); } const T* pointer() const { return GetOrCreateValue(); } const T& get() const { return *pointer(); } void set(const T& value) { *pointer() = value; } private: // Holds a value of T. Can be deleted via its base class without the caller // knowing the type of T. class ValueHolder : public ThreadLocalValueHolderBase { public: ValueHolder() : value_() {} explicit ValueHolder(const T& value) : value_(value) {} T* pointer() { return &value_; } private: T value_; ValueHolder(const ValueHolder&) = delete; ValueHolder& operator=(const ValueHolder&) = delete; }; T* GetOrCreateValue() const { return static_cast<ValueHolder*>( ThreadLocalRegistry::GetValueOnCurrentThread(this)) ->pointer(); } ThreadLocalValueHolderBase* NewValueForCurrentThread() const override { return default_factory_->MakeNewHolder(); } class ValueHolderFactory { public: ValueHolderFactory() {} virtual ~ValueHolderFactory() {} virtual ValueHolder* MakeNewHolder() const = 0; private: ValueHolderFactory(const ValueHolderFactory&) = delete; ValueHolderFactory& operator=(const ValueHolderFactory&) = delete; }; class DefaultValueHolderFactory : public ValueHolderFactory { public: DefaultValueHolderFactory() {} ValueHolder* MakeNewHolder() const override { return new ValueHolder(); } private: DefaultValueHolderFactory(const DefaultValueHolderFactory&) = delete; DefaultValueHolderFactory& operator=(const DefaultValueHolderFactory&) = delete; }; class InstanceValueHolderFactory : public ValueHolderFactory { public: explicit InstanceValueHolderFactory(const T& value) : value_(value) {} ValueHolder* MakeNewHolder() const override { return new ValueHolder(value_); } private: const T value_; // The value for each thread. InstanceValueHolderFactory(const InstanceValueHolderFactory&) = delete; InstanceValueHolderFactory& operator=(const InstanceValueHolderFactory&) = delete; }; std::unique_ptr<ValueHolderFactory> default_factory_; ThreadLocal(const ThreadLocal&) = delete; ThreadLocal& operator=(const ThreadLocal&) = delete; }; #elif GTEST_HAS_PTHREAD // MutexBase and Mutex implement mutex on pthreads-based platforms. class MutexBase { public: // Acquires this mutex. void Lock() { GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&mutex_)); owner_ = pthread_self(); has_owner_ = true; } // Releases this mutex. void Unlock() { // Since the lock is being released the owner_ field should no longer be // considered valid. We don't protect writing to has_owner_ here, as it's // the caller's responsibility to ensure that the current thread holds the // mutex when this is called. has_owner_ = false; GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&mutex_)); } // Does nothing if the current thread holds the mutex. Otherwise, crashes // with high probability. void AssertHeld() const { GTEST_CHECK_(has_owner_ && pthread_equal(owner_, pthread_self())) << "The current thread is not holding the mutex @" << this; } // A static mutex may be used before main() is entered. It may even // be used before the dynamic initialization stage. Therefore we // must be able to initialize a static mutex object at link time. // This means MutexBase has to be a POD and its member variables // have to be public. public: pthread_mutex_t mutex_; // The underlying pthread mutex. // has_owner_ indicates whether the owner_ field below contains a valid thread // ID and is therefore safe to inspect (e.g., to use in pthread_equal()). All // accesses to the owner_ field should be protected by a check of this field. // An alternative might be to memset() owner_ to all zeros, but there's no // guarantee that a zero'd pthread_t is necessarily invalid or even different // from pthread_self(). bool has_owner_; pthread_t owner_; // The thread holding the mutex. }; // Forward-declares a static mutex. #define GTEST_DECLARE_STATIC_MUTEX_(mutex) \ extern ::testing::internal::MutexBase mutex // Defines and statically (i.e. at link time) initializes a static mutex. // The initialization list here does not explicitly initialize each field, // instead relying on default initialization for the unspecified fields. In // particular, the owner_ field (a pthread_t) is not explicitly initialized. // This allows initialization to work whether pthread_t is a scalar or struct. // The flag -Wmissing-field-initializers must not be specified for this to work. #define GTEST_DEFINE_STATIC_MUTEX_(mutex) \ ::testing::internal::MutexBase mutex = {PTHREAD_MUTEX_INITIALIZER, false, 0} // The Mutex class can only be used for mutexes created at runtime. It // shares its API with MutexBase otherwise. class Mutex : public MutexBase { public: Mutex() { GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, nullptr)); has_owner_ = false; } ~Mutex() { GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&mutex_)); } private: Mutex(const Mutex&) = delete; Mutex& operator=(const Mutex&) = delete; }; // We cannot name this class MutexLock because the ctor declaration would // conflict with a macro named MutexLock, which is defined on some // platforms. That macro is used as a defensive measure to prevent against // inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than // "MutexLock l(&mu)". Hence the typedef trick below. class GTestMutexLock { public: explicit GTestMutexLock(MutexBase* mutex) : mutex_(mutex) { mutex_->Lock(); } ~GTestMutexLock() { mutex_->Unlock(); } private: MutexBase* const mutex_; GTestMutexLock(const GTestMutexLock&) = delete; GTestMutexLock& operator=(const GTestMutexLock&) = delete; }; typedef GTestMutexLock MutexLock; // Helpers for ThreadLocal. // pthread_key_create() requires DeleteThreadLocalValue() to have // C-linkage. Therefore it cannot be templatized to access // ThreadLocal<T>. Hence the need for class // ThreadLocalValueHolderBase. class ThreadLocalValueHolderBase { public: virtual ~ThreadLocalValueHolderBase() {} }; // Called by pthread to delete thread-local data stored by // pthread_setspecific(). extern "C" inline void DeleteThreadLocalValue(void* value_holder) { delete static_cast<ThreadLocalValueHolderBase*>(value_holder); } // Implements thread-local storage on pthreads-based systems. template <typename T> class GTEST_API_ ThreadLocal { public: ThreadLocal() : key_(CreateKey()), default_factory_(new DefaultValueHolderFactory()) {} explicit ThreadLocal(const T& value) : key_(CreateKey()), default_factory_(new InstanceValueHolderFactory(value)) {} ~ThreadLocal() { // Destroys the managed object for the current thread, if any. DeleteThreadLocalValue(pthread_getspecific(key_)); // Releases resources associated with the key. This will *not* // delete managed objects for other threads. GTEST_CHECK_POSIX_SUCCESS_(pthread_key_delete(key_)); } T* pointer() { return GetOrCreateValue(); } const T* pointer() const { return GetOrCreateValue(); } const T& get() const { return *pointer(); } void set(const T& value) { *pointer() = value; } private: // Holds a value of type T. class ValueHolder : public ThreadLocalValueHolderBase { public: ValueHolder() : value_() {} explicit ValueHolder(const T& value) : value_(value) {} T* pointer() { return &value_; } private: T value_; ValueHolder(const ValueHolder&) = delete; ValueHolder& operator=(const ValueHolder&) = delete; }; static pthread_key_t CreateKey() { pthread_key_t key; // When a thread exits, DeleteThreadLocalValue() will be called on // the object managed for that thread. GTEST_CHECK_POSIX_SUCCESS_( pthread_key_create(&key, &DeleteThreadLocalValue)); return key; } T* GetOrCreateValue() const { ThreadLocalValueHolderBase* const holder = static_cast<ThreadLocalValueHolderBase*>(pthread_getspecific(key_)); if (holder != nullptr) { return CheckedDowncastToActualType<ValueHolder>(holder)->pointer(); } ValueHolder* const new_holder = default_factory_->MakeNewHolder(); ThreadLocalValueHolderBase* const holder_base = new_holder; GTEST_CHECK_POSIX_SUCCESS_(pthread_setspecific(key_, holder_base)); return new_holder->pointer(); } class ValueHolderFactory { public: ValueHolderFactory() {} virtual ~ValueHolderFactory() {} virtual ValueHolder* MakeNewHolder() const = 0; private: ValueHolderFactory(const ValueHolderFactory&) = delete; ValueHolderFactory& operator=(const ValueHolderFactory&) = delete; }; class DefaultValueHolderFactory : public ValueHolderFactory { public: DefaultValueHolderFactory() {} ValueHolder* MakeNewHolder() const override { return new ValueHolder(); } private: DefaultValueHolderFactory(const DefaultValueHolderFactory&) = delete; DefaultValueHolderFactory& operator=(const DefaultValueHolderFactory&) = delete; }; class InstanceValueHolderFactory : public ValueHolderFactory { public: explicit InstanceValueHolderFactory(const T& value) : value_(value) {} ValueHolder* MakeNewHolder() const override { return new ValueHolder(value_); } private: const T value_; // The value for each thread. InstanceValueHolderFactory(const InstanceValueHolderFactory&) = delete; InstanceValueHolderFactory& operator=(const InstanceValueHolderFactory&) = delete; }; // A key pthreads uses for looking up per-thread values. const pthread_key_t key_; std::unique_ptr<ValueHolderFactory> default_factory_; ThreadLocal(const ThreadLocal&) = delete; ThreadLocal& operator=(const ThreadLocal&) = delete; }; #endif // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ #else // GTEST_IS_THREADSAFE // A dummy implementation of synchronization primitives (mutex, lock, // and thread-local variable). Necessary for compiling Google Test where // mutex is not supported - using Google Test in multiple threads is not // supported on such platforms. class Mutex { public: Mutex() {} void Lock() {} void Unlock() {} void AssertHeld() const {} }; #define GTEST_DECLARE_STATIC_MUTEX_(mutex) \ extern ::testing::internal::Mutex mutex #define GTEST_DEFINE_STATIC_MUTEX_(mutex) ::testing::internal::Mutex mutex // We cannot name this class MutexLock because the ctor declaration would // conflict with a macro named MutexLock, which is defined on some // platforms. That macro is used as a defensive measure to prevent against // inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than // "MutexLock l(&mu)". Hence the typedef trick below. class GTestMutexLock { public: explicit GTestMutexLock(Mutex*) {} // NOLINT }; typedef GTestMutexLock MutexLock; template <typename T> class GTEST_API_ ThreadLocal { public: ThreadLocal() : value_() {} explicit ThreadLocal(const T& value) : value_(value) {} T* pointer() { return &value_; } const T* pointer() const { return &value_; } const T& get() const { return value_; } void set(const T& value) { value_ = value; } private: T value_; }; #endif // GTEST_IS_THREADSAFE // Returns the number of threads running in the process, or 0 to indicate that // we cannot detect it. GTEST_API_ size_t GetThreadCount(); #if GTEST_OS_WINDOWS #define GTEST_PATH_SEP_ "\\" #define GTEST_HAS_ALT_PATH_SEP_ 1 #else #define GTEST_PATH_SEP_ "/" #define GTEST_HAS_ALT_PATH_SEP_ 0 #endif // GTEST_OS_WINDOWS // Utilities for char. // isspace(int ch) and friends accept an unsigned char or EOF. char // may be signed, depending on the compiler (or compiler flags). // Therefore we need to cast a char to unsigned char before calling // isspace(), etc. inline bool IsAlpha(char ch) { return isalpha(static_cast<unsigned char>(ch)) != 0; } inline bool IsAlNum(char ch) { return isalnum(static_cast<unsigned char>(ch)) != 0; } inline bool IsDigit(char ch) { return isdigit(static_cast<unsigned char>(ch)) != 0; } inline bool IsLower(char ch) { return islower(static_cast<unsigned char>(ch)) != 0; } inline bool IsSpace(char ch) { return isspace(static_cast<unsigned char>(ch)) != 0; } inline bool IsUpper(char ch) { return isupper(static_cast<unsigned char>(ch)) != 0; } inline bool IsXDigit(char ch) { return isxdigit(static_cast<unsigned char>(ch)) != 0; } #ifdef __cpp_lib_char8_t inline bool IsXDigit(char8_t ch) { return isxdigit(static_cast<unsigned char>(ch)) != 0; } #endif inline bool IsXDigit(char16_t ch) { const unsigned char low_byte = static_cast<unsigned char>(ch); return ch == low_byte && isxdigit(low_byte) != 0; } inline bool IsXDigit(char32_t ch) { const unsigned char low_byte = static_cast<unsigned char>(ch); return ch == low_byte && isxdigit(low_byte) != 0; } inline bool IsXDigit(wchar_t ch) { const unsigned char low_byte = static_cast<unsigned char>(ch); return ch == low_byte && isxdigit(low_byte) != 0; } inline char ToLower(char ch) { return static_cast<char>(tolower(static_cast<unsigned char>(ch))); } inline char ToUpper(char ch) { return static_cast<char>(toupper(static_cast<unsigned char>(ch))); } inline std::string StripTrailingSpaces(std::string str) { std::string::iterator it = str.end(); while (it != str.begin() && IsSpace(*--it)) it = str.erase(it); return str; } // The testing::internal::posix namespace holds wrappers for common // POSIX functions. These wrappers hide the differences between // Windows/MSVC and POSIX systems. Since some compilers define these // standard functions as macros, the wrapper cannot have the same name // as the wrapped function. namespace posix { // Functions with a different name on Windows. #if GTEST_OS_WINDOWS typedef struct _stat StatStruct; #ifdef __BORLANDC__ inline int DoIsATTY(int fd) { return isatty(fd); } inline int StrCaseCmp(const char* s1, const char* s2) { return stricmp(s1, s2); } inline char* StrDup(const char* src) { return strdup(src); } #else // !__BORLANDC__ #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS || GTEST_OS_IOS || \ GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT || defined(ESP_PLATFORM) inline int DoIsATTY(int /* fd */) { return 0; } #else inline int DoIsATTY(int fd) { return _isatty(fd); } #endif // GTEST_OS_WINDOWS_MOBILE inline int StrCaseCmp(const char* s1, const char* s2) { return _stricmp(s1, s2); } inline char* StrDup(const char* src) { return _strdup(src); } #endif // __BORLANDC__ #if GTEST_OS_WINDOWS_MOBILE inline int FileNo(FILE* file) { return reinterpret_cast<int>(_fileno(file)); } // Stat(), RmDir(), and IsDir() are not needed on Windows CE at this // time and thus not defined there. #else inline int FileNo(FILE* file) { return _fileno(file); } inline int Stat(const char* path, StatStruct* buf) { return _stat(path, buf); } inline int RmDir(const char* dir) { return _rmdir(dir); } inline bool IsDir(const StatStruct& st) { return (_S_IFDIR & st.st_mode) != 0; } #endif // GTEST_OS_WINDOWS_MOBILE #elif GTEST_OS_ESP8266 typedef struct stat StatStruct; inline int FileNo(FILE* file) { return fileno(file); } inline int DoIsATTY(int fd) { return isatty(fd); } inline int Stat(const char* path, StatStruct* buf) { // stat function not implemented on ESP8266 return 0; } inline int StrCaseCmp(const char* s1, const char* s2) { return strcasecmp(s1, s2); } inline char* StrDup(const char* src) { return strdup(src); } inline int RmDir(const char* dir) { return rmdir(dir); } inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); } #else typedef struct stat StatStruct; inline int FileNo(FILE* file) { return fileno(file); } inline int DoIsATTY(int fd) { return isatty(fd); } inline int Stat(const char* path, StatStruct* buf) { return stat(path, buf); } inline int StrCaseCmp(const char* s1, const char* s2) { return strcasecmp(s1, s2); } inline char* StrDup(const char* src) { return strdup(src); } inline int RmDir(const char* dir) { return rmdir(dir); } inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); } #endif // GTEST_OS_WINDOWS inline int IsATTY(int fd) { // DoIsATTY might change errno (for example ENOTTY in case you redirect stdout // to a file on Linux), which is unexpected, so save the previous value, and // restore it after the call. int savedErrno = errno; int isAttyValue = DoIsATTY(fd); errno = savedErrno; return isAttyValue; } // Functions deprecated by MSVC 8.0. GTEST_DISABLE_MSC_DEPRECATED_PUSH_() // ChDir(), FReopen(), FDOpen(), Read(), Write(), Close(), and // StrError() aren't needed on Windows CE at this time and thus not // defined there. #if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && \ !GTEST_OS_WINDOWS_RT && !GTEST_OS_ESP8266 && !GTEST_OS_XTENSA inline int ChDir(const char* dir) { return chdir(dir); } #endif inline FILE* FOpen(const char* path, const char* mode) { #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW struct wchar_codecvt : public std::codecvt<wchar_t, char, std::mbstate_t> {}; std::wstring_convert<wchar_codecvt> converter; std::wstring wide_path = converter.from_bytes(path); std::wstring wide_mode = converter.from_bytes(mode); return _wfopen(wide_path.c_str(), wide_mode.c_str()); #else // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW return fopen(path, mode); #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW } #if !GTEST_OS_WINDOWS_MOBILE inline FILE* FReopen(const char* path, const char* mode, FILE* stream) { return freopen(path, mode, stream); } inline FILE* FDOpen(int fd, const char* mode) { return fdopen(fd, mode); } #endif inline int FClose(FILE* fp) { return fclose(fp); } #if !GTEST_OS_WINDOWS_MOBILE inline int Read(int fd, void* buf, unsigned int count) { return static_cast<int>(read(fd, buf, count)); } inline int Write(int fd, const void* buf, unsigned int count) { return static_cast<int>(write(fd, buf, count)); } inline int Close(int fd) { return close(fd); } inline const char* StrError(int errnum) { return strerror(errnum); } #endif inline const char* GetEnv(const char* name) { #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \ GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266 || GTEST_OS_XTENSA // We are on an embedded platform, which has no environment variables. static_cast<void>(name); // To prevent 'unused argument' warning. return nullptr; #elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9) // Environment variables which we programmatically clear will be set to the // empty string rather than unset (NULL). Handle that case. const char* const env = getenv(name); return (env != nullptr && env[0] != '\0') ? env : nullptr; #else return getenv(name); #endif } GTEST_DISABLE_MSC_DEPRECATED_POP_() #if GTEST_OS_WINDOWS_MOBILE // Windows CE has no C library. The abort() function is used in // several places in Google Test. This implementation provides a reasonable // imitation of standard behaviour. [[noreturn]] void Abort(); #else [[noreturn]] inline void Abort() { abort(); } #endif // GTEST_OS_WINDOWS_MOBILE } // namespace posix // MSVC "deprecates" snprintf and issues warnings wherever it is used. In // order to avoid these warnings, we need to use _snprintf or _snprintf_s on // MSVC-based platforms. We map the GTEST_SNPRINTF_ macro to the appropriate // function in order to achieve that. We use macro definition here because // snprintf is a variadic function. #if _MSC_VER && !GTEST_OS_WINDOWS_MOBILE // MSVC 2005 and above support variadic macros. #define GTEST_SNPRINTF_(buffer, size, format, ...) \ _snprintf_s(buffer, size, size, format, __VA_ARGS__) #elif defined(_MSC_VER) // Windows CE does not define _snprintf_s #define GTEST_SNPRINTF_ _snprintf #else #define GTEST_SNPRINTF_ snprintf #endif // The biggest signed integer type the compiler supports. // // long long is guaranteed to be at least 64-bits in C++11. using BiggestInt = long long; // NOLINT // The maximum number a BiggestInt can represent. constexpr BiggestInt kMaxBiggestInt = (std::numeric_limits<BiggestInt>::max)(); // This template class serves as a compile-time function from size to // type. It maps a size in bytes to a primitive type with that // size. e.g. // // TypeWithSize<4>::UInt // // is typedef-ed to be unsigned int (unsigned integer made up of 4 // bytes). // // Such functionality should belong to STL, but I cannot find it // there. // // Google Test uses this class in the implementation of floating-point // comparison. // // For now it only handles UInt (unsigned int) as that's all Google Test // needs. Other types can be easily added in the future if need // arises. template <size_t size> class TypeWithSize { public: // This prevents the user from using TypeWithSize<N> with incorrect // values of N. using UInt = void; }; // The specialization for size 4. template <> class TypeWithSize<4> { public: using Int = std::int32_t; using UInt = std::uint32_t; }; // The specialization for size 8. template <> class TypeWithSize<8> { public: using Int = std::int64_t; using UInt = std::uint64_t; }; // Integer types of known sizes. using TimeInMillis = int64_t; // Represents time in milliseconds. // Utilities for command line flags and environment variables. // Macro for referencing flags. #if !defined(GTEST_FLAG) #define GTEST_FLAG_NAME_(name) gtest_##name #define GTEST_FLAG(name) FLAGS_gtest_##name #endif // !defined(GTEST_FLAG) // Pick a command line flags implementation. #if GTEST_HAS_ABSL // Macros for defining flags. #define GTEST_DEFINE_bool_(name, default_val, doc) \ ABSL_FLAG(bool, GTEST_FLAG_NAME_(name), default_val, doc) #define GTEST_DEFINE_int32_(name, default_val, doc) \ ABSL_FLAG(int32_t, GTEST_FLAG_NAME_(name), default_val, doc) #define GTEST_DEFINE_string_(name, default_val, doc) \ ABSL_FLAG(std::string, GTEST_FLAG_NAME_(name), default_val, doc) // Macros for declaring flags. #define GTEST_DECLARE_bool_(name) \ ABSL_DECLARE_FLAG(bool, GTEST_FLAG_NAME_(name)) #define GTEST_DECLARE_int32_(name) \ ABSL_DECLARE_FLAG(int32_t, GTEST_FLAG_NAME_(name)) #define GTEST_DECLARE_string_(name) \ ABSL_DECLARE_FLAG(std::string, GTEST_FLAG_NAME_(name)) #define GTEST_FLAG_SAVER_ ::absl::FlagSaver #define GTEST_FLAG_GET(name) ::absl::GetFlag(GTEST_FLAG(name)) #define GTEST_FLAG_SET(name, value) \ (void)(::absl::SetFlag(&GTEST_FLAG(name), value)) #define GTEST_USE_OWN_FLAGFILE_FLAG_ 0 #else // GTEST_HAS_ABSL // Macros for defining flags. #define GTEST_DEFINE_bool_(name, default_val, doc) \ namespace testing { \ GTEST_API_ bool GTEST_FLAG(name) = (default_val); \ } \ static_assert(true, "no-op to require trailing semicolon") #define GTEST_DEFINE_int32_(name, default_val, doc) \ namespace testing { \ GTEST_API_ std::int32_t GTEST_FLAG(name) = (default_val); \ } \ static_assert(true, "no-op to require trailing semicolon") #define GTEST_DEFINE_string_(name, default_val, doc) \ namespace testing { \ GTEST_API_ ::std::string GTEST_FLAG(name) = (default_val); \ } \ static_assert(true, "no-op to require trailing semicolon") // Macros for declaring flags. #define GTEST_DECLARE_bool_(name) \ namespace testing { \ GTEST_API_ extern bool GTEST_FLAG(name); \ } \ static_assert(true, "no-op to require trailing semicolon") #define GTEST_DECLARE_int32_(name) \ namespace testing { \ GTEST_API_ extern std::int32_t GTEST_FLAG(name); \ } \ static_assert(true, "no-op to require trailing semicolon") #define GTEST_DECLARE_string_(name) \ namespace testing { \ GTEST_API_ extern ::std::string GTEST_FLAG(name); \ } \ static_assert(true, "no-op to require trailing semicolon") #define GTEST_FLAG_SAVER_ ::testing::internal::GTestFlagSaver #define GTEST_FLAG_GET(name) ::testing::GTEST_FLAG(name) #define GTEST_FLAG_SET(name, value) (void)(::testing::GTEST_FLAG(name) = value) #define GTEST_USE_OWN_FLAGFILE_FLAG_ 1 #endif // GTEST_HAS_ABSL // Thread annotations #if !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_) #define GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks) #define GTEST_LOCK_EXCLUDED_(locks) #endif // !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_) // Parses 'str' for a 32-bit signed integer. If successful, writes the result // to *value and returns true; otherwise leaves *value unchanged and returns // false. GTEST_API_ bool ParseInt32(const Message& src_text, const char* str, int32_t* value); // Parses a bool/int32_t/string from the environment variable // corresponding to the given Google Test flag. bool BoolFromGTestEnv(const char* flag, bool default_val); GTEST_API_ int32_t Int32FromGTestEnv(const char* flag, int32_t default_val); std::string OutputFlagAlsoCheckEnvVar(); const char* StringFromGTestEnv(const char* flag, const char* default_val); } // namespace internal } // namespace testing #if !defined(GTEST_INTERNAL_DEPRECATED) // Internal Macro to mark an API deprecated, for googletest usage only // Usage: class GTEST_INTERNAL_DEPRECATED(message) MyClass or // GTEST_INTERNAL_DEPRECATED(message) <return_type> myFunction(); Every usage of // a deprecated entity will trigger a warning when compiled with // `-Wdeprecated-declarations` option (clang, gcc, any __GNUC__ compiler). // For msvc /W3 option will need to be used // Note that for 'other' compilers this macro evaluates to nothing to prevent // compilations errors. #if defined(_MSC_VER) #define GTEST_INTERNAL_DEPRECATED(message) __declspec(deprecated(message)) #elif defined(__GNUC__) #define GTEST_INTERNAL_DEPRECATED(message) __attribute__((deprecated(message))) #else #define GTEST_INTERNAL_DEPRECATED(message) #endif #endif // !defined(GTEST_INTERNAL_DEPRECATED) #if GTEST_HAS_ABSL // Always use absl::any for UniversalPrinter<> specializations if googletest // is built with absl support. #define GTEST_INTERNAL_HAS_ANY 1 #include "absl/types/any.h" namespace testing { namespace internal { using Any = ::absl::any; } // namespace internal } // namespace testing #else #ifdef __has_include #if __has_include(<any>) && __cplusplus >= 201703L // Otherwise for C++17 and higher use std::any for UniversalPrinter<> // specializations. #define GTEST_INTERNAL_HAS_ANY 1 #include <any> namespace testing { namespace internal { using Any = ::std::any; } // namespace internal } // namespace testing // The case where absl is configured NOT to alias std::any is not // supported. #endif // __has_include(<any>) && __cplusplus >= 201703L #endif // __has_include #endif // GTEST_HAS_ABSL #if GTEST_HAS_ABSL // Always use absl::optional for UniversalPrinter<> specializations if // googletest is built with absl support. #define GTEST_INTERNAL_HAS_OPTIONAL 1 #include "absl/types/optional.h" namespace testing { namespace internal { template <typename T> using Optional = ::absl::optional<T>; inline ::absl::nullopt_t Nullopt() { return ::absl::nullopt; } } // namespace internal } // namespace testing #else #ifdef __has_include #if __has_include(<optional>) && __cplusplus >= 201703L // Otherwise for C++17 and higher use std::optional for UniversalPrinter<> // specializations. #define GTEST_INTERNAL_HAS_OPTIONAL 1 #include <optional> namespace testing { namespace internal { template <typename T> using Optional = ::std::optional<T>; inline ::std::nullopt_t Nullopt() { return ::std::nullopt; } } // namespace internal } // namespace testing // The case where absl is configured NOT to alias std::optional is not // supported. #endif // __has_include(<optional>) && __cplusplus >= 201703L #endif // __has_include #endif // GTEST_HAS_ABSL #if GTEST_HAS_ABSL // Always use absl::string_view for Matcher<> specializations if googletest // is built with absl support. #define GTEST_INTERNAL_HAS_STRING_VIEW 1 #include "absl/strings/string_view.h" namespace testing { namespace internal { using StringView = ::absl::string_view; } // namespace internal } // namespace testing #else #ifdef __has_include #if __has_include(<string_view>) && __cplusplus >= 201703L // Otherwise for C++17 and higher use std::string_view for Matcher<> // specializations. #define GTEST_INTERNAL_HAS_STRING_VIEW 1 #include <string_view> namespace testing { namespace internal { using StringView = ::std::string_view; } // namespace internal } // namespace testing // The case where absl is configured NOT to alias std::string_view is not // supported. #endif // __has_include(<string_view>) && __cplusplus >= 201703L #endif // __has_include #endif // GTEST_HAS_ABSL #if GTEST_HAS_ABSL // Always use absl::variant for UniversalPrinter<> specializations if googletest // is built with absl support. #define GTEST_INTERNAL_HAS_VARIANT 1 #include "absl/types/variant.h" namespace testing { namespace internal { template <typename... T> using Variant = ::absl::variant<T...>; } // namespace internal } // namespace testing #else #ifdef __has_include #if __has_include(<variant>) && __cplusplus >= 201703L // Otherwise for C++17 and higher use std::variant for UniversalPrinter<> // specializations. #define GTEST_INTERNAL_HAS_VARIANT 1 #include <variant> namespace testing { namespace internal { template <typename... T> using Variant = ::std::variant<T...>; } // namespace internal } // namespace testing // The case where absl is configured NOT to alias std::variant is not supported. #endif // __has_include(<variant>) && __cplusplus >= 201703L #endif // __has_include #endif // GTEST_HAS_ABSL #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
{'content_hash': '2c339fd6703fa4f5c2b2e8ad4b10fcad', 'timestamp': '', 'source': 'github', 'line_count': 2413, 'max_line_length': 80, 'avg_line_length': 36.32034811438044, 'alnum_prop': 0.6916397576476763, 'repo_name': 'aws/aws-sdk-cpp', 'id': 'd59c519fc7e3df2db80ceeb26de5a05e9f15994a', 'size': '87641', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'testing-resources/include/aws/external/gtest/internal/gtest-port.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '309797'}, {'name': 'C++', 'bytes': '476866144'}, {'name': 'CMake', 'bytes': '1245180'}, {'name': 'Dockerfile', 'bytes': '11688'}, {'name': 'HTML', 'bytes': '8056'}, {'name': 'Java', 'bytes': '413602'}, {'name': 'Python', 'bytes': '79245'}, {'name': 'Shell', 'bytes': '9246'}]}
/* * 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. */ package com.facebook.presto.sql.planner.plan; import com.facebook.presto.sql.planner.Symbol; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import javax.annotation.concurrent.Immutable; import java.util.List; @Immutable public class RemoteSourceNode extends PlanNode { private final List<PlanFragmentId> sourceFragmentIds; private final List<Symbol> outputs; @JsonCreator public RemoteSourceNode( @JsonProperty("id") PlanNodeId id, @JsonProperty("sourceFragmentIds") List<PlanFragmentId> sourceFragmentIds, @JsonProperty("outputs") List<Symbol> outputs) { super(id); Preconditions.checkNotNull(outputs, "outputs is null"); this.sourceFragmentIds = sourceFragmentIds; this.outputs = ImmutableList.copyOf(outputs); } public RemoteSourceNode(PlanNodeId id, PlanFragmentId sourceFragmentId, List<Symbol> outputs) { this(id, ImmutableList.of(sourceFragmentId), outputs); } @Override public List<PlanNode> getSources() { return ImmutableList.of(); } @Override @JsonProperty("outputs") public List<Symbol> getOutputSymbols() { return outputs; } @JsonProperty("sourceFragmentIds") public List<PlanFragmentId> getSourceFragmentIds() { return sourceFragmentIds; } @Override public <C, R> R accept(PlanVisitor<C, R> visitor, C context) { return visitor.visitRemoteSource(this, context); } }
{'content_hash': '8fe001191ddb0ac43d38cf73ee0a06ea', 'timestamp': '', 'source': 'github', 'line_count': 76, 'max_line_length': 97, 'avg_line_length': 29.30263157894737, 'alnum_prop': 0.7085765603951504, 'repo_name': 'bd-dev-mobileum/presto', 'id': '5d8d26ddceaf046163ff33a6659073a314a3c018', 'size': '2227', 'binary': False, 'copies': '37', 'ref': 'refs/heads/proteum_master_0.105', 'path': 'presto-main/src/main/java/com/facebook/presto/sql/planner/plan/RemoteSourceNode.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '16543'}, {'name': 'HTML', 'bytes': '43984'}, {'name': 'Java', 'bytes': '11499800'}, {'name': 'JavaScript', 'bytes': '1431'}, {'name': 'Makefile', 'bytes': '6819'}, {'name': 'PLSQL', 'bytes': '3849'}, {'name': 'Python', 'bytes': '4481'}, {'name': 'SQLPL', 'bytes': '6363'}, {'name': 'Shell', 'bytes': '12902'}]}
// // MPNativeCache.h // MoPub // // Copyright (c) 2014 MoPub. All rights reserved. // #import <Foundation/Foundation.h> @interface MPNativeCache : NSObject + (instancetype)sharedCache; /* * Do NOT call any of the following methods on the main thread, potentially lengthy wait for disk IO */ - (BOOL)cachedDataExistsForKey:(NSString *)key; - (NSData *)retrieveDataForKey:(NSString *)key; - (void)storeData:(NSData *)data forKey:(NSString *)key; - (void)removeAllDataFromCache; - (void)setInMemoryCacheEnabled:(BOOL)enabled; @end
{'content_hash': '41e03dacacc1b4f3badadf10a3ced73f', 'timestamp': '', 'source': 'github', 'line_count': 23, 'max_line_length': 100, 'avg_line_length': 23.434782608695652, 'alnum_prop': 0.7291280148423006, 'repo_name': 'LawrenceHan/iOS-project-playground', 'id': '10762e72ec66cb1715394144a84310eb0e7bd98e', 'size': '539', 'binary': False, 'copies': '45', 'ref': 'refs/heads/master', 'path': 'AutoSizingCellTest/HomePwner/HomePwner/Vendor/MoPubSDK/Native Ads/Internal/MPNativeCache.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Awk', 'bytes': '478'}, {'name': 'C', 'bytes': '313417'}, {'name': 'C++', 'bytes': '1976805'}, {'name': 'CSS', 'bytes': '16017'}, {'name': 'DTrace', 'bytes': '3708'}, {'name': 'HTML', 'bytes': '645689'}, {'name': 'JavaScript', 'bytes': '138236'}, {'name': 'Metal', 'bytes': '4464'}, {'name': 'Objective-C', 'bytes': '14856610'}, {'name': 'Objective-C++', 'bytes': '2017738'}, {'name': 'Ruby', 'bytes': '13122'}, {'name': 'Shell', 'bytes': '180624'}, {'name': 'Swift', 'bytes': '1517280'}]}
// The MIT License (MIT) // // Copyright (c) 2017 Smart&Soft // // 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. using System; using System.Windows.Media; namespace ModernApp4Me.WP8.Util { /// <summary> /// A toolbox, that handle <see cref="Color"/> transformations and manipulations. /// </summary> /// /// <author>Ludovic ROLAND</author> /// <since>2014.03.24</since> public static class M4MColorToolbox { /// <summary> /// Converts an hexadecimal color to a <see cref="SolidColorBrush"/>. /// </summary> /// <param name="hexColor">the hexadecimal color code</param> /// <returns>the <see cref="SolidColorBrush"/> equivalent to the hexadecimal code</returns> public static SolidColorBrush ColorFromHex(string hexColor) { return new SolidColorBrush( Color.FromArgb( Convert.ToByte(hexColor.Substring(1, 2), 16), Convert.ToByte(hexColor.Substring(3, 2), 16), Convert.ToByte(hexColor.Substring(5, 2), 16), Convert.ToByte(hexColor.Substring(7, 2), 16) ) ); } } }
{'content_hash': '0c50f23b288cc0645cb7e809d0018695', 'timestamp': '', 'source': 'github', 'line_count': 57, 'max_line_length': 99, 'avg_line_length': 39.08771929824562, 'alnum_prop': 0.6651705565529623, 'repo_name': 'smartnsoft/ModernApp4Me', 'id': 'bd0dd529ee77e0bb0d6e50c248a8352e82584800', 'size': '2230', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'ModernApp4Me.WP8/Util/M4MColorToolbox.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '16140'}, {'name': 'C#', 'bytes': '308551'}, {'name': 'CSS', 'bytes': '32796'}, {'name': 'HTML', 'bytes': '3709716'}, {'name': 'JavaScript', 'bytes': '70054'}, {'name': 'PHP', 'bytes': '11914'}]}
 namespace Apache.Ignite.Core.Impl.Binary.IO { using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Text; /// <summary> /// Stream capable of working with binary objects. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] internal unsafe interface IBinaryStream : IDisposable { /// <summary> /// Write bool. /// </summary> /// <param name="val">Bool value.</param> void WriteBool(bool val); /// <summary> /// Read bool. /// </summary> /// <returns>Bool value.</returns> bool ReadBool(); /// <summary> /// Write bool array. /// </summary> /// <param name="val">Bool array.</param> void WriteBoolArray(bool[] val); /// <summary> /// Read bool array. /// </summary> /// <param name="cnt">Count.</param> /// <returns>Bool array.</returns> bool[] ReadBoolArray(int cnt); /// <summary> /// Write byte. /// </summary> /// <param name="val">Byte value.</param> void WriteByte(byte val); /// <summary> /// Read byte. /// </summary> /// <returns>Byte value.</returns> byte ReadByte(); /// <summary> /// Write byte array. /// </summary> /// <param name="val">Byte array.</param> void WriteByteArray(byte[] val); /// <summary> /// Read byte array. /// </summary> /// <param name="cnt">Count.</param> /// <returns>Byte array.</returns> byte[] ReadByteArray(int cnt); /// <summary> /// Write short. /// </summary> /// <param name="val">Short value.</param> void WriteShort(short val); /// <summary> /// Read short. /// </summary> /// <returns>Short value.</returns> short ReadShort(); /// <summary> /// Write short array. /// </summary> /// <param name="val">Short array.</param> void WriteShortArray(short[] val); /// <summary> /// Read short array. /// </summary> /// <param name="cnt">Count.</param> /// <returns>Short array.</returns> short[] ReadShortArray(int cnt); /// <summary> /// Write char. /// </summary> /// <param name="val">Char value.</param> void WriteChar(char val); /// <summary> /// Read char. /// </summary> /// <returns>Char value.</returns> char ReadChar(); /// <summary> /// Write char array. /// </summary> /// <param name="val">Char array.</param> void WriteCharArray(char[] val); /// <summary> /// Read char array. /// </summary> /// <param name="cnt">Count.</param> /// <returns>Char array.</returns> char[] ReadCharArray(int cnt); /// <summary> /// Write int. /// </summary> /// <param name="val">Int value.</param> void WriteInt(int val); /// <summary> /// Write int to specific position. /// </summary> /// <param name="writePos">Position.</param> /// <param name="val">Value.</param> void WriteInt(int writePos, int val); /// <summary> /// Read int. /// </summary> /// <returns>Int value.</returns> int ReadInt(); /// <summary> /// Write int array. /// </summary> /// <param name="val">Int array.</param> void WriteIntArray(int[] val); /// <summary> /// Read int array. /// </summary> /// <param name="cnt">Count.</param> /// <returns>Int array.</returns> int[] ReadIntArray(int cnt); /// <summary> /// Write long. /// </summary> /// <param name="val">Long value.</param> void WriteLong(long val); /// <summary> /// Read long. /// </summary> /// <returns>Long value.</returns> long ReadLong(); /// <summary> /// Write long array. /// </summary> /// <param name="val">Long array.</param> void WriteLongArray(long[] val); /// <summary> /// Read long array. /// </summary> /// <param name="cnt">Count.</param> /// <returns>Long array.</returns> long[] ReadLongArray(int cnt); /// <summary> /// Write float. /// </summary> /// <param name="val">Float value.</param> void WriteFloat(float val); /// <summary> /// Read float. /// </summary> /// <returns>Float value.</returns> float ReadFloat(); /// <summary> /// Write float array. /// </summary> /// <param name="val">Float array.</param> void WriteFloatArray(float[] val); /// <summary> /// Read float array. /// </summary> /// <param name="cnt">Count.</param> /// <returns>Float array.</returns> float[] ReadFloatArray(int cnt); /// <summary> /// Write double. /// </summary> /// <param name="val">Double value.</param> void WriteDouble(double val); /// <summary> /// Read double. /// </summary> /// <returns>Double value.</returns> double ReadDouble(); /// <summary> /// Write double array. /// </summary> /// <param name="val">Double array.</param> void WriteDoubleArray(double[] val); /// <summary> /// Read double array. /// </summary> /// <param name="cnt">Count.</param> /// <returns>Double array.</returns> double[] ReadDoubleArray(int cnt); /// <summary> /// Write string. /// </summary> /// <param name="chars">Characters.</param> /// <param name="charCnt">Char count.</param> /// <param name="byteCnt">Byte count.</param> /// <param name="encoding">Encoding.</param> /// <returns>Amounts of bytes written.</returns> int WriteString(char* chars, int charCnt, int byteCnt, Encoding encoding); /// <summary> /// Write arbitrary data. /// </summary> /// <param name="src">Source array.</param> /// <param name="off">Offset</param> /// <param name="cnt">Count.</param> void Write(byte[] src, int off, int cnt); /// <summary> /// Read arbitrary data. /// </summary> /// <param name="dest">Destination array.</param> /// <param name="off">Offset.</param> /// <param name="cnt">Count.</param> /// <returns>Amount of bytes read.</returns> void Read(byte[] dest, int off, int cnt); /// <summary> /// Write arbitrary data. /// </summary> /// <param name="src">Source.</param> /// <param name="cnt">Count.</param> void Write(byte* src, int cnt); /// <summary> /// Read arbitrary data. /// </summary> /// <param name="dest">Destination.</param> /// <param name="cnt">Count.</param> void Read(byte* dest, int cnt); /// <summary> /// Position. /// </summary> int Position { get; } /// <summary> /// Gets remaining bytes in the stream. /// </summary> /// <value>Remaining bytes.</value> int Remaining { get; } /// <summary> /// Gets underlying array, avoiding copying. /// </summary> /// <returns>Underlying array.</returns> byte[] GetArray(); /// <summary> /// Gets a value indicating whether this instance can return underlying array without copying. /// </summary> bool CanGetArray { get; } /// <summary> /// Gets underlying data in a new array. /// </summary> /// <returns>New array with data.</returns> byte[] GetArrayCopy(); /// <summary> /// Check whether array passed as argument is the same as the stream hosts. /// </summary> /// <param name="arr">Array.</param> /// <returns><c>True</c> if they are same.</returns> bool IsSameArray(byte[] arr); /// <summary> /// Seek to the given position. /// </summary> /// <param name="offset">Offset.</param> /// <param name="origin">Seek origin.</param> /// <returns>Position.</returns> int Seek(int offset, SeekOrigin origin); /// <summary> /// Applies specified processor to the raw stream data. /// </summary> T Apply<TArg, T>(IBinaryStreamProcessor<TArg, T> proc, TArg arg); /// <summary> /// Flushes the data to underlying storage. /// </summary> void Flush(); } }
{'content_hash': '697cf932e9e876cfbc9b0abbf72a4813', 'timestamp': '', 'source': 'github', 'line_count': 320, 'max_line_length': 102, 'avg_line_length': 28.559375, 'alnum_prop': 0.4879089615931721, 'repo_name': 'apache/ignite', 'id': '32bca5e4759e1fea7b055c9f063c79d7e5f9f5d9', 'size': '9943', 'binary': False, 'copies': '25', 'ref': 'refs/heads/master', 'path': 'modules/platforms/dotnet/Apache.Ignite.Core/Impl/Binary/Io/IBinaryStream.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '55118'}, {'name': 'C', 'bytes': '7601'}, {'name': 'C#', 'bytes': '7749887'}, {'name': 'C++', 'bytes': '4522204'}, {'name': 'CMake', 'bytes': '54473'}, {'name': 'Dockerfile', 'bytes': '12067'}, {'name': 'FreeMarker', 'bytes': '18828'}, {'name': 'HTML', 'bytes': '14341'}, {'name': 'Java', 'bytes': '50663394'}, {'name': 'JavaScript', 'bytes': '1085'}, {'name': 'Jinja', 'bytes': '33639'}, {'name': 'Makefile', 'bytes': '932'}, {'name': 'PHP', 'bytes': '11079'}, {'name': 'PowerShell', 'bytes': '9247'}, {'name': 'Python', 'bytes': '336150'}, {'name': 'Scala', 'bytes': '425434'}, {'name': 'Shell', 'bytes': '311819'}]}
require 'spec_helper' describe CompareService do let(:project) { create(:project, :repository) } let(:user) { create(:user) } let(:service) { described_class.new(project, 'feature') } describe '#execute' do context 'compare with base, like feature...fix' do subject { service.execute(project, 'fix', straight: false) } it { expect(subject.diffs.size).to eq(1) } end context 'straight compare, like feature..fix' do subject { service.execute(project, 'fix', straight: true) } it { expect(subject.diffs.size).to eq(3) } end end end
{'content_hash': '1f693c61a592f90e8f44734cb99a9e45', 'timestamp': '', 'source': 'github', 'line_count': 21, 'max_line_length': 66, 'avg_line_length': 27.857142857142858, 'alnum_prop': 0.652991452991453, 'repo_name': 't-zuehlsdorff/gitlabhq', 'id': '9e15eae8c13201c49bcfe1193d8f53e9474e4158', 'size': '585', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'spec/services/compare_service_spec.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '558077'}, {'name': 'Gherkin', 'bytes': '115565'}, {'name': 'HTML', 'bytes': '1054670'}, {'name': 'JavaScript', 'bytes': '2305094'}, {'name': 'Ruby', 'bytes': '12136142'}, {'name': 'Shell', 'bytes': '27385'}, {'name': 'Vue', 'bytes': '222165'}]}
package adoc2odt; import org.asciidoctor.ast.AbstractBlock; import org.asciidoctor.ast.Document; import org.jruby.runtime.builtin.IRubyObject; import java.util.List; public interface TableCell extends AbstractBlock { List<String> lines(); IRubyObject inner_document(); String style(); String text(); int colspan(); int rowspan(); }
{'content_hash': '7fde1f1f253ef2bd9cc615c585dc81d0', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 50, 'avg_line_length': 16.59090909090909, 'alnum_prop': 0.7205479452054795, 'repo_name': 'rzabini/adoc2odt', 'id': '0a1e0b053b879203d020ae3de33ec21aa3d76ac0', 'size': '365', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/adoc2odt/TableCell.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Groovy', 'bytes': '12679'}, {'name': 'Java', 'bytes': '67344'}]}
IF(NOT DEFINED CMAKE_INSTALL_PREFIX) SET(CMAKE_INSTALL_PREFIX "/opt/ros/groovy") ENDIF(NOT DEFINED CMAKE_INSTALL_PREFIX) STRING(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}") # Set the install configuration name. IF(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME) IF(BUILD_TYPE) STRING(REGEX REPLACE "^[^A-Za-z0-9_]+" "" CMAKE_INSTALL_CONFIG_NAME "${BUILD_TYPE}") ELSE(BUILD_TYPE) SET(CMAKE_INSTALL_CONFIG_NAME "Release") ENDIF(BUILD_TYPE) MESSAGE(STATUS "Install configuration: \"${CMAKE_INSTALL_CONFIG_NAME}\"") ENDIF(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME) # Set the component getting installed. IF(NOT CMAKE_INSTALL_COMPONENT) IF(COMPONENT) MESSAGE(STATUS "Install component: \"${COMPONENT}\"") SET(CMAKE_INSTALL_COMPONENT "${COMPONENT}") ELSE(COMPONENT) SET(CMAKE_INSTALL_COMPONENT) ENDIF(COMPONENT) ENDIF(NOT CMAKE_INSTALL_COMPONENT) # Install shared libraries without execute permission? IF(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE) SET(CMAKE_INSTALL_SO_NO_EXE "1") ENDIF(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE) IF(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified") FILE(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/bin" TYPE PROGRAM FILES "/wg/stor5/mpomarlan/ompl/scripts/ompl_benchmark_statistics.py") ENDIF(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
{'content_hash': '492fbb413fab62301351e28990b3db62', 'timestamp': '', 'source': 'github', 'line_count': 35, 'max_line_length': 140, 'avg_line_length': 39.885714285714286, 'alnum_prop': 0.7406876790830945, 'repo_name': 'mpomarlan/ompl_slprm', 'id': '48a3efb1e038833e240b6c645278bc59e1a5c8f8', 'size': '1487', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'build/scripts/cmake_install.cmake', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C', 'bytes': '135078'}, {'name': 'C++', 'bytes': '2776858'}, {'name': 'JavaScript', 'bytes': '69501'}, {'name': 'Objective-C', 'bytes': '22385'}, {'name': 'PHP', 'bytes': '11620'}, {'name': 'Python', 'bytes': '152447'}, {'name': 'Shell', 'bytes': '4562'}]}
package org.killbill.billing.payment.core.sm; import org.killbill.billing.payment.api.PaymentApiException; public class VoidInitiated extends PaymentLeavingStateCallback { public VoidInitiated(final PaymentAutomatonDAOHelper daoHelper, final PaymentStateContext paymentStateContext) throws PaymentApiException { super(daoHelper, paymentStateContext); } }
{'content_hash': 'a857f756b698d84eb65358f78309a9d9', 'timestamp': '', 'source': 'github', 'line_count': 12, 'max_line_length': 143, 'avg_line_length': 31.333333333333332, 'alnum_prop': 0.8191489361702128, 'repo_name': 'gsanblas/Prueba', 'id': 'b5bbb6592b9097897f2360b5fa69c63f21dd90fb', 'size': '1041', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'payment/src/main/java/org/killbill/billing/payment/core/sm/VoidInitiated.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '90220'}, {'name': 'Java', 'bytes': '6774160'}, {'name': 'JavaScript', 'bytes': '528124'}, {'name': 'Ruby', 'bytes': '6721'}, {'name': 'Shell', 'bytes': '14196'}]}
<?xml version="1.0" ?><!DOCTYPE TS><TS language="sr" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About Worldcoin</source> <translation>О Worldcoin-у</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;Worldcoin&lt;/b&gt; version</source> <translation>&lt;b&gt;Worldcoin&lt;/b&gt; верзија</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source> <translation type="unfinished"/> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Dr. Kimoto Chan</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Адресар</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>Кликните два пута да промените адресу и/или етикету</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Прави нову адресу</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Копира изабрану адресу на системски клипборд</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>&amp;Нова адреса</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your Worldcoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation>Ово су Ваше Worldcoin адресе за примање уплата. Можете да сваком пошиљаоцу дате другачију адресу да би пратили ко је вршио уплате.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>Prikaži &amp;QR kod</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a Worldcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified Worldcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Избриши</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your Worldcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation type="unfinished"/> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>Извоз података из адресара</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Зарезом одвојене вредности (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Грешка током извоза</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Није могуће писати у фајл %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Етикета</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Адреса</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(без етикете)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Унесите лозинку</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Нова лозинка</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Поновите нову лозинку</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Унесите нову лозинку за приступ новчанику.&lt;br/&gt;Молимо Вас да лозинка буде &lt;b&gt;10 или више насумице одабраних знакова&lt;/b&gt;, или &lt;b&gt;осам или више речи&lt;/b&gt;.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Шифровање новчаника</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Ова акција захтева лозинку Вашег новчаника да би га откључала.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Откључавање новчаника</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Ова акција захтева да унесете лозинку да би дешифловала новчаник.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Дешифровање новчаника</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Промена лозинке</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Унесите стару и нову лозинку за шифровање новчаника.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Одобрите шифровање новчаника</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR WORLDCOINS&lt;/b&gt;!</source> <translation>Упозорење: Ако се ваш новчаник шифрује а потом изгубите лозинкзу, ви ћете &lt;b&gt;ИЗГУБИТИ СВЕ WORLDCOIN-Е&lt;/b&gt;!</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Да ли сте сигурни да желите да се новчаник шифује?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation type="unfinished"/> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>Новчаник је шифрован</translation> </message> <message> <location line="-56"/> <source>Worldcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your worldcoins from being stolen by malware infecting your computer.</source> <translation>Worldcoin će se sad zatvoriti da bi završio proces enkripcije. Zapamti da enkripcija tvog novčanika ne može u potpunosti da zaštiti tvoje worldcoine da ne budu ukradeni od malawarea koji bi inficirao tvoj kompjuter.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Неуспело шифровање новчаника</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Настала је унутрашња грешка током шифровања новчаника. Ваш новчаник није шифрован.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>Лозинке које сте унели се не подударају.</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>Неуспело откључавање новчаника</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Лозинка коју сте унели за откључавање новчаника је нетачна.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Неуспело дешифровање новчаника</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Лозинка за приступ новчанику је успешно промењена.</translation> </message> </context> <context> <name>WorldcoinGUI</name> <message> <location filename="../worldcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation type="unfinished"/> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation>Синхронизација са мрежом у току...</translation> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation>&amp;Општи преглед</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Погледајте општи преглед новчаника</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>&amp;Трансакције</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Претражите историјат трансакција</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>Уредите запамћене адресе и њихове етикете</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>Прегледајте листу адреса на којима прихватате уплате</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>I&amp;zlaz</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Напустите програм</translation> </message> <message> <location line="+4"/> <source>Show information about Worldcoin</source> <translation>Прегледајте информације о Worldcoin-у</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>О &amp;Qt-у</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Прегледајте информације о Qt-у</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>П&amp;оставке...</translation> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Шифровање новчаника...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Backup новчаника</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>Промени &amp;лозинку...</translation> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation type="unfinished"/> </message> <message> <location line="-347"/> <source>Send coins to a Worldcoin address</source> <translation>Пошаљите новац на Worldcoin адресу</translation> </message> <message> <location line="+49"/> <source>Modify configuration options for Worldcoin</source> <translation>Изаберите могућности worldcoin-а</translation> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Мењање лозинке којом се шифрује новчаник</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation type="unfinished"/> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation type="unfinished"/> </message> <message> <location line="-165"/> <location line="+530"/> <source>Worldcoin</source> <translation type="unfinished"/> </message> <message> <location line="-530"/> <source>Wallet</source> <translation>новчаник</translation> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>&amp;About Worldcoin</source> <translation>&amp;О Worldcoin-у</translation> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Sign messages with your Worldcoin addresses to prove you own them</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified Worldcoin addresses</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;Фајл</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>&amp;Подешавања</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>П&amp;омоћ</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>Трака са картицама</translation> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location line="+47"/> <source>Worldcoin client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to Worldcoin network</source> <translation><numerusform>%n активна веза са Worldcoin мрежом</numerusform><numerusform>%n активне везе са Worldcoin мрежом</numerusform><numerusform>%n активних веза са Worldcoin мрежом</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>Ажурно</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>Ажурирање у току...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>Послана трансакција</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>Придошла трансакција</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Datum: %1⏎ Iznos: %2⏎ Tip: %3⏎ Adresa: %4⏎</translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid Worldcoin address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Новчаник јс &lt;b&gt;шифрован&lt;/b&gt; и тренутно &lt;b&gt;откључан&lt;/b&gt;</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Новчаник јс &lt;b&gt;шифрован&lt;/b&gt; и тренутно &lt;b&gt;закључан&lt;/b&gt;</translation> </message> <message> <location filename="../worldcoin.cpp" line="+111"/> <source>A fatal error occurred. Worldcoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Измени адресу</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Етикета</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Адреса</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>New sending address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>Унешена адреса &quot;%1&quot; се већ налази у адресару.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid Worldcoin address.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Немогуће откључати новчаник.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation type="unfinished"/> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>Worldcoin-Qt</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>version</source> <translation>верзија</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Korišćenje:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>UI options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Поставке</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Automatically start Worldcoin after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Start Worldcoin on system login</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Automatically open the Worldcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Connect to the Worldcoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting Worldcoin.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Јединица за приказивање износа:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Whether to show Worldcoin addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation type="unfinished"/> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting Worldcoin.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation type="unfinished"/> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Форма</translation> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Worldcoin network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-124"/> <source>Balance:</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>Непотврђено:</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>новчаник</translation> </message> <message> <location line="+107"/> <source>Immature:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Недавне трансакције&lt;/b&gt;</translation> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation type="unfinished"/> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start worldcoin: click-to-pay handler</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>Zatraži isplatu</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>Iznos:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>&amp;Етикета</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>Poruka:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>&amp;Snimi kao...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+339"/> <source>N/A</source> <translation type="unfinished"/> </message> <message> <location line="-217"/> <source>Client version</source> <translation type="unfinished"/> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation type="unfinished"/> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Network</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Block chain</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Last block time</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show the Worldcoin-Qt help message to get a list with possible Worldcoin command-line options.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation type="unfinished"/> </message> <message> <location line="-260"/> <source>Build date</source> <translation type="unfinished"/> </message> <message> <location line="-104"/> <source>Worldcoin - Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Worldcoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Open the Worldcoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation type="unfinished"/> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the Worldcoin RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+124"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Слање новца</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>Ukloni sva polja sa transakcijama</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Balance:</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>123.456 WDC</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Потврди акцију слања</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>&amp;Пошаљи</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>Да ли сте сигурни да желите да пошаљете %1?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation>и</translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>Форма</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. MNS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation type="unfinished"/> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>&amp;Етикета</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation>Izaberite adresu iz adresara</translation> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a Worldcoin address (e.g. MNS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Unesite Worldcoin adresu (n.pr. MNS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. MNS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation type="unfinished"/> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation type="unfinished"/> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Signature</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this Worldcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. MNS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified Worldcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a Worldcoin address (e.g. MNS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Unesite Worldcoin adresu (n.pr. MNS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Enter Worldcoin signature</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation type="unfinished"/> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>Dr. Kimoto Chan</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>Otvorite do %1</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/nepotvrdjeno</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 potvrde</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>datum</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Generated</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation type="unfinished"/> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>label</source> <translation>етикета</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation type="unfinished"/> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Net amount</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Message</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Comment</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Debug information</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Transaction</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Amount</source> <translation>iznos</translation> </message> <message> <location line="+1"/> <source>true</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>false</source> <translation type="unfinished"/> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, nije još uvek uspešno emitovan</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>nepoznato</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>detalji transakcije</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Ovaj odeljak pokazuje detaljan opis transakcije</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>datum</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>tip</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Адреса</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>iznos</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>Otvoreno do %1</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>Offline * van mreže (%1 potvrdjenih)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>Nepotvrdjeno (%1 of %2 potvrdjenih)</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>Potvrdjena (%1 potvrdjenih)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Ovaj blok nije primljen od ostalih čvorova (nodova) i verovatno neće biti prihvaćen!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Generisan ali nije prihvaćen</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>Primljen sa</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Primljeno od</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Poslat ka</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Isplata samom sebi</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Minirano</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(n/a)</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Status vaše transakcije. Predjite mišem preko ovog polja da bi ste videli broj konfirmacija</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Datum i vreme primljene transakcije.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Tip transakcije</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Destinacija i adresa transakcije</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Iznos odbijen ili dodat balansu.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>Sve</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Danas</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>ove nedelje</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Ovog meseca</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Prošlog meseca</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Ove godine</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Opseg...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Primljen sa</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Poslat ka</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Vama - samom sebi</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Minirano</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Drugi</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Navedite adresu ili naziv koji bi ste potražili</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Min iznos</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>kopiraj adresu</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>kopiraj naziv</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>kopiraj iznos</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>promeni naziv</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation>Izvezi podatke o transakcijama</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Зарезом одвојене вредности (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Potvrdjen</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>datum</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>tip</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Етикета</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Адреса</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>iznos</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Грешка током извоза</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Није могуће писати у фајл %1.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Opseg:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>do</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation>Слање новца</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation type="unfinished"/> </message> </context> <context> <name>worldcoin-core</name> <message> <location filename="../worldcoinstrings.cpp" line="+94"/> <source>Worldcoin version</source> <translation>Worldcoin верзија</translation> </message> <message> <location line="+102"/> <source>Usage:</source> <translation>Korišćenje:</translation> </message> <message> <location line="-29"/> <source>Send command to -server or worldcoind</source> <translation>Pošalji naredbu na -server ili worldcoinid </translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>Listaj komande</translation> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation>Zatraži pomoć za komande</translation> </message> <message> <location line="+24"/> <source>Options:</source> <translation>Opcije</translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: worldcoin.conf)</source> <translation>Potvrdi željeni konfiguracioni fajl (podrazumevani:worldcoin.conf)</translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: worldcoind.pid)</source> <translation>Konkretizuj pid fajl (podrazumevani: worldcoind.pid)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Gde je konkretni data direktorijum </translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation type="unfinished"/> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 7951 or testnet: 17951)</source> <translation>Slušaj konekcije na &lt;port&gt; (default: 7951 or testnet: 17951)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Održavaj najviše &lt;n&gt; konekcija po priključku (default: 125) </translation> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 7950 or testnet: 17950)</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation>Prihvati komandnu liniju i JSON-RPC komande</translation> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation>Radi u pozadini kao daemon servis i prihvati komande</translation> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation>Koristi testnu mrežu</translation> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </message> <message> <location line="-80"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=worldcoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;Worldcoin Alert&quot; [email protected] </source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. Worldcoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong Worldcoin will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation type="unfinished"/> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation type="unfinished"/> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>SSL options: (see the Worldcoin Wiki for SSL setup instructions)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>System error: </source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation>Korisničko ime za JSON-RPC konekcije</translation> </message> <message> <location line="+4"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation>Lozinka za JSON-RPC konekcije</translation> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Dozvoli JSON-RPC konekcije sa posebne IP adrese</translation> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Pošalji komande to nodu koji radi na &lt;ip&gt; (default: 127.0.0.1)</translation> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation type="unfinished"/> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation type="unfinished"/> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Odredi veličinu zaštićenih ključeva na &lt;n&gt; (default: 100)</translation> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Ponovo skeniraj lanac blokova za nedostajuće transakcije iz novčanika</translation> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Koristi OpenSSL (https) za JSON-RPC konekcije</translation> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>privatni ključ za Server (podrazumevan: server.pem)</translation> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Prihvatljive cifre (podrazumevano: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation> </message> <message> <location line="+165"/> <source>This help message</source> <translation>Ova poruka Pomoći</translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation type="unfinished"/> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation type="unfinished"/> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation type="unfinished"/> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation>učitavam adrese....</translation> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of Worldcoin</source> <translation type="unfinished"/> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart Worldcoin to complete</source> <translation type="unfinished"/> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation type="unfinished"/> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>Učitavam blok indeksa...</translation> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation type="unfinished"/> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. Worldcoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation>Новчаник се учитава...</translation> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation>Ponovo skeniram...</translation> </message> <message> <location line="-57"/> <source>Done loading</source> <translation>Završeno učitavanje</translation> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation type="unfinished"/> </message> <message> <location line="-74"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation type="unfinished"/> </message> </context> </TS>
{'content_hash': '5ef8cf90ef9ba9b20cb9aa0c9d3ae435', 'timestamp': '', 'source': 'github', 'line_count': 2919, 'max_line_length': 395, 'avg_line_length': 34.68824940047961, 'alnum_prop': 0.5993185521702632, 'repo_name': 'Bluejudy/worldcoin', 'id': 'bf4e548837e70f0389dff33742a7e9a8527f1058', 'size': '103441', 'binary': False, 'copies': '6', 'ref': 'refs/heads/dev-0.8', 'path': 'src/qt/locale/worldcoin_sr.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '91744'}, {'name': 'C++', 'bytes': '2583266'}, {'name': 'CSS', 'bytes': '1127'}, {'name': 'Objective-C++', 'bytes': '5634'}, {'name': 'Python', 'bytes': '69717'}, {'name': 'Shell', 'bytes': '9702'}, {'name': 'TypeScript', 'bytes': '5313907'}]}
var es = require('event-stream'); var domain = require('domain'); // __Module Definition__ var decorator = module.exports = function (options, protect) { // __Protected Module Members__ // A utility method for ordering through streams. protect.pipeline = function (handler) { var streams = []; var d = domain.create(); d.on('error', handler); return function (transmute) { // If it's a stream, add it to the reserve pipeline. if (transmute && (transmute.writable || transmute.readable)) { streams.push(transmute); d.add(transmute); return transmute; } // If it's a function, create a map stream with it. if (transmute) { transmute = es.map(transmute); streams.push(transmute); d.add(transmute); return transmute; } // If called without arguments, return a pipeline linking all streams. if (streams.length > 0) { return d.run(function() { return es.pipeline.apply(es, streams); }); } // But, if no streams were added, just pass back a through stream. return d.run(es.through); }; }; // __Middleware__ // Create the pipeline interface the user interacts with. this.request(function (request, response, next) { request.baucis.incoming = protect.pipeline(next); request.baucis.outgoing = protect.pipeline(next); next(); }); };
{'content_hash': '5c411fe70806fc1fe2ffb55fbf428ebc', 'timestamp': '', 'source': 'github', 'line_count': 43, 'max_line_length': 76, 'avg_line_length': 33.02325581395349, 'alnum_prop': 0.6176056338028169, 'repo_name': 'mmoulton/baucis', 'id': '51e00068330a2479342e4b6dda7b7b95805e4b0b', 'size': '1440', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'Controller/request/streams.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '150093'}]}
import { Object3D, Quaternion, Vector3 } from 'three'; const _translationObject = new Vector3(); const _quaternionObject = new Quaternion(); const _scaleObject = new Vector3(); const _translationWorld = new Vector3(); const _quaternionWorld = new Quaternion(); const _scaleWorld = new Vector3(); class Gyroscope extends Object3D { constructor() { super(); } updateMatrixWorld( force ) { this.matrixAutoUpdate && this.updateMatrix(); // update matrixWorld if ( this.matrixWorldNeedsUpdate || force ) { if ( this.parent !== null ) { this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); this.matrixWorld.decompose( _translationWorld, _quaternionWorld, _scaleWorld ); this.matrix.decompose( _translationObject, _quaternionObject, _scaleObject ); this.matrixWorld.compose( _translationWorld, _quaternionObject, _scaleWorld ); } else { this.matrixWorld.copy( this.matrix ); } this.matrixWorldNeedsUpdate = false; force = true; } // update children for ( let i = 0, l = this.children.length; i < l; i ++ ) { this.children[ i ].updateMatrixWorld( force ); } } } export { Gyroscope };
{'content_hash': 'e249f41500b26d9163460740e6c3b91f', 'timestamp': '', 'source': 'github', 'line_count': 66, 'max_line_length': 83, 'avg_line_length': 18.0, 'alnum_prop': 0.6826599326599326, 'repo_name': 'looeee/three.js', 'id': '9269c9c819112da69212d171d1cda1a59971c813', 'size': '1188', 'binary': False, 'copies': '15', 'ref': 'refs/heads/dev', 'path': 'examples/jsm/misc/Gyroscope.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '50622'}, {'name': 'HTML', 'bytes': '5586533'}, {'name': 'JavaScript', 'bytes': '7453817'}, {'name': 'Roff', 'bytes': '478172'}]}
using System.Collections.Generic; using System.Collections.ObjectModel; using System.Net.Http.Headers; using System.Web.Http.Description; namespace WebChat.Access.Areas.HelpPage.Models { /// <summary> /// The model that represents an API displayed on the help page. /// </summary> public class HelpPageApiModel { /// <summary> /// Initializes a new instance of the <see cref="HelpPageApiModel"/> class. /// </summary> public HelpPageApiModel() { SampleRequests = new Dictionary<MediaTypeHeaderValue, object>(); SampleResponses = new Dictionary<MediaTypeHeaderValue, object>(); ErrorMessages = new Collection<string>(); } /// <summary> /// Gets or sets the <see cref="ApiDescription"/> that describes the API. /// </summary> public ApiDescription ApiDescription { get; set; } /// <summary> /// Gets the sample requests associated with the API. /// </summary> public IDictionary<MediaTypeHeaderValue, object> SampleRequests { get; private set; } /// <summary> /// Gets the sample responses associated with the API. /// </summary> public IDictionary<MediaTypeHeaderValue, object> SampleResponses { get; private set; } /// <summary> /// Gets the error messages associated with this model. /// </summary> public Collection<string> ErrorMessages { get; private set; } } }
{'content_hash': 'f09d840e08b2d1aa43934752a60e8a73', 'timestamp': '', 'source': 'github', 'line_count': 43, 'max_line_length': 94, 'avg_line_length': 35.02325581395349, 'alnum_prop': 0.6254980079681275, 'repo_name': 'niki-funky/Telerik_Academy', 'id': 'f96ccb2c77777b4fc98005dbfc08616ede15caea', 'size': '1506', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'Web Development/Web_and_Cloud/Teamwork_WebChat/WebChat.Access/Areas/HelpPage/Models/HelpPageApiModel.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '2773'}, {'name': 'C#', 'bytes': '4074086'}, {'name': 'CSS', 'bytes': '850276'}, {'name': 'JavaScript', 'bytes': '5915582'}, {'name': 'PowerShell', 'bytes': '785001'}, {'name': 'Puppet', 'bytes': '329334'}]}
export interface IPropertyPaneLoggingFieldProps { label?: string; description?: string; value: any; retrieve?: Function; }
{'content_hash': 'fa203cf68c66d1a591fccfa6aac55c5e', 'timestamp': '', 'source': 'github', 'line_count': 6, 'max_line_length': 49, 'avg_line_length': 23.0, 'alnum_prop': 0.7028985507246377, 'repo_name': 'SharePoint/sp-dev-fx-webparts', 'id': '83dc814cde4afe6316476c4535d86f086d75b24d', 'size': '138', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'samples/react-search/src/webparts/searchSpfx/PropertyPaneControls/IPropertyPaneLoggingFieldProps.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '15907'}, {'name': 'JavaScript', 'bytes': '11884'}, {'name': 'TypeScript', 'bytes': '57801'}]}
package alluxio.client.block.stream; import alluxio.client.file.options.InStreamOptions; import alluxio.metrics.MetricKey; import alluxio.metrics.MetricsSystem; import alluxio.network.protocol.databuffer.DataBuffer; import alluxio.network.protocol.databuffer.NioDataBuffer; import alluxio.proto.dataserver.Protocol; import alluxio.util.IdUtils; import alluxio.worker.block.BlockWorker; import alluxio.worker.block.io.BlockReader; import com.google.common.base.Preconditions; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Objects; import javax.annotation.concurrent.NotThreadSafe; /** * A data reader that reads from a worker in the same process of this client directly. * * This data reader is similar to read from local worker via {@link GrpcDataReader} * except that all communication with the local worker is via internal method call * instead of external RPC frameworks. */ @NotThreadSafe public final class BlockWorkerDataReader implements DataReader { /** The block reader to read from the local worker block or UFS block. */ private final BlockReader mReader; private final long mEnd; private final long mChunkSize; private long mPos; private boolean mClosed; /** * Creates an instance of {@link BlockWorkerDataReader}. * * @param reader the block reader to read data from * @param offset the offset * @param len the length to read * @param chunkSize the chunk size */ private BlockWorkerDataReader(BlockReader reader, long offset, long len, long chunkSize) { Objects.requireNonNull(reader); mReader = reader; Preconditions.checkArgument(chunkSize > 0); mPos = offset; mEnd = Math.min(mReader.getLength(), offset + len); mChunkSize = chunkSize; } @Override public DataBuffer readChunk() throws IOException { if (mPos >= mEnd) { return null; } ByteBuffer buffer = mReader.read(mPos, Math.min(mChunkSize, mEnd - mPos)); DataBuffer dataBuffer = new NioDataBuffer(buffer, buffer.remaining()); mPos += dataBuffer.getLength(); MetricsSystem.counter(MetricKey.WORKER_BYTES_READ_DIRECT.getName()).inc(dataBuffer.getLength()); MetricsSystem.meter(MetricKey.WORKER_BYTES_READ_DIRECT_THROUGHPUT.getName()) .mark(dataBuffer.getLength()); return dataBuffer; } @Override public long pos() { return mPos; } @Override public void close() throws IOException { if (mClosed) { return; } if (mReader != null) { mReader.close(); } mClosed = true; } /** * Factory class to create {@link BlockWorkerDataReader}s. */ @NotThreadSafe public static class Factory implements DataReader.Factory { private final long mChunkSize; private final BlockWorker mBlockWorker; private final long mBlockId; private final boolean mIsPositionShort; private final Protocol.OpenUfsBlockOptions mOpenUfsBlockOptions; /** * Creates an instance of {@link Factory}. * * @param blockWorker the block worker * @param blockId the block ID * @param chunkSize chunk size in bytes * @param options the instream options */ public Factory(BlockWorker blockWorker, long blockId, long chunkSize, InStreamOptions options) { Preconditions.checkNotNull(blockWorker); mBlockId = blockId; mBlockWorker = blockWorker; mChunkSize = chunkSize; mIsPositionShort = options.getPositionShort(); mOpenUfsBlockOptions = options.getOpenUfsBlockOptions(blockId); } @Override public DataReader create(long offset, long len) throws IOException { try { BlockReader reader = mBlockWorker.createBlockReader(IdUtils.createSessionId(), mBlockId, offset, mIsPositionShort, mOpenUfsBlockOptions); return new BlockWorkerDataReader(reader, offset, len, mChunkSize); } catch (Exception e) { throw new IOException(e); } } @Override public void close() throws IOException {} } }
{'content_hash': '96b6ecf091862cd4345f69d42f62496f', 'timestamp': '', 'source': 'github', 'line_count': 130, 'max_line_length': 100, 'avg_line_length': 30.892307692307693, 'alnum_prop': 0.7161354581673307, 'repo_name': 'wwjiang007/alluxio', 'id': '8a2af1769899f9ec91760b8b0cee1bd3f4e83c6d', 'size': '4528', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'core/client/fs/src/main/java/alluxio/client/block/stream/BlockWorkerDataReader.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '7326'}, {'name': 'C++', 'bytes': '47930'}, {'name': 'Dockerfile', 'bytes': '12161'}, {'name': 'Go', 'bytes': '290492'}, {'name': 'HTML', 'bytes': '3412'}, {'name': 'Handlebars', 'bytes': '3633'}, {'name': 'Java', 'bytes': '15480256'}, {'name': 'JavaScript', 'bytes': '9992'}, {'name': 'Makefile', 'bytes': '6312'}, {'name': 'Mustache', 'bytes': '22163'}, {'name': 'Python', 'bytes': '18085'}, {'name': 'Roff', 'bytes': '5919'}, {'name': 'Ruby', 'bytes': '15044'}, {'name': 'SCSS', 'bytes': '12027'}, {'name': 'Shell', 'bytes': '278579'}, {'name': 'TypeScript', 'bytes': '324466'}]}
<?php namespace Craft; class FruitLinkItService extends BaseApplicationComponent { protected $plugin; protected $pluginHandle; protected $commerce; public function __construct() { $this->plugin = craft()->plugins->getPlugin('fruitlinkit'); $this->pluginHandle = $this->plugin->getPluginHandle(); $this->commerce = craft()->plugins->getPlugin('commerce', true); } public function getLinkItElementSources() { return array( 'entry' => $this->_getElementSourcesWithUrls(ElementType::Entry), 'asset' => $this->_getElementSourcesWithUrls(ElementType::Asset), 'category' => $this->_getElementSourcesWithUrls(ElementType::Category), 'product' => $this->commerce && $this->commerce->isInstalled ? $this->_getElementSourcesWithUrls('Commerce_Product') : null, ); } // Gives plugins a chance to add their own element types public function getThirdPartyElementTypes() { $elementTypesConfig = array(); $allPluginElementTypes = craft()->plugins->call('linkit_registerElementTypes'); foreach ($allPluginElementTypes as $pluginElementType) { $elementTypesConfig = array_merge($elementTypesConfig, $pluginElementType); } return $elementTypesConfig; } private function _getElementSourcesWithUrls($type) { $elementType = craft()->elements->getElementType($type); $sources = array(); foreach ($elementType->getSources() as $key => $source) { if (!isset($source['heading'])) { $sources[] = array( 'label' => $source['label'], 'value' => $key ); } } return $sources; } }
{'content_hash': '6a3b6e191c0f6b0c4df92117240a8826', 'timestamp': '', 'source': 'github', 'line_count': 62, 'max_line_length': 136, 'avg_line_length': 29.241935483870968, 'alnum_prop': 0.5945945945945946, 'repo_name': 'fruitstudios/LinkIt', 'id': 'cf74752e5c8f58c02ece33e06b48cab926e14d07', 'size': '2027', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'fruitlinkit/services/FruitLinkItService.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '491'}, {'name': 'HTML', 'bytes': '8672'}, {'name': 'JavaScript', 'bytes': '1045'}, {'name': 'PHP', 'bytes': '33284'}]}
<?php declare(strict_types = 1); namespace Zortje\MVC\Tests\Model\Table\Entity; use Zortje\MVC\Model\Table\Entity\EntityFactory; use Zortje\MVC\Tests\Model\Fixture\CarEntity; /** * Class EntityFactoryTest * * @package Zortje\MVC\Tests\Model\Table\Entity * * @coversDefaultClass Zortje\MVC\Model\Table\Entity\EntityFactory */ class EntityFactoryTest extends \PHPUnit_Framework_TestCase { /** * @covers ::__construct */ public function testConstruct() { $entityFactory = new EntityFactory('Foo'); $reflector = new \ReflectionClass($entityFactory); $property = $reflector->getProperty('entityClass'); $property->setAccessible(true); $this->assertSame('Foo', $property->getValue($entityFactory)); } /** * @covers ::createFromArray */ public function testCreateFromArray() { $entityFactory = new EntityFactory(CarEntity::class); /** * @var CarEntity $carEntity */ $carEntity = $entityFactory->createFromArray([ 'id' => 'bb4250bc-8258-11e6-ae22-56b6b6499611', 'make' => 'Ford', 'model' => 'Model T', 'horsepower' => '20', 'doors' => 'TWO', 'released' => '1908-10-01', 'modified' => '2015-05-03 00:53:42', 'created' => '2015-05-03 00:53:42' ]); $this->assertFalse($carEntity->isAltered()); $this->assertSame(CarEntity::class, get_class($carEntity)); $this->assertSame('bb4250bc-8258-11e6-ae22-56b6b6499611', $carEntity->get('id')); $this->assertSame('Ford', $carEntity->get('make')); $this->assertSame('Model T', $carEntity->get('model')); $this->assertSame(20, $carEntity->get('horsepower')); $this->assertEquals(new \DateTime('1908-10-01'), $carEntity->get('released')); $this->assertEquals(new \DateTime('2015-05-03 00:53:42'), $carEntity->get('modified')); $this->assertEquals(new \DateTime('2015-05-03 00:53:42'), $carEntity->get('created')); } }
{'content_hash': '1edda34090d6e90a66e55cc272071196', 'timestamp': '', 'source': 'github', 'line_count': 64, 'max_line_length': 95, 'avg_line_length': 33.0, 'alnum_prop': 0.5880681818181818, 'repo_name': 'zortje/mvc', 'id': '97d3934d1700edff4c3b7cde8a4c4a3886bd8acf', 'size': '2112', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'tests/Model/Table/Entity/EntityFactoryTest.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'PHP', 'bytes': '175083'}]}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_07) on Sun Sep 20 02:53:08 CST 2015 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>Uses of Class org.xclcharts.common.PointHelper</title> <meta name="date" content="2015-09-20"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.xclcharts.common.PointHelper"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../org/xclcharts/common/PointHelper.html" title="class in org.xclcharts.common">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/xclcharts/common/class-use/PointHelper.html" target="_top">Frames</a></li> <li><a href="PointHelper.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.xclcharts.common.PointHelper" class="title">Uses of Class<br>org.xclcharts.common.PointHelper</h2> </div> <div class="classUseContainer">No usage of org.xclcharts.common.PointHelper</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../org/xclcharts/common/PointHelper.html" title="class in org.xclcharts.common">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/xclcharts/common/class-use/PointHelper.html" target="_top">Frames</a></li> <li><a href="PointHelper.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{'content_hash': '361ad5cd61914f736f60b896c029175a', 'timestamp': '', 'source': 'github', 'line_count': 116, 'max_line_length': 127, 'avg_line_length': 35.525862068965516, 'alnum_prop': 0.6187818490657607, 'repo_name': 'billhello/XCL-Charts', 'id': 'd92091d92841d27ea5a49da6ac526ba35f6f14e1', 'size': '4121', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'doc/org/xclcharts/common/class-use/PointHelper.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '1'}, {'name': 'C++', 'bytes': '1'}, {'name': 'Java', 'bytes': '1290500'}]}
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd"> <import resource="classpath:jpa-tx-context.xml" /> <context:component-scan base-package="ca.isda.service"/> </beans>
{'content_hash': 'ae7e23b2d828906e4c22a6361c23181b', 'timestamp': '', 'source': 'github', 'line_count': 12, 'max_line_length': 140, 'avg_line_length': 52.583333333333336, 'alnum_prop': 0.7083993660855784, 'repo_name': 'vollov/isda-java', 'id': '551b4b7f06fbc66e86247aedec78d4196eb1e108', 'size': '631', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/webapp/WEB-INF/spring/root-context.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '3350'}, {'name': 'HTML', 'bytes': '9973'}, {'name': 'Java', 'bytes': '109539'}]}
namespace base { namespace debug { bool BeingDebugged() { return false; } void BreakDebugger() { _exit(1); } } // namespace debug } // namespace base
{'content_hash': '86772d741d1544d567028c18e6d89066', 'timestamp': '', 'source': 'github', 'line_count': 10, 'max_line_length': 24, 'avg_line_length': 16.8, 'alnum_prop': 0.6190476190476191, 'repo_name': 'kku1993/libquic', 'id': 'bd03fad51838111d4b5d136f973c782ada0ad337', 'size': '224', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'src/base/debug/debugger.cc', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Assembly', 'bytes': '187232'}, {'name': 'C', 'bytes': '5998742'}, {'name': 'C++', 'bytes': '7099361'}, {'name': 'CMake', 'bytes': '52252'}, {'name': 'CSS', 'bytes': '870'}, {'name': 'Go', 'bytes': '544017'}, {'name': 'Makefile', 'bytes': '294632'}, {'name': 'Objective-C', 'bytes': '20209'}, {'name': 'Objective-C++', 'bytes': '33832'}, {'name': 'Perl', 'bytes': '1821585'}, {'name': 'Python', 'bytes': '55638'}, {'name': 'Shell', 'bytes': '12070'}]}
package timeseries import ( "log" "time" ) type level struct { clock Clock granularity time.Duration length int end time.Time oldest int newest int buckets []int } func newLevel(clock Clock, granularity time.Duration, length int) level { level := level{clock: clock, granularity: granularity, length: length} level.init() return level } func (l *level) init() { buckets := make([]int, l.length) l.buckets = buckets l.clear(time.Time{}) } func (l *level) clear(time time.Time) { l.oldest = 1 l.newest = 0 l.end = time.Truncate(l.granularity) for i := range l.buckets { l.buckets[i] = 0 } } func (l *level) duration() time.Duration { return l.granularity*time.Duration(l.length) - l.granularity } func (l *level) earliest() time.Time { return l.end.Add(-l.duration()) } func (l *level) latest() time.Time { return l.end } func (l *level) increaseAtTime(amount int, time time.Time) { difference := l.end.Sub(time.Truncate(l.granularity)) if difference < 0 { // this cannot be negative because we advance before // can at least be 0 log.Println("level.increaseTime was called with a time in the future") } // l.length-1 because the newest element is always l.length-1 away from oldest steps := (l.length - 1) - int(difference/l.granularity) index := (l.oldest + steps) % l.length l.buckets[index] += amount } func (l *level) advance(target time.Time) { if !l.end.Before(target) { return } for target.After(l.end) { l.end = l.end.Add(l.granularity) l.buckets[l.oldest] = 0 l.newest = l.oldest l.oldest = (l.oldest + 1) % len(l.buckets) } } // TODO: find a better way to handle latest parameter // The parameter is used to avoid the overlap computation if end overlaps with the current time. // Probably will find away when implementing redis version. func (l *level) sumInterval(start, end time.Time, latest time.Time) float64 { if start.Before(l.earliest()) { start = l.earliest() } if end.After(l.latest()) { end = l.latest() } idx := 0 // this is how many time steps start is away from earliest startSteps := start.Sub(l.earliest()) / l.granularity idx += int(startSteps) currentTime := l.earliest() currentTime = currentTime.Add(startSteps * l.granularity) sum := 0.0 for idx < l.length && currentTime.Before(end) { nextTime := currentTime.Add(l.granularity) if nextTime.After(latest) { nextTime = latest } if nextTime.Before(start) { // the case nextTime.Before(start) happens when start is after latest // therefore we don't have data and can return break } count := float64(l.buckets[(l.oldest+idx)%l.length]) if currentTime.Before(start) || nextTime.After(end) { // current bucket overlaps time range overlapStart := max(currentTime, start) overlapEnd := min(nextTime, end) overlap := overlapEnd.Sub(overlapStart).Seconds() / l.granularity.Seconds() count *= overlap } sum += count idx++ currentTime = currentTime.Add(l.granularity) } return sum } func min(t1, t2 time.Time) time.Time { if t1.Before(t2) { return t1 } return t2 } func max(t1, t2 time.Time) time.Time { if t1.After(t2) { return t1 } return t2 }
{'content_hash': '49751380fe0405c30630d91f91bcbff8', 'timestamp': '', 'source': 'github', 'line_count': 132, 'max_line_length': 96, 'avg_line_length': 24.174242424242426, 'alnum_prop': 0.6784706988404888, 'repo_name': 'codesuki/go-time-series', 'id': '8dd41b0c81e64c123c37b2b48b0d4e86a52f1990', 'size': '3191', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'level.go', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Go', 'bytes': '18432'}]}
<?php namespace Drupal\block_test\Plugin\Condition; use Drupal\Core\Condition\ConditionPluginBase; /** * Provides a 'missing_schema' condition. * * @Condition( * id = "missing_schema", * label = @Translation("Missing schema"), * ) */ class MissingSchema extends ConditionPluginBase { /** * {@inheritdoc} */ public function evaluate() { return FALSE; } /** * {@inheritdoc} */ public function summary() { return 'Summary'; } }
{'content_hash': 'afcc3ec484c89a24a4c396f705ce8afe', 'timestamp': '', 'source': 'github', 'line_count': 31, 'max_line_length': 49, 'avg_line_length': 15.290322580645162, 'alnum_prop': 0.6286919831223629, 'repo_name': 'kgatjens/d8_vm_vagrant', 'id': '977374c513233a425a7eb1c81f22ed86ce6026fe', 'size': '474', 'binary': False, 'copies': '452', 'ref': 'refs/heads/master', 'path': 'project/core/modules/block/tests/modules/block_test/src/Plugin/Condition/MissingSchema.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '9038'}, {'name': 'CSS', 'bytes': '962176'}, {'name': 'HTML', 'bytes': '1769288'}, {'name': 'JavaScript', 'bytes': '1302117'}, {'name': 'PHP', 'bytes': '40520904'}, {'name': 'PLpgSQL', 'bytes': '2020'}, {'name': 'PowerShell', 'bytes': '471'}, {'name': 'Ruby', 'bytes': '6985'}, {'name': 'Shell', 'bytes': '85027'}]}
module TimeSlotHelper DAYS = %w(Monday Tuesday Wednesday Thursday Friday Saturday Sunday) # Option tags whose text is the day name, and value is the day's integer. # # E.g., <option value="0">Monday</option>...<option value="6">Sunday</option> def day_select_option_tags options_for_select DAYS.map.with_index.to_a end # Convert the day of the week from an integer to the name of a day. # # E.g., day_label(0) #=> 'Monday' # day_label(0, max_length: 3) #=> 'Mon' # # @param [Integer] day the day of the week, where Monday is 0 # @param [Hash<Symbol, Integer>] max_length the number of characters to keep # from the beginning of the day's full name; if nil, don't truncate the name def day_label(day, max_length: nil) full_name = DAYS[day] max_length ? full_name[0..(max_length - 1)] : full_name end # The day of the week that the given time slot starts. # # @param [TimeSlot] time_slot the time slot in question # @param [Hash<Symbol, Integer>] max_length the number of characters to keep # from the beginning of the day's full name; if nil, don't truncate the name def time_slot_day_label(time_slot, max_length: 0) day_label time_slot.day, max_length: max_length end # The range of a time slot displayed when viewing time slots. # # E.g., '10:00am - 11:00am (EDT)' def time_slot_range_label(time_slot) start_time = time_slot.start_time.to_s(:time_slot_short) end_time = time_slot.end_time.to_s(:time_slot_long) "#{start_time} - #{end_time}" end # The range of a time slot displayed when viewing recitation conflicts. # # E.g., '10:00am - 11:00am (EDT)' def conflict_time_period_label(start_time, end_time) start_time = TimeSlot.time_at(start_time).to_s(:time_slot_short) end_time = TimeSlot.time_at(end_time).to_s(:time_slot_long) "#{start_time} - #{end_time}" end # A string representation of the time slot. # # E.g., 'Monday 10:00am (EDT) - 11:00am (EDT)' # # @param [TimeSlot] time_slot the time slot in question # @param [Hash<Symbol, Integer>] max_length the number of characters to keep # from the beginning of the slot's day; if nil, don't truncate the name def time_slot_label(time_slot, max_length: 0) day = content_tag :span, class: 'time-slot-day' do time_slot_day_label time_slot, max_length: max_length end time = content_tag :span, class: 'time-slot-period' do time_slot_range_label time_slot end safe_join [day, time], ' ' end # The number of hours and minutes in a time slot. E.g., "1hr 30min" # # We currently support durations from 0 to 23:59 hours. def time_slot_duration(time_slot) diff = time_slot.ends_at - time_slot.starts_at diff += 2400 if diff < 0 hour, minute = diff.divmod 100 result = "#{hour}hr" result << " #{minute}min" unless minute == 0 result end # A checkbox list of time slots you can allot to the given recitation. # # TODO(spark008): Make this less ugly. Maybe extract into a partial. def time_slot_check_box_list_tag(recitation) name = 'recitation_section[time_slot_ids][]' blank = hidden_field_tag name, '' check_box_list_items = recitation.course.time_slots.map do |ts| is_checked = recitation.time_slots.include? ts content_tag :li do safe_join([ check_box_tag(name, ts.id, is_checked, id: ts.id), label_tag(ts.id, time_slot_label(ts)) ]) end end content_tag :ul, id: 'recitation_section_time_slot_ids', class: 'no-bullet' do safe_join [blank, check_box_list_items] end end end
{'content_hash': '6958106f3b7024c38cad06b507517d1c', 'timestamp': '', 'source': 'github', 'line_count': 100, 'max_line_length': 80, 'avg_line_length': 36.34, 'alnum_prop': 0.6554760594386351, 'repo_name': 'spark008/igor', 'id': '1a18c90adc91e27d10fe2e83e35bcddc0b02d207', 'size': '3634', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'app/helpers/time_slot_helper.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '40088'}, {'name': 'CoffeeScript', 'bytes': '17159'}, {'name': 'HTML', 'bytes': '163914'}, {'name': 'JavaScript', 'bytes': '662'}, {'name': 'Python', 'bytes': '10765'}, {'name': 'Ruby', 'bytes': '770036'}, {'name': 'Shell', 'bytes': '569'}]}
<?php session_start(); include_once "templates/base.php"; /************************************************ Make an API request authenticated with a service account. ************************************************/ require_once realpath(dirname(__FILE__) . '/../autoload.php'); /************************************************ ATTENTION: Fill in these values! You can get them by creating a new Service Account in the API console. Be sure to store the key file somewhere you can get to it - though in real operations you'd want to make sure it wasn't accessible from the webserver! The name is the email address value provided as part of the service account (not your address!) Make sure the Books API is enabled on this account as well, or the call will fail. ************************************************/ $client_id = '<YOUR_CLIENT_ID>'; //Client ID $service_account_name = ''; //Email Address $key_file_location = ''; //key.p12 echo pageHeader("Service Account Access"); if ($client_id == '<YOUR_CLIENT_ID>' || !strlen($service_account_name) || !strlen($key_file_location)) { echo missingServiceAccountDetailsWarning(); } $client = new Google_Client(); $client->setApplicationName("Client_Library_Examples"); $service = new Google_Service_Books($client); /************************************************ If we have an access token, we can carry on. Otherwise, we'll get one with the help of an assertion credential. In other examples the list of scopes was managed by the Client, but here we have to list them manually. We also supply the service account ************************************************/ if (isset($_SESSION['service_token'])) { $client->setAccessToken($_SESSION['service_token']); } $key = file_get_contents($key_file_location); $cred = new Google_Auth_AssertionCredentials( $service_account_name, array('https://www.googleapis.com/auth/books'), $key ); $client->setAssertionCredentials($cred); if($client->getAuth()->isAccessTokenExpired()) { $client->getAuth()->refreshTokenWithAssertion($cred); } $_SESSION['service_token'] = $client->getAccessToken(); /************************************************ We're just going to make the same call as in the simple query as an example. ************************************************/ $optParams = array('filter' => 'free-ebooks'); $results = $service->volumes->listVolumes('Henry David Thoreau', $optParams); echo "<h3>Results Of Call:</h3>"; foreach ($results as $item) { echo $item['volumeInfo']['title'], "<br /> \n"; } echo pageFooter(__FILE__);
{'content_hash': 'c0f9beb4000670305c8220b5a0ea662e', 'timestamp': '', 'source': 'github', 'line_count': 74, 'max_line_length': 77, 'avg_line_length': 35.270270270270274, 'alnum_prop': 0.5973180076628353, 'repo_name': 'Bhalinder/test', 'id': '7478d8c9ea42a3f1ad5297731d2300d6a90b3c80', 'size': '3204', 'binary': False, 'copies': '12', 'ref': 'refs/heads/master', 'path': 'examples/service-account.php', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '1924'}, {'name': 'PHP', 'bytes': '4561153'}]}
V.509 ===== Validate your X.509 certificate implementations. **This is just an idea and nothing works now. Stay tuned!** ### The Idea The idea is to check TLS clients, especially non-browser clients to see how well they validate the X.509 certificates. This is the certificate which the server provides to the client, to prove itself. X.509 is the standard used by these certificates. There are some interesting test cases that can conducted to know how well these certificates are validated. The following RFC proposal does a very good job of listing down all the important checks to be made. [RFC 6125 - Representation and Verification of Domain-Based Application Service Identity within Internet Public Key Infrastructure Using X.509 (PKIX) Certificates in the Context of Transport Layer Security](https://tools.ietf.org/html/rfc6125) ### Architecture Since the TLS clients are going to be tested for their implementations, we are talking about an heterogeneous environment. The best way to handle this is to expose a form of REST APIs to tell the validation server about the states happening in the client. This includes *START, STOP* etc. The tester has to write custom scripts on the client machine to facilitate, complete testing. Also, the validator knows whenever it presents a certain certificate, that whether it is a good or bad one. That way depending upon the TLS alerts / errors, the validator can know what is going on. The validator is a NodeJS server which listens on a given domain name. Say, **v509.com** . This domain name has to be configured on the client side using /etc/hosts or by having a DNS configuration which sends all traffic to the validator. The Validator requires the host name to start itself( Eg. v509.com). Also, the client has to be configured with a CA which the validator gives. This shall be used only during the testing and can be removed later. The validator should generate certificates on the fly depending upon the test cases and provide it to the client to do the test. ### TODO * Generate custom certificates for the given host name and other X.509 artifacts, from the cert-test-suite. * Make a modular cert-test-suite which specifies the Test Name, X.509 fields, Good / Bad and other constraints. * A REST API which says the validator to START and STOP the scans. * Config scripts to do the dirty job on the client side. ### Existing work * TLSPretense - ### Critics and comments I would love to know your thoughts on what will work and what won't. You should create a new issue with your critics / comments.
{'content_hash': 'b0d45d3cbb837d3f50caeaf9a677d1d5', 'timestamp': '', 'source': 'github', 'line_count': 40, 'max_line_length': 383, 'avg_line_length': 64.625, 'alnum_prop': 0.7802707930367505, 'repo_name': 'skepticfx/v509', 'id': '4a738d79d3f5fdd17eccfa52ded4d066186d0ea8', 'size': '2585', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': []}
package org.marketcetera.strategy; import static org.junit.Assert.*; import static org.marketcetera.module.TestMessages.FLOW_REQUESTER_PROVIDER; import static org.marketcetera.strategy.Status.FAILED; import static org.marketcetera.strategy.Status.RUNNING; import static org.marketcetera.strategy.Status.STOPPED; import java.beans.ExceptionListener; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.lang.management.ManagementFactory; import java.math.BigDecimal; import java.math.RoundingMode; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.util.*; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicLong; import java.util.jar.Manifest; import javax.management.JMX; import javax.management.MBeanServer; import javax.management.ObjectName; import org.apache.commons.lang.SerializationUtils; import org.apache.commons.lang.SystemUtils; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.marketcetera.client.*; import org.marketcetera.client.brokers.BrokerStatus; import org.marketcetera.client.brokers.BrokersStatus; import org.marketcetera.client.users.UserInfo; import org.marketcetera.core.BigDecimalUtils; import org.marketcetera.core.LoggerConfiguration; import org.marketcetera.core.notifications.ServerStatusListener; import org.marketcetera.core.position.PositionKey; import org.marketcetera.event.*; import org.marketcetera.marketdata.DateUtils; import org.marketcetera.marketdata.MarketDataFeedTestBase; import org.marketcetera.marketdata.TestMessages; import org.marketcetera.marketdata.bogus.BogusFeedModuleFactory; import org.marketcetera.module.*; import org.marketcetera.quickfix.FIXVersion; import org.marketcetera.strategy.StrategyModule.ClientFactory; import org.marketcetera.trade.*; import org.marketcetera.trade.Currency; import org.marketcetera.util.log.I18NMessage; import quickfix.Message; import quickfix.field.OrdStatus; import quickfix.field.Side; import quickfix.field.TransactTime; import com.google.common.collect.LinkedHashMultimap; import com.google.common.collect.Multimap; /* $License$ */ /** * Base class for <code>Strategy</code> tests. * * @author <a href="mailto:[email protected]">Colin DuPlantis</a> * @version $Id: StrategyTestBase.java 16888 2014-04-22 18:32:36Z colin $ * @since 1.0.0 */ public class StrategyTestBase extends ModuleTestBase implements Messages { public static final File SAMPLE_STRATEGY_DIR = new File("src" + File.separator + "test" + File.separator + "sample_data", "inputs"); /** * Tuple which describes the location and name of a strategy. * * @author <a href="mailto:[email protected]">Colin DuPlantis</a> * @version $Id: StrategyTestBase.java 16888 2014-04-22 18:32:36Z colin $ * @since 1.0.0 */ public static class StrategyCoordinates { private final File file; private final String name; public static StrategyCoordinates get(File inFile, String inName) { return new StrategyCoordinates(inFile, inName); } private StrategyCoordinates(File inFile, String inName) { file = inFile; name = inName; } /** * Get the file value. * * @return a <code>File</code> value */ public final File getFile() { return file; } /** * Get the name value. * * @return a <code>String</code> value */ public final String getName() { return name; } } /** * A {@link DataReceiver} implementation that stores the data it receives. * * @author <a href="mailto:[email protected]">Colin DuPlantis</a> * @version $Id: StrategyTestBase.java 16888 2014-04-22 18:32:36Z colin $ * @since 1.0.0 */ public static class MockRecorderModule extends Module implements DataReceiver, DataEmitter { /** * indicates if the module should emit execution reports when it receives order objects */ public static boolean shouldSendExecutionReports = true; public static boolean shouldFullyFillOrders = true; public static boolean shouldIgnoreLogMessages = true; public static int ordersReceived = 0; /** * Create a new MockRecorderModule instance. * * @param inURN */ protected MockRecorderModule(ModuleURN inURN) { super(inURN, false); } /* (non-Javadoc) * @see org.marketcetera.module.Module#preStart() */ @Override protected void preStart() throws ModuleException { } /* (non-Javadoc) * @see org.marketcetera.module.Module#preStop() */ @Override protected void preStop() throws ModuleException { } /* (non-Javadoc) * @see org.marketcetera.module.DataReceiver#receiveData(org.marketcetera.module.DataFlowID, java.lang.Object) */ @Override public void receiveData(DataFlowID inFlowID, Object inData) throws UnsupportedDataTypeException, StopDataFlowException { if(inData instanceof LogEvent) { if(shouldIgnoreLogMessages) { return; } } synchronized(data) { data.add(new DataReceived(inFlowID, inData)); } if(inData instanceof OrderSingle) { if(shouldSendExecutionReports) { OrderSingle order = (OrderSingle)inData; try { List<ExecutionReport> executionReports = generateExecutionReports(order); synchronized(subscribers) { for(ExecutionReport executionReport : executionReports) { for(DataEmitterSupport subscriber : subscribers.values()) { subscriber.send(executionReport); } } } } catch (Exception e) { e.printStackTrace(); throw new StopDataFlowException(e, null); } } ordersReceived += 1; } } /* (non-Javadoc) * @see org.marketcetera.module.DataEmitter#cancel(org.marketcetera.module.RequestID) */ @Override public void cancel(DataFlowID inFlowID, RequestID inRequestID) { synchronized(subscribers) { subscribers.remove(inRequestID); } } /* (non-Javadoc) * @see org.marketcetera.module.DataEmitter#requestData(org.marketcetera.module.DataRequest, org.marketcetera.module.DataEmitterSupport) */ @Override public void requestData(DataRequest inRequest, DataEmitterSupport inRequester) throws RequestDataException { synchronized(subscribers) { subscribers.put(inRequester.getRequestID(), inRequester); } } /** * collection of subscribers interested in data emitter by this module */ private final Map<RequestID,DataEmitterSupport> subscribers = new HashMap<RequestID,DataEmitterSupport>(); /** * Resets the collection of data received. */ public void resetDataReceived() { synchronized(data) { data.clear(); } } /** * Returns a copy of the list of the received data. * * @return a <code>list&lt;DataReceived&gt;</code> value */ public List<DataReceived> getDataReceived() { synchronized(data) { return new ArrayList<DataReceived>(data); } } /** * collection of data received by this module */ private final List<DataReceived> data = new ArrayList<DataReceived>(); /** * The {@link ModuleFactory} implementation for {@link MockRecorderModule}. * * @author <a href="mailto:[email protected]">Colin DuPlantis</a> * @version $Id: StrategyTestBase.java 16888 2014-04-22 18:32:36Z colin $ * @since 1.0.0 */ public static class Factory extends ModuleFactory { /** * used to generate unique identifiers for the instance counters */ private static final AtomicLong instanceCounter = new AtomicLong(); /** * provider URN for {@link StrategyDataEmissionModule} */ public static final ModuleURN PROVIDER_URN = new ModuleURN("metc:receiver:system"); public static final Map<ModuleURN,MockRecorderModule> recorders = new HashMap<ModuleURN,MockRecorderModule>(); /** * Create a new Factory instance. */ public Factory() { super(PROVIDER_URN, FLOW_REQUESTER_PROVIDER, true, false); } /* (non-Javadoc) * @see org.marketcetera.module.ModuleFactory#create(java.lang.Object[]) */ @Override public Module create(Object... inParameters) throws ModuleCreationException { MockRecorderModule module = new MockRecorderModule(new ModuleURN(PROVIDER_URN, "mockRecorderModule" + instanceCounter.incrementAndGet())); recorders.put(module.getURN(), module); return module; } } /** * Stores the data received by {@link MockRecorderModule}. * * @author <a href="mailto:[email protected]">Colin DuPlantis</a> * @version $Id: StrategyTestBase.java 16888 2014-04-22 18:32:36Z colin $ * @since 1.0.0 */ public static class DataReceived { /** * the data flow ID of the data received */ private final DataFlowID dataFlowID; /** * the actual data received */ private final Object data; /** * Create a new DataReceived instance. * * @param inDataFlowID a <code>DataFlowID</code> value * @param inData an <code>Object</code> value */ private DataReceived(DataFlowID inDataFlowID, Object inData) { dataFlowID = inDataFlowID; data = inData; } /** * Get the dataFlowID value. * * @return a <code>DataFlowID</code> value */ public DataFlowID getDataFlowID() { return dataFlowID; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return data == null ? "null data" : data.toString(); } /** * Get the data value. * * @return an <code>Object</code> value */ public Object getData() { return data; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((data == null) ? 0 : data.hashCode()); return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; DataReceived other = (DataReceived) obj; if (data == null) { if (other.data != null) return false; } else if (!data.equals(other.data)) return false; return true; } } } /** * A {@link DataEmitter} implementation that emits each type of data a {@link RunningStrategy} can receive. * * @author <a href="mailto:[email protected]">Colin DuPlantis</a> * @version $Id: StrategyTestBase.java 16888 2014-04-22 18:32:36Z colin $ * @since 1.0.0 */ public static class StrategyDataEmissionModule extends Module implements DataEmitter { /** * data to transmit */ private static final List<Object> dataToSend = new ArrayList<Object>(); /** * Gets the data that will be tramsitted. * * @return a <code>List&lt;Object&gt;</code> value */ public static List<Object> getDataToSend() { synchronized(dataToSend) { return dataToSend; } } /** * Rests the data to be transmitted to its default setting. * * @throws Exception if an error occurs */ public static void setDataToSendToDefaults() throws Exception { synchronized(dataToSend) { dataToSend.clear(); dataToSend.add(EventTestBase.generateEquityTradeEvent(System.nanoTime(), System.currentTimeMillis(), new Equity("GOOG"), "Exchange", new BigDecimal("100"), new BigDecimal("10000"))); dataToSend.add(EventTestBase.generateEquityBidEvent(System.nanoTime(), System.currentTimeMillis(), new Equity("GOOG"), "Exchange", new BigDecimal("200"), new BigDecimal("20000"))); dataToSend.add(EventTestBase.generateEquityAskEvent(System.nanoTime(), System.currentTimeMillis(), new Equity("GOOG"), "Exchange", new BigDecimal("200"), new BigDecimal("20000"))); dataToSend.add(EventTestBase.generateDividendEvent()); Message orderCancelReject = FIXVersion.FIX44.getMessageFactory().newOrderCancelReject(); OrderCancelReject cancel = org.marketcetera.trade.Factory.getInstance().createOrderCancelReject(orderCancelReject, null, Originator.Server, null, null); dataToSend.add(cancel); Message executionReport = FIXVersion.FIX44.getMessageFactory().newExecutionReport("orderid", "clOrderID", "execID", OrdStatus.FILLED, Side.BUY, new BigDecimal(100), new BigDecimal(200), new BigDecimal(300), new BigDecimal(400), new BigDecimal(500), new BigDecimal(600), new Equity("Symbol"), "account", "text"); dataToSend.add(org.marketcetera.trade.Factory.getInstance().createExecutionReport(executionReport, new BrokerID("some-broker"), Originator.Server, null, null)); // send an object that doesn't fit one of the categories dataToSend.add(new Date()); } } /** * Create a new MockRecorderModule instance. * * @param inURN */ protected StrategyDataEmissionModule(ModuleURN inURN) { super(inURN, false); } /* (non-Javadoc) * @see org.marketcetera.module.Module#preStart() */ @Override protected void preStart() throws ModuleException { } /* (non-Javadoc) * @see org.marketcetera.module.Module#preStop() */ @Override protected void preStop() throws ModuleException { } /* (non-Javadoc) * @see org.marketcetera.module.DataEmitter#cancel(org.marketcetera.module.RequestID) */ @Override public void cancel(DataFlowID inFlowID, RequestID inRequestID) { // nothing to do here } /* (non-Javadoc) * @see org.marketcetera.module.DataEmitter#requestData(org.marketcetera.module.DataRequest, org.marketcetera.module.DataEmitterSupport) */ @Override public void requestData(DataRequest inRequest, DataEmitterSupport inSupport) throws UnsupportedRequestParameterType, IllegalRequestParameterValue { try { sendDataTypes(inSupport); } catch (Exception e) { e.printStackTrace(); throw new IllegalRequestParameterValue(null, e); } } /** * Sends each type of data a {@link RunningStrategy} must be able to respond to. * * <p>When a new call-back is added to {@link RunningStrategy}, this method should * be expanded to send that data. * * @param inSupport a <code>DataEmitterSupport</code> value to which to send the data * @throws Exception if an error occurs */ private void sendDataTypes(DataEmitterSupport inSupport) throws Exception { synchronized(dataToSend) { for(Object o : dataToSend) { inSupport.send(o); } } } /** * The {@link ModuleFactory} implementation for {@link StrategyDataEmissionModule}. * * @author <a href="mailto:[email protected]">Colin DuPlantis</a> * @version $Id: StrategyTestBase.java 16888 2014-04-22 18:32:36Z colin $ * @since 1.0.0 */ public static class Factory extends ModuleFactory { /** * used to generate unique identifiers for the instance counters */ private static final AtomicLong instanceCounter = new AtomicLong(); /** * provider URN for {@link StrategyDataEmissionModule} */ public static final ModuleURN PROVIDER_URN = new ModuleURN("metc:emitter:system"); /** * Create a new Factory instance. */ public Factory() { super(PROVIDER_URN, FLOW_REQUESTER_PROVIDER, true, false); } /* (non-Javadoc) * @see org.marketcetera.module.ModuleFactory#create(java.lang.Object[]) */ @Override public Module create(Object... inParameters) throws ModuleCreationException { return new StrategyDataEmissionModule(new ModuleURN(PROVIDER_URN, "strategyDataEmissionModule" + instanceCounter.incrementAndGet())); } } } public static class MockClient implements Client { public static class MockClientFactory implements org.marketcetera.client.ClientFactory { /* (non-Javadoc) * @see org.marketcetera.client.ClientFactory#getClient(org.marketcetera.client.ClientParameters) */ @Override public Client getClient(ClientParameters inClientParameters) throws ClientInitException, ConnectionException { return new MockClient(); } } /** * indicates whether calls to {@link #getBrokersStatus()} should fail automatically */ public static boolean getBrokersFails = false; /** * indicates whether calls to {@link #getEquityPositionAsOf(Date, Equity)} should fail automatically */ public static boolean getPositionFails = false; /** * Broker status listeners */ private final Deque<BrokerStatusListener> mBrokerStatusListeners= new LinkedList<BrokerStatusListener>(); /** * indicates whether calls to {@link #addBrokerStatusListener(BrokerStatusListener)} should fail automatically */ public static boolean addBrokerStatusListenerFails = false; /* (non-Javadoc) * @see org.marketcetera.client.Client#addExceptionListener(java.beans.ExceptionListener) */ @Override public void addExceptionListener(ExceptionListener inArg0) { throw new UnsupportedOperationException(); } /* (non-Javadoc) * @see org.marketcetera.client.Client#addReportListener(org.marketcetera.client.ReportListener) */ @Override public void addReportListener(ReportListener inArg0) { throw new UnsupportedOperationException(); } /* (non-Javadoc) * @see org.marketcetera.client.Client#addBrokerStatusListener(org.marketcetera.client.BrokerStatusListener) */ @Override public void addBrokerStatusListener (BrokerStatusListener listener) { if (addBrokerStatusListenerFails) { throw new RuntimeException("This exception is expected"); } synchronized (mBrokerStatusListeners) { mBrokerStatusListeners.addFirst(listener); } } /* (non-Javadoc) * @see org.marketcetera.client.Client#addServerStatusListener(org.marketcetera.client.ServerStatusListener) */ @Override public void addServerStatusListener(ServerStatusListener inArg0) { throw new UnsupportedOperationException(); } /* (non-Javadoc) * @see org.marketcetera.client.Client#close() */ @Override public void close() { throw new UnsupportedOperationException(); } /* (non-Javadoc) * @see org.marketcetera.client.Client#getBrokersStatus() */ @Override public BrokersStatus getBrokersStatus() throws ConnectionException { if(getBrokersFails) { throw new NullPointerException("This exception is expected"); } return brokers; } /* (non-Javadoc) * @see org.marketcetera.client.Client#getUserInfo(UserID, boolean) */ @Override public UserInfo getUserInfo(UserID id, boolean useCache) throws ConnectionException { throw new UnsupportedOperationException(); } /* (non-Javadoc) * @see org.marketcetera.client.Client#getLastConnectTime() */ @Override public Date getLastConnectTime() { throw new UnsupportedOperationException(); } /* (non-Javadoc) * @see org.marketcetera.client.Client#getParameters() */ @Override public ClientParameters getParameters() { throw new UnsupportedOperationException(); } /* (non-Javadoc) * @see org.marketcetera.client.Client#getEquityPositionAsOf(java.util.Date, org.marketcetera.trade.Equity) */ @Override public BigDecimal getEquityPositionAsOf(Date inDate, Equity inEquity) throws ConnectionException { if(getPositionFails) { throw new NullPointerException("This exception is expected"); } Position position = positions.get(inEquity); if(position == null) { return null; } return position.getPositionAt(inDate); } /* (non-Javadoc) * @see org.marketcetera.client.Client#getAllEquityPositionsAsOf(java.util.Date) */ @Override public Map<PositionKey<Equity>,BigDecimal> getAllEquityPositionsAsOf(Date inDate) throws ConnectionException { if(getPositionFails) { throw new NullPointerException("This exception is expected"); } Map<PositionKey<Equity>,BigDecimal> result = new LinkedHashMap<PositionKey<Equity>,BigDecimal>(); for(Map.Entry<Instrument,Position> entry : positions.entrySet()) { if(entry.getKey() instanceof Equity) { final Equity equity = (Equity)entry.getKey(); BigDecimal value = getEquityPositionAsOf(inDate, equity); if(value != null) { PositionKey<Equity> key = new PositionKey<Equity>() { @Override public String getAccount() { return null; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return getInstrument().getSymbol(); } @Override public Equity getInstrument() { return equity; } @Override public String getTraderId() { return null; } }; result.put(key, value); } } } return result; } /* (non-Javadoc) * @see org.marketcetera.client.Client#getAllOptionPositionsAsOf(java.util.Date) */ @Override public Map<PositionKey<Option>, BigDecimal> getAllOptionPositionsAsOf(Date inDate) throws ConnectionException { if(getPositionFails) { throw new NullPointerException("This exception is expected"); } Map<PositionKey<Option>,BigDecimal> result = new LinkedHashMap<PositionKey<Option>,BigDecimal>(); for(Map.Entry<Instrument,Position> entry : positions.entrySet()) { if(entry.getKey() instanceof Option) { final Option option = (Option)entry.getKey(); BigDecimal value = getOptionPositionAsOf(inDate, option); if(value != null) { PositionKey<Option> key = new PositionKey<Option>() { /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return getInstrument().getSymbol(); } @Override public String getAccount() { return null; } @Override public Option getInstrument() { return option; } @Override public String getTraderId() { return null; } }; result.put(key, value); } } } return result; } /* (non-Javadoc) * @see org.marketcetera.client.Client#getOptionPositionAsOf(java.util.Date, org.marketcetera.trade.Option) */ @Override public BigDecimal getOptionPositionAsOf(Date inDate, Option inOption) throws ConnectionException { if(getPositionFails) { throw new NullPointerException("This exception is expected"); } Position position = positions.get(inOption); if(position == null) { return null; } return position.getPositionAt(inDate); } /* (non-Javadoc) * @see org.marketcetera.client.Client#getOptionPositionsAsOf(java.util.Date, java.lang.String[]) */ @Override public Map<PositionKey<Option>,BigDecimal> getOptionPositionsAsOf(Date inDate, String... inRootSymbols) throws ConnectionException { if(getPositionFails) { throw new NullPointerException("This exception is expected"); } Set<String> rootSymbols = new HashSet<String>(Arrays.asList(inRootSymbols)); Map<PositionKey<Option>,BigDecimal> allOptionPositions = getAllOptionPositionsAsOf(inDate); Map<PositionKey<Option>,BigDecimal> result = new LinkedHashMap<PositionKey<Option>,BigDecimal>(); for(Map.Entry<PositionKey<Option>,BigDecimal> position : allOptionPositions.entrySet()) { if(rootSymbols.contains(position.getKey().getInstrument().getSymbol())) { result.put(position.getKey(), position.getValue()); } } return result; } /* (non-Javadoc) * @see org.marketcetera.client.Client#getAllFuturePositionsAsOf(java.util.Date) */ @Override public Map<PositionKey<Future>, BigDecimal> getAllFuturePositionsAsOf(Date inDate) throws ConnectionException { throw new UnsupportedOperationException(); } /* (non-Javadoc) * @see org.marketcetera.client.Client#getFuturePositionAsOf(java.util.Date, org.marketcetera.trade.Future) */ @Override public BigDecimal getFuturePositionAsOf(Date inDate, Future inEquity) throws ConnectionException { throw new UnsupportedOperationException(); } /* (non-Javadoc) * @see org.marketcetera.client.Client#getOptionRoots(java.lang.String) */ @Override public Collection<String> getOptionRoots(String inUnderlying) throws ConnectionException { if(getPositionFails) { throw new NullPointerException("This exception is expected"); } return roots.get(inUnderlying); } /* (non-Javadoc) * @see org.marketcetera.client.Client#getUnderlying(java.lang.String) */ @Override public String getUnderlying(String inOptionRoot) throws ConnectionException { if(getPositionFails) { throw new NullPointerException("This exception is expected"); } return underlyings.get(inOptionRoot); } /* (non-Javadoc) * @see org.marketcetera.client.Client#getReportsSince(java.util.Date) */ @Override public ReportBase[] getReportsSince(Date inDate) throws ConnectionException { if(getReportsSinceThrows != null) { throw getReportsSinceThrows; } List<ReportBase> reportsToReturn = new ArrayList<ReportBase>(); for(ReportBase report : reports) { if(report.getSendingTime().compareTo(inDate) != -1) { reportsToReturn.add(report); } } return reportsToReturn.toArray(new ReportBase[reportsToReturn.size()]); } /* (non-Javadoc) * @see org.marketcetera.client.Client#reconnect() */ @Override public void reconnect() throws ConnectionException { throw new UnsupportedOperationException(); } /* (non-Javadoc) * @see org.marketcetera.client.Client#reconnect(org.marketcetera.client.ClientParameters) */ @Override public void reconnect(ClientParameters inArg0) throws ConnectionException { throw new UnsupportedOperationException(); } /* (non-Javadoc) * @see org.marketcetera.client.Client#removeExceptionListener(java.beans.ExceptionListener) */ @Override public void removeExceptionListener(ExceptionListener inArg0) { throw new UnsupportedOperationException(); } /* (non-Javadoc) * @see org.marketcetera.client.Client#removeReportListener(org.marketcetera.client.ReportListener) */ @Override public void removeReportListener(ReportListener inArg0) { throw new UnsupportedOperationException(); } /* (non-Javadoc) * @see org.marketcetera.client.Client#removeBrokerStatusListener(org.marketcetera.client.BrokerStatusListener) */ @Override public void removeBrokerStatusListener (BrokerStatusListener listener) { synchronized (mBrokerStatusListeners) { mBrokerStatusListeners.removeFirstOccurrence(listener); } } /* (non-Javadoc) * @see org.marketcetera.client.Client#removeServerStatusListener(org.marketcetera.client.ServerStatusListener) */ @Override public void removeServerStatusListener(ServerStatusListener inArg0) { throw new UnsupportedOperationException(); } /* (non-Javadoc) * @see org.marketcetera.client.Client#sendOrder(org.marketcetera.trade.OrderSingle) */ @Override public void sendOrder(OrderSingle inArg0) throws ConnectionException, OrderValidationException { throw new UnsupportedOperationException(); } /* (non-Javadoc) * @see org.marketcetera.client.Client#sendOrder(org.marketcetera.trade.OrderReplace) */ @Override public void sendOrder(OrderReplace inArg0) throws ConnectionException, OrderValidationException { throw new UnsupportedOperationException(); } /* (non-Javadoc) * @see org.marketcetera.client.Client#sendOrder(org.marketcetera.trade.OrderCancel) */ @Override public void sendOrder(OrderCancel inArg0) throws ConnectionException, OrderValidationException { throw new UnsupportedOperationException(); } /* (non-Javadoc) * @see org.marketcetera.client.Client#sendOrderRaw(org.marketcetera.trade.FIXOrder) */ @Override public void sendOrderRaw(FIXOrder inArg0) throws ConnectionException, OrderValidationException { throw new UnsupportedOperationException(); } /* (non-Javadoc) * @see org.marketcetera.client.Client#isCredentialsMatch(String, char[]) */ @Override public boolean isCredentialsMatch(String inUsername, char[] inPassword) { throw new UnsupportedOperationException(); } @Override public boolean isServerAlive() { throw new UnsupportedOperationException(); } /* (non-Javadoc) * @see org.marketcetera.client.Client#getUserData() */ @Override public Properties getUserData() throws ConnectionException { return userdata; } /* (non-Javadoc) * @see org.marketcetera.client.Client#setUserData(java.util.Properties) */ @Override public void setUserData(Properties inProperties) throws ConnectionException { userdata = inProperties; } public Properties userdata; /** * reports used to feed report-related calls */ private final Set<ReportBase> reports = new TreeSet<ReportBase>(ReportSendingTimeComparator.INSTANCE); /** * if non-null, will be thrown during {@link #getReportsSince(Date)}. */ private volatile ConnectionException getReportsSinceThrows; /* (non-Javadoc) * @see org.marketcetera.client.Client#getCurrencyPositionAsOf(java.util.Date, org.marketcetera.trade.Currency) */ @Override public BigDecimal getCurrencyPositionAsOf(Date inDate, Currency inCurrency) throws ConnectionException { if(getPositionFails) { throw new NullPointerException("This exception is expected"); } Position position = positions.get(inCurrency); if(position == null) { return null; } return position.getPositionAt(inDate); } /* (non-Javadoc) * @see org.marketcetera.client.Client#getAllCurrencyPositionsAsOf(java.util.Date) */ @Override public Map<PositionKey<Currency>,BigDecimal> getAllCurrencyPositionsAsOf(Date inDate) throws ConnectionException { if(getPositionFails) { throw new NullPointerException("This exception is expected"); } Map<PositionKey<Currency>,BigDecimal> result = new LinkedHashMap<PositionKey<Currency>,BigDecimal>(); for(Map.Entry<Instrument,Position> entry : positions.entrySet()) { if(entry.getKey() instanceof Currency) { final Currency currency = (Currency)entry.getKey(); BigDecimal value = getCurrencyPositionAsOf(inDate, currency); if(value != null) { PositionKey<Currency> key = new PositionKey<Currency>() { @Override public String getAccount() { return null; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return getInstrument().getSymbol(); } @Override public Currency getInstrument() { return currency; } @Override public String getTraderId() { return null; } }; result.put(key, value); } } } return result; } /* (non-Javadoc) * @see org.marketcetera.client.Client#deleteReport(org.marketcetera.trade.ExecutionReportImpl) */ @Override public void deleteReport(ExecutionReportImpl inReport) throws ConnectionException { throw new UnsupportedOperationException(); } /** * Sends the given <code>BrokerStatus</code> to registered broker status listeners. * * @param inBrokerStatus a <code>BrokerStatus</code> value */ public void sendToListeners(BrokerStatus inBrokerStatus) { for(BrokerStatusListener brokerStatusListener : mBrokerStatusListeners) { brokerStatusListener.receiveBrokerStatus(inBrokerStatus); } } /* (non-Javadoc) * @see org.marketcetera.client.Client#resolveSymbol(java.lang.String) */ @Override public Instrument resolveSymbol(String inSymbol) throws ConnectionException { throw new UnsupportedOperationException(); } /* (non-Javadoc) * @see org.marketcetera.client.Client#getOpenOrders() */ @Override public List<ReportBaseImpl> getOpenOrders() throws ConnectionException { return Collections.emptyList(); } /* (non-Javadoc) * @see org.marketcetera.client.Client#findRootOrderIdFor(org.marketcetera.trade.OrderID) */ @Override public OrderID findRootOrderIdFor(OrderID inOrderID) { throw new UnsupportedOperationException(); // TODO } /* (non-Javadoc) * @see org.marketcetera.client.Client#addReport(org.marketcetera.trade.FIXMessageWrapper, org.marketcetera.trade.BrokerID, org.marketcetera.trade.Hierarchy) */ @Override public void addReport(FIXMessageWrapper inReport, BrokerID inBrokerID, Hierarchy inHierarchy) throws ConnectionException { throw new UnsupportedOperationException(); // TODO } } /** * Compares the sending times of two <code>ReportBase</code> values. * * @author <a href="mailto:[email protected]">Colin DuPlantis</a> * @version $Id: StrategyTestBase.java 16888 2014-04-22 18:32:36Z colin $ * @since 2.1.4 */ private enum ReportSendingTimeComparator implements Comparator<ReportBase> { INSTANCE; /* (non-Javadoc) * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) */ @Override public int compare(ReportBase inO1, ReportBase inO2) { return inO1.getSendingTime().compareTo(inO2.getSendingTime()); } } /** * Generates a random set of broker status objects. * * @return a <code>BrokerStatus</code> value */ public static final BrokersStatus generateBrokersStatus() { List<BrokerStatus> brokers = new ArrayList<BrokerStatus>(); for(int counter=0;counter<9;counter++) { brokers.add(new BrokerStatus("Broker-" + System.nanoTime(), new BrokerID("broker-" + ++counter), random.nextBoolean())); } // make sure at least one broker is logged on brokers.add(new BrokerStatus("Broker-" + System.nanoTime(), new BrokerID("broker-10"), true)); return new BrokersStatus(brokers); } /** * A period of time during which a value is in effect. * * <p>This class can be used to track a value which changes over time. * A series of <code>Interval&lt;T&gt;</code> objects can represent * a value that changes over time by sorting them by the interval * date. To determine the value of a function represented by a series * of intervals, find the intersection of the desired date (D) and the interval * where: D > interval1.getDate() && D < interval2.getDate(). * * @author <a href="mailto:[email protected]">Colin DuPlantis</a> * @version $Id: StrategyTestBase.java 16888 2014-04-22 18:32:36Z colin $ * @since 1.0.0 */ public static class Interval<T> implements Comparable<Interval<T>> { /** * the date at which this interval takes effect */ private final Date date; /** * value for this interval */ private final T value; /** * Create a new Interval instance. * * @param inDate a <code>Date</code> value * @param inValue a <code>T</code> value */ public Interval(Date inDate, T inValue) { assert(inDate != null); date = inDate; value = inValue; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((date == null) ? 0 : date.hashCode()); return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Interval<?> other = (Interval<?>) obj; if (date == null) { if (other.date != null) return false; } else if (!date.equals(other.date)) return false; return true; } /** * Get the date at which this interval takes effect. * * @return a <code>Date</code> value */ public final Date getDate() { return date; } /** * Get the interval value. * * @return a <code>T</code> value */ public final T getValue() { return value; } /* (non-Javadoc) * @see java.lang.Comparable#compareTo(java.lang.Object) */ @Override public int compareTo(Interval<T> inOther) { return getDate().compareTo(inOther.getDate()); } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return String.format("[%s:%s]", getDate(), getValue()); } } /** * A set of intervals representing the change of the position of a security over time. * * @author <a href="mailto:[email protected]">Colin DuPlantis</a> * @version $Id: StrategyTestBase.java 16888 2014-04-22 18:32:36Z colin $ * @since 1.0.0 */ public static class Position { /** * the set of intervals that define the position change points */ private final SortedSet<Interval<BigDecimal>> position = new TreeSet<Interval<BigDecimal>>(); /** * the instrument for which this position is defined */ private final Instrument instrument; /** * Create a new Position instance. * * <p>The initial position is randomly generated. * * @param inInstrument an <code>Instrument</code> value */ public Position(Instrument inInstrument) { this(inInstrument, generateRandomPosition()); } /** * Create a new Position instance. * * @param inInstrument an <code>Instrument</code> value * @param inStartingPosition a <code>List&lt;Interval&lt;BigDecimal&gt;&gt;</code> value as the initial position */ public Position(Instrument inInstrument, List<Interval<BigDecimal>> inStartingPosition) { assert(inInstrument != null); assert(inStartingPosition != null); instrument = inInstrument; position.addAll(inStartingPosition); } /** * Adds a data-point to the position. * * <p>If the given <code>Date</code> is already present in the position, * the position will be updated with the new quantity. * * @param inDate a <code>Date</code> value * @param inQuantity a <code>BigDecimal</code> value */ public void add(Date inDate, BigDecimal inQuantity) { position.add(new Interval<BigDecimal>(inDate, inQuantity)); } /** * Gets an immutable view of the position. * * @return a <code>List&lt;Interval&lt;BigDecimal&gt;&gt;</code> value */ public List<Interval<BigDecimal>> getPositionView() { return Collections.unmodifiableList(new ArrayList<Interval<BigDecimal>>(position)); } /** * Gets the position at the given date. * * @param inDate a <code>Date</code> value * @return a <code>BigDecimal</code> value containing the position at the given date */ public BigDecimal getPositionAt(Date inDate) { Date dataPoint = new Date(inDate.getTime() + 1); Interval<BigDecimal> point = new Interval<BigDecimal>(dataPoint, BigDecimal.ZERO); // if there are no intervals or the asked-for date precedes our first data-point, // then the position is 0 if(position.isEmpty() || position.first().compareTo(point) > 0) { return BigDecimal.ZERO; } SortedSet<Interval<BigDecimal>> earlierIntervals = position.headSet(point); if(earlierIntervals.isEmpty()) { // the point asked for is later than all our intervals, return the tail of the master set return new BigDecimal(position.last().getValue().toString()); } else { // the point asked for falls somewhere within the intervals, return the last value of the tail set return new BigDecimal(earlierIntervals.last().getValue().toString()); } } /** * The instrument for this position. * * @return an <code>Instrument</code> value */ public Instrument getInstrument() { return instrument; } /** * Generates a random position. * * <p>The position returned is a series of <code>Interval&lt;BigDecimal&gt;</code> values * arranged in chronologically increasing order. The interval values are randomly * distributed between [-10000,10000). The position will begin at a randomly determined point * 1-52 weeks before the current time. The minimum granularity of a position change is one * minute, the maximum is 5 days. * * @return a <code>List&lt;Interval&lt;BigDecimal&gt;&gt;</code> value */ public static final List<Interval<BigDecimal>> generateRandomPosition() { final BigDecimal MINUS_ONE = new BigDecimal("-1"); long currentMillis = System.currentTimeMillis(); // start the position 1-52 wks in the past int seedWeek = random.nextInt(52)+1; long difference = (long)seedWeek * 1000 * 60 * 60 * 24 * 7; long seedMillis = currentMillis - difference; List<Interval<BigDecimal>> position = new ArrayList<Interval<BigDecimal>>(); while(seedMillis < currentMillis) { position.add(new Interval<BigDecimal>(new Date(seedMillis), BigDecimalUtils.multiply(BigDecimalUtils.multiply(new BigDecimal(10000), random.nextDouble()).setScale(0, RoundingMode.HALF_UP), (random.nextBoolean() ? MINUS_ONE : BigDecimal.ONE)))); // minimum granularity for a change in position is 1 min, maximum is 5 days (this is entirely arbitrary) seedMillis += (random.nextInt(1 * 60 * 24 * 5) + 1) * 1000 * 60; } return position; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { StringBuffer output = new StringBuffer(); output.append("Position for ").append(getInstrument()).append(SystemUtils.LINE_SEPARATOR); for(Interval<BigDecimal> interval : position) { output.append(interval).append(","); } return output.toString(); } } /** * Generates positions for the given symbols. * * @param inInstruments a <code>List&lt;Instrument&gt;</code> value containing the instruments for which to generate positions * @return a <code>Map&lt;Instrument,Position&gt;</code> value containing the generated positions */ public static final Map<Instrument,Position> generatePositions(List<Instrument> inInstruments) { Map<Instrument,Position> positions = new HashMap<Instrument,Position>(); for(Instrument instrument : inInstruments) { positions.put(instrument, new Position(instrument)); } return positions; } /** * Verifies that the event created contains the expected information. * * @param inActualEvent a <code>LogEvent</code> value containing the event to verify * @param inExpectedLevel a <code>Priority</code> value containing the expected priority * @param inException a <code>Throwable</code> value containing the expected exception or <code>null</code> for none * @param inExpectedMessage an <code>I18NMessage</code> value containing the expected message * @param inExpectedParameters a <code>Serializable[]</code> value containing the expected parameters */ public static void verifyEvent(LogEvent inActualEvent, LogEventLevel inExpectedLevel, Throwable inException, I18NMessage inExpectedMessage, Serializable...inExpectedParameters) throws Exception { assertEquals(inExpectedLevel, inActualEvent.getLevel()); assertEquals(inException, inActualEvent.getException()); String messageText = inExpectedMessage.getMessageProvider().getText(inExpectedMessage, (Object[])inExpectedParameters); assertEquals(messageText, inActualEvent.getMessage()); // serialize event LogEvent serializedEvent = (LogEvent) SerializationUtils.deserialize (SerializationUtils.serialize(inActualEvent)); assertEquals(inExpectedLevel, serializedEvent.getLevel()); if(inException == null) { assertNull(serializedEvent.getException()); } else { assertEquals(inException.getMessage(), serializedEvent.getException().getMessage()); } assertEquals(messageText, serializedEvent.getMessage()); } /** * Run at the beginning of execution of all tests. */ @BeforeClass public static void once() throws Exception { LoggerConfiguration.logSetup(); try { ClientManager.setClientFactory(new MockClient.MockClientFactory()); ClientManager.init(null); } catch (ClientInitException ignored) {} client = (MockClient)ClientManager.getInstance(); System.setProperty(org.marketcetera.strategy.Strategy.CLASSPATH_PROPERTYNAME, StrategyTestBase.SAMPLE_STRATEGY_DIR.getCanonicalPath()); List<Instrument> testInstruments = new ArrayList<Instrument>(); testInstruments.add(new Equity("METC")); testInstruments.add(new Equity("GOOG")); testInstruments.add(new Equity("YHOO")); testInstruments.add(new Equity("ORCL")); testInstruments.add(new Equity("AAPL")); testInstruments.add(new Equity("JAVA")); testInstruments.add(new Equity("MSFT")); testInstruments.add(new Option("METC1", DateUtils.dateToString(new Date(), DateUtils.DAYS), EventTestBase.generateDecimalValue(), OptionType.Call)); testInstruments.add(new Option("METC2", DateUtils.dateToString(new Date(), DateUtils.DAYS), EventTestBase.generateDecimalValue(), OptionType.Put)); testInstruments.add(new Option("METC3", DateUtils.dateToString(new Date(), DateUtils.DAYS), EventTestBase.generateDecimalValue(), OptionType.Call)); testInstruments.add(new Option("METC4", DateUtils.dateToString(new Date(), DateUtils.DAYS), EventTestBase.generateDecimalValue(), OptionType.Put)); testInstruments.add(new Currency("USD/GBP")); testInstruments.add(new Currency("USD/JPY")); testInstruments.add(new Currency("USD/INR")); roots.putAll("METC", Arrays.asList(new String[] { "METC1", "METC2", "METC3", "METC4" } )); underlyings.put("METC1", "METC"); underlyings.put("METC2", "METC"); underlyings.put("METC3", "METC"); underlyings.put("METC4", "METC"); testInstruments.add(new Option("MSFT1", DateUtils.dateToString(new Date(), DateUtils.DAYS), EventTestBase.generateDecimalValue(), OptionType.Call)); testInstruments.add(new Option("MSFT2", DateUtils.dateToString(new Date(), DateUtils.DAYS), EventTestBase.generateDecimalValue(), OptionType.Put)); testInstruments.add(new Option("MSFT3", DateUtils.dateToString(new Date(), DateUtils.DAYS), EventTestBase.generateDecimalValue(), OptionType.Call)); testInstruments.add(new Option("MSFT4", DateUtils.dateToString(new Date(), DateUtils.DAYS), EventTestBase.generateDecimalValue(), OptionType.Put)); roots.putAll("MSFT", Arrays.asList(new String[] { "MSFT1", "MSFT2", "MSFT3", "MSFT4" } )); underlyings.put("MSFT1", "MSFT"); underlyings.put("MSFT2", "MSFT"); underlyings.put("MSFT3", "MSFT"); underlyings.put("MSFT4", "MSFT"); positions.putAll(generatePositions(testInstruments)); } /** * Run before each test. * * @throws Exception if an error occurs */ @Before public void setup() throws Exception { StringBuilder classpath = new StringBuilder(); for(String path : getClassPath()) { classpath.append(path).append(File.pathSeparator); } System.setProperty(JavaCompilerExecutionEngine.CLASSPATH_KEY, classpath.toString()); brokers = generateBrokersStatus(); MockClient.getBrokersFails = false; MockClient.getPositionFails = false; MockClient.addBrokerStatusListenerFails = false; executionReportMultiplicity = 1; MockRecorderModule.shouldSendExecutionReports = true; MockRecorderModule.shouldFullyFillOrders = true; MockRecorderModule.shouldIgnoreLogMessages = true; MockRecorderModule.ordersReceived = 0; getClientFails = false; final MockClient testClient = new MockClient(); StrategyModule.clientFactory = new ClientFactory() { @Override public Client getClient() throws ClientInitException { if(getClientFails) { throw new ClientInitException(TestMessages.EXPECTED_EXCEPTION); } return testClient; } }; moduleManager = new ModuleManager(); moduleManager.init(); outputURN = moduleManager.createModule(MockRecorderModule.Factory.PROVIDER_URN); moduleManager.start(outputURN); moduleManager.start(bogusDataFeedURN); factory = new StrategyModuleFactory(); runningModules.clear(); runningModules.add(outputURN); runningModules.add(bogusDataFeedURN); setPropertiesToNull(); tradeEvent = EventTestBase.generateEquityTradeEvent(System.nanoTime(), System.currentTimeMillis(), new Equity("METC"), "Q", new BigDecimal("1000.25"), new BigDecimal("1000")); askEvent = EventTestBase.generateEquityAskEvent(System.nanoTime(), System.currentTimeMillis(), new Equity("METC"), "Q", new BigDecimal("100.00"), new BigDecimal("10000")); StrategyDataEmissionModule.setDataToSendToDefaults(); } /** * Run after each test. * * @throws Exception if an error occurs */ @After public void cleanup() throws Exception { cancelDataFlows(null); for(ModuleURN strategy : runningModules) { try { moduleManager.stop(strategy); } catch (Exception e) { // ignore failures, just press ahead } } try { moduleManager.stop(outputURN); } catch (ModuleException ignore) { // ignore failures, just press ahead } moduleManager.deleteModule(outputURN); moduleManager.stop(); } /** * Cancels all active data flows. * @param inStrategyURN a <code>ModuleURN</code> containing a strategy URN for which to cancel flows * or null to cancel all flows */ protected final void cancelDataFlows(ModuleURN inStrategyURN) { synchronized(dataFlowsByStrategy) { Collection<List<DataFlowID>> flowsToCancel; if(inStrategyURN == null) { flowsToCancel = dataFlowsByStrategy.values(); } else { List<DataFlowID> singleList = dataFlowsByStrategy.get(inStrategyURN); if(singleList == null) { return; } flowsToCancel = new ArrayList<List<DataFlowID>>(); flowsToCancel.add(singleList); } for(List<DataFlowID> flows : flowsToCancel) { for(DataFlowID dataFlow : flows) { try { moduleManager.cancel(dataFlow); } catch (Exception e) { // ignore all exceptions and keep canceling } } } dataFlowsByStrategy.clear(); } } /** * Starts the given strategy and hooks it up to the mock ORS client. * * @param inStrategyURN a <code>ModuleURN</code> value * @throws Exception if an error occurs */ protected final void startStrategy(ModuleURN inStrategyURN) throws Exception { moduleManager.start(inStrategyURN); setupMockORSConnection(inStrategyURN); verifyStrategyReady(inStrategyURN); } /** * Stops the given strategy and cancels all active data flows. * * @param inStrategyURN a <code> * @throws Exception */ protected final void stopStrategy(ModuleURN inStrategyURN) throws Exception { cancelDataFlows(null); moduleManager.stop(inStrategyURN); verifyStrategyStopped(inStrategyURN); } /** * Sets up a connection to the testing ORSClient for execution reports. * * <p>The data flow established will be automatically stopped by invocations of * {@link #cancelDataFlows(ModuleURN)}. * * @param inStrategyURN a <code>ModuleURN</code> connecting the module to which to plumb the ORSClient output * @return a <code>DataFlowID</code> representing the data flow * @throws Exception if an error occurs */ protected final DataFlowID setupMockORSConnection(ModuleURN inStrategyURN) throws Exception { DataFlowID flowID = moduleManager.createDataFlow(new DataRequest[] { new DataRequest(outputURN), new DataRequest(inStrategyURN) }, false); synchronized(dataFlowsByStrategy) { List<DataFlowID> flows = dataFlowsByStrategy.get(inStrategyURN); if(flows == null) { flows = new ArrayList<DataFlowID>(); dataFlowsByStrategy.put(inStrategyURN, flows); } flows.add(flowID); } return flowID; } /** * Generates an <code>ExecutionReport</code> from the given <code>OrderSingle</code>. * * @param inOrder an <code>OrderSingle</code> value * @return an <code>ExecutionReport</code> value * @throws Exception if an error exists */ protected static List<ExecutionReport> generateExecutionReports(OrderSingle inOrder) throws Exception { List<ExecutionReport> reports = new ArrayList<ExecutionReport>(); for(Message rawExeReport : generateFixExecutionReports(inOrder)) { reports.add(org.marketcetera.trade.Factory.getInstance().createExecutionReport(rawExeReport, inOrder.getBrokerID(), Originator.Broker, null, null)); } return reports; } /** * Generates FIX <code>Message</code> objects that contain execution reports for partial and/or * complete fills of the given order. * * <p>The number of objects returned can be adjusted by changing the value of {@link #executionReportMultiplicity}. * Whether or not the list partially or fully fills the given order can be adjusted by changing the * value of {@link MockRecorderModule#shouldFullyFillOrders}. * * @param inOrder an <code>OrderSingle</code> value * @return a <code>List&lt;Message&gt;</code> value * @throws Exception if an error occurs */ protected static List<Message> generateFixExecutionReports(OrderSingle inOrder) throws Exception { int multiplicity = executionReportMultiplicity; List<Message> reports = new ArrayList<Message>(); if(inOrder.getQuantity() != null) { BigDecimal totalQuantity = new BigDecimal(inOrder.getQuantity().toString()); BigDecimal lastQuantity = BigDecimal.ZERO; for(int iteration=0;iteration<multiplicity-1;iteration++) { BigDecimal thisQuantity = totalQuantity.subtract(totalQuantity.divide(new BigDecimal(Integer.toString(multiplicity)))); totalQuantity = totalQuantity.subtract(thisQuantity); Message rawExeReport = generateFixExecutionReport(inOrder, OrdStatus.PARTIALLY_FILLED, thisQuantity, lastQuantity, FIXVersion.FIX44); reports.add(rawExeReport); lastQuantity = thisQuantity; } Message rawExeReport = generateFixExecutionReport(inOrder, MockRecorderModule.shouldFullyFillOrders ? OrdStatus.FILLED : OrdStatus.PARTIALLY_FILLED, totalQuantity, lastQuantity, FIXVersion.FIX44); reports.add(rawExeReport); } return reports; } /** * Generates a FIX <code>Message</code> containing an execution report of the given * status for the given order. * * <p><em>Warning</em> - most of the attributes of the FIX message returned are arbitrary and possibly * incorrect. It is the caller's responsibility to review and modify the returned value * for the intended purpose. * * @param inOrder an <code>OrderSingle</code> value * @param inOrderStatus a <code>char</code> value corresponding to an {@link OrdStatus} value * @param inQuantity a <code>BigDecimal</code> value * @param inLastQuantity a <code>BigDecimal</code> value * @return a <code>Message</code> value * @throws Exception if an error occurs */ protected static Message generateFixExecutionReport(OrderSingle inOrder, char inOrderStatus, BigDecimal inQuantity, BigDecimal inLastQuantity, FIXVersion inFIXVersion) throws Exception { Message exeReport = inFIXVersion.getMessageFactory().newExecutionReport(inOrder.getOrderID().toString(), inOrder.getOrderID().toString(), "execID", inOrderStatus, Side.BUY, inQuantity, inOrder.getPrice(), inLastQuantity, inOrder.getPrice(), inOrder.getQuantity(), inOrder.getPrice(), inOrder.getInstrument(), inOrder.getAccount(), inOrder.getText()); exeReport.setField(new TransactTime(extractTransactTimeFromRunningStrategy())); return exeReport; } /** * Creates an <code>OrderSingle</code> value with the given <code>OrderID</code>. * * <p>If a null <code>OrderID</code> is given, a new <code>OrderID</code> is assigned to * the <code>OrderSingle</code>. * * @param inOrderID an <code>OrderID</code> value or <code>null</code> * @return an <code>OrderSingle</code> value */ protected static OrderSingle createOrderWithID(OrderID inOrderID) { OrderSingle order = Factory.getInstance().createOrderSingle(); order.setOrderType(OrderType.Limit); order.setPrice(new BigDecimal("100.23")); order.setQuantity(new BigDecimal("10000")); order.setSide(org.marketcetera.trade.Side.Buy); order.setInstrument(new Equity("METC")); if(inOrderID != null) { order.setOrderID(inOrderID); } return order; } /** * Extracts the date used to generate an order from a running strategy, if applicable. * * @return a <code>Date</code> value used to generate the most recent order in a running strategy or the current time if none exists */ protected static Date extractTransactTimeFromRunningStrategy() { String transactTimeString = AbstractRunningStrategy.getProperty("transactTime"); Date transactTime = new Date(); if(transactTimeString != null) { transactTime = new Date(Long.parseLong(transactTimeString)); } return transactTime; } /** * Verifies that a strategy module can start and stop with the given parameters. * * @param inParameters an <code>Object...</code> value containing the parameters to pass to the module creation command * @throws Exception if an error occurs */ protected void verifyStrategyStartsAndStops(Object...inParameters) throws Exception { ModuleURN urn = createStrategy(inParameters); moduleManager.stop(urn); assertFalse(moduleManager.getModuleInfo(urn).getState().isStarted()); moduleManager.deleteModule(urn); } /** * Waits until the given strategy has either started or erred out. * * @param inStrategyURN a <code>ModuleURN</code> value * @throws Exception if an error occurs */ protected void verifyStrategyReady(final ModuleURN inStrategyURN) throws Exception { MarketDataFeedTestBase.wait(new Callable<Boolean>() { @Override public Boolean call() throws Exception { Status status = getStatus(inStrategyURN); return status.equals(RUNNING) || status.equals(FAILED); } }); } /** * Waits until the given strategy has stopped, either with or without error. * * @param inStrategyURN a <code>ModuleURN</code> value * @throws Exception if an error occurs */ protected void verifyStrategyStopped(final ModuleURN inStrategyURN) throws Exception { MarketDataFeedTestBase.wait(new Callable<Boolean>() { @Override public Boolean call() throws Exception { Status status = getStatus(inStrategyURN); return status.equals(STOPPED) || status.equals(FAILED); } }); } /** * Verifies that the given strategy is at the given status. * * @param inStrategy a <code>ModuleURN</code> value * @param inStatus a <code>Status</code> value * @throws Exception if an error occurs */ protected void verifyStrategyStatus(ModuleURN inStrategy, Status inStatus) throws Exception { assertEquals(inStatus, getStatus(inStrategy)); } /** * Returns the status of the given strategy. * * @param inStrategy a <code>ModuleURN</code> value * @return a <code>Status</code> value * @throws Exception if an error occurs */ protected Status getStatus(ModuleURN inStrategy) throws Exception { return Status.valueOf(getMXProxy(inStrategy).getStatus()); } /** * Asserts that the values in the common strategy storage area for some well-known testing keys are null. */ protected void verifyNullProperties() { verifyPropertyNull("onAsk"); verifyPropertyNull("onBid"); verifyPropertyNull("onCancel"); verifyPropertyNull("onDividend"); verifyPropertyNull("onExecutionReport"); verifyPropertyNull("onOther"); verifyPropertyNull("onTrade"); } /** * Asserts that the values in the common strategy storage area for some well-known testing keys are not null. * @throws Exception if an error occurs */ protected void verifyNonNullProperties() throws Exception { verifyPropertyNonNull("onAsk"); verifyPropertyNonNull("onBid"); verifyPropertyNonNull("onCancel"); verifyPropertyNonNull("onDividend"); verifyPropertyNonNull("onExecutionReport"); verifyPropertyNonNull("onOther"); verifyPropertyNonNull("onTrade"); } /** * Sets the values in the common strategy storage area for some well-known testing keys to null. */ protected void setPropertiesToNull() { Properties properties = AbstractRunningStrategy.getProperties(); properties.clear(); verifyNullProperties(); } /** * Verifies the given property is non-null. * * @param inKey a <code>String</code> value * @return a <code>String</code> value or null * @throws Exception if an error occurs */ protected String verifyPropertyNonNull(final String inKey) throws Exception { MarketDataFeedTestBase.wait(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return AbstractRunningStrategy.getProperty(inKey) != null; } }); return AbstractRunningStrategy.getProperty(inKey); } /** * Verifies the given property is null. * * @param inKey a <code>String</code> value */ protected void verifyPropertyNull(String inKey) { Properties properties = AbstractRunningStrategy.getProperties(); assertNull(inKey + " is supposed to be null", properties.getProperty(inKey)); } /** * Creates a strategy with the given parameters. * * <p>The strategy is guaranteed to be running at the successful exit of this method. Strategies created by this method * are tracked and shut down, if necessary, at the end of the test. * * @param inParameters an <code>Object...</code> value containing the parameters to pass to the module creation command * @return a <code>ModuleURN</code> value containing the URN of the strategy * @throws Exception if an error occurs */ protected ModuleURN createStrategy(Object...inParameters) throws Exception { verifyNullProperties(); LinkedList<Object> actualParameters = new LinkedList<Object>(Arrays.asList(inParameters)); if(inParameters.length <= 6) { actualParameters.addFirst(null); } ModuleURN strategyURN = createModule(StrategyModuleFactory.PROVIDER_URN, actualParameters.toArray()); theStrategy = strategyURN; verifyStrategyReady(strategyURN); return strategyURN; } /** * Creates and starts a module with the given URN and the given parameters. * * <p>The module is guaranteed to be running at the successful exit of this method. Modules created by this method * are tracked and shut down, if necessary, at the end of the test. * * @param inProvider a <code>ModuleURN</code> value * @param inParameters an <code>Object...</code> value containing the parameters to pass to the module creation command * @return a <code>ModuleURN</code> value containing the URN of the strategy * @throws Exception if an error occurs */ protected ModuleURN createModule(ModuleURN inProvider, Object...inParameters) throws Exception { ModuleURN urn = moduleManager.createModule(inProvider, inParameters); assertFalse(moduleManager.getModuleInfo(urn).getState().isStarted()); moduleManager.start(urn); assertTrue(moduleManager.getModuleInfo(urn).getState().isStarted()); runningModules.add(urn); return urn; } /** * Returns an <code>MXBean</code> interface to the given strategy. * * @param inModuleURN a <code>ModuleURN</code> value containing a strategy * @return a <code>StrategyMXBean</code> value * @throws Exception if an error occurs */ protected StrategyMXBean getMXProxy(ModuleURN inModuleURN) throws Exception { ObjectName objectName = inModuleURN.toObjectName(); MBeanServer server = ManagementFactory.getPlatformMBeanServer(); return JMX.newMXBeanProxy(server, objectName, StrategyMXBean.class, true); } /** * Gets a handle to the given strategy; * * @param inStrategyURN a <code>ModuleURN</code> value * * <p>Note that this method will <em>fail</em> if the given strategy is not running * * @return a <code>StrategyImpl</code> value */ protected final StrategyImpl getRunningStrategy(ModuleURN inStrategyURN) { Set<StrategyImpl> runningStrategies = StrategyImpl.getRunningStrategies(); for(StrategyImpl runningStrategy : runningStrategies) { if(runningStrategy.getDefaultNamespace().equals(inStrategyURN.instanceName())) { return runningStrategy; } } fail(inStrategyURN + " not currently running"); return null; } /** * Constructs a classpath to use for Java compilation. * * <p>This method will make a best-effort to create the classpath, * ignoring errors that occur during the collection. This method * is not expected to throw exceptions, muddling on instead. * * @return a <code>Set&lt;String&gt;</code> value */ private Set<String> getClassPath() { // get the classloader that was used to load this class ClassLoader classLoader = getClass().getClassLoader(); // this collection will hold all the paths we find, duplicates discarded, in the order they appear Set<String> paths = new LinkedHashSet<String>(); // //Collect all URLs from the URL Class Loaders. // do { // if(classLoader instanceof URLClassLoader) { // URLClassLoader urlClassLoader = (URLClassLoader)classLoader; // for(URL url : urlClassLoader.getURLs()) { // try { // paths.add(url.toURI().getPath()); // } catch (URISyntaxException ignore) { // } // } // } // // traverse the classloader tree upwards until no more remain // } while((classLoader = classLoader.getParent()) != null); // // reset the classloader to the current // classLoader = getClass().getClassLoader(); //iterate through the manifests of all the jars to find the // values of their Class-Path attribute value and add them to the // set. try { Enumeration<URL> resourceEnumeration = classLoader.getResources("META-INF/MANIFEST.MF"); while(resourceEnumeration.hasMoreElements()) { URL resourceURL = resourceEnumeration.nextElement(); InputStream is = null; try { // open the resource is = resourceURL.openStream(); Manifest manifest = new Manifest(is); String theClasspath = manifest.getMainAttributes().getValue("Class-Path"); if(theClasspath != null && !theClasspath.trim().isEmpty()) { //manifest classpath is space separated URLs for(String path : theClasspath.split(" ")) { try { URL pathURL = new URL(path); paths.add(pathURL.toURI().getPath()); } catch (MalformedURLException ignore) { } catch (URISyntaxException ignore) { } } } } catch (IOException ignore) { } finally { if(is != null) { try { is.close(); } catch (IOException ignore) { } } } } } catch (IOException ignore) { } return paths; } /** * random number generator for public use */ public static final Random random = new Random(System.nanoTime()); /** * indicates if the getClient call in the StrategyModule should fail */ protected static boolean getClientFails; /** * global singleton module manager */ protected ModuleManager moduleManager; /** * the factory to use to create the market data provider modules */ protected ModuleFactory factory; /** * test destination of output */ protected ModuleURN outputURN; /** * list of strategies started during test */ protected final List<ModuleURN> runningModules = new ArrayList<ModuleURN>(); /** * data flows by the strategy that caused their creation */ private final Map<ModuleURN,List<DataFlowID>> dataFlowsByStrategy = new HashMap<ModuleURN,List<DataFlowID>>(); /** * URN for market data provider */ protected final ModuleURN bogusDataFeedURN = BogusFeedModuleFactory.INSTANCE_URN; /** * trade event with generic information */ protected TradeEvent tradeEvent; /** * ask event with generic information */ protected AskEvent askEvent; /** * can be used to track a central strategy */ protected ModuleURN theStrategy; /** * positions for a set of symbols */ protected final static Map<Instrument,Position> positions = new LinkedHashMap<Instrument,Position>(); /** * list of option roots for a given single underlying symbol */ protected final static Multimap<String,String> roots = LinkedHashMultimap.create(); /** * the underlying symbol for each root */ protected final static Map<String,String> underlyings = new LinkedHashMap<String,String>(); /** * a set of test brokers */ protected static BrokersStatus brokers; /** * determines how many execution reports should be produced for each order received */ protected static int executionReportMultiplicity = 1; /** * test client used to simulate connections to the server */ protected static MockClient client; }
{'content_hash': 'cb8c23a15621941119cc61740c5b0e04', 'timestamp': '', 'source': 'github', 'line_count': 2270, 'max_line_length': 165, 'avg_line_length': 41.21497797356828, 'alnum_prop': 0.5191538938412535, 'repo_name': 'nagyist/marketcetera', 'id': 'd129ddd4b44d1ec66a2ef893288278913fe4aac4', 'size': '93558', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'trunk/modules/strategy/src/test/java/org/marketcetera/strategy/StrategyTestBase.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '3625095'}, {'name': 'Ruby', 'bytes': '655'}]}
#include <linux/backlight.h> #include "../dsim.h" #include "dsim_backlight.h" #include "panel_info.h" #ifdef CONFIG_PANEL_AID_DIMMING #include "aid_dimming.h" #endif #ifndef USE_PANEL_PARAMETER_MAX_SIZE #define ELVSS_LEN_MAX ELVSS_LEN #define TSET_LEN_MAX TSET_LEN #endif #ifdef CONFIG_PANEL_AID_DIMMING static unsigned int get_actual_br_value(struct dsim_device *dsim, int index) { struct panel_private *panel = &dsim->priv; struct SmtDimInfo *dimming_info = (struct SmtDimInfo *)panel->dim_info; if (dimming_info == NULL) { dsim_err("%s : dimming info is NULL\n", __func__); goto get_br_err; } if (index > MAX_BR_INFO) index = MAX_BR_INFO; return dimming_info[index].br; get_br_err: return 0; } static unsigned char *get_gamma_from_index(struct dsim_device *dsim, int index) { struct panel_private *panel = &dsim->priv; struct SmtDimInfo *dimming_info = (struct SmtDimInfo *)panel->dim_info; if (dimming_info == NULL) { dsim_err("%s : dimming info is NULL\n", __func__); goto get_gamma_err; } if (index > MAX_BR_INFO) index = MAX_BR_INFO; return (unsigned char *)dimming_info[index].gamma; get_gamma_err: return NULL; } static unsigned char *get_aid_from_index(struct dsim_device *dsim, int index) { struct panel_private *panel = &dsim->priv; struct SmtDimInfo *dimming_info = (struct SmtDimInfo *)panel->dim_info; if (dimming_info == NULL) { dsim_err("%s : dimming info is NULL\n", __func__); goto get_aid_err; } if (index > MAX_BR_INFO) index = MAX_BR_INFO; return (u8 *)dimming_info[index].aid; get_aid_err: return NULL; } static unsigned char *get_elvss_from_index(struct dsim_device *dsim, int index, int caps) { struct panel_private *panel = &dsim->priv; struct SmtDimInfo *dimming_info = (struct SmtDimInfo *)panel->dim_info; if (dimming_info == NULL) { dsim_err("%s : dimming info is NULL\n", __func__); goto get_elvess_err; } if(caps) return (unsigned char *)dimming_info[index].elvCaps; else return (unsigned char *)dimming_info[index].elv; get_elvess_err: return NULL; } static void dsim_panel_gamma_ctrl(struct dsim_device *dsim) { u8 *gamma = NULL; gamma = get_gamma_from_index(dsim, dsim->priv.br_index); if (gamma == NULL) { dsim_err("%s :faied to get gamma\n", __func__); return; } if (dsim_write_hl_data(dsim, gamma, GAMMA_CMD_CNT) < 0) dsim_err("%s : failed to write gamma \n", __func__); } static char dsim_panel_get_elvssoffset(struct dsim_device *dsim) { int nit = 0; char retVal = 0x00; struct panel_private* panel = &(dsim->priv); // bool bIsHbm = (LEVEL_IS_HBM(panel->auto_brightness) && (panel->bd->props.brightness == panel->bd->props.max_brightness)); nit = panel->br_tbl[panel->bd->props.brightness]; /* if((!bIsHbm) && (panel->interpolation)) { if(panel->weakness_hbm_comp == HBM_COLORBLIND_ON) retVal = -panel->hbm_elvss_comp; else if(panel->weakness_hbm_comp == HBM_GALLERY_ON) retVal = -HBM_INTER_22TH_OFFSET[panel->br_index - 65]; else pr_info("%s invaid weakness_hbm_comp:%d\n", __func__, panel->weakness_hbm_comp); goto exit_get_elvss; } */ if (nit <=360 && UNDER_0(panel->temperature)) { // 0xB6 4th para - 0x0A retVal = - 0xA; } pr_info("%s %d\n", __func__, retVal); return retVal; } static void dsim_panel_aid_ctrl(struct dsim_device *dsim) { u8 *aid = NULL; aid = get_aid_from_index(dsim, dsim->priv.br_index); if (aid == NULL) { dsim_err("%s : faield to get aid value\n", __func__); return; } if (dsim_write_hl_data(dsim, aid, AID_CMD_CNT) < 0) dsim_err("%s : failed to write gamma \n", __func__); } static void dsim_panel_set_elvss(struct dsim_device *dsim) { u8 *elvss = NULL; unsigned char SEQ_ELVSS[ELVSS_LEN_MAX] = {0, }; int elvss_len = 5; // struct panel_private *panel = &dsim->priv; // bool bIsHbm = (LEVEL_IS_HBM(panel->auto_brightness) && (panel->bd->props.brightness == panel->bd->props.max_brightness)); SEQ_ELVSS[0] = ELVSS_REG; elvss = get_elvss_from_index(dsim, dsim->priv.br_index, dsim->priv.caps_enable); if (elvss == NULL) { dsim_err("%s : failed to get elvss value\n", __func__); return; } memcpy(&SEQ_ELVSS[1], dsim->priv.elvss_set, elvss_len-1); memcpy(SEQ_ELVSS, elvss, ELVSS_CMD_CNT); SEQ_ELVSS[4] += dsim_panel_get_elvssoffset(dsim); if (dsim_write_hl_data(dsim, SEQ_ELVSS, elvss_len) < 0) dsim_err("%s : failed to write elvss \n", __func__); } static int dsim_panel_set_acl(struct dsim_device *dsim, int force) { int ret = 0, level = ACL_STATUS_8P; struct panel_private *panel = &dsim->priv; if (panel == NULL) { dsim_err("%s : panel is NULL\n", __func__); goto exit; } if (dsim->priv.siop_enable || LEVEL_IS_HBM(dsim->priv.auto_brightness)) // auto acl or hbm is acl on goto acl_update; if (!dsim->priv.acl_enable) level = ACL_STATUS_0P; acl_update: if(force || dsim->priv.current_acl != panel->acl_cutoff_tbl[level][1]) { if((ret = dsim_write_hl_data(dsim, panel->acl_opr_tbl[level], 2)) < 0) { dsim_err("fail to write acl opr command.\n"); goto exit; } if((ret = dsim_write_hl_data(dsim, panel->acl_cutoff_tbl[level], 2)) < 0) { dsim_err("fail to write acl command.\n"); goto exit; } dsim->priv.current_acl = panel->acl_cutoff_tbl[level][1]; dsim_info("acl: %d, auto_brightness: %d\n", dsim->priv.current_acl, dsim->priv.auto_brightness); } exit: if (!ret) ret = -EPERM; return ret; } static int dsim_panel_set_tset(struct dsim_device *dsim, int force) { int ret = 0; int tset = 0; unsigned char SEQ_TSET[TSET_LEN_MAX] = {0, }; SEQ_TSET[0] = TSET_REG; tset = (dsim->priv.temperature < 0) ? BIT(7) | abs(dsim->priv.temperature) : dsim->priv.temperature; if(force || dsim->priv.tset[TSET_LEN - 2] != tset) { memcpy(&SEQ_TSET[1], dsim->priv.tset, TSET_LEN - 1); dsim->priv.tset[TSET_LEN - 2] = SEQ_TSET[TSET_LEN - 1] = tset; if ((ret = dsim_write_hl_data(dsim, SEQ_TSET, ARRAY_SIZE(SEQ_TSET))) < 0) { dsim_err("fail to write tset command.\n"); ret = -EPERM; } dsim_info("%s temperature: %d, tset: %d\n", __func__, dsim->priv.temperature, SEQ_TSET[TSET_LEN - 1]); } return ret; } static int dsim_panel_set_hbm(struct dsim_device *dsim, int force) { int ret = 0, level = LEVEL_IS_HBM(dsim->priv.auto_brightness); struct panel_private *panel = &dsim->priv; if (panel == NULL) { dsim_err("%s : panel is NULL\n", __func__); goto exit; } if(force || dsim->priv.current_hbm != panel->hbm_tbl[level][1]) { dsim->priv.current_hbm = panel->hbm_tbl[level][1]; if((ret = dsim_write_hl_data(dsim, EA8061V_SEQ_HBM_PARA_SKIP, ARRAY_SIZE(EA8061V_SEQ_HBM_PARA_SKIP))) < 0) { dsim_err("fail to write hbm command.\n"); ret = -EPERM; } if((ret = dsim_write_hl_data(dsim, panel->hbm_tbl[level], ARRAY_SIZE(SEQ_HBM_OFF))) < 0) { dsim_err("fail to write hbm command.\n"); ret = -EPERM; } dsim_info("hbm: %d, auto_brightness: %d\n", dsim->priv.current_hbm, dsim->priv.auto_brightness); } exit: return ret; } static int low_level_set_brightness(struct dsim_device *dsim ,int force) { if (dsim_write_hl_data(dsim, SEQ_TEST_KEY_ON_F0, ARRAY_SIZE(SEQ_TEST_KEY_ON_F0)) < 0) dsim_err("%s : fail to write F0 on command.\n", __func__); dsim_panel_gamma_ctrl(dsim); dsim_panel_aid_ctrl(dsim); dsim_panel_set_elvss(dsim); if (dsim_write_hl_data(dsim, SEQ_GAMMA_UPDATE, ARRAY_SIZE(SEQ_GAMMA_UPDATE)) < 0) dsim_err("%s : failed to write gamma \n", __func__); dsim_panel_set_acl(dsim, force); dsim_panel_set_tset(dsim, force); #ifdef CONFIG_LCD_ALPM if (!(dsim->priv.current_alpm && dsim->priv.alpm)) #endif dsim_panel_set_hbm(dsim, force); if (dsim_write_hl_data(dsim, SEQ_TEST_KEY_OFF_F0, ARRAY_SIZE(SEQ_TEST_KEY_OFF_F0)) < 0) dsim_err("%s : fail to write F0 on command\n", __func__); return 0; } static int get_acutal_br_index(struct dsim_device *dsim, int br) { int i; int min; int gap; int index = 0; struct panel_private *panel = &dsim->priv; struct SmtDimInfo *dimming_info = panel->dim_info; if (dimming_info == NULL) { dsim_err("%s : dimming_info is NULL\n", __func__); return 0; } min = MAX_BRIGHTNESS; for (i = 0; i < MAX_BR_INFO; i++) { if (br > dimming_info[i].br) gap = br - dimming_info[i].br; else gap = dimming_info[i].br - br; if (gap == 0) { index = i; break; } if (gap < min) { min = gap; index = i; } } return index; } #endif int dsim_panel_set_brightness(struct dsim_device *dsim, int force) { int ret = 0; #ifndef CONFIG_PANEL_AID_DIMMING dsim_info("%s:this panel does not support dimming \n", __func__); #else struct dim_data *dimming; struct panel_private *panel = &dsim->priv; int p_br = panel->bd->props.brightness; int acutal_br = 0; int real_br = 0; int prev_index = panel->br_index; bool bIsHbm = (LEVEL_IS_HBM(panel->auto_brightness) && (p_br == panel->bd->props.max_brightness)); dimming = (struct dim_data *)panel->dim_data; if ((dimming == NULL) || (panel->br_tbl == NULL)) { dsim_info("%s : this panel does not support dimming\n", __func__); return ret; } if (panel->weakness_hbm_comp == 1) acutal_br = panel->hbm_inter_br_tbl[p_br]; else if(panel->weakness_hbm_comp == 2) acutal_br = panel->gallery_br_tbl[p_br]; else acutal_br = panel->br_tbl[p_br]; panel->br_index = get_acutal_br_index(dsim, acutal_br); real_br = get_actual_br_value(dsim, panel->br_index); panel->caps_enable = CAPS_IS_ON(real_br); panel->acl_enable = ACL_IS_ON(real_br); if(bIsHbm) { panel->br_index = panel->hbm_index; panel->acl_enable = 1; // hbm is acl on panel->caps_enable = 1; // hbm is caps on } if(panel->siop_enable) // check auto acl panel->acl_enable = 1; if (real_br > MAX_BRIGHTNESS) { panel->interpolation = 1; } else { panel->interpolation = 0; } if (panel->weakness_hbm_comp) { panel->acl_enable = 1; if((!bIsHbm) && (p_br == 255)) panel->acl_enable = 0; } if (panel->state != PANEL_STATE_RESUMED) { dsim_info("%s : panel is not active state..\n", __func__); goto set_br_exit; } dsim_info("%s : platform : %d, : mapping : %d, real : %d, index : %d, interpolation : %d\n", __func__, p_br, acutal_br, real_br, panel->br_index, panel->interpolation); if (!force && panel->br_index == prev_index) goto set_br_exit; if ((acutal_br == 0) || (real_br == 0)) goto set_br_exit; mutex_lock(&panel->lock); ret = low_level_set_brightness(dsim, force); if (ret) { dsim_err("%s failed to set brightness : %d\n", __func__, acutal_br); } mutex_unlock(&panel->lock); set_br_exit: #endif return ret; } static int panel_get_brightness(struct backlight_device *bd) { return bd->props.brightness; } static int panel_set_brightness(struct backlight_device *bd) { int ret = 0; int brightness = bd->props.brightness; struct panel_private *priv = bl_get_data(bd); struct dsim_device *dsim; dsim = container_of(priv, struct dsim_device, priv); if (brightness < UI_MIN_BRIGHTNESS || brightness > UI_MAX_BRIGHTNESS) { printk(KERN_ALERT "Brightness should be in the range of 0 ~ 255\n"); ret = -EINVAL; goto exit_set; } ret = dsim_panel_set_brightness(dsim, 0); if (ret) { dsim_err("%s : fail to set brightness\n", __func__); goto exit_set; } exit_set: return ret; } static const struct backlight_ops panel_backlight_ops = { .get_brightness = panel_get_brightness, .update_status = panel_set_brightness, }; int dsim_backlight_probe(struct dsim_device *dsim) { int ret = 0; struct panel_private *panel = &dsim->priv; panel->bd = backlight_device_register("panel", dsim->dev, &dsim->priv, &panel_backlight_ops, NULL); if (IS_ERR(panel->bd)) { dsim_err("%s:failed register backlight\n", __func__); ret = PTR_ERR(panel->bd); } panel->bd->props.max_brightness = UI_MAX_BRIGHTNESS; panel->bd->props.brightness = UI_DEFAULT_BRIGHTNESS; return ret; }
{'content_hash': '75e99010b69127d55622e9b56cc6dede', 'timestamp': '', 'source': 'github', 'line_count': 457, 'max_line_length': 124, 'avg_line_length': 25.805251641137854, 'alnum_prop': 0.6475027558721276, 'repo_name': 'ghostkim-sc/SMG920T_profiling_enabled', 'id': '273ae94ae1b6efdfebde918fac362fb187c14241', 'size': '12189', 'binary': False, 'copies': '44', 'ref': 'refs/heads/master', 'path': 'drivers/video/exynos/decon_royce/panels/dsim_backlight_ea8061v.c', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'ASP', 'bytes': '4528'}, {'name': 'Assembly', 'bytes': '9791460'}, {'name': 'Awk', 'bytes': '18681'}, {'name': 'C', 'bytes': '518034272'}, {'name': 'C++', 'bytes': '13105745'}, {'name': 'GDB', 'bytes': '18113'}, {'name': 'Lex', 'bytes': '40805'}, {'name': 'M4', 'bytes': '3388'}, {'name': 'Makefile', 'bytes': '1522326'}, {'name': 'Objective-C', 'bytes': '1278363'}, {'name': 'Perl', 'bytes': '372361'}, {'name': 'Python', 'bytes': '22590'}, {'name': 'Roff', 'bytes': '22012'}, {'name': 'Scilab', 'bytes': '21433'}, {'name': 'Shell', 'bytes': '218756'}, {'name': 'SourcePawn', 'bytes': '2711'}, {'name': 'Stata', 'bytes': '4176'}, {'name': 'UnrealScript', 'bytes': '6113'}, {'name': 'Yacc', 'bytes': '83091'}]}
<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); class GeneraFactura { function facturar($infoFactura,$conceptos) { //obtenemos la fecha de la factura $fch = "$infoFactura->facturaFecha"; $fecha = explode(" ",$fch); //variable para detectar error $error = false; //variable para detectar si solo se maneja impuesto tasa 0.160000 o tambien tasa 0.000000 $tasa0 = false; $tasa16 = false; //iniciamos la variable de cadena_original $cadena_original = ''; //creamos la cadena original //atributos del comprobante ---> $cadena_original .= '||3.3|';// ||-> version * $cadena_original .= $infoFactura->facturaSerie.'|';// ||-> serie folio fiscal original $cadena_original .= $infoFactura->facturaFolio.'|';// ||-> folio fiscal original $cadena_original .= $fecha[0].'T'.$fecha[1].'|';// ||-> fecha * $cadena_original .= $infoFactura->facturaMetodoPagoClave.'|';// ||-> forma de pago * /* formas de pago 01 = EFECTIVO 02 = CHEQUE NOMINATIVO 03 = TRANSFERENCIA ELECTRONICA DE FONDOS 04 = TARJETA DE CREDITO 05 = MONEDERO ELECTRONICO 06 = DINERO ELECTRONICO 08 = VALES DE DESPENSA 28 = TARJETA DE DEBITO 29 = TARJETA DE SERVICIOS 99 = POR DEFINIR */ $cadena_original .= $infoFactura->empresaCertificadoNumero.'|';// ||-> numero de certificado del emisor $cadena_original .= number_format($infoFactura->facturaSubtotal,2,'.','').'|';// ||-> subtotal * $cadena_original .= 'MXN|';// ||-> moneda $cadena_original .= '1|';// ||-> tipo de cambio $cadena_original .= number_format($infoFactura->facturaTotal,2,'.','').'|';// ||-> total * $cadena_original .= 'I|';// ||-> tipo de comprobante * /* tipo de comprobante I = INGRESO E = EGRESO T = TRASLADO N = NOMINA P = PAGO */ $cadena_original .= $infoFactura->facturaFormaPagoClave.'|';// ||-> metodo de pago * /* metodo de pago PUE = PAGO EN UNA SOLA EXHIBICION PPD = PAGO EN PARCIALIDADES O DIFERIDO */ $cadena_original .= $infoFactura->sucursalCp.'|';// ||-> lugar de expedicion * ---> SOLO CODIGO POSTAL //$cadena_original .= '|';// ||-> condiciones de pago //$cadena_original .= number_format(0,2,'.','').'|';// ||-> descuento //$cadena_original .= '|';// ||-> numero de cuenta //$cadena_original .= '|';// ||-> monto folio fiscal original //atributos del emisor ---> $cadena_original .= $infoFactura->empresaRFC.'|';// ||-> rfc * $cadena_original .= $infoFactura->empresaRazon.'|';// ||-> nombre //$cadena_original .= $infoFactura->empresaDireccion.'|';// ||-> calle * //$cadena_original .= $infoFactura->empresaNumExt.'|';// ||-> numero exterior //$cadena_original .= '|';// ||-> numero interior //$cadena_original .= $infoFactura->empresaColonia.'|';// ||-> colonia //$cadena_original .= $infoFactura->empresaCiudad.'|';// ||-> localidad //$cadena_original .= '|';// ||-> referencia //$cadena_original .= $infoFactura->empresaCiudad.'|';// ||-> municipio * //$cadena_original .= $infoFactura->empresaEstado.'|';// ||-> estado * //$cadena_original .= 'MEXICO|';// ||-> pais * //$cadena_original .= $infoFactura->empresaCp.'|';// ||-> codigo postal * //atributos expedidoEn ---> //$cadena_original .= $infoFactura->sucursalDireccion.'|';// ||-> calle * //$cadena_original .= $infoFactura->sucursalNumExt.'|';// ||-> numero exterior //$cadena_original .= '|';// ||-> numero interior //$cadena_original .= $infoFactura->sucursalColonia.'|';// ||-> colonia //$cadena_original .= $infoFactura->sucursalCiudad.'|';// ||-> localidad //$cadena_original .= '|';// ||-> referencia //$cadena_original .= $infoFactura->sucursalCiudad.'|';// ||-> municipio * //$cadena_original .= $infoFactura->sucursalEstado.'|';// ||-> estado * //$cadena_original .= 'MEXICO|';// ||-> pais * //$cadena_original .= $infoFactura->sucursalCp.'|';// ||-> codigo postal * $cadena_original .= $infoFactura->empresaRegimenClave.'|';// ||-> regimen fiscal * /* regimen fiscal 601 = GENERAL DE LEY PERSONAS MORALES 612 = PERSONAS FISICAS CON ACTIVIDADES EMPRESARIALES Y PROFESIONALES 621 = INCORPORACION FISCAL */ //atributos del receptor ---> $cadena_original .= $infoFactura->clienteRFC.'|';// ||-> rfc * $cadena_original .= $infoFactura->clienteRazon.'|';// ||-> nombre //$cadena_original .= $infoFactura->clienteDireccion.'|';// ||-> calle * //$infoFactura->clienteNumExt != NULL ? $cadena_original .= $infoFactura->clienteNumExt.'|' : '';// ||-> numero exterior //$infoFactura->clienteNumInt != NULL ? $cadena_original .= $infoFactura->clienteNumInt.'|' : '';// ||-> numero interior //$infoFactura->clienteColonia != NULL ? $cadena_original .= $infoFactura->clienteColonia.'|' : '';// ||-> colonia //$cadena_original .= $infoFactura->clienteCiudad.'|';// ||-> localidad //$cadena_original .= '|';// ||-> referencia //$cadena_original .= $infoFactura->clienteCiudad.'|';// ||-> municipio * //$cadena_original .= $infoFactura->clienteEstado.'|';// ||-> estado * //$cadena_original .= 'MEXICO|';// ||-> pais * //$infoFactura->clienteCp != NULL ? $cadena_original .= $infoFactura->clienteCp.'|' : '';// ||-> codigo postal * $cadena_original .= $infoFactura->facturaUsoCFDI.'|'; // |-> uso CFDI /* USO CFDI G01 = ADQUISICION DE MERCANCIAS G02 = DEVOLUCIONES, DESCUENTOS O BONIFICACIONES G03 = GASTOS EN GENERAL IO1 = CONSTRUCCIONES I02 = MOBILIARIO Y EQUIPO DE OFICINA POR INVERSIONES I03 = EQUIPO DE TRANSPORTE I04 = EQUIPO DE COMPUTO Y ACCESORIOS I05 = DADOS, TROQUELES, MOLDES, MATRICES Y HERRAMENTAL ... N USOS -- PO1 = POR DEFINIR */ //iteramos los conceptos foreach ($conceptos as $key => $concepto) { //calculamos precio unitario e importe antes de iva //validamos si se mostraras las partidas originales o solo la partida de facturacion if ($infoFactura->ventaPartidaFactura == 0) { //$preciou = $concepto->precio - calcularDescuento($concepto->precio,$concepto->descuento); $preciou = $concepto->precioUnitarioXML; //$importe = $preciou * $concepto->cantidad; $importe = $concepto->importe; $tasaCuota = ($concepto->partidaIVA / 100); //$importeImpuesto = $importe * $tasaCuota; $importeImpuesto = $concepto->iva; }else{ $preciou = $infoFactura->facturaSubtotal; $importe = $preciou; $tasaCuota = ($concepto->partidaIVA / 100); $importeImpuesto = $infoFactura->facturaIVA; } $cadena_original .= $concepto->claveProductoServicio.'|'; // |->clave de producto o servicio * $cadena_original .= $concepto->codigob.'|';// ||-> numero de identificacion $cadena_original .= number_format($concepto->cantidad,3,'.','').'|';// ||-> cantidad* $cadena_original .= $concepto->claveUnidad.'|'; // |->clave de unidad $cadena_original .= $concepto->descripcion.'|';// ||-> descripcion* $cadena_original .= number_format($preciou,2,'.','').'|';// ||-> valor unitario* $cadena_original .= number_format($importe,2,'.','').'|';// ||-> importe* // ---- informacion de traslado de conceptos Impuestos $cadena_original .= number_format($importe,2,'.','').'|'; // |->base* es el importe del concepto $cadena_original .= '002|'; // |->Impuesto /* impuesto 001 = ISR 002 = IVA 003 = IEPS */ $cadena_original .= 'Tasa|';// |->tipo factor /* TIPO FACTOR ->TASA ->CUOTA ->EXCENTO */ if ($tasaCuota == 0) { $tasa0 = true; }else{ $tasa16 = true; } $cadena_original .= number_format($tasaCuota,6,'.','').'|';// |->tasa cuota $cadena_original .= number_format($importeImpuesto,2,'.','').'|';// |->importe del impuesto } if ($tasa16 === true) { // informacion total de impuestos $cadena_original .= '002|';// ||-> nombre del impuesto* /* impuesto 001 = ISR 002 = IVA 003 = IEPS */ $cadena_original .= 'Tasa|';// |->tipo factor /* TIPO FACTOR ->TASA ->CUOTA ->EXCENTO */ $cadena_original .= '0.160000|';// |->tasa cuota $cadena_original .= number_format($infoFactura->facturaIVA, 2,'.','').'|';// ||-> importe* } if ($tasa0 === true) { // informacion total de impuestos $cadena_original .= '002|';// ||-> nombre del impuesto* /* impuesto 001 = ISR 002 = IVA 003 = IEPS */ $cadena_original .= 'Tasa|';// |->tipo factor /* TIPO FACTOR ->TASA ->CUOTA ->EXCENTO */ $cadena_original .= '0.000000|';// |->tasa cuota $cadena_original .= '0.00|';// ||-> importe* } $cadena_original .= number_format($infoFactura->facturaIVA, 2,'.','').'||'; // ||-> total de impuestos trasladados //limpiamos la cadena original de espacios y codificamos a utf8 $cadena_original = str_replace(" "," ",$cadena_original); $cadena_original = utf8_decode($cadena_original); $cadena_original = utf8_encode($cadena_original); //CERTIFICADO DIGITAL DEL CONTRIBUYENTE $num_certificado = $infoFactura->empresaCertificadoNumero; $archivo_cer = 'files/sellos/'.$infoFactura->empresaCertificadoNumero.'.cer'; $certificado_texto = str_replace(array('\n', '\r'), '', base64_encode(file_get_contents($archivo_cer))); $llave = 'files/sellos/llave.key.pem'; // == GENERACION DE SELLO DIGITAL == // $fp = fopen($llave,"r"); $priv_key = fread($fp,8192); fclose($fp); $pkeyid = openssl_get_privatekey($priv_key); openssl_sign($cadena_original,$cadena_firmada,$pkeyid,OPENSSL_ALGO_SHA256); $sello = base64_encode($cadena_firmada); // ================================= // //creo el xml en memoria $cadena_xml = ''; $cadena_xml .= '<?xml version="1.0" encoding="UTF-8"?>'; $cadena_xml .= '<cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sat.gob.mx/cfd/3 http://www.sat.gob.mx/sitio_internet/cfd/3/cfdv33.xsd" Version="3.3" '; $cadena_xml .= 'Sello="'.$sello.'"'; $cadena_xml .= ' Serie="'.$infoFactura->facturaSerie.'" Folio="'.$infoFactura->facturaFolio.'" Fecha="'.$fecha[0].'T'.$fecha[1].'" FormaPago="'.$infoFactura->facturaMetodoPagoClave.'" NoCertificado="'.$num_certificado.'" '; $cadena_xml .= 'Certificado="'.$certificado_texto.'"'; $cadena_xml .= ' SubTotal="'.number_format($infoFactura->facturaSubtotal,2,'.','').'" Total="'.number_format($infoFactura->facturaTotal,2,'.','').'"'; $cadena_xml .= ' MetodoPago="'.$infoFactura->facturaFormaPagoClave.'" TipoDeComprobante="I" TipoCambio="1" Moneda="MXN" LugarExpedicion="'.$infoFactura->sucursalCp.'" > '; $cadena_xml .= ' <cfdi:Emisor Rfc="'.$infoFactura->empresaRFC.'" Nombre="'.$infoFactura->empresaRazon.'" RegimenFiscal="'.$infoFactura->empresaRegimenClave.'" /> '; $cadena_xml .= ' <cfdi:Receptor Rfc="'.$infoFactura->clienteRFC.'" Nombre="'.$this->limpiarCaracteres($infoFactura->clienteRazon).'" UsoCFDI="'.$infoFactura->facturaUsoCFDI.'" /> '; $cadena_xml .= ' <cfdi:Conceptos> '; foreach ($conceptos as $key => $concepto) { //calculamos precio unitario e importe antes de iva //validamos si se mostraras las partidas originales o solo la partida de facturacion if ($infoFactura->ventaPartidaFactura == 0) { //$preciou = $concepto->precio - calcularDescuento($concepto->precio,$concepto->descuento); $preciou = $concepto->precioUnitarioXML; //$importe = $preciou * $concepto->cantidad; $importe = $concepto->importe; $tasaCuota = ($concepto->partidaIVA / 100); //$importeImpuesto = $importe * $tasaCuota; $importeImpuesto = $concepto->iva; }else{ $preciou = $infoFactura->facturaSubtotal; $importe = $preciou; $tasaCuota = ($concepto->partidaIVA / 100); $importeImpuesto = $infoFactura->facturaIVA; } $cadena_xml .= ' <cfdi:Concepto ClaveProdServ="'.$concepto->claveProductoServicio.'" ClaveUnidad="'.$concepto->claveUnidad.'" Cantidad="'.number_format($concepto->cantidad,3,'.','').'" NoIdentificacion="'.$concepto->codigob.'" Descripcion="'.$this->limpiarCaracteres($concepto->descripcion).'" ValorUnitario="'.number_format($preciou,2,'.','').'" Importe="'.number_format($importe,2,'.','').'"> <cfdi:Impuestos> <cfdi:Traslados> <cfdi:Traslado Base="'.number_format($importe,2,'.','').'" Impuesto="002" TipoFactor="Tasa" TasaOCuota="'.number_format($tasaCuota,6,'.','').'" Importe="'.number_format($importeImpuesto,2,'.','').'" /> </cfdi:Traslados> </cfdi:Impuestos> </cfdi:Concepto> '; } $cadena_xml .= ' </cfdi:Conceptos> '; $cadena_xml .= ' <cfdi:Impuestos TotalImpuestosTrasladados="'.number_format($infoFactura->facturaIVA,2,'.','').'"> <cfdi:Traslados> '; if ($tasa16 === true) { $cadena_xml .= '<cfdi:Traslado Impuesto="002" TipoFactor="Tasa" TasaOCuota="0.160000" Importe="'.number_format($infoFactura->facturaIVA,2,'.','').'" />'; } if ($tasa0 === true) { $cadena_xml .= '<cfdi:Traslado Impuesto="002" TipoFactor="Tasa" TasaOCuota="0.000000" Importe="0.00" />'; } $cadena_xml .= ' </cfdi:Traslados> </cfdi:Impuestos> </cfdi:Comprobante> '; $cadena_xml=str_replace(" "," ",$cadena_xml); //Dado que un String convencional no esta adecuado para recibir acentos, se deben interpretar esos caracteres, de la siguiente manera. $cadena_xml = utf8_decode($cadena_xml); //Una ves que ya tengo la cadena con los acentos debidamente codificados, aplico la codificion UTF-8 al XML. $cadena_xml = utf8_encode($cadena_xml); // ===== creamos ruta para almacenar el XML/PDF ===== ---> //descomponemos la fecha, para almacenar los archivos en el directorio correcto, ..\AÑO\MES\ aqui los archivos $fc = explode("-",$fecha[0]);//$fc[0]=año, $fc[1]=mes //creamos el nombre de la carpeta de la empresa con el rfc $folder_factura = $infoFactura->empresaRFC; //validamos si existe la carpeta con el rfc de la empresa, sino la cremos if(!file_exists('files/facturas/'.$folder_factura.'/')){ mkdir('files/facturas/'.$folder_factura.'/',0777); } //crear folder de clientes en caso de no existir if(!file_exists('files/facturas/'.$folder_factura.'/clientes/')){ mkdir('files/facturas/'.$folder_factura.'/clientes/',0777); } //crear folder del año en caso de no existir if(!file_exists('files/facturas/'.$folder_factura.'/clientes/'.$fc[0].'/')){ mkdir('files/facturas/'.$folder_factura.'/clientes/'.$fc[0].'/',0777); } //crear folder del mes en caso de no existir if(!file_exists('files/facturas/'.$folder_factura.'/clientes/'.$fc[0].'/'.$fc[1].'/')){ mkdir('files/facturas/'.$folder_factura.'/clientes/'.$fc[0].'/'.$fc[1].'/',0777); } $ruta_xml = 'files/facturas/'.$folder_factura.'/clientes/'.$fc[0].'/'.$fc[1].'/'.$infoFactura->facturaSerie.$infoFactura->facturaFolio; // ================================================== //Se guarda el XML con el siguiente nombre. $new_xml = fopen ($ruta_xml.".xml", "w"); fwrite($new_xml,$cadena_xml); fclose($new_xml); //covertimos a zip $zip = new ZipArchive(); $zip_file = $ruta_xml.".zip"; $zip->open($zip_file, ZipArchive::CREATE); $zip->addFile($ruta_xml.".xml",$infoFactura->facturaSerie.$infoFactura->facturaFolio.".xml"); $zip->close(); // == TIMBRADO == // $wsdl="https://sat.sifei.com.mx:8443/SIFEI/SIFEI?wsdl"; $file = base64_encode(file_get_contents($ruta_xml.".zip")); $parametros=array("Usuario"=>"$infoFactura->sifeiUsuario","Password"=>"$infoFactura->sifeiPassword","archivoXMLZip"=>$file,"Serie"=>" ","IdEquipo"=>"$infoFactura->sifeiIdEquipo"); $client= new nusoap_client($wsdl,true); $rst=$client->call('getCFDI',$parametros); //borramos el archivo ZIP unlink($ruta_xml.".zip"); //verificar que no causo algun error if(isset($rst['detail']['SifeiException']['message'])){ //unlink($ruta_xml.".xml");//borramos el archivo XML creado $error["codigoError"] = $rst['detail']['SifeiException']['codigo']; $error["error"] = true; }elseif($rst==""){ unlink($ruta_xml.".xml");//borramos el archivo XML creado $error["codigoError"] = 999; $error["error"] = true; }else{ // |-> si no causo error genera la factura unlink($ruta_xml.".xml");//borramos el archivo XML creado $timbre = base64_decode($rst["return"]);//decodificamos respuesta //creamos un ZIP con el XML dentro del ZIP $new_xml = fopen ($ruta_xml.".zip", "w"); fwrite($new_xml,$timbre); fclose($new_xml); $zip = new ZipArchive; if ($zip->open($ruta_xml.".zip") === TRUE) { $name = $zip->getNameIndex(0); $zip->extractTo('files/facturas/'.$folder_factura.'/clientes/'.$fc[0].'/'.$fc[1].'/'); $zip->close(); unlink($ruta_xml.".zip"); rename('files/facturas/'.$folder_factura.'/clientes/'.$fc[0].'/'.$fc[1].'/'.$name,$ruta_xml.".xml"); //leemos XML para extraer informacion generada por el PAC $load_xml = simplexml_load_file($ruta_xml.'.xml'); $ns = $load_xml->getNamespaces(true); $load_xml->registerXPathNamespace('t', $ns['tfd']); foreach ($load_xml->xpath('//t:TimbreFiscalDigital') as $tfd) { $uuid = "{$tfd['UUID']}"; $selloSAT = "{$tfd['SelloSAT']}"; $certificadoSAT = "{$tfd['NoCertificadoSAT']}"; $sellocfd = "{$tfd['SelloCFD']}"; $fechaTimbradoS = "{$tfd['FechaTimbrado']}"; $fechaTimbrado = "{$tfd['FechaTimbrado']}"; $fechaTimbrado = str_replace("T"," ",$fechaTimbrado); } //generamos la cadena original del complemento de certificacion del sat $cadena_original_sat = '||1.0|'; $cadena_original_sat .= $uuid.'|'; $cadena_original_sat .= $fechaTimbradoS.'|'; $cadena_original_sat .= $sellocfd.'|'; $cadena_original_sat .= $certificadoSAT.'||'; //generamos el codigo qr2 y lo guardamos en el servidor al terminar lo borramos $texto_qr2 = '?re='.$infoFactura->empresaRFC.'&rr='.$infoFactura->clienteRFC.'&tt='.$infoFactura->facturaTotal.'&id='.$uuid; QRcode::png($texto_qr2, 'temp/qr2.png'); } // ============== GENERAMOS PDF ================== $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false); // remove default header/footer $pdf->setPrintHeader(false); $pdf->setPrintFooter(false); // set default monospaced font $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED); // set margins $pdf->SetMargins("10", "10", "10"); // set auto page breaks $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM); // set image scale factor $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO); // set some language-dependent strings (optional) if (@file_exists(dirname(__FILE__).'/lang/eng.php')) { require_once(dirname(__FILE__).'/lang/eng.php'); $pdf->setLanguageArray($l); } // set font $pdf->SetFont('', '', 7); // add a page $pdf->AddPage(); $html = '<table width="670" border="0" cellspacing="0" cellpadding="0"> <tr> <td><table width="100%" border="0" cellspacing="10" cellpadding="0"> <tr> <td width="'.$infoFactura->medidas[0].'%" valign="top"><img src="'.base_url("assets/images/logo_cotiza.jpg").'" width="'.$infoFactura->medidas[3].'" /></td> <td width="'.$infoFactura->medidas[1].'%" valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr align="center"> <td><strong>'.$infoFactura->empresaRazon.'</strong></td> </tr> <tr align="center"> <td>'.$infoFactura->empresaDireccion.' No. Ext. '.$infoFactura->empresaNumExt; if ($infoFactura->empresaNumInt != '' && $infoFactura->empresaNumInt != NULL) { $html .= ', No. Int '.$infoFactura->empresaNumInt; } $html .= ' , '.$infoFactura->empresaColonia.'</td> </tr> <tr align="center"> <td>C.P. '.$infoFactura->empresaCp.', '.$infoFactura->empresaCiudad.', '.$infoFactura->empresaEstado.'</td> </tr> <tr align="center"> <td>RFC: '.$infoFactura->empresaRFC.'</td> </tr> <tr align="center"> <td>'.$infoFactura->empresaRegimenClave.' - '.$infoFactura->empresaRegimenNombre.'</td> </tr> </table></td> <td width="'.$infoFactura->medidas[2].'%" valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td align="center"><span style="color:red;">FACTURA '.$infoFactura->facturaSerie.$infoFactura->facturaFolio.'</span></td> </tr> <tr> <td align="center"><span style="color:blue;">Fecha/Hora</span></td> </tr> <tr> <td align="center"><span style="color:blue;">Certificación</span></td> </tr> <tr> <td align="center">'.$fechaTimbrado.'</td> </tr> <tr> <td align="center"><span style="color:blue;">Fecha de Emisión</span></td> </tr> <tr> <td align="center">'.$fecha[0].' '.$fecha[1].'</td> </tr> <tr> <td align="center"><span style="color:blue;">Tipo de Comprobante</span></td> </tr> <tr> <td align="center">I - Ingreso</td> </tr> <tr> <td align="center"><span style="color:blue;">Lugar de Expedicion</span></td> </tr> <tr> <td align="center">'.$infoFactura->sucursalCp.'</td> </tr> </table></td> </tr> </table></td> </tr> <tr> <td>&nbsp;</td> </tr> <tr> <td><table width="100%" border="0" cellspacing="10" cellpadding="0"> <tr> <td width="36%" valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td><span style="color:blue;">Receptor del comprobante fiscal</span></td> </tr> <tr> <td>&nbsp;</td> </tr> <tr> <td><strong>'.$infoFactura->clienteRazon.'</strong></td> </tr> <tr> <td>'.$infoFactura->clienteDireccion; if($infoFactura->clienteNumExt != '' && $infoFactura->clienteNumExt != NULL && $infoFactura->clienteNumExt != 0){ $html .= ', No. Ext. '.$infoFactura->clienteNumExt; } if($infoFactura->clienteNumInt != '' && $infoFactura->clienteNumInt != NULL){ $html .= ', No. Int. '.$infoFactura->clienteNumInt; } $html .= ' , '.$infoFactura->clienteColonia.',</td> </tr> <tr> <td>C.P. '.$infoFactura->clienteCp.', '.$infoFactura->clienteCiudad.', '.$infoFactura->clienteEstado.', México</td> </tr> <tr> <td>RFC: '.$infoFactura->clienteRFC.'</td> </tr> <tr> <td><strong>Uso CFDI: </strong>'.$infoFactura->facturaUsoCFDI.' - '.$infoFactura->facturaUsoCFDInombre.'</td> </tr> </table></td> <td width="32%" valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td>&nbsp;</td> </tr> <tr> <td>&nbsp;</td> </tr> </table></td> <td width="32%" valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td align="center"><span style="color:blue;">Folio Fiscal</span></td> </tr> <tr> <td align="center">'.$uuid.'</td> </tr> <tr> <td align="center">&nbsp;</td> </tr> <tr> <td align="center"><span style="color:blue;">Numero de Serie del Certificado</span></td> </tr> <tr> <td align="center">'.$num_certificado.'</td> </tr> <tr> <td align="center">&nbsp;</td> </tr> <tr> <td align="center"><span style="color:blue;">Numero de Serie del Certificado del SAT</span></td> </tr> <tr> <td align="center">'.$certificadoSAT.'</td> </tr> </table></td> </tr> </table></td> </tr> '; // Aqui se incluyen los comentarios de la venta $html .= ' <tr> <td>'.$infoFactura->ventaComentarios.'</td> </tr> '; $html .= ' <tr> <td>&nbsp;</td> </tr> <tr> <td><table width="100%" border="0" cellspacing="2" cellpadding="3" style="border:#CCC solid 1px; border-radius:5px;"> <tr style="background-color:#EBEBEB;"> <td width="8%" align="center"><strong style="color:#00F;">Cantidad</strong></td> <td width="14%" align="center"> <strong style="color:#00F;">ClaveProdServ</strong><br> <strong style="color:#00F;">Clave unidad</strong><br> <strong style="color:#00F;">No. Identificacion</strong> </td> <td width="'.$infoFactura->porcentajeDescripcion.'%" align="center"><strong style="color:#00F;">Descripción</strong></td> <td width="13%" align="center"><strong style="color:#00F;">Valor Unitario</strong></td> '; // == campos dinamicos == if ($infoFactura->camposDinamicos !== false){ foreach ($infoFactura->camposDinamicos as $key => $campo){ if (in_array($campo->venta_campos_cot_id, $infoFactura->camposVenta)){ $html .= '<td width="8%" align="center"><strong style="color:#00F;">'.$campo->venta_campos_cot_nombre.'</strong></td>'; } } } $html .= ' <td width="13%" align="center"><strong style="color:#00F;">Impuesto</strong></td> <td width="12%" align="center"><strong style="color:#00F;">Importe</strong></td> </tr>'; //==== productos foreach ($conceptos as $key => $concepto) { //calculamos precio unitario e importe antes de iva //validamos si se mostraras las partidas originales o solo la partida de facturacion if ($infoFactura->ventaPartidaFactura == 0) { //$preciou = $concepto->precio - calcularDescuento($concepto->precio,$concepto->descuento); $preciou = $concepto->precioUnitario; //$importe = $preciou * $concepto->cantidad; $importe = $concepto->importe; }else{ $preciou = $infoFactura->facturaSubtotal; $importe = $preciou; } $html .= ' <tr> <td align="center">'.$concepto->cantidad.'</td> <td align="center">'.$concepto->claveProductoServicio.'<br>'.$concepto->claveUnidad.'<br>'.$concepto->codigob.'</td> <td align="center">'.$concepto->descripcion.'</td> <td align="center">$ '.number_format($preciou,2).'</td> '; // == campos dinamicos == if ($infoFactura->camposDinamicos !== false){ foreach ($infoFactura->camposDinamicos as $key => $campo){ if (in_array($campo->venta_campos_cot_id, $infoFactura->camposVenta)){ $html .= '<td align="center">'; //aqui traemos la informacion de los campos adicionales $primerNivel = explode("||", $concepto->camposCotizacion); foreach ($primerNivel as $key => $Pnivel) { $segundoNivel = explode("@", $Pnivel); if ($segundoNivel[0] == $campo->venta_campos_cot_id) { $html .= $segundoNivel[1]; } } $html .= '</td>'; } } } if ($infoFactura->ventaPartidaFactura == 0) { $html .= '<td align="center">002-IVA | $ '.number_format($concepto->iva,2).'</td>'; }else{ $html .= '<td align="center">002-IVA | $ '.number_format($infoFactura->facturaIVA,2).'</td>'; } $html .= ' <td align="center">$ '.number_format($importe,2).'</td> </tr> '; if($concepto->comentario !='' && $concepto->comentario != NULL){ $comentario = nl2br($concepto->comentario); $html .= ' <tr> <td colspan="2" align="right"><strong>Comentarios:</strong></td> <td align="justify" colspan="3">'.$comentario.'</td> <td></td> </tr> '; } } $html .= '</table></td> </tr> <tr> <td><table width="100%" border="0" cellspacing="10" cellpadding="0"> <tr> <td width="65%" valign="top"><table width="100%" border="0" cellspacing="10" cellpadding="0"> <tr> <td><strong>Moneda: </strong>MXN - Peso Mexicano</td> </tr> <tr> <td><strong>Forma de pago: </strong>'.$infoFactura->facturaMetodoPago.'</td> </tr> <tr> <td><strong>Metodo de Pago: </strong>'.$infoFactura->facturaFormaPagoClave.' - '.$infoFactura->facturaFormaPago.'</td> </tr> <tr> <td><strong>Importe Total con letra: </strong>( '.$infoFactura->facturaTotalLetras.' )</td> </tr> </table></td> <td width="35%" valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td colspan="2" align="center"><strong style="color:#00F;">&nbsp;</strong></td> </tr> <tr> <td width="70%">Subtotal</td> <td width="30%" align="right">$ '.number_format($infoFactura->facturaSubtotal,2).'</td> </tr> <tr> <td>Total Impuestos Trasladados</td> <td align="right">$ '.number_format($infoFactura->facturaIVA,2).'</td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td colspan="2"><hr></td> </tr> <tr> <td>Total Comprobante</td> <td align="right">$ '.number_format($infoFactura->facturaTotal,2).'</td> </tr> </table></td> </tr> </table></td> </tr> <tr> <td><table width="100%" border="0" cellspacing="10" cellpadding="0"> <tr> <td><strong style="color:blue;">Cadena original del complemento de certificación digital del SAT</strong></td> </tr> <tr> <td>'.$cadena_original_sat.'</td> </tr> </table></td> </tr> <tr> <td>&nbsp;</td> </tr> <tr> <td><table width="100%" border="0" cellspacing="10" cellpadding="0"> <tr> <td width="20%" rowspan="4" valign="top"><img src="temp/qr2.png" width="120" /></td> <td width="80%" valign="top"><strong style="color:blue;">Sello Digital del CFDI</strong></td> </tr> <tr> <td valign="top">'.$sellocfd.'</td> </tr> <tr> <td valign="top"><strong style="color:blue;">Sello digital del SAT</strong></td> </tr> <tr> <td valign="top">'.$selloSAT.'</td> </tr> </table></td> </tr> <tr> <td>&nbsp;</td> </tr> <tr> <td>&nbsp;</td> </tr> <tr> <td>&nbsp;</td> </tr> <tr> <td align="center">Este documento es una representación impresa de un CFDI</td> </tr> </table>'; // output the HTML content $pdf->writeHTML($html, true, false, true, false, ''); //Close and output PDF document $pdf->Output($ruta_xml.'.pdf', 'F'); // ======== fin PDF ======== //informacion para retornar y actualizar la factura como TImbrada $facturaTimbrada = array( "uuid" => $uuid, "selloSAT" => $selloSAT, "certificadoSAT" => $certificadoSAT, "sellocfd" => $sellocfd, "fechaTimbrado" => $fechaTimbrado, "rutaXML" => $ruta_xml.".xml", "rutaPDF" => $ruta_xml.".pdf", "error" => false ); } //si existio algun error en el proceso se retorna el objeto error con el codigo de error //de lo contrario se retorna la informacion de la factura timbrada if ($error === false) { return $facturaTimbrada; }else{ return $error; } } function cancelar($infoFactura) { //ruta del archivo PFX $archivo_pfx = "files/sellos/CER_KEY.pfx"; //timbrar cancelacion de factura $wsdl="https://sat.sifei.com.mx:8443/SIFEI/SIFEI?wsdl"; $file=base64_encode(file_get_contents($archivo_pfx)); $parametros=array("usuarioSIFEI"=>"$infoFactura->sifeiUsuario", "passUser"=>"$infoFactura->sifeiPassword","rfc"=>"$infoFactura->empresaRFC","pfx"=>"$file","passPFX"=>"$infoFactura->sifeiPassPFX","UUIDS"=>"$infoFactura->facturaFolioFiscal"); $client= new nusoap_client($wsdl,true); $rst=$client->call('cancelaCFDI',$parametros); //verificar que no causo algun error if(isset($rst['detail']['SifeiException']['message'])){ return false; }elseif($rst==""){ return false; }else{ return true; } } function complementoDePago($infoPago,$documentosRelacionados) { $error = false; // === CONTRUCCION DE CADENA ORIGINAL === // $cadena_original = ''; //atributos del comprobante ---> $cadena_original .= '||3.3|';// ||-> version * $cadena_original .= $infoPago->pagoSerie.'|';// ||-> serie $cadena_original .= $infoPago->pagoFolio.'|';// ||-> folio interno $cadena_original .= $infoPago->fechaActualCFDI.'|';// ||-> fecha * $cadena_original .= $infoPago->empresaCertificadoNumero.'|';// ||-> numero de certificado del emisor $cadena_original .= '0|';// ||-> subtotal * $cadena_original .= 'XXX|';// ||-> moneda $cadena_original .= '0|';// ||-> total * $cadena_original .= 'P|';// ||-> tipo de comprobante * /* tipo de comprobante I = INGRESO E = EGRESO T = TRASLADO N = NOMINA P = PAGO */ $cadena_original .= $infoPago->sucursalCP.'|';// ||-> lugar de expedicion * ---> SOLO CODIGO POSTAL //atributos del emisor ---> $cadena_original .= $infoPago->empresaRFC.'|';// ||-> rfc * $cadena_original .= $infoPago->empresaRazon.'|';// ||-> nombre $cadena_original .= $infoPago->empresaRegimenFiscalClave.'|';// ||-> regimen fiscal* /* regimen fiscal 601 = GENERAL DE LEY PERSONAS MORALES 612 = PERSONAS FISICAS CON ACTIVIDADES EMPRESARIALES Y PROFESIONALES 621 = INCORPORACION FISCAL */ //atributos del receptor ---> $cadena_original .= $infoPago->clienteRFC.'|';// ||-> rfc* $cadena_original .= $infoPago->clienteRazon.'|';// ||-> nombre $cadena_original .= 'P01|'; // |-> uso CFDI /* USO CFDI G01 = ADQUISICION DE MERCANCIAS G02 = DEVOLUCIONES, DESCUENTOS O BONIFICACIONES G03 = GASTOS EN GENERAL IO1 = CONSTRUCCIONES I02 = MOBILIARIO Y EQUIPO DE OFICINA POR INVERSIONES I03 = EQUIPO DE TRANSPORTE I04 = EQUIPO DE COMPUTO Y ACCESORIOS I05 = DADOS, TROQUELES, MOLDES, MATRICES Y HERRAMENTAL ... N USOS -- PO1 = POR DEFINIR */ $cadena_original .= '84111506|'; // |->clave de producto o servicio * $cadena_original .= '1|';// ||-> cantidad * $cadena_original .= 'ACT|'; // |->clave de unidad $cadena_original .= 'Pago|';// ||-> descripcion * $cadena_original .= '0|';// ||-> valor unitario * $cadena_original .= '0|';// ||-> importe * //complemento de pago $cadena_original .= '1.0|';// ||->version $cadena_original .= $infoPago->pagoFechaPagoCFDI.'|';// ||->fecha de pago $cadena_original .= $infoPago->metodoPagoClave.'|';// ||->forma de pago $cadena_original .= 'MXN|';// ||->moneda $cadena_original .= number_format($infoPago->pagoTotal,2,".","").'|';// ||->monto $cadena_original .= $infoPago->pagoNumeroOperacion.'|';// ||->referencia //documentos relacionados foreach ($documentosRelacionados as $key => $documento) { $cadena_original .= $documento->facturaUUID.'|'; $cadena_original .= 'MXN|'; $cadena_original .= 'PPD|'; $cadena_original .= '1|'; $cadena_original .= number_format($documento->cxcTotal,2,'.','').'|'; $cadena_original .= number_format($documento->cxcTotal,2,'.','').'|'; $cadena_original .= '0.00|'; } $cadena_original .= '|'; $cadena_original = str_replace(" "," ",$cadena_original); $cadena_original = utf8_decode($cadena_original); $cadena_original = utf8_encode($cadena_original); // ====================================== // ||-> resultado -> CADENA ORIGINAL DEL DOCUMENTO //CERTIFICADO DIGITAL DEL CONTRIBUYENTE $num_certificado = $infoPago->empresaCertificadoNumero; $archivo_cer = 'files/sellos/'.$infoPago->empresaCertificadoNumero.'.cer'; $certificado_texto = str_replace(array('\n', '\r'), '', base64_encode(file_get_contents($archivo_cer))); $llave = 'files/sellos/llave.key.pem'; // == GENERACION DE SELLO DIGITAL == // $fp = fopen($llave,"r"); $priv_key = fread($fp,8192); fclose($fp); $pkeyid = openssl_get_privatekey($priv_key); openssl_sign($cadena_original,$cadena_firmada,$pkeyid,OPENSSL_ALGO_SHA256); $sello = base64_encode($cadena_firmada); // ================================= // //creo el xml en memoria $cadena_xml = ''; $cadena_xml .= '<?xml version="1.0" encoding="UTF-8"?>'; $cadena_xml .= '<cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sat.gob.mx/cfd/3 http://www.sat.gob.mx/sitio_internet/cfd/3/cfdv33.xsd" Version="3.3" '; $cadena_xml .= 'Sello="'.$sello.'"'; $cadena_xml .= ' Serie="'.$infoPago->pagoSerie.'" Folio="'.$infoPago->pagoFolio.'" Fecha="'.$infoPago->fechaActualCFDI.'" NoCertificado="'.$num_certificado.'" '; $cadena_xml .= 'Certificado="'.$certificado_texto.'"'; $cadena_xml .= ' SubTotal="0" Total="0"'; $cadena_xml .= ' TipoDeComprobante="P" Moneda="XXX" LugarExpedicion="'.$infoPago->sucursalCP.'" > '; $cadena_xml .= ' <cfdi:Emisor Rfc="'.$infoPago->empresaRFC.'" Nombre="'.$infoPago->empresaRazon.'" RegimenFiscal="'.$infoPago->empresaRegimenFiscalClave.'" /> '; $cadena_xml .= ' <cfdi:Receptor Rfc="'.$infoPago->clienteRFC.'" Nombre="'.$this->limpiarCaracteres($infoPago->clienteRazon).'" UsoCFDI="P01" /> '; $cadena_xml .= ' <cfdi:Conceptos> '; $cadena_xml .= ' <cfdi:Concepto ClaveProdServ="84111506" ClaveUnidad="ACT" Cantidad="1" Descripcion="Pago" ValorUnitario="0" Importe="0" /> '; $cadena_xml .= ' </cfdi:Conceptos> '; $cadena_xml .= '<cfdi:Complemento>'; $cadena_xml .= ' <pago10:Pagos xmlns:pago10="http://www.sat.gob.mx/Pagos" Version="1.0" xsi:schemaLocation="http://www.sat.gob.mx/Pagos http://www.sat.gob.mx/sitio_internet/cfd/Pagos/Pagos10.xsd"> '; $cadena_xml .= ' <pago10:Pago FechaPago="'.$infoPago->pagoFechaPagoCFDI.'" FormaDePagoP="'.$infoPago->metodoPagoClave.'" MonedaP="MXN" Monto="'.number_format($infoPago->pagoTotal,2,'.','').'" NumOperacion="'.$infoPago->pagoNumeroOperacion.'"> '; //documentos relacionados foreach ($documentosRelacionados as $key => $documento) { $cadena_xml .= ' <pago10:DoctoRelacionado IdDocumento="'.$documento->facturaUUID.'" MonedaDR="MXN" MetodoDePagoDR="PPD" NumParcialidad="1" ImpSaldoAnt="'.$documento->cxcTotal.'" ImpPagado="'.$documento->cxcTotal.'" ImpSaldoInsoluto="0.00" /> '; } $cadena_xml .= ' </pago10:Pago> '; $cadena_xml .= ' </pago10:Pagos> '; $cadena_xml .= '</cfdi:Complemento>'; $cadena_xml .= '</cfdi:Comprobante>'; $cadena_xml=str_replace(" "," ",$cadena_xml); //Dado que un String convencional no esta adecuado para recibir acentos, se deben interpretar esos caracteres, de la siguiente manera. $cadena_xml = utf8_decode($cadena_xml); //Una ves que ya tengo la cadena con los acentos debidamente codificados, aplico la codificion UTF-8 al XML. $cadena_xml = utf8_encode($cadena_xml); // ================================================== // ===== creamos ruta para almacenar el XML/PDF ===== ---> //descomponemos la fecha, para almacenar los archivos en el directorio correcto, ..\AÑO\MES\ aqui los archivos $fc = explode("-",$infoPago->fechaActual);//$fc[0]=año, $fc[1]=mes //creamos el nombre de la carpeta de la empresa con el rfc $folder_factura = $infoPago->empresaRFC; //validamos si existe la carpeta con el rfc de la empresa, sino la cremos if(!file_exists('files/facturas/'.$folder_factura.'/')){ mkdir('files/facturas/'.$folder_factura.'/',0777); } //crear folder de clientes en caso de no existir if(!file_exists('files/facturas/'.$folder_factura.'/clientes/')){ mkdir('files/facturas/'.$folder_factura.'/clientes/',0777); } //crear folder del año en caso de no existir if(!file_exists('files/facturas/'.$folder_factura.'/clientes/'.$fc[0].'/')){ mkdir('files/facturas/'.$folder_factura.'/clientes/'.$fc[0].'/',0777); } //crear folder del mes en caso de no existir if(!file_exists('files/facturas/'.$folder_factura.'/clientes/'.$fc[0].'/'.$fc[1].'/')){ mkdir('files/facturas/'.$folder_factura.'/clientes/'.$fc[0].'/'.$fc[1].'/',0777); } $ruta_xml = 'files/facturas/'.$folder_factura.'/clientes/'.$fc[0].'/'.$fc[1].'/'.$infoPago->pagoSerie.$infoPago->pagoFolio; // ================================================== //Se guarda el XML con el siguiente nombre. $new_xml = fopen ($ruta_xml.".xml", "w"); fwrite($new_xml,$cadena_xml); fclose($new_xml); //covertimos a zip $zip = new ZipArchive(); $zip_file = $ruta_xml.".zip"; $zip->open($zip_file, ZipArchive::CREATE); $zip->addFile($ruta_xml.".xml",$infoPago->pagoSerie.$infoPago->pagoFolio.".xml"); $zip->close(); // == TIMBRADO == // $wsdl="https://sat.sifei.com.mx:8443/SIFEI/SIFEI?wsdl"; $file = base64_encode(file_get_contents($ruta_xml.".zip")); $parametros=array("Usuario"=>"$infoPago->sifeiUsuario","Password"=>"$infoPago->sifeiPassword","archivoXMLZip"=>$file,"Serie"=>" ","IdEquipo"=>"$infoPago->sifeiIdEquipo"); $client= new nusoap_client($wsdl,true); $rst=$client->call('getCFDI',$parametros); //borramos el archivo ZIP unlink($ruta_xml.".zip"); //verificar que no causo algun error if(isset($rst['detail']['SifeiException']['message'])){ unlink($ruta_xml.".xml");//borramos el archivo XML creado $error["codigoError"] = $rst['detail']['SifeiException']['codigo']; $error["error"] = true; }elseif($rst==""){ unlink($ruta_xml.".xml");//borramos el archivo XML creado $error["codigoError"] = 999; $error["error"] = true; }else{ // |-> si no causo error genera la factura unlink($ruta_xml.".xml");//borramos el archivo XML creado $timbre = base64_decode($rst["return"]);//decodificamos respuesta //creamos un ZIP con el XML dentro del ZIP $new_xml = fopen ($ruta_xml.".zip", "w"); fwrite($new_xml,$timbre); fclose($new_xml); $zip = new ZipArchive; if ($zip->open($ruta_xml.".zip") === TRUE) { $name = $zip->getNameIndex(0); $zip->extractTo('files/facturas/'.$folder_factura.'/clientes/'.$fc[0].'/'.$fc[1].'/'); $zip->close(); unlink($ruta_xml.".zip"); rename('files/facturas/'.$folder_factura.'/clientes/'.$fc[0].'/'.$fc[1].'/'.$name,$ruta_xml.".xml"); //leemos XML para extraer informacion generada por el PAC $load_xml = simplexml_load_file($ruta_xml.'.xml'); $ns = $load_xml->getNamespaces(true); $load_xml->registerXPathNamespace('t', $ns['tfd']); foreach ($load_xml->xpath('//t:TimbreFiscalDigital') as $tfd) { $uuid = "{$tfd['UUID']}"; $selloSAT = "{$tfd['SelloSAT']}"; $certificadoSAT = "{$tfd['NoCertificadoSAT']}"; $sellocfd = "{$tfd['SelloCFD']}"; $fechaTimbradoS = "{$tfd['FechaTimbrado']}"; $fechaTimbrado = "{$tfd['FechaTimbrado']}"; $fechaTimbrado = str_replace("T"," ",$fechaTimbrado); } //generamos la cadena original del complemento de certificacion del sat $cadena_original_sat = '||1.0|'; $cadena_original_sat .= $uuid.'|'; $cadena_original_sat .= $fechaTimbradoS.'|'; $cadena_original_sat .= $sellocfd.'|'; $cadena_original_sat .= $certificadoSAT.'||'; } } if ($error === false) { //informacion para retornar y actualizar la factura como TImbrada $pagoTimbrado = array( "uuid" => $uuid, "selloSAT" => $selloSAT, "certificadoSAT" => $certificadoSAT, "sellocfd" => $sellocfd, "fechaTimbrado" => $fechaTimbrado, "rutaXML" => $ruta_xml.".xml", "error" => false ); return $pagoTimbrado; }else{ return $error; } } function regenerarCFDI($infoFactura,$conceptos) { //obtenemos la fecha de la factura $fch = "$infoFactura->facturaFecha"; $fecha = explode(" ",$fch); //variable para detectar error $error = false; //variable para detectar si solo se maneja impuesto tasa 0.160000 o tambien tasa 0.000000 $tasa0 = false; $tasa16 = false; //iniciamos la variable de cadena_original $cadena_original = ''; //creamos la cadena original //atributos del comprobante ---> $cadena_original .= '||3.3|';// ||-> version * $cadena_original .= $infoFactura->facturaSerie.'|';// ||-> serie folio fiscal original $cadena_original .= $infoFactura->facturaFolio.'|';// ||-> folio fiscal original $cadena_original .= $fecha[0].'T'.$fecha[1].'|';// ||-> fecha * $cadena_original .= $infoFactura->facturaMetodoPagoClave.'|';// ||-> forma de pago * /* formas de pago 01 = EFECTIVO 02 = CHEQUE NOMINATIVO 03 = TRANSFERENCIA ELECTRONICA DE FONDOS 04 = TARJETA DE CREDITO 05 = MONEDERO ELECTRONICO 06 = DINERO ELECTRONICO 08 = VALES DE DESPENSA 28 = TARJETA DE DEBITO 29 = TARJETA DE SERVICIOS 99 = POR DEFINIR */ $cadena_original .= $infoFactura->empresaCertificadoNumero.'|';// ||-> numero de certificado del emisor $cadena_original .= number_format($infoFactura->facturaSubtotal,2,'.','').'|';// ||-> subtotal * $cadena_original .= 'MXN|';// ||-> moneda $cadena_original .= '1|';// ||-> tipo de cambio $cadena_original .= number_format($infoFactura->facturaTotal,2,'.','').'|';// ||-> total * $cadena_original .= 'I|';// ||-> tipo de comprobante * /* tipo de comprobante I = INGRESO E = EGRESO T = TRASLADO N = NOMINA P = PAGO */ $cadena_original .= $infoFactura->facturaFormaPagoClave.'|';// ||-> metodo de pago * /* metodo de pago PUE = PAGO EN UNA SOLA EXHIBICION PPD = PAGO EN PARCIALIDADES O DIFERIDO */ $cadena_original .= $infoFactura->sucursalCp.'|';// ||-> lugar de expedicion * ---> SOLO CODIGO POSTAL //$cadena_original .= '|';// ||-> condiciones de pago //$cadena_original .= number_format(0,2,'.','').'|';// ||-> descuento //$cadena_original .= '|';// ||-> numero de cuenta //$cadena_original .= '|';// ||-> monto folio fiscal original //atributos del emisor ---> $cadena_original .= $infoFactura->empresaRFC.'|';// ||-> rfc * $cadena_original .= $infoFactura->empresaRazon.'|';// ||-> nombre //$cadena_original .= $infoFactura->empresaDireccion.'|';// ||-> calle * //$cadena_original .= $infoFactura->empresaNumExt.'|';// ||-> numero exterior //$cadena_original .= '|';// ||-> numero interior //$cadena_original .= $infoFactura->empresaColonia.'|';// ||-> colonia //$cadena_original .= $infoFactura->empresaCiudad.'|';// ||-> localidad //$cadena_original .= '|';// ||-> referencia //$cadena_original .= $infoFactura->empresaCiudad.'|';// ||-> municipio * //$cadena_original .= $infoFactura->empresaEstado.'|';// ||-> estado * //$cadena_original .= 'MEXICO|';// ||-> pais * //$cadena_original .= $infoFactura->empresaCp.'|';// ||-> codigo postal * //atributos expedidoEn ---> //$cadena_original .= $infoFactura->sucursalDireccion.'|';// ||-> calle * //$cadena_original .= $infoFactura->sucursalNumExt.'|';// ||-> numero exterior //$cadena_original .= '|';// ||-> numero interior //$cadena_original .= $infoFactura->sucursalColonia.'|';// ||-> colonia //$cadena_original .= $infoFactura->sucursalCiudad.'|';// ||-> localidad //$cadena_original .= '|';// ||-> referencia //$cadena_original .= $infoFactura->sucursalCiudad.'|';// ||-> municipio * //$cadena_original .= $infoFactura->sucursalEstado.'|';// ||-> estado * //$cadena_original .= 'MEXICO|';// ||-> pais * //$cadena_original .= $infoFactura->sucursalCp.'|';// ||-> codigo postal * $cadena_original .= $infoFactura->empresaRegimenClave.'|';// ||-> regimen fiscal * /* regimen fiscal 601 = GENERAL DE LEY PERSONAS MORALES 612 = PERSONAS FISICAS CON ACTIVIDADES EMPRESARIALES Y PROFESIONALES 621 = INCORPORACION FISCAL */ //atributos del receptor ---> $cadena_original .= $infoFactura->clienteRFC.'|';// ||-> rfc * $cadena_original .= $infoFactura->clienteRazon.'|';// ||-> nombre //$cadena_original .= $infoFactura->clienteDireccion.'|';// ||-> calle * //$infoFactura->clienteNumExt != NULL ? $cadena_original .= $infoFactura->clienteNumExt.'|' : '';// ||-> numero exterior //$infoFactura->clienteNumInt != NULL ? $cadena_original .= $infoFactura->clienteNumInt.'|' : '';// ||-> numero interior //$infoFactura->clienteColonia != NULL ? $cadena_original .= $infoFactura->clienteColonia.'|' : '';// ||-> colonia //$cadena_original .= $infoFactura->clienteCiudad.'|';// ||-> localidad //$cadena_original .= '|';// ||-> referencia //$cadena_original .= $infoFactura->clienteCiudad.'|';// ||-> municipio * //$cadena_original .= $infoFactura->clienteEstado.'|';// ||-> estado * //$cadena_original .= 'MEXICO|';// ||-> pais * //$infoFactura->clienteCp != NULL ? $cadena_original .= $infoFactura->clienteCp.'|' : '';// ||-> codigo postal * $cadena_original .= $infoFactura->facturaUsoCFDI.'|'; // |-> uso CFDI /* USO CFDI G01 = ADQUISICION DE MERCANCIAS G02 = DEVOLUCIONES, DESCUENTOS O BONIFICACIONES G03 = GASTOS EN GENERAL IO1 = CONSTRUCCIONES I02 = MOBILIARIO Y EQUIPO DE OFICINA POR INVERSIONES I03 = EQUIPO DE TRANSPORTE I04 = EQUIPO DE COMPUTO Y ACCESORIOS I05 = DADOS, TROQUELES, MOLDES, MATRICES Y HERRAMENTAL ... N USOS -- PO1 = POR DEFINIR */ //iteramos los conceptos foreach ($conceptos as $key => $concepto) { //calculamos precio unitario e importe antes de iva //validamos si se mostraras las partidas originales o solo la partida de facturacion if ($infoFactura->ventaPartidaFactura == 0) { //$preciou = $concepto->precio - calcularDescuento($concepto->precio,$concepto->descuento); $preciou = $concepto->precioUnitarioXML; //$importe = $preciou * $concepto->cantidad; $importe = $concepto->importe; $tasaCuota = ($concepto->partidaIVA / 100); //$importeImpuesto = $importe * $tasaCuota; $importeImpuesto = $concepto->iva; }else{ $preciou = $infoFactura->facturaSubtotal; $importe = $preciou; $tasaCuota = ($concepto->partidaIVA / 100); $importeImpuesto = $infoFactura->facturaIVA; } $cadena_original .= $concepto->claveProductoServicio.'|'; // |->clave de producto o servicio * $cadena_original .= $concepto->codigob.'|';// ||-> numero de identificacion $cadena_original .= number_format($concepto->cantidad,3,'.','').'|';// ||-> cantidad* $cadena_original .= $concepto->claveUnidad.'|'; // |->clave de unidad $cadena_original .= $concepto->descripcion.'|';// ||-> descripcion* $cadena_original .= number_format($preciou,2,'.','').'|';// ||-> valor unitario* $cadena_original .= number_format($importe,2,'.','').'|';// ||-> importe* // ---- informacion de traslado de conceptos Impuestos $cadena_original .= number_format($importe,2,'.','').'|'; // |->base* es el importe del concepto $cadena_original .= '002|'; // |->Impuesto /* impuesto 001 = ISR 002 = IVA 003 = IEPS */ $cadena_original .= 'Tasa|';// |->tipo factor /* TIPO FACTOR ->TASA ->CUOTA ->EXCENTO */ if ($tasaCuota == 0) { $tasa0 = true; }else{ $tasa16 = true; } $cadena_original .= number_format($tasaCuota,6,'.','').'|';// |->tasa cuota $cadena_original .= number_format($importeImpuesto,2,'.','').'|';// |->importe del impuesto } // informacion total de impuestos $cadena_original .= '002|';// ||-> nombre del impuesto* /* impuesto 001 = ISR 002 = IVA 003 = IEPS */ $cadena_original .= 'Tasa|';// |->tipo factor /* TIPO FACTOR ->TASA ->CUOTA ->EXCENTO */ if ($tasa16 === true) { $cadena_original .= '0.160000|';// |->tasa cuota $cadena_original .= number_format($infoFactura->facturaIVA, 2,'.','').'|';// ||-> importe* } if ($tasa0 === true) { $cadena_original .= '0.000000|';// |->tasa cuota $cadena_original .= '0.00|';// ||-> importe* } $cadena_original .= number_format($infoFactura->facturaIVA, 2,'.','').'||'; // ||-> total de impuestos trasladados //limpiamos la cadena original de espacios y codificamos a utf8 $cadena_original = str_replace(" "," ",$cadena_original); $cadena_original = utf8_decode($cadena_original); $cadena_original = utf8_encode($cadena_original); // ===== creamos ruta para almacenar el XML/PDF ===== ---> //descomponemos la fecha, para almacenar los archivos en el directorio correcto, ..\AÑO\MES\ aqui los archivos $fc = explode("-",$fecha[0]);//$fc[0]=año, $fc[1]=mes //creamos el nombre de la carpeta de la empresa con el rfc $folder_factura = $infoFactura->empresaRFC; //validamos si existe la carpeta con el rfc de la empresa, sino la cremos if(!file_exists('files/facturas/'.$folder_factura.'/')){ mkdir('files/facturas/'.$folder_factura.'/',0777); } //crear folder de clientes en caso de no existir if(!file_exists('files/facturas/'.$folder_factura.'/clientes/')){ mkdir('files/facturas/'.$folder_factura.'/clientes/',0777); } //crear folder del año en caso de no existir if(!file_exists('files/facturas/'.$folder_factura.'/clientes/'.$fc[0].'/')){ mkdir('files/facturas/'.$folder_factura.'/clientes/'.$fc[0].'/',0777); } //crear folder del mes en caso de no existir if(!file_exists('files/facturas/'.$folder_factura.'/clientes/'.$fc[0].'/'.$fc[1].'/')){ mkdir('files/facturas/'.$folder_factura.'/clientes/'.$fc[0].'/'.$fc[1].'/',0777); } $ruta_xml = 'files/facturas/'.$folder_factura.'/clientes/'.$fc[0].'/'.$fc[1].'/'.$infoFactura->facturaSerie.$infoFactura->facturaFolio; // ================================================== //generamos la cadena original del complemento de certificacion del sat $fechaTimbradoS = str_replace("T"," ",$infoFactura->facturaFechaTimbrado); $cadena_original_sat = '||1.0|'; $cadena_original_sat .= $infoFactura->facturaUUID.'|'; $cadena_original_sat .= $fechaTimbradoS.'|'; $cadena_original_sat .= $infoFactura->facturaSelloCFD.'|'; $cadena_original_sat .= $infoFactura->facturaCertificadoSAT.'||'; // ============== GENERAMOS PDF ================== $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false); // remove default header/footer $pdf->setPrintHeader(false); $pdf->setPrintFooter(false); // set default monospaced font $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED); // set margins $pdf->SetMargins("10", "10", "10"); // set auto page breaks $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM); // set image scale factor $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO); // set some language-dependent strings (optional) if (@file_exists(dirname(__FILE__).'/lang/eng.php')) { require_once(dirname(__FILE__).'/lang/eng.php'); $pdf->setLanguageArray($l); } // set font $pdf->SetFont('', '', 7); // add a page $pdf->AddPage(); $html = '<table width="670" border="0" cellspacing="0" cellpadding="0"> <tr> <td><table width="100%" border="0" cellspacing="10" cellpadding="0"> <tr> <td width="'.$infoFactura->medidas[0].'%" valign="top"><img src="'.base_url("assets/images/logo_cotiza.jpg").'" width="'.$infoFactura->medidas[3].'" /></td> <td width="'.$infoFactura->medidas[1].'%" valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr align="center"> <td><strong>'.$infoFactura->empresaRazon.'</strong></td> </tr> <tr align="center"> <td>'.$infoFactura->empresaDireccion.' No. Ext. '.$infoFactura->empresaNumExt; if ($infoFactura->empresaNumInt != '' && $infoFactura->empresaNumInt != NULL) { $html .= ', No. Int '.$infoFactura->empresaNumInt; } $html .= ' , '.$infoFactura->empresaColonia.'</td> </tr> <tr align="center"> <td>C.P. '.$infoFactura->empresaCp.', '.$infoFactura->empresaCiudad.', '.$infoFactura->empresaEstado.'</td> </tr> <tr align="center"> <td>RFC: '.$infoFactura->empresaRFC.'</td> </tr> <tr align="center"> <td>'.$infoFactura->empresaRegimenClave.' - '.$infoFactura->empresaRegimenNombre.'</td> </tr> </table></td> <td width="'.$infoFactura->medidas[2].'%" valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td align="center"><span style="color:red;">FACTURA '.$infoFactura->facturaSerie.$infoFactura->facturaFolio.'</span></td> </tr> <tr> <td align="center"><span style="color:blue;">Fecha/Hora</span></td> </tr> <tr> <td align="center"><span style="color:blue;">Certificación</span></td> </tr> <tr> <td align="center">'.$infoFactura->facturaFechaTimbrado.'</td> </tr> <tr> <td align="center"><span style="color:blue;">Fecha de Emisión</span></td> </tr> <tr> <td align="center">'.$fecha[0].' '.$fecha[1].'</td> </tr> <tr> <td align="center"><span style="color:blue;">Tipo de Comprobante</span></td> </tr> <tr> <td align="center">I - Ingreso</td> </tr> <tr> <td align="center"><span style="color:blue;">Lugar de Expedicion</span></td> </tr> <tr> <td align="center">'.$infoFactura->sucursalCp.'</td> </tr> </table></td> </tr> </table></td> </tr> <tr> <td>&nbsp;</td> </tr> <tr> <td><table width="100%" border="0" cellspacing="10" cellpadding="0"> <tr> <td width="36%" valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td><span style="color:blue;">Receptor del comprobante fiscal</span></td> </tr> <tr> <td>&nbsp;</td> </tr> <tr> <td><strong>'.$infoFactura->clienteRazon.'</strong></td> </tr> <tr> <td>'.$infoFactura->clienteDireccion; if($infoFactura->clienteNumExt != '' && $infoFactura->clienteNumExt != NULL && $infoFactura->clienteNumExt != 0){ $html .= ', No. Ext. '.$infoFactura->clienteNumExt; } if($infoFactura->clienteNumInt != '' && $infoFactura->clienteNumInt != NULL){ $html .= ', No. Int. '.$infoFactura->clienteNumInt; } $html .= ' , '.$infoFactura->clienteColonia.',</td> </tr> <tr> <td>C.P. '.$infoFactura->clienteCp.', '.$infoFactura->clienteCiudad.', '.$infoFactura->clienteEstado.', México</td> </tr> <tr> <td>RFC: '.$infoFactura->clienteRFC.'</td> </tr> <tr> <td><strong>Uso CFDI: </strong>'.$infoFactura->facturaUsoCFDI.' - '.$infoFactura->facturaUsoCFDInombre.'</td> </tr> </table></td> <td width="32%" valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td>&nbsp;</td> </tr> <tr> <td>&nbsp;</td> </tr> </table></td> <td width="32%" valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td align="center"><span style="color:blue;">Folio Fiscal</span></td> </tr> <tr> <td align="center">'.$infoFactura->facturaUUID.'</td> </tr> <tr> <td align="center">&nbsp;</td> </tr> <tr> <td align="center"><span style="color:blue;">Numero de Serie del Certificado</span></td> </tr> <tr> <td align="center">'.$infoFactura->empresaCertificadoNumero.'</td> </tr> <tr> <td align="center">&nbsp;</td> </tr> <tr> <td align="center"><span style="color:blue;">Numero de Serie del Certificado del SAT</span></td> </tr> <tr> <td align="center">'.$infoFactura->facturaCertificadoSAT.'</td> </tr> </table></td> </tr> </table></td> </tr> '; // Aqui se incluyen los comentarios de la venta $html .= ' <tr> <td>'.$infoFactura->ventaComentarios.'</td> </tr> '; $html .= ' <tr> <td>&nbsp;</td> </tr> <tr> <td><table width="100%" border="0" cellspacing="2" cellpadding="3" style="border:#CCC solid 1px; border-radius:5px;"> <tr style="background-color:#EBEBEB;"> <td width="8%" align="center"><strong style="color:#00F;">Cantidad</strong></td> <td width="14%" align="center"> <strong style="color:#00F;">ClaveProdServ</strong><br> <strong style="color:#00F;">Clave unidad</strong><br> <strong style="color:#00F;">No. Identificacion</strong> </td> <td width="'.$infoFactura->porcentajeDescripcion.'%" align="center"><strong style="color:#00F;">Descripción</strong></td> <td width="13%" align="center"><strong style="color:#00F;">Valor Unitario</strong></td> '; // == campos dinamicos == if ($infoFactura->camposDinamicos !== false){ foreach ($infoFactura->camposDinamicos as $key => $campo){ if (in_array($campo->venta_campos_cot_id, $infoFactura->camposVenta)){ $html .= '<td width="8%" align="center"><strong style="color:#00F;">'.$campo->venta_campos_cot_nombre.'</strong></td>'; } } } $html .= ' <td width="13%" align="center"><strong style="color:#00F;">Impuesto</strong></td> <td width="12%" align="center"><strong style="color:#00F;">Importe</strong></td> </tr>'; //==== productos foreach ($conceptos as $key => $concepto) { //calculamos precio unitario e importe antes de iva //validamos si se mostraras las partidas originales o solo la partida de facturacion if ($infoFactura->ventaPartidaFactura == 0) { //$preciou = $concepto->precio - calcularDescuento($concepto->precio,$concepto->descuento); $preciou = $concepto->precioUnitario; //$importe = $preciou * $concepto->cantidad; $importe = $concepto->importe; }else{ $preciou = $infoFactura->facturaSubtotal; $importe = $preciou; } $html .= ' <tr> <td align="center">'.$concepto->cantidad.'</td> <td align="center">'.$concepto->claveProductoServicio.'<br>'.$concepto->claveUnidad.'<br>'.$concepto->codigob.'</td> <td align="center">'.$concepto->descripcion.'</td> <td align="center">$ '.number_format($preciou,2).'</td> '; // == campos dinamicos == if ($infoFactura->camposDinamicos !== false){ foreach ($infoFactura->camposDinamicos as $key => $campo){ if (in_array($campo->venta_campos_cot_id, $infoFactura->camposVenta)){ $html .= '<td align="center">'; //aqui traemos la informacion de los campos adicionales $primerNivel = explode("||", $concepto->camposCotizacion); foreach ($primerNivel as $key => $Pnivel) { $segundoNivel = explode("@", $Pnivel); if ($segundoNivel[0] == $campo->venta_campos_cot_id) { $html .= $segundoNivel[1]; } } $html .= '</td>'; } } } if ($infoFactura->ventaPartidaFactura == 0) { $html .= '<td align="center">002-IVA | $ '.number_format($concepto->iva,2).'</td>'; }else{ $html .= '<td align="center">002-IVA | $ '.number_format($infoFactura->facturaIVA,2).'</td>'; } $html .= ' <td align="center">$ '.number_format($importe,2).'</td> </tr> '; if($concepto->comentario !='' && $concepto->comentario != NULL){ $comentario = nl2br($concepto->comentario); $html .= ' <tr> <td colspan="2" align="right"><strong>Comentarios:</strong></td> <td align="justify" colspan="3">'.$comentario.'</td> <td></td> </tr> '; } } $html .= '</table></td> </tr> <tr> <td><table width="100%" border="0" cellspacing="10" cellpadding="0"> <tr> <td width="65%" valign="top"><table width="100%" border="0" cellspacing="10" cellpadding="0"> <tr> <td><strong>Moneda: </strong>MXN - Peso Mexicano</td> </tr> <tr> <td><strong>Forma de pago: </strong>'.$infoFactura->facturaMetodoPago.'</td> </tr> <tr> <td><strong>Metodo de Pago: </strong>'.$infoFactura->facturaFormaPagoClave.' - '.$infoFactura->facturaFormaPago.'</td> </tr> <tr> <td><strong>Importe Total con letra: </strong>( '.$infoFactura->facturaTotalLetras.' )</td> </tr> </table></td> <td width="35%" valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td colspan="2" align="center"><strong style="color:#00F;">&nbsp;</strong></td> </tr> <tr> <td width="70%">Subtotal</td> <td width="30%" align="right">$ '.number_format($infoFactura->facturaSubtotal,2).'</td> </tr> <tr> <td>Total Impuestos Trasladados</td> <td align="right">$ '.number_format($infoFactura->facturaIVA,2).'</td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td colspan="2"><hr></td> </tr> <tr> <td>Total Comprobante</td> <td align="right">$ '.number_format($infoFactura->facturaTotal,2).'</td> </tr> </table></td> </tr> </table></td> </tr> <tr> <td><table width="100%" border="0" cellspacing="10" cellpadding="0"> <tr> <td><strong style="color:blue;">Cadena original del complemento de certificación digital del SAT</strong></td> </tr> <tr> <td>'.$cadena_original_sat.'</td> </tr> </table></td> </tr> <tr> <td>&nbsp;</td> </tr> <tr> <td><table width="100%" border="0" cellspacing="10" cellpadding="0"> <tr> <td width="20%" rowspan="4" valign="top"><img src="temp/qr2.png" width="120" /></td> <td width="80%" valign="top"><strong style="color:blue;">Sello Digital del CFDI</strong></td> </tr> <tr> <td valign="top">'.$infoFactura->facturaSelloCFD.'</td> </tr> <tr> <td valign="top"><strong style="color:blue;">Sello digital del SAT</strong></td> </tr> <tr> <td valign="top">'.$infoFactura->facturaSelloSAT.'</td> </tr> </table></td> </tr> <tr> <td>&nbsp;</td> </tr> <tr> <td>&nbsp;</td> </tr> <tr> <td>&nbsp;</td> </tr> <tr> <td align="center">Este documento es una representación impresa de un CFDI</td> </tr> </table>'; // output the HTML content $pdf->writeHTML($html, true, false, true, false, ''); //Close and output PDF document $pdf->Output($ruta_xml.'.pdf', 'F'); // ======== fin PDF ======== return true; } function limpiarCaracteres($cadena) { $search = array("<", ">", "&", "'",'"'); $replace = array("&lt;", "&gt;", "&amp;", "&apos;","&quot;"); $final = str_replace($search, $replace, $cadena); return $final; } } ?>
{'content_hash': '105632002c7be21fbdac40966ce296a1', 'timestamp': '', 'source': 'github', 'line_count': 2133, 'max_line_length': 242, 'avg_line_length': 32.190342240975156, 'alnum_prop': 0.5735632518714864, 'repo_name': 'georgesks/sistema', 'id': 'f14b85f1815e6995202a1c9e1d2c1bbbd4fa0fed', 'size': '68683', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'versiones/v_1_13_1/libraries/GeneraFactura.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '21'}, {'name': 'CSS', 'bytes': '830362'}, {'name': 'HTML', 'bytes': '6419'}, {'name': 'JavaScript', 'bytes': '396620'}, {'name': 'PHP', 'bytes': '20888101'}, {'name': 'Shell', 'bytes': '25'}]}
package org.apache.activemq.openwire.v5; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; /** * Test case for the OpenWire marshalling for DataResponse * * * NOTE!: This file is auto generated - do not modify! * if you need to make a change, please see the modify the groovy scripts in the * under src/gram/script and then use maven openwire:generate to regenerate * this file. * * */ public class DataResponseTest extends ResponseTest { public static DataResponseTest SINGLETON = new DataResponseTest(); public Object createObject() throws Exception { DataResponse info = new DataResponse(); populateObject(info); return info; } protected void populateObject(Object object) throws Exception { super.populateObject(object); DataResponse info = (DataResponse) object; info.setData(createDataStructure("Data:1")); } }
{'content_hash': '928be5edc20132faa8b2088a3fb09407', 'timestamp': '', 'source': 'github', 'line_count': 40, 'max_line_length': 87, 'avg_line_length': 26.2, 'alnum_prop': 0.7032442748091603, 'repo_name': 'chirino/activemq', 'id': 'd1047de6ac92a0308681e19a6efacd3e08b0955b', 'size': '1849', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'activemq-unit-tests/src/test/java/org/apache/activemq/openwire/v5/DataResponseTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '17712'}, {'name': 'C#', 'bytes': '27536'}, {'name': 'C++', 'bytes': '17404'}, {'name': 'CSS', 'bytes': '34997'}, {'name': 'HTML', 'bytes': '158883'}, {'name': 'Java', 'bytes': '25304453'}, {'name': 'JavaScript', 'bytes': '438641'}, {'name': 'PHP', 'bytes': '3665'}, {'name': 'Perl', 'bytes': '4128'}, {'name': 'Protocol Buffer', 'bytes': '13867'}, {'name': 'Python', 'bytes': '14547'}, {'name': 'Ruby', 'bytes': '6594'}, {'name': 'Scala', 'bytes': '302023'}, {'name': 'Shell', 'bytes': '87001'}]}
<?php define('BC_Slider_URI', BIKE_COOP_PLUGIN_URI.'framework/modules/slider'); define('BC_Slider_DIR', BIKE_COOP_PLUGIN_DIR.'framework/modules/slider'); class BC_Slider{ protected static $instance; public static function get_instance() { if ( ! isset( self::$instance ) ) { self::$instance = new self; } return self::$instance; } public function __construct(){ $this->load_dependencies(); $this->init(); } public function wp_enqueue_scripts(){ // Slick slider wp_enqueue_style( 'bc-module-slick', BC_Slider_URI . '/assets/css/vendor/slick/slick.css', array(), '1' ); wp_enqueue_style( 'bc-module-slick-theme', BC_Slider_URI . '/assets/css/vendor/slick/slick-theme.css', array(), '1' ); wp_enqueue_style( 'bc-module-slick-overrides', BC_Slider_URI . '/assets/css/slider-module.min.css', array(), '1' ); } // TODO: create instructions for user (custom fields, etc.) public function browser_body_class($classes) { $classes[] = 'bc-slider'; return $classes; } /** * Load Requires. * Loads all files that are required by the theme. * * @return none * @see __construct */ private function load_dependencies(){ /** Load includes */ foreach(glob(BC_Slider_DIR."/framework/inc/*.php") as $file): require_once($file); endforeach; //var_dump(BC_Slider_DIR); die(); /** Load Classes */ foreach(glob(BC_Slider_DIR."/framework/classes/*.php") as $file): require_once($file); endforeach; } private function init(){ add_action('wp_enqueue_scripts', array(&$this,'wp_enqueue_scripts'), 100); add_filter('body_class', array(&$this,'browser_body_class')); } } BC_Slider::get_instance(); ?>
{'content_hash': 'fa0d5a4fe3e03cee2c253dd0f363dd5d', 'timestamp': '', 'source': 'github', 'line_count': 62, 'max_line_length': 123, 'avg_line_length': 28.14516129032258, 'alnum_prop': 0.6269340974212034, 'repo_name': 'CodeForFoco/bike-coop-plugin', 'id': '4d82b97c9b872a30b6478b861a99d17d47b49ae6', 'size': '1745', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'framework/modules/slider/slider.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '20790'}, {'name': 'JavaScript', 'bytes': '1700'}, {'name': 'PHP', 'bytes': '76778'}]}
AddCSLuaFile("cl_init.lua") AddCSLuaFile("shared.lua") include('shared.lua') function ENT:Initialize( ) --This function is run when the entity is created so it's a good place to setup our entity. self:SetModel( "models/hunter/plates/plate1x2.mdl" ) -- Sets the model of the NPC. self:PhysicsInit(SOLID_VPHYSICS) self:SetMoveType(MOVETYPE_VPHYSICS) self:SetSolid(SOLID_VPHYSICS) self:SetUseType(SIMPLE_USE) self:SetPos(self:GetPos()+Vector(0,0,90)) local phys = self:GetPhysicsObject() if phys:IsValid() then phys:Wake() end end function ENT:AcceptInput( iName, Activator, Caller ) if iName == "Use" and Caller:IsPlayer() then -- if player presses e do this end end
{'content_hash': 'b765f252ab6f4fd53650924e05271263', 'timestamp': '', 'source': 'github', 'line_count': 28, 'max_line_length': 118, 'avg_line_length': 25.571428571428573, 'alnum_prop': 0.7094972067039106, 'repo_name': 'GamingMad101/GMF-Website', 'id': 'f49594dc44f8cc8f0006f84f167711d15e8161fd', 'size': '716', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'GmodFraternal/entities/entities/GMF_TV/init.lua', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '38499'}, {'name': 'Lua', 'bytes': '24336'}]}
#ifndef NRF_SVC__ #define NRF_SVC__ #ifdef SVCALL_AS_NORMAL_FUNCTION #define SVCALL(number, return_type, signature) return_type signature #else #ifndef SVCALL #if defined (__CC_ARM) #define SVCALL(number, return_type, signature) return_type __svc(number) signature #elif defined (__GNUC__) #define SVCALL(number, return_type, signature) \ _Pragma("GCC diagnostic ignored \"-Wunused-function\"") \ _Pragma("GCC diagnostic ignored \"-Wunused-parameter\"") \ _Pragma("GCC diagnostic push") \ _Pragma("GCC diagnostic ignored \"-Wreturn-type\"") \ __attribute__((naked)) static return_type signature \ { \ __asm( \ "svc %0\n" \ "bx r14" : : "I" ((uint32_t) number) : "r0" \ ); \ } \ _Pragma("GCC diagnostic pop") #elif defined (__ICCARM__) #define PRAGMA(x) _Pragma(#x) #define SVCALL(number, return_type, signature) \ PRAGMA(swi_number = number) \ __swi return_type signature; #else #define SVCALL(number, return_type, signature) return_type signature #endif #endif // SVCALL #endif // SVCALL_AS_NORMAL_FUNCTION #endif // NRF_SVC__
{'content_hash': '6b566d3d582c58658f38efcc53ef384b', 'timestamp': '', 'source': 'github', 'line_count': 38, 'max_line_length': 82, 'avg_line_length': 28.5, 'alnum_prop': 0.6629732225300092, 'repo_name': 'fvincenzo/mbed-os', 'id': 'e7b8f59471cac8f96ce2e016b435459770338e76', 'size': '2699', 'binary': False, 'copies': '9', 'ref': 'refs/heads/master', 'path': 'features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/nrf_svc.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '5738539'}, {'name': 'C', 'bytes': '164076248'}, {'name': 'C++', 'bytes': '8132550'}, {'name': 'CMake', 'bytes': '27635'}, {'name': 'HTML', 'bytes': '1543876'}, {'name': 'Makefile', 'bytes': '131072'}, {'name': 'Objective-C', 'bytes': '169382'}, {'name': 'Python', 'bytes': '18259'}, {'name': 'Shell', 'bytes': '24790'}, {'name': 'XSLT', 'bytes': '11192'}]}
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in Observ. Mag. Gesell. Naturf. Freunde Berl. 1: 15 (1805) #### Original name Penicillium glaucum Link, 1805 ### Remarks null
{'content_hash': 'e47aec9423e3cab064072a6337b9c70e', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 55, 'avg_line_length': 16.23076923076923, 'alnum_prop': 0.7109004739336493, 'repo_name': 'mdoering/backbone', 'id': '6c113ce6e8f3be45c04b0ec57f2e592135b8ba26', 'size': '265', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Fungi/Ascomycota/Eurotiomycetes/Eurotiales/Trichocomaceae/Penicillium/Penicillium glaucum/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <link rel="stylesheet" type="text/css" href="../css/layout.css" media="all"> <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Noto+Sans"> <style> #header { font-family: Noto Sans, sans-serif } </style> <title>Thegither PyBake 2013 Job Board (DEMO)</title> </head> <body class="post"> <div id="main_wrapper"> <div id="header"> <div id="title"><a href="board-ag1kZXZ-dGhlZ2l0aGlychILEgVCb2FyZBiAgICAgICACgw.html">PyBake 2013 Job Board</a> (DEMO)</div> </div> <!-- /header --> <div id="page_contents"> <div> <div id="user_id"> <a href="">[email protected]</a> </div> </div> <div id="main_contents"> <div id="page_intro"> <h2>Graphic designer, 7 years experience</h2> </div> <div id="sidebar"> <div class="board-description">The PyBake Planning Committee provides this job board as a service to the sponsors and attendees of the PyBake 2013 Decamp. ─Please do not post to this board if you are not a sponsor or attendee of PyBake 2013. ─If you are a sponsor, please do not post a job unless you are hiring for it now. ─If you are an attendee, please do not post unless you are available immediately. Please do not abuse this board. If the adminstrators believe you are abusing it, they will remove your post.</div> </div> <!-- /sidebar --> <div id="contents" class="with-sidebar"> <div id="post_contents"> <div id="post_timestamp"> Posted on: 2013-10-09 22:50:06.751706 </div> <div id="post_summary"> <span class="post-type want">I'm Available:</span> Graphic designer, 7 years experience </div> <div id="post_information">* Photoshop, Blender, CSS3, HTML5. * BA Graphic Design from the Mpls College of Arts and Design. * Self-starter, detail-oriented, proven time-management skills.</div> <form id="post_response" method="POST"> <h3>Respond to this post:</h3> <input name="post-id" value="ag1kZXZ-dGhlZ2l0aGlychQLEgdQb3N0aW5nGICAgICAwK8KDA" type="hidden"> <div class="form-field"> <textarea name="response-text" id="response_text" rows="5"></textarea> <div class="user-hint"> When you respond to this post, your Google account email address will be provided to the poster. </div> </div> <div style="margin-top: 0.5em"> <input value="Submit" type="submit"> </div> </form> </div> <!-- /post_contents --> </div> <!-- /contents --> </div> <!-- /main-contents --> </div> <!-- /page-contents --> <div id="footer"> <div class="layout-wrapper"> <div id="slogan"><a href="..">A' thegither they will sup!</a></div> <!-- <div id="copyright">Copyright 2013. All rights reserved.</div> --> </div> <!-- /layout-wrapper --> </div> <!-- /footer --> </div> <!-- /main-wrapper --> </body> </html>
{'content_hash': '4f72f50f1fb82e14e75f2b56685e1516', 'timestamp': '', 'source': 'github', 'line_count': 77, 'max_line_length': 172, 'avg_line_length': 48.5974025974026, 'alnum_prop': 0.504008551576697, 'repo_name': 'bpreece/thegither-php', 'id': '6714041a5b7b7e66e0fa6e9fbd1bc1fa5faec041', 'size': '3748', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'demo/post-ag1kZXZ-dGhlZ2l0aGlychQLEgdQb3N0aW5nGICAgICAwK8KDA.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '30024'}, {'name': 'PHP', 'bytes': '96731'}]}
@implementation CCSQLiteTest + (void) SQLiteTest { NSLog(@"SQLiteTest"); NSString *path = nil; #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) lastObject]; #else path = NSTemporaryDirectory() ; #endif path = [path stringByAppendingPathComponent:CCSQLiteTestDB]; if ([[NSFileManager defaultManager] fileExistsAtPath:path]) { [[NSFileManager defaultManager] removeItemAtPath:path error: nil]; } CCSQLite *SQLite = [CCSQLite databaseWithPath: path]; if ([SQLite open]) { BOOL result = [SQLite executeUpdate: @"create table if not exists t_student (id integer primary key autoincrement, name text not NULL, age integer not NULL);"]; if (result) { NSLog(@"create table t_student ok"); NSLog(@"path : %@", path); } } [SQLite executeUpdate:@"insert into t_student (name, age) values (?, ?);", @"cc test 0", @0]; [SQLite executeUpdate:@"insert into t_student (name, age) values (?, ?);", @"cc test 1", @1]; [SQLite executeUpdateWithFormat:@"insert into t_student (name, age) values (%@, %i);", @"cc test 2", 2000]; // [SQLite executeUpdate:@"delete from t_student where id = ?", @1]; CCResultSet *resultSet = [SQLite executeQuery:@"select * from t_student;"]; while ([resultSet next]) { int idNum = [resultSet intForColumn:@"id"]; NSString *name = [resultSet objectForColumnName:@"name"]; int age = [resultSet intForColumn:@"age"]; NSLog(@"id = %d name = %@ age = %d", idNum, name, age); } // [SQLite executeUpdate:@"drop table if exists t_student;"]; NSString *sql = @"create table bulktest1 (id integer primary key autoincrement, x text);" "create table bulktest2 (id integer primary key autoincrement, y text);" "create table bulktest3 (id integer primary key autoincrement, z text);" "insert into bulktest1 (x) values ('XXX');" "insert into bulktest2 (y) values ('YYY');" "insert into bulktest3 (z) values ('ZZZ');"; BOOL success = [SQLite executeStatements:sql]; if (success) { NSLog(@"success"); } sql = @"select count(*) as count from bulktest1;" "select count(*) as count from bulktest2;" "select count(*) as count from bulktest3;"; [SQLite executeStatements:sql withResultBlock:^int(NSDictionary *resultsDictionary) { NSInteger count = [resultsDictionary[@"count"] integerValue]; NSLog(@"count = %ld", count); return 0; }]; [SQLite close]; [[CCKeyValue defaultKeyValueWithPath:path] setObject:@"CC china 1112" key:@"china key"]; [[CCKeyValue defaultKeyValueWithPath:path] setObject:@"CCVV" key:@"CC"]; id test = [[CCKeyValue defaultKeyValueWithPath:path] objectForKey:@"CC"]; NSLog(@"test 1 : %@", test); [[CCKeyValue defaultKeyValueWithPath:path] setObject:@[@1, @2, @3] key:@"CA"]; test = [[CCKeyValue defaultKeyValueWithPath:path] objectForKey:@"CA"]; NSLog(@"test 2 : %@", test); CCSQLiteQueue *queue = [CCSQLiteQueue databaseQueueWithPath:path]; __block NSInteger index = 3000; [queue inDatabase:^(CCSQLite *db) { while (index < 3100) { index++; [db executeUpdate:@"insert into t_student (name, age) values (?, ?);", [NSString stringWithFormat:@"cc test inDatabase %ld", index], @(index)]; } }]; [queue inTransaction:^(CCSQLite *db, BOOL *rollback) { NSLog(@"rollback NO"); while (index < 3150) { index++; [db executeUpdate:@"insert into t_student (name, age) values (?, ?);", [NSString stringWithFormat:@"cc test inTransaction %ld", index], @(index)]; } }]; [queue inTransaction:^(CCSQLite *db, BOOL *rollback) { NSLog(@"rollback YES"); while (index < 3200) { index++; [db executeUpdate:@"insert into t_student (name, age) values (?, ?);", [NSString stringWithFormat:@"cc test inTransaction %ld", index], @(index)]; if (index == 3188) { *rollback = YES; return ; } } }]; CCKeyValue *kv = [CCKeyValue defaultKeyValueWithPath:path]; kv.valueType = CCKeyValueTypeJson; NSData * data = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"CCJSON" ofType:@"json"]]; [kv setObject:data key:@"jsonkey"]; id CCJSON = [kv objectForKey:@"jsonkey"]; if ([CCJSON isKindOfClass:[NSArray class]]) { NSArray *list = CCJSON; [list enumerateObjectsUsingBlock:^(NSDictionary *d, NSUInteger idx, BOOL * _Nonnull stop) { NSLog(@"%@\n", d); }]; } } @end
{'content_hash': '5f54db93fc6323c258bc31200a550652', 'timestamp': '', 'source': 'github', 'line_count': 136, 'max_line_length': 168, 'avg_line_length': 35.99264705882353, 'alnum_prop': 0.6, 'repo_name': 'ccworld1000/CCSQLite', 'id': '49d73c2a90e1b26482bb39d63e387bc133b0ef39', 'size': '5100', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'CCSQLiteDemo/CCSQLiteTest/CCSQLiteTest.m', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Objective-C', 'bytes': '229508'}, {'name': 'Ruby', 'bytes': '1730'}, {'name': 'Swift', 'bytes': '4153'}]}
/* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_HAL_DEF #define __STM32F0xx_HAL_DEF #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx.h" #include "stm32_hal_legacy.h" #include <stdio.h> /* Exported types ------------------------------------------------------------*/ /** * @brief HAL Status structures definition */ typedef enum { HAL_OK = 0x00, HAL_ERROR = 0x01, HAL_BUSY = 0x02, HAL_TIMEOUT = 0x03 } HAL_StatusTypeDef; /** * @brief HAL Lock structures definition */ typedef enum { HAL_UNLOCKED = 0x00, HAL_LOCKED = 0x01 } HAL_LockTypeDef; /* Exported macro ------------------------------------------------------------*/ #define HAL_MAX_DELAY 0xFFFFFFFFU #define HAL_IS_BIT_SET(REG, BIT) (((REG) & (BIT)) != RESET) #define HAL_IS_BIT_CLR(REG, BIT) (((REG) & (BIT)) == RESET) #define __HAL_LINKDMA(__HANDLE__, __PPP_DMA_FIELD_, __DMA_HANDLE_) \ do{ \ (__HANDLE__)->__PPP_DMA_FIELD_ = &(__DMA_HANDLE_); \ (__DMA_HANDLE_).Parent = (__HANDLE__); \ } while(0) #define UNUSED(x) ((void)(x)) /** @brief Reset the Handle's State field. * @param __HANDLE__: specifies the Peripheral Handle. * @note This macro can be used for the following purpose: * - When the Handle is declared as local variable; before passing it as parameter * to HAL_PPP_Init() for the first time, it is mandatory to use this macro * to set to 0 the Handle's "State" field. * Otherwise, "State" field may have any random value and the first time the function * HAL_PPP_Init() is called, the low level hardware initialization will be missed * (i.e. HAL_PPP_MspInit() will not be executed). * - When there is a need to reconfigure the low level hardware: instead of calling * HAL_PPP_DeInit() then HAL_PPP_Init(), user can make a call to this macro then HAL_PPP_Init(). * In this later function, when the Handle's "State" field is set to 0, it will execute the function * HAL_PPP_MspInit() which will reconfigure the low level hardware. * @retval None */ #define __HAL_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = 0) #if (USE_RTOS == 1) #error " USE_RTOS should be 0 in the current HAL release " #else #define __HAL_LOCK(__HANDLE__) \ do{ \ if((__HANDLE__)->Lock == HAL_LOCKED) \ { \ return HAL_BUSY; \ } \ else \ { \ (__HANDLE__)->Lock = HAL_LOCKED; \ } \ }while (0) #define __HAL_UNLOCK(__HANDLE__) \ do{ \ (__HANDLE__)->Lock = HAL_UNLOCKED; \ }while (0) #endif /* USE_RTOS */ #if defined ( __GNUC__ ) #ifndef __weak #define __weak __attribute__((weak)) #endif /* __weak */ #ifndef __packed #define __packed __attribute__((__packed__)) #endif /* __packed */ #endif /* __GNUC__ */ /* Macro to get variable aligned on 4-bytes, for __ICCARM__ the directive "#pragma data_alignment=4" must be used instead */ #if defined (__GNUC__) /* GNU Compiler */ #ifndef __ALIGN_END #define __ALIGN_END __attribute__ ((aligned (4))) #endif /* __ALIGN_END */ #ifndef __ALIGN_BEGIN #define __ALIGN_BEGIN #endif /* __ALIGN_BEGIN */ #else #ifndef __ALIGN_END #define __ALIGN_END #endif /* __ALIGN_END */ #ifndef __ALIGN_BEGIN #if defined (__CC_ARM) /* ARM Compiler */ #define __ALIGN_BEGIN __align(4) #elif defined (__ICCARM__) /* IAR Compiler */ #define __ALIGN_BEGIN #endif /* __CC_ARM */ #endif /* __ALIGN_BEGIN */ #endif /* __GNUC__ */ /** * @brief __NOINLINE definition */ #if defined ( __CC_ARM ) || defined ( __GNUC__ ) /* ARM & GNUCompiler ---------------- */ #define __NOINLINE __attribute__ ( (noinline) ) #elif defined ( __ICCARM__ ) /* ICCARM Compiler --------------- */ #define __NOINLINE _Pragma("optimize = no_inline") #endif #ifdef __cplusplus } #endif #endif /* ___STM32F0xx_HAL_DEF */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
{'content_hash': 'd01f24c5b87dcab59b0a9f0a33cbaab7', 'timestamp': '', 'source': 'github', 'line_count': 146, 'max_line_length': 124, 'avg_line_length': 35.86986301369863, 'alnum_prop': 0.43631850295970975, 'repo_name': 'ARM-software/mbed-beetle', 'id': '167258f2f82715b80bf0c58f56d1850e27d2d00d', 'size': '7357', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'hal/targets/cmsis/TARGET_STM/TARGET_STM32F0/stm32f0xx_hal_def.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '4866344'}, {'name': 'C', 'bytes': '118924404'}, {'name': 'C++', 'bytes': '7214365'}, {'name': 'CMake', 'bytes': '4724'}, {'name': 'HTML', 'bytes': '1068721'}, {'name': 'Makefile', 'bytes': '4207'}, {'name': 'Objective-C', 'bytes': '61382'}, {'name': 'Python', 'bytes': '1766'}]}
#import <Foundation/Foundation.h> #include <libxml2/libxml/tree.h> @class DDXMLDocument; /** * Welcome to KissXML. * * The project page has documentation if you have questions. * https://github.com/robbiehanson/KissXML * * If you're new to the project you may wish to read the "Getting Started" wiki. * https://github.com/robbiehanson/KissXML/wiki/GettingStarted * * KissXML provides a drop-in replacement for Apple's NSXML class cluster. * The goal is to get the exact same behavior as the NSXML classes. * * For API Reference, see Apple's excellent documentation, * either via Xcode's Mac OS X documentation, or via the web: * * https://github.com/robbiehanson/KissXML/wiki/Reference **/ enum { DDXMLInvalidKind = 0, DDXMLDocumentKind = XML_DOCUMENT_NODE, DDXMLElementKind = XML_ELEMENT_NODE, DDXMLAttributeKind = XML_ATTRIBUTE_NODE, DDXMLNamespaceKind = XML_NAMESPACE_DECL, DDXMLProcessingInstructionKind = XML_PI_NODE, DDXMLCommentKind = XML_COMMENT_NODE, DDXMLTextKind = XML_TEXT_NODE, DDXMLDTDKind = XML_DTD_NODE, DDXMLEntityDeclarationKind = XML_ENTITY_DECL, DDXMLAttributeDeclarationKind = XML_ATTRIBUTE_DECL, DDXMLElementDeclarationKind = XML_ELEMENT_DECL, DDXMLNotationDeclarationKind = XML_NOTATION_NODE }; typedef NSUInteger DDXMLNodeKind; enum { DDXMLNodeOptionsNone = 0, DDXMLNodeExpandEmptyElement = 1 << 1, DDXMLNodeCompactEmptyElement = 1 << 2, DDXMLNodePrettyPrint = 1 << 17, }; //extern struct _xmlKind; @interface DDXMLNode : NSObject <NSCopying> { // Every DDXML object is simply a wrapper around an underlying libxml node struct _xmlKind *genericPtr; // Every libxml node resides somewhere within an xml tree heirarchy. // We cannot free the tree heirarchy until all referencing nodes have been released. // So all nodes retain a reference to the node that created them, // and when the last reference is released the tree gets freed. DDXMLNode *owner; } //- (id)initWithKind:(DDXMLNodeKind)kind; //- (id)initWithKind:(DDXMLNodeKind)kind options:(NSUInteger)options; //+ (id)document; //+ (id)documentWithRootElement:(DDXMLElement *)element; + (id)elementWithName:(NSString *)name; + (id)elementWithName:(NSString *)name URI:(NSString *)URI; + (id)elementWithName:(NSString *)name stringValue:(NSString *)string; + (id)elementWithName:(NSString *)name children:(NSArray *)children attributes:(NSArray *)attributes; + (id)attributeWithName:(NSString *)name stringValue:(NSString *)stringValue; + (id)attributeWithName:(NSString *)name URI:(NSString *)URI stringValue:(NSString *)stringValue; + (id)namespaceWithName:(NSString *)name stringValue:(NSString *)stringValue; + (id)processingInstructionWithName:(NSString *)name stringValue:(NSString *)stringValue; + (id)commentWithStringValue:(NSString *)stringValue; + (id)textWithStringValue:(NSString *)stringValue; //+ (id)DTDNodeWithXMLString:(NSString *)string; #pragma mark --- Properties --- - (DDXMLNodeKind)kind; - (void)setName:(NSString *)name; - (NSString *)name; //- (void)setObjectValue:(id)value; //- (id)objectValue; - (void)setStringValue:(NSString *)string; //- (void)setStringValue:(NSString *)string resolvingEntities:(BOOL)resolve; - (NSString *)stringValue; #pragma mark --- Tree Navigation --- - (NSUInteger)index; - (NSUInteger)level; - (DDXMLDocument *)rootDocument; - (DDXMLNode *)parent; - (NSUInteger)childCount; - (NSArray *)children; - (DDXMLNode *)childAtIndex:(NSUInteger)index; - (DDXMLNode *)previousSibling; - (DDXMLNode *)nextSibling; - (DDXMLNode *)previousNode; - (DDXMLNode *)nextNode; - (void)detach; - (NSString *)XPath; #pragma mark --- QNames --- - (NSString *)localName; - (NSString *)prefix; - (void)setURI:(NSString *)URI; - (NSString *)URI; + (NSString *)localNameForName:(NSString *)name; + (NSString *)prefixForName:(NSString *)name; //+ (DDXMLNode *)predefinedNamespaceForPrefix:(NSString *)name; #pragma mark --- Output --- - (NSString *)description; - (NSString *)XMLString; - (NSString *)XMLStringWithOptions:(NSUInteger)options; //- (NSString *)canonicalXMLStringPreservingComments:(BOOL)comments; #pragma mark --- XPath/XQuery --- - (NSArray *)nodesForXPath:(NSString *)xpath error:(NSError **)error; //- (NSArray *)objectsForXQuery:(NSString *)xquery constants:(NSDictionary *)constants error:(NSError **)error; //- (NSArray *)objectsForXQuery:(NSString *)xquery error:(NSError **)error; @end
{'content_hash': '90a05b6d024882d7503a95b854e48a68', 'timestamp': '', 'source': 'github', 'line_count': 156, 'max_line_length': 111, 'avg_line_length': 29.326923076923077, 'alnum_prop': 0.7114754098360656, 'repo_name': 'duger/DianDianer', 'id': 'f2d420b8f190e5f0b5ab5a658073924e9eed2113', 'size': '4575', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'DianDianEr/XMPP/Vendor/KissXML/DDXMLNode.h', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '92847'}, {'name': 'C++', 'bytes': '202'}, {'name': 'JavaScript', 'bytes': '6175'}, {'name': 'M', 'bytes': '14860'}, {'name': 'Matlab', 'bytes': '36009'}, {'name': 'Objective-C', 'bytes': '4442520'}, {'name': 'Shell', 'bytes': '5452'}]}
1. Opening slide 1. How this presentation works. Interactiveness explained. Large credit to RustByExample.com 1. Link to presentation. 1. Goals of presentation. 1. Things that are covered. 1. Explain what Rust is and where it comes from. 1. Offer basic examples of all core aspects of language. 1. Things that aren't covered. 1. Cargo. 1. How to organize projects. 1. What is Rust. 1. Photo from rustcamp (Rust is X without Y). 1. Learning basics. 1. Hello world. ```rust fn main() { println!("Hello World!"); } ``` 1. Printing options. ```rust fn main() { println!("{} days", 31); println!("{0}, this is {1}. {1}, this is {0}", "Alice", "Bob"); println!("{subject} {verb} {predicate}", predicate="over the lazy dog", subject="the quick brown fox", verb="jumps"); println!("{} of {:b} people know binary, the other half don't", 1, 2); println!("My name is {0}, {1} {0}", "Bond", "James"); } ``` 1. Printing complex things. ```rust struct Structure(i32); fn main() { // Custom types such as this structure require more complicated // handling. This will not work. println!("This struct `{}` won't print...", Structure(3)); } ``` 1. Printing complex things. ```rust #[derive(Debug)] struct Structure(i32); fn main() { // Printing with `{:?}` is similar to with `{}`. println!("{:?} months in a year.", 12); println!("{1:?} {0:?} is the {actor:?} name.", "Slater", "Christian", actor="actor's"); // `Structure` is printable! println!("Now {:?} will print!", Structure(3)); } ``` 1. Custom printing, imports, traits. ```rust // Import (via `use`) the `fmt` module to make it available. use std::fmt; // Define a structure which `fmt::Display` will be implemented for. This is simply // a tuple struct containing an `i32` bound to the name `Structure`. struct Structure(i32); // In order to use the `{}` marker, the trait `fmt::Display` must be implemented // manually for the type. impl fmt::Display for Structure { // This trait requires `fmt` with this exact signature. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // Write strictly the first element into the supplied output // stream: `f`. Returns `fmt::Result` which indicates whether the // operation succeeded or failed. Note that `write!` uses syntax which // is very similar to `println!`. write!(f, "{}", self.0) } } ``` ### Unsorted * Best places to learn. * RustByExample.com * Best tools. * Releases explained. * Writing a safe Python extension. * Rust community. * Cargo. * Documentation generation. * Strengths / Weaknesses. * Strengths: * Safe. * Weaknesses: * Complex. * Rigid.
{'content_hash': 'ad3ac7cf8ca8e8edead473bcf6594037', 'timestamp': '', 'source': 'github', 'line_count': 109, 'max_line_length': 92, 'avg_line_length': 27.01834862385321, 'alnum_prop': 0.5887945670628183, 'repo_name': 'code-ape/intro_to_rust_slides', 'id': '0747872f59bd44067937cdaf08293a26f9a9d789', 'size': '2983', 'binary': False, 'copies': '1', 'ref': 'refs/heads/gh-pages', 'path': 'outline.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '24147'}]}
static CGFloat kBodyFontSyze = 14; static CGFloat kMinimumWidth = 40; NSString *VKOutboundTextBubbleCellReuseIdentifier = @"VKOutboundTextBubbleCell"; @implementation VKOutboundTextBubbleCell + (VKTextBubbleViewProperties *) newBubbleViewProperties { static VKTextBubbleViewProperties *bubbleViewProperties = nil; if (!bubbleViewProperties) { bubbleViewProperties = [[VKTextBubbleViewProperties alloc] initWithEdgeInsets:UIEdgeInsetsMake(10, 10, 10, 14) font:[UIFont systemFontOfSize:kBodyFontSyze] textColor:[UIColor whiteColor]]; bubbleViewProperties.minimumWidth = kMinimumWidth; } return bubbleViewProperties; } + (VKTextBubbleView *) newBubbleView { return [[VKTextBubbleView alloc] initWithBubbleProperties:[[self class] newBubbleViewProperties]]; } + (CGFloat) heightForText:(NSString *) text widht:(CGFloat) width { UIEdgeInsets insets = [[self class] edgeInsets]; return insets.top + insets.bottom + [VKTextBubbleView sizeWithText:text Properties:[[self class] newBubbleViewProperties] constrainedToWidth:[[self class] bubbleViewWidthConstraintForCellWidth:width]].height; } - (void) setMessageText:(NSString *)messageText { self.bubbleView.messageBody.text = [[NSAttributedString alloc] initWithString:messageText attributes:self.bubbleView.properties.textAttributes]; } - (NSString *) messageText { return self.bubbleView.messageBody.text; } @end
{'content_hash': 'f239b827905c8eafc475feae1f2d0ef4', 'timestamp': '', 'source': 'github', 'line_count': 39, 'max_line_length': 138, 'avg_line_length': 45.1025641025641, 'alnum_prop': 0.6327458783399659, 'repo_name': 'vkovtash/VKMessagesViewController', 'id': 'f7da64da5a1346effc79a8885e6f21e1b0ad825f', 'size': '1960', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'VKMessagesViewController/DefaultStyle/VKOutboundTextBubbleCell.m', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Objective-C', 'bytes': '112040'}, {'name': 'Ruby', 'bytes': '810'}]}
<?php namespace PHPExiftool\Driver\Tag\MXF; use JMS\Serializer\Annotation\ExclusionPolicy; use PHPExiftool\Driver\AbstractTag; /** * @ExclusionPolicy("all") */ class LocalFilePath extends AbstractTag { protected $Id = 'mixed'; protected $Name = 'LocalFilePath'; protected $FullName = 'MXF::Main'; protected $GroupName = 'MXF'; protected $g0 = 'MXF'; protected $g1 = 'MXF'; protected $g2 = 'Video'; protected $Type = 'mixed'; protected $Writable = false; protected $Description = 'Local File Path'; }
{'content_hash': '6d46ef37022869a40e06b3270bd0dedb', 'timestamp': '', 'source': 'github', 'line_count': 35, 'max_line_length': 47, 'avg_line_length': 15.914285714285715, 'alnum_prop': 0.6552962298025135, 'repo_name': 'romainneutron/PHPExiftool', 'id': 'd6e1075f4d14a9b7962033373896f1aa7b531167', 'size': '779', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/PHPExiftool/Driver/Tag/MXF/LocalFilePath.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'PHP', 'bytes': '22042446'}]}
using System.Linq; using VersionOne.ServiceHost.ConfigurationTool.Attributes; using VersionOne.ServiceHost.ConfigurationTool.Entities; namespace VersionOne.ServiceHost.ConfigurationTool.BZ { /// <summary> /// Dependency validator to check Services consistency, validate dependencies that exist between services /// and to enforce pages requiring established V1 connection. /// </summary> public class DependencyValidator { private readonly IFacade facade; public DependencyValidator(IFacade facade) { this.facade = facade; } /// <summary> /// Throw exception if entity requires connection to V1 and actual connection is down. /// </summary> /// <param name="entity">entity to validate</param> /// <exception cref="V1ConnectionRequiredException"/> public void CheckVersionOneDependency(BaseServiceEntity entity) { if(entity.GetType().IsDefined(typeof(DependsOnVersionOneAttribute), false) && !facade.IsConnected) { throw new V1ConnectionRequiredException(); } } /// <summary> /// Throw exception if entity depends on other entity that is missing. /// </summary> /// <param name="entity">entity to validate</param> /// <param name="config">Service Host configuration container</param> /// <exception cref="DependencyFailureException" /> public void CheckOtherServiceDependency(BaseServiceEntity entity, ServiceHostConfiguration config) { var attributes = entity.GetType().GetCustomAttributes(typeof (DependsOnServiceAttribute), false); if(attributes.Length < 1) { return; } foreach(var attribute in attributes.Cast<DependsOnServiceAttribute>().Where(attribute => config[attribute.ServiceType] == null)) { throw new DependencyFailureException(attribute.ServiceType, "Service dependency does not exist"); } } /// <summary> /// Throw exception if Service entities depend on other entities that are missing. Usable when business-validating data /// coming from configuration file. /// </summary> /// <param name="config">Service Host configuration container to validate</param> /// <exception cref="DependencyFailureException" /> public void CheckServiceDependencies(ServiceHostConfiguration config) { foreach(var entity in config.Services) { CheckOtherServiceDependency(entity, config); } } } }
{'content_hash': '67e14f6fd080665f9219be37843313fc', 'timestamp': '', 'source': 'github', 'line_count': 58, 'max_line_length': 142, 'avg_line_length': 45.241379310344826, 'alnum_prop': 0.6570121951219512, 'repo_name': 'versionone/VersionOne.Integration.QualityCenter', 'id': '390d7855aee5c01875d71c993bc5380ab63799ad', 'size': '2624', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'VersionOne.ServiceHost.ConfigurationTool/BZ/DependencyValidator.cs', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C#', 'bytes': '335571'}, {'name': 'PowerShell', 'bytes': '3173'}, {'name': 'Shell', 'bytes': '4671'}]}
namespace gfx { class MultiAnimation; } // namespace gfx namespace views { class Button; } // namespace views namespace message_center { class MessageCenter; class MessageCenterBubble; class NotificationCenterButton; class MessageCenterButtonBar; class MessageCenterTray; class MessageCenterView; class MessageView; class MessageViewContextMenuController; class MessageListView; class NotificationView; class NotifierSettingsView; // MessageCenterView /////////////////////////////////////////////////////////// class MESSAGE_CENTER_EXPORT MessageCenterView : public views::View, public MessageCenterObserver, public MessageCenterController, public gfx::AnimationDelegate { public: MessageCenterView(MessageCenter* message_center, MessageCenterTray* tray, int max_height, bool initially_settings_visible, bool top_down); virtual ~MessageCenterView(); void SetNotifications(const NotificationList::Notifications& notifications); void ClearAllNotifications(); void OnAllNotificationsCleared(); size_t NumMessageViewsForTest() const; void SetSettingsVisible(bool visible); void OnSettingsChanged(); bool settings_visible() const { return settings_visible_; } void SetIsClosing(bool is_closing); protected: // Overridden from views::View: virtual void Layout() OVERRIDE; virtual gfx::Size GetPreferredSize() OVERRIDE; virtual int GetHeightForWidth(int width) OVERRIDE; virtual bool OnMouseWheel(const ui::MouseWheelEvent& event) OVERRIDE; virtual void OnMouseExited(const ui::MouseEvent& event) OVERRIDE; // Overridden from MessageCenterObserver: virtual void OnNotificationAdded(const std::string& id) OVERRIDE; virtual void OnNotificationRemoved(const std::string& id, bool by_user) OVERRIDE; virtual void OnNotificationUpdated(const std::string& id) OVERRIDE; // Overridden from MessageCenterController: virtual void ClickOnNotification(const std::string& notification_id) OVERRIDE; virtual void RemoveNotification(const std::string& notification_id, bool by_user) OVERRIDE; virtual scoped_ptr<ui::MenuModel> CreateMenuModel( const NotifierId& notifier_id, const base::string16& display_source) OVERRIDE; virtual bool HasClickedListener(const std::string& notification_id) OVERRIDE; virtual void ClickOnNotificationButton(const std::string& notification_id, int button_index) OVERRIDE; // Overridden from gfx::AnimationDelegate: virtual void AnimationEnded(const gfx::Animation* animation) OVERRIDE; virtual void AnimationProgressed(const gfx::Animation* animation) OVERRIDE; virtual void AnimationCanceled(const gfx::Animation* animation) OVERRIDE; private: friend class MessageCenterViewTest; void AddNotificationAt(const Notification& notification, int index); void NotificationsChanged(); void SetNotificationViewForTest(MessageView* view); MessageCenter* message_center_; // Weak reference. MessageCenterTray* tray_; // Weak reference. // Map notification_id->NotificationView*. It contains all NotificaitonViews // currently displayed in MessageCenter. typedef std::map<std::string, NotificationView*> NotificationViewsMap; NotificationViewsMap notification_views_; // Weak. // Child views. views::ScrollView* scroller_; scoped_ptr<MessageListView> message_list_view_; scoped_ptr<views::View> empty_list_view_; NotifierSettingsView* settings_view_; MessageCenterButtonBar* button_bar_; bool top_down_; // Data for transition animation between settings view and message list. bool settings_visible_; // Animation managing transition between message center and settings (and vice // versa). scoped_ptr<gfx::MultiAnimation> settings_transition_animation_; // Helper data to keep track of the transition between settings and // message center views. views::View* source_view_; int source_height_; views::View* target_view_; int target_height_; // True when the widget is closing so that further operations should be // ignored. bool is_closing_; scoped_ptr<MessageViewContextMenuController> context_menu_controller_; DISALLOW_COPY_AND_ASSIGN(MessageCenterView); }; } // namespace message_center #endif // UI_MESSAGE_CENTER_VIEWS_MESSAGE_CENTER_VIEW_H_
{'content_hash': '49b193cba13cd3ed3eac6583e876651b', 'timestamp': '', 'source': 'github', 'line_count': 128, 'max_line_length': 80, 'avg_line_length': 35.65625, 'alnum_prop': 0.7129710780017529, 'repo_name': 'ChromiumWebApps/chromium', 'id': '8a870ee0c5baba309f30d9fad1a3065829e9e09e', 'size': '5238', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'ui/message_center/views/message_center_view.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'ASP', 'bytes': '853'}, {'name': 'AppleScript', 'bytes': '6973'}, {'name': 'Arduino', 'bytes': '464'}, {'name': 'Assembly', 'bytes': '52960'}, {'name': 'Awk', 'bytes': '8660'}, {'name': 'C', 'bytes': '42286199'}, {'name': 'C#', 'bytes': '1132'}, {'name': 'C++', 'bytes': '198616766'}, {'name': 'CSS', 'bytes': '937333'}, {'name': 'DOT', 'bytes': '2984'}, {'name': 'Java', 'bytes': '5695686'}, {'name': 'JavaScript', 'bytes': '21967126'}, {'name': 'M', 'bytes': '2190'}, {'name': 'Matlab', 'bytes': '2262'}, {'name': 'Objective-C', 'bytes': '7602057'}, {'name': 'PHP', 'bytes': '97817'}, {'name': 'Perl', 'bytes': '1210885'}, {'name': 'Python', 'bytes': '10774996'}, {'name': 'R', 'bytes': '262'}, {'name': 'Shell', 'bytes': '1316721'}, {'name': 'Tcl', 'bytes': '277091'}, {'name': 'TypeScript', 'bytes': '1560024'}, {'name': 'XSLT', 'bytes': '13493'}, {'name': 'nesC', 'bytes': '15243'}]}
package org.netbeans.cubeon.ui.internals; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import org.netbeans.cubeon.tasks.spi.task.TaskElement; import org.openide.filesystems.FileChangeListener; import org.openide.filesystems.FileLock; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileStateInvalidException; import org.openide.filesystems.FileSystem; import org.openide.nodes.Node; /** * * @author Anuradha */ public class TaskElementFileObject extends FileObject { Map<String, Object> map = new HashMap<String, Object>(); private TaskElement element; private Node node; public TaskElementFileObject(TaskElement element, Node node) { this.element = element; this.node = node; } public Node getNode() { return node; } @Override public String getName() { return element.getName(); } @Override public String getExt() { return ""; } @Override public void rename(FileLock lock, String name, String ext) throws IOException { //DONOTHING } @Override public FileSystem getFileSystem() throws FileStateInvalidException { return new TaskFileSystem(); } @Override public FileObject getParent() { //NO parent return null; } @Override public boolean isFolder() { return false; } @Override public Date lastModified() { //TODO : add task modified Date return new Date(); } @Override public boolean isRoot() { return true; } @Override public boolean isData() { return true; } @Override public boolean isValid() { return true; } @Override public void delete(FileLock lock) throws IOException { //DONOTHING } @Override public Object getAttribute(String attrName) { return map.get(attrName); } @Override public void setAttribute(String attrName, Object value) throws IOException { map.put(attrName, value); } @Override public Enumeration<String> getAttributes() { //TODO ADD return null; } @Override public void addFileChangeListener(FileChangeListener fcl) { //DONOTHING } @Override public void removeFileChangeListener(FileChangeListener fcl) { //DONOTHING } @Override public long getSize() { return 0L; } @Override public InputStream getInputStream() throws FileNotFoundException { return null; } @Override public OutputStream getOutputStream(FileLock lock) throws IOException { return null; } @Override public FileLock lock() throws IOException { return null; } @Override @Deprecated public void setImportant(boolean b) { //DONOTHING } @Override public FileObject[] getChildren() { return new FileObject[0]; } @Override public FileObject getFileObject(String name, String ext) { return null; } @Override public FileObject createFolder(String name) throws IOException { throw new IOException("Not supported"); } @Override public FileObject createData(String name, String ext) throws IOException { throw new IOException("Not supported"); } @Override @Deprecated public boolean isReadOnly() { return false; } }
{'content_hash': '3caf9fc52300ad76ba28646ea8854efd', 'timestamp': '', 'source': 'github', 'line_count': 173, 'max_line_length': 83, 'avg_line_length': 22.034682080924856, 'alnum_prop': 0.6183105981112277, 'repo_name': 'theanuradha/cubeon', 'id': 'bb6433a0fb45e07f9b80b5740cdbfa2609671d28', 'size': '4456', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'core/ui/src/main/java/org/netbeans/cubeon/ui/internals/TaskElementFileObject.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '2006529'}]}
external help file: Microsoft.Azure.Commands.Network.dll-Help.xml online version: schema: 2.0.0 --- # Get-AzureRmNetworkWatcher ## SYNOPSIS Gets the properties of a Network Watcher ## SYNTAX ### Get ``` Get-AzureRmNetworkWatcher -Name <String> -ResourceGroupName <String> [<CommonParameters>] ``` ### List ``` Get-AzureRmNetworkWatcher [-ResourceGroupName <String>] [<CommonParameters>] ``` ## DESCRIPTION The Get-AzureRmNetworkWatcher cmdlet gets one or more Azure Network Watcher resources. ## EXAMPLES ### -------------------------- Example 1: Get a Network Watcher -------------------------- ``` Get-AzureRmNetworkWatcher -Name NetworkWatcher_westcentralus -ResourceGroup NetworkWatcherRG Name : NetworkWatcher_westcentralus Id : /subscriptions/bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb/resourceGroups/NetworkWatcherRG/providers/Microsoft.Network/networkWatchers/NetworkWatcher_westcentralus Etag : W/"ac624778-0214-49b9-a04c-794863485fa6" Location : westcentralus Tags : ProvisioningState : Succeeded ``` Gets the Network Watcher named NetworkWatcher_westcentralus in the resource group NetworkWatcherRG. ## PARAMETERS ### -Name The network watcher name. ```yaml Type: String Parameter Sets: Get Aliases: ResourceName Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ResourceGroupName The resource group name. ```yaml Type: String Parameter Sets: Get Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ```yaml Type: String Parameter Sets: List Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None ## OUTPUTS ### Microsoft.Azure.Commands.Network.Models.PSNetworkWatcher ## NOTES Keywords: azure, azurerm, arm, resource, management, manager, network, networking, network watcher ## RELATED LINKS [New-AzureRmNetworkWatcher]() [Remove-AzureRmNetworkWatcher]() [New-AzureRmNetworkWatcherPacketCapture]() [New-AzureRmPacketCaptureFilterConfig]() [Get-AzureRmNetworkWatcherPacketCapture]() [Remove-AzureRmNetworkWatcherPacketCapture]() [Stop-AzureRmNetworkWatcherPacketCapture]() [Test-AzureRmNetworkWatcherIPFlow]() [Get-AzureRmNetworkWatcherNextHop]() [Get-AzureRmNetworkWatcherSecurityGroupView]() [Get-AzureRmNetworkWatcherTopology]() [Start-AzureRmNetworkWatcherResourceTroubleshooting]()
{'content_hash': '630d6c54f982a2571da383c2cbbfb016', 'timestamp': '', 'source': 'github', 'line_count': 115, 'max_line_length': 314, 'avg_line_length': 24.930434782608696, 'alnum_prop': 0.7603767003836763, 'repo_name': 'pankajsn/azure-powershell', 'id': 'f9887ad9f6b152130ccd225bebdba81787fbf560', 'size': '2871', 'binary': False, 'copies': '6', 'ref': 'refs/heads/dev', 'path': 'src/ResourceManager/Network/Commands.Network/help/Get-AzureRmNetworkWatcher.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '16509'}, {'name': 'C#', 'bytes': '38528895'}, {'name': 'HTML', 'bytes': '209'}, {'name': 'JavaScript', 'bytes': '4979'}, {'name': 'PHP', 'bytes': '41'}, {'name': 'PowerShell', 'bytes': '3821358'}, {'name': 'Ruby', 'bytes': '265'}, {'name': 'Shell', 'bytes': '50'}, {'name': 'XSLT', 'bytes': '6114'}]}
set(CMAKE_RELATIVE_PATH_TOP_SOURCE "/Users/brendanbusey/Desktop/Github/InterviewPreparation/LeetCode/Easy/RemoveAllAdjacentDuplicatesInString") set(CMAKE_RELATIVE_PATH_TOP_BINARY "/Users/brendanbusey/Desktop/Github/InterviewPreparation/LeetCode/Easy/RemoveAllAdjacentDuplicatesInString/cmake-build-debug") # Force unix paths in dependencies. set(CMAKE_FORCE_UNIX_PATHS 1) # The C and CXX include file regular expressions for this directory. set(CMAKE_C_INCLUDE_REGEX_SCAN "^.*$") set(CMAKE_C_INCLUDE_REGEX_COMPLAIN "^$") set(CMAKE_CXX_INCLUDE_REGEX_SCAN ${CMAKE_C_INCLUDE_REGEX_SCAN}) set(CMAKE_CXX_INCLUDE_REGEX_COMPLAIN ${CMAKE_C_INCLUDE_REGEX_COMPLAIN})
{'content_hash': '4c38459b01595a071129d931cd961f36', 'timestamp': '', 'source': 'github', 'line_count': 12, 'max_line_length': 161, 'avg_line_length': 55.0, 'alnum_prop': 0.8075757575757576, 'repo_name': 'busebd12/InterviewPreparation', 'id': 'c1a00c89303e03cb4321fee6e2150c120faf828c', 'size': '804', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'LeetCode/C++/General/Easy/RemoveAllAdjacentDuplicatesInString/cmake-build-debug/CMakeFiles/CMakeDirectoryInformation.cmake', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '9011022'}, {'name': 'C++', 'bytes': '14785379'}, {'name': 'CMake', 'bytes': '10099860'}, {'name': 'Java', 'bytes': '54365'}, {'name': 'Makefile', 'bytes': '5154401'}, {'name': 'TeX', 'bytes': '41241'}]}
import inviwopy as ivw from inviwopy.glm import * network = ivw.app.network factory = ivw.app.processorFactory; network.clear() p1 = factory.create('org.inviwo.NoiseProcessor', ivec2(75 , -100)) p2 = factory.create('org.inviwo.ImageLowPass' , ivec2(75 , -25)) p3 = factory.create('org.inviwo.CanvasGL') p3.position = ivec2(75 , 50) network.addProcessor(p1) network.addProcessor(p2) network.addProcessor(p3) network.addConnection( p1.outports[0] , p2.inports[0] ) network.addConnection( p2.outports[0] , p3.inports[0] )
{'content_hash': '46aa989cc0d98ff15a8de24b95e43acd', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 67, 'avg_line_length': 24.0, 'alnum_prop': 0.7386363636363636, 'repo_name': 'inviwo/inviwo', 'id': 'b3ddf05067f58c836a870d639b410c1c9e381f20', 'size': '551', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'data/scripts/create_network.py', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'C', 'bytes': '146426'}, {'name': 'C++', 'bytes': '15986580'}, {'name': 'CMake', 'bytes': '444333'}, {'name': 'CSS', 'bytes': '8925'}, {'name': 'Dockerfile', 'bytes': '1760'}, {'name': 'GLSL', 'bytes': '615425'}, {'name': 'Groovy', 'bytes': '12826'}, {'name': 'HTML', 'bytes': '148248'}, {'name': 'JavaScript', 'bytes': '286267'}, {'name': 'Mathematica', 'bytes': '304992'}, {'name': 'Python', 'bytes': '1965605'}, {'name': 'QMake', 'bytes': '172'}, {'name': 'Shell', 'bytes': '992'}]}
require 'active_support/concern' module SolrDoc extend ActiveSupport::Concern include ActionView::Helpers::SanitizeHelper include SolrDocLocal included do before_destroy :delete_from_index # Prepare Solr document hash for the record def solr_doc_data data = parse_unit_data doc = {} doc[:title] = title doc[:record_type] = self.class.to_s.underscore doc[:record_id] = self.id doc[:uri] = uri doc[:identifier] = data[:identifiers] doc[:primary_agent] = data[:primary_agent] doc[:abstract] = strip_tags(data[:abstract]) doc[:date_statement] = data[:date_statement] doc[:extent_statement] = data[:extent_statement] doc[:notes] = [] doc[:inclusive_years] = data[:inclusive_years] doc[:id_0] = data[:id_0] if data[:notes] data[:notes].each do |k,v| v.each { |note| doc[:notes] << note[:content] } end end doc[:primary_agent] = data[:primary_agent] agents.each do |a| (doc[:agents] ||= []) << a.display_name (doc[:agents_uri] ||= []) << a.uri (doc[:agents_id] ||= []) << a.id end subjects.each do |s| (doc[:subjects] ||= []) << s.subject (doc[:subjects_uri] ||= []) << s.uri (doc[:subjects_id] ||= []) << s.id end case self when Resource doc[:resource_uri] = uri doc[:resource_title] = title doc[:resource_id] = id doc[:resource_collection_id] = data[:collection_id] doc[:resource_abstract] = strip_tags(data[:abstract]) doc[:resource_primary_agent] = data[:primary_agent] doc[:resource_date_statement] = data[:date_statement] doc[:resource_extent_statement] = data[:extent_statement] if has_digital_objects || has_descendant_digital_objects doc[:resource_digital_content] = true end doc[:resource_eadid] = eadid doc[:eadid] = eadid when ArchivalObject if resource r_data = resource.parse_unit_data doc[:resource_uri] = resource.uri doc[:resource_title] = resource.title doc[:resource_id] = resource.id doc[:resource_collection_id] = r_data[:collection_id] doc[:resource_abstract] = strip_tags(r_data[:abstract]) doc[:resource_primary_agent] = r_data[:primary_agent] doc[:resource_date_statement] = r_data[:date_statement] doc[:resource_extent_statement] = r_data[:extent_statement] doc[:component_ancestors_title] = ancestors.map { |x| x.title } doc[:component_ancestors_id] = ancestors.map { |x| x.id } if has_digital_objects doc[:digital_content] = true end if resource.has_digital_objects || resource.has_descendant_digital_objects doc[:resource_digital_content] = true end doc[:resource_eadid] = resource.eadid doc[:containers] = data[:containers] else puts "ERROR indexing ArchivalObject #{ id.to_s }" puts "No resource found" puts; puts self.inspect; puts puts "Continuing in 10 seconds..." puts sleep 10 end end # *** # TO DO: Calcualted dates # *** add_local_fields(doc,data) doc.delete_if { |k,v| v.blank? } doc end # Updates the record in the Solr index def update_index SearchIndex.update_record(self) end # Remove the record from the Solr index def delete_from_index SearchIndex.delete_record(self) end end end
{'content_hash': '8652969275dde4cf6add8126e1c5ed2e', 'timestamp': '', 'source': 'github', 'line_count': 123, 'max_line_length': 84, 'avg_line_length': 29.642276422764226, 'alnum_prop': 0.5776193088315963, 'repo_name': 'NCSU-Libraries/aspace_public', 'id': '9dc49a129f58fc5b63c484d0445355643d546349', 'size': '3646', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/models/concerns/solr_doc.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '65780'}, {'name': 'HTML', 'bytes': '20174'}, {'name': 'JavaScript', 'bytes': '17974'}, {'name': 'Ruby', 'bytes': '337630'}]}
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_SYNC_H #define BITCOIN_SYNC_H #include "threadsafety.h" #include <boost/thread/condition_variable.hpp> #include <boost/thread/locks.hpp> #include <boost/thread/mutex.hpp> #include <boost/thread/recursive_mutex.hpp> ///////////////////////////////////////////////// // // // THE SIMPLE DEFINITION, EXCLUDING DEBUG CODE // // // ///////////////////////////////////////////////// /* CCriticalSection mutex; boost::recursive_mutex mutex; LOCK(mutex); boost::unique_lock<boost::recursive_mutex> criticalblock(mutex); LOCK2(mutex1, mutex2); boost::unique_lock<boost::recursive_mutex> criticalblock1(mutex1); boost::unique_lock<boost::recursive_mutex> criticalblock2(mutex2); TRY_LOCK(mutex, name); boost::unique_lock<boost::recursive_mutex> name(mutex, boost::try_to_lock_t); ENTER_CRITICAL_SECTION(mutex); // no RAII mutex.lock(); LEAVE_CRITICAL_SECTION(mutex); // no RAII mutex.unlock(); */ /////////////////////////////// // // // THE ACTUAL IMPLEMENTATION // // // /////////////////////////////// /** * Template mixin that adds -Wthread-safety locking * annotations to a subset of the mutex API. */ template <typename PARENT> class LOCKABLE AnnotatedMixin : public PARENT { public: void lock() EXCLUSIVE_LOCK_FUNCTION() { PARENT::lock(); } void unlock() UNLOCK_FUNCTION() { PARENT::unlock(); } bool try_lock() EXCLUSIVE_TRYLOCK_FUNCTION(true) { return PARENT::try_lock(); } }; /** * Wrapped boost mutex: supports recursive locking, but no waiting * TODO: We should move away from using the recursive lock by default. */ typedef AnnotatedMixin<boost::recursive_mutex> CCriticalSection; /** Wrapped boost mutex: supports waiting but not recursive locking */ typedef AnnotatedMixin<boost::mutex> CWaitableCriticalSection; /** Just a typedef for boost::condition_variable, can be wrapped later if desired */ typedef boost::condition_variable CConditionVariable; #ifdef DEBUG_LOCKORDER void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry = false); void LeaveCritical(); std::string LocksHeld(); void AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, void* cs); #else void static inline EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry = false) {} void static inline LeaveCritical() {} void static inline AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, void* cs) {} #endif #define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs) #ifdef DEBUG_LOCKCONTENTION void PrintLockContention(const char* pszName, const char* pszFile, int nLine); #endif /** Wrapper around boost::unique_lock<Mutex> */ template <typename Mutex> class SCOPED_LOCKABLE CMutexLock { private: boost::unique_lock<Mutex> lock; void Enter(const char* pszName, const char* pszFile, int nLine) { EnterCritical(pszName, pszFile, nLine, (void*)(lock.mutex())); #ifdef DEBUG_LOCKCONTENTION if (!lock.try_lock()) { PrintLockContention(pszName, pszFile, nLine); #endif lock.lock(); #ifdef DEBUG_LOCKCONTENTION } #endif } bool TryEnter(const char* pszName, const char* pszFile, int nLine) { EnterCritical(pszName, pszFile, nLine, (void*)(lock.mutex()), true); lock.try_lock(); if (!lock.owns_lock()) LeaveCritical(); return lock.owns_lock(); } public: CMutexLock(Mutex& mutexIn, const char* pszName, const char* pszFile, int nLine, bool fTry = false) EXCLUSIVE_LOCK_FUNCTION(mutexIn) : lock(mutexIn, boost::defer_lock) { if (fTry) TryEnter(pszName, pszFile, nLine); else Enter(pszName, pszFile, nLine); } CMutexLock(Mutex* pmutexIn, const char* pszName, const char* pszFile, int nLine, bool fTry = false) EXCLUSIVE_LOCK_FUNCTION(pmutexIn) { if (!pmutexIn) return; lock = boost::unique_lock<Mutex>(*pmutexIn, boost::defer_lock); if (fTry) TryEnter(pszName, pszFile, nLine); else Enter(pszName, pszFile, nLine); } ~CMutexLock() UNLOCK_FUNCTION() { if (lock.owns_lock()) LeaveCritical(); } operator bool() { return lock.owns_lock(); } }; typedef CMutexLock<CCriticalSection> CCriticalBlock; #define LOCK(cs) CCriticalBlock criticalblock(cs, #cs, __FILE__, __LINE__) #define LOCK2(cs1, cs2) CCriticalBlock criticalblock1(cs1, #cs1, __FILE__, __LINE__), criticalblock2(cs2, #cs2, __FILE__, __LINE__) #define TRY_LOCK(cs, name) CCriticalBlock name(cs, #cs, __FILE__, __LINE__, true) #define ENTER_CRITICAL_SECTION(cs) \ { \ EnterCritical(#cs, __FILE__, __LINE__, (void*)(&cs)); \ (cs).lock(); \ } #define LEAVE_CRITICAL_SECTION(cs) \ { \ (cs).unlock(); \ LeaveCritical(); \ } class CSemaphore { private: boost::condition_variable condition; boost::mutex mutex; int value; public: CSemaphore(int init) : value(init) {} void wait() { boost::unique_lock<boost::mutex> lock(mutex); while (value < 1) { condition.wait(lock); } value--; } bool try_wait() { boost::unique_lock<boost::mutex> lock(mutex); if (value < 1) return false; value--; return true; } void post() { { boost::unique_lock<boost::mutex> lock(mutex); value++; } condition.notify_one(); } }; /** RAII-style semaphore lock */ class CSemaphoreGrant { private: CSemaphore* sem; bool fHaveGrant; public: void Acquire() { if (fHaveGrant) return; sem->wait(); fHaveGrant = true; } void Release() { if (!fHaveGrant) return; sem->post(); fHaveGrant = false; } bool TryAcquire() { if (!fHaveGrant && sem->try_wait()) fHaveGrant = true; return fHaveGrant; } void MoveTo(CSemaphoreGrant& grant) { grant.Release(); grant.sem = sem; grant.fHaveGrant = fHaveGrant; sem = NULL; fHaveGrant = false; } CSemaphoreGrant() : sem(NULL), fHaveGrant(false) {} CSemaphoreGrant(CSemaphore& sema, bool fTry = false) : sem(&sema), fHaveGrant(false) { if (fTry) TryAcquire(); else Acquire(); } ~CSemaphoreGrant() { Release(); } operator bool() { return fHaveGrant; } }; #endif // BITCOIN_SYNC_H
{'content_hash': '950adbe74e169d4e5dbc25effce257a4', 'timestamp': '', 'source': 'github', 'line_count': 280, 'max_line_length': 170, 'avg_line_length': 25.917857142857144, 'alnum_prop': 0.5835744798125947, 'repo_name': 'AdnCoin/AdnCoin', 'id': '393a669062958c25322e563a80d478f4e21225fc', 'size': '7257', 'binary': False, 'copies': '24', 'ref': 'refs/heads/master', 'path': 'src/sync.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '1315019'}, {'name': 'C++', 'bytes': '5256245'}, {'name': 'CSS', 'bytes': '124311'}, {'name': 'HTML', 'bytes': '50621'}, {'name': 'Java', 'bytes': '2100'}, {'name': 'M4', 'bytes': '147843'}, {'name': 'Makefile', 'bytes': '97140'}, {'name': 'Objective-C', 'bytes': '4930'}, {'name': 'Objective-C++', 'bytes': '7222'}, {'name': 'Protocol Buffer', 'bytes': '2308'}, {'name': 'Python', 'bytes': '706091'}, {'name': 'QMake', 'bytes': '2054'}, {'name': 'Roff', 'bytes': '3649'}, {'name': 'Shell', 'bytes': '35573'}]}
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v0.6.1 */ (function() { 'use strict'; /** * @ngdoc module * @name material.components.tabs * @description * * Tabs, created with the `<md-tabs>` directive provide *tabbed* navigation with different styles. * The Tabs component consists of clickable tabs that are aligned horizontally side-by-side. * * Features include support for: * * - static or dynamic tabs, * - responsive designs, * - accessibility support (ARIA), * - tab pagination, * - external or internal tab content, * - focus indicators and arrow-key navigations, * - programmatic lookup and access to tab controllers, and * - dynamic transitions through different tab contents. * */ /* * @see js folder for tabs implementation */ angular.module('material.components.tabs', [ 'material.core' ]); })(); (function() { 'use strict'; /** * Conditionally configure ink bar animations when the * tab selection changes. If `mdNoBar` then do not show the * bar nor animate. */ angular.module('material.components.tabs') .directive('mdTabsInkBar', MdTabInkDirective); function MdTabInkDirective($mdConstant, $window, $$rAF, $timeout) { return { restrict: 'E', require: ['^?mdNoBar', '^mdTabs'], link: postLink }; function postLink(scope, element, attr, ctrls) { var nobar = ctrls[0], tabsCtrl = ctrls[1], timeout; if (nobar) return; tabsCtrl.inkBarElement = element; scope.$watch(tabsCtrl.selected, updateBar); scope.$on('$mdTabsChanged', updateBar); function updateBar() { var selected = tabsCtrl.selected(); var hideInkBar = !selected || tabsCtrl.count() < 2 || (scope.pagination || {}).itemsPerPage === 1; element.css('display', hideInkBar ? 'none' : 'block'); if (!hideInkBar) { var count = tabsCtrl.count(); var scale = 1 / count; var left = tabsCtrl.indexOf(selected); element.css($mdConstant.CSS.TRANSFORM, 'scaleX(' + scale + ') ' + 'translate3d(' + left * 100 + '%,0,0)'); element.addClass('md-ink-bar-grow'); if (timeout) $timeout.cancel(timeout); timeout = $timeout(function () { element.removeClass('md-ink-bar-grow'); }, 250, false); } } } } MdTabInkDirective.$inject = ["$mdConstant", "$window", "$$rAF", "$timeout"]; })(); (function() { 'use strict'; angular.module('material.components.tabs') .directive('mdTabsPagination', TabPaginationDirective); function TabPaginationDirective($mdConstant, $window, $$rAF, $$q, $timeout) { // TODO allow configuration of TAB_MIN_WIDTH // Must match tab min-width rule in _tabs.scss var TAB_MIN_WIDTH = 8 * 12; // Must match (2 * width of paginators) in scss var PAGINATORS_WIDTH = (8 * 4) * 2; return { restrict: 'A', require: '^mdTabs', link: postLink }; function postLink(scope, element, attr, tabsCtrl) { var tabsParent = element.children(); var state = scope.pagination = { page: -1, active: false, clickNext: function() { userChangePage(+1); }, clickPrevious: function() { userChangePage(-1); } }; updatePagination(); var debouncedUpdatePagination = $$rAF.debounce(updatePagination); scope.$on('$mdTabsChanged', debouncedUpdatePagination); angular.element($window).on('resize', debouncedUpdatePagination); scope.$on('$destroy', function() { angular.element($window).off('resize', debouncedUpdatePagination); }); scope.$watch(tabsCtrl.selected, onSelectedTabChange); scope.$watch(function() { return tabsCtrl.tabToFocus; }, onTabFocus); // Make sure we don't focus an element on the next page // before it's in view function onTabFocus(tab, oldTab) { if (!tab) return; var pageIndex = getPageForTab(tab); if (!state.active || pageIndex === state.page) { tab.element.focus(); } else { // Go to the new page, wait for the page transition to end, then focus. oldTab && oldTab.element.blur(); setPage(pageIndex).then(function() { tab.element.focus(); }); } } function onSelectedTabChange(selectedTab) { if (!selectedTab) return; if (state.active) { var selectedTabPage = getPageForTab(selectedTab); setPage(selectedTabPage); } else { debouncedUpdatePagination(); } } // Called when page is changed by a user action (click) function userChangePage(increment) { var newPage = state.page + increment; var newTab; if (!tabsCtrl.selected() || getPageForTab(tabsCtrl.selected()) !== newPage) { var startIndex; if (increment < 0) { // If going backward, select the previous available tab, starting from // the first item on the page after newPage. startIndex = (newPage + 1) * state.itemsPerPage; newTab = tabsCtrl.previous( tabsCtrl.itemAt(startIndex) ); } else { // If going forward, select the next available tab, starting with the // last item before newPage. startIndex = (newPage * state.itemsPerPage) - 1; newTab = tabsCtrl.next( tabsCtrl.itemAt(startIndex) ); } } setPage(newPage).then(function() { newTab && newTab.element.focus(); }); newTab && tabsCtrl.select(newTab); } function updatePagination() { var tabs = element.find('md-tab'); var tabsWidth = element.parent().prop('clientWidth') - PAGINATORS_WIDTH; var needPagination = tabsWidth && TAB_MIN_WIDTH * tabsCtrl.count() > tabsWidth; var paginationToggled = needPagination !== state.active; // If the md-tabs element is not displayed, then do nothing. if ( tabsWidth <= 0 ) { needPagination = false; paginationToggled = true; } state.active = needPagination; if (needPagination) { state.pagesCount = Math.ceil((TAB_MIN_WIDTH * tabsCtrl.count()) / tabsWidth); state.itemsPerPage = Math.max(1, Math.floor(tabsCtrl.count() / state.pagesCount)); state.tabWidth = tabsWidth / state.itemsPerPage; tabsParent.css('width', state.tabWidth * tabsCtrl.count() + 'px'); tabs.css('width', state.tabWidth + 'px'); var selectedTabPage = getPageForTab(tabsCtrl.selected()); setPage(selectedTabPage); } else { if (paginationToggled) { $timeout(function() { tabsParent.css('width', ''); tabs.css('width', ''); slideTabButtons(0); state.page = -1; }); } } } function slideTabButtons(x) { if (tabsCtrl.pagingOffset === x) { // Resolve instantly if no change return $$q.when(); } var deferred = $$q.defer(); tabsCtrl.$$pagingOffset = x; tabsParent.css($mdConstant.CSS.TRANSFORM, 'translate3d(' + x + 'px,0,0)'); tabsParent.on($mdConstant.CSS.TRANSITIONEND, onTabsParentTransitionEnd); return deferred.promise; function onTabsParentTransitionEnd(ev) { // Make sure this event didn't bubble up from an animation in a child element. if (ev.target === tabsParent[0]) { tabsParent.off($mdConstant.CSS.TRANSITIONEND, onTabsParentTransitionEnd); deferred.resolve(); } } } function getPageForTab(tab) { var tabIndex = tabsCtrl.indexOf(tab); if (tabIndex === -1) return 0; return Math.floor(tabIndex / state.itemsPerPage); } function setPage(page) { if (page === state.page) return; var lastPage = state.pagesCount; if (page < 0) page = 0; if (page > lastPage) page = lastPage; state.hasPrev = page > 0; state.hasNext = ((page + 1) * state.itemsPerPage) < tabsCtrl.count(); state.page = page; $timeout(function() { scope.$broadcast('$mdTabsPaginationChanged'); }); return slideTabButtons(-page * state.itemsPerPage * state.tabWidth); } } } TabPaginationDirective.$inject = ["$mdConstant", "$window", "$$rAF", "$$q", "$timeout"]; })(); (function() { 'use strict'; angular.module('material.components.tabs') .controller('$mdTab', TabItemController); function TabItemController($scope, $element, $attrs, $compile, $animate, $mdUtil, $parse) { var self = this; // Properties self.contentContainer = angular.element('<div class="md-tab-content ng-hide">'); self.hammertime = new Hammer(self.contentContainer[0]); self.element = $element; // Methods self.isDisabled = isDisabled; self.onAdd = onAdd; self.onRemove = onRemove; self.onSelect = onSelect; self.onDeselect = onDeselect; var disabledParsed = $parse($attrs.ngDisabled); function isDisabled() { return disabledParsed($scope.$parent); } /** * Add the tab's content to the DOM container area in the tabs, * @param contentArea the contentArea to add the content of the tab to */ function onAdd(contentArea) { if (self.content.length) { self.contentContainer.append(self.content); self.contentScope = $scope.$parent.$new(); contentArea.append(self.contentContainer); $compile(self.contentContainer)(self.contentScope); $mdUtil.disconnectScope(self.contentScope); } } function onRemove() { self.hammertime.destroy(); $animate.leave(self.contentContainer).then(function() { self.contentScope && self.contentScope.$destroy(); self.contentScope = null; }); } function onSelect() { // Resume watchers and events firing when tab is selected $mdUtil.reconnectScope(self.contentScope); self.hammertime.on('swipeleft swiperight', $scope.onSwipe); $element.addClass('active'); $element.attr('aria-selected', true); $element.attr('tabIndex', 0); $animate.removeClass(self.contentContainer, 'ng-hide'); $scope.onSelect(); } function onDeselect() { // Stop watchers & events from firing while tab is deselected $mdUtil.disconnectScope(self.contentScope); self.hammertime.off('swipeleft swiperight', $scope.onSwipe); $element.removeClass('active'); $element.attr('aria-selected', false); // Only allow tabbing to the active tab $element.attr('tabIndex', -1); $animate.addClass(self.contentContainer, 'ng-hide'); $scope.onDeselect(); } } TabItemController.$inject = ["$scope", "$element", "$attrs", "$compile", "$animate", "$mdUtil", "$parse"]; })(); (function() { 'use strict'; angular.module('material.components.tabs') .directive('mdTab', MdTabDirective); /** * @ngdoc directive * @name mdTab * @module material.components.tabs * * @restrict E * * @description * `<md-tab>` is the nested directive used [within `<md-tabs>`] to specify each tab with a **label** and optional *view content*. * * If the `label` attribute is not specified, then an optional `<md-tab-label>` tag can be used to specified more * complex tab header markup. If neither the **label** nor the **md-tab-label** are specified, then the nested * markup of the `<md-tab>` is used as the tab header markup. * * If a tab **label** has been identified, then any **non-**`<md-tab-label>` markup * will be considered tab content and will be transcluded to the internal `<div class="md-tabs-content">` container. * * This container is used by the TabsController to show/hide the active tab's content view. This synchronization is * automatically managed by the internal TabsController whenever the tab selection changes. Selection changes can * be initiated via data binding changes, programmatic invocation, or user gestures. * * @param {string=} label Optional attribute to specify a simple string as the tab label * @param {boolean=} md-active When evaluteing to true, selects the tab. * @param {boolean=} disabled If present, disabled tab selection. * @param {expression=} md-on-deselect Expression to be evaluated after the tab has been de-selected. * @param {expression=} md-on-select Expression to be evaluated after the tab has been selected. * * * @usage * * <hljs lang="html"> * <md-tab label="" disabled="" md-on-select="" md-on-deselect="" > * <h3>My Tab content</h3> * </md-tab> * * <md-tab > * <md-tab-label> * <h3>My Tab content</h3> * </md-tab-label> * <p> * Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, * totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae * dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, * sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. * </p> * </md-tab> * </hljs> * */ function MdTabDirective($mdInkRipple, $compile, $mdAria, $mdUtil, $mdConstant) { return { restrict: 'E', require: ['mdTab', '^mdTabs'], controller: '$mdTab', scope: { onSelect: '&mdOnSelect', onDeselect: '&mdOnDeselect', label: '@' }, compile: compile }; function compile(element, attr) { var tabLabel = element.find('md-tab-label'); if (tabLabel.length) { // If a tab label element is found, remove it for later re-use. tabLabel.remove(); } else if (angular.isDefined(attr.label)) { // Otherwise, try to use attr.label as the label tabLabel = angular.element('<md-tab-label>').html(attr.label); } else { // If nothing is found, use the tab's content as the label tabLabel = angular.element('<md-tab-label>') .append(element.contents().remove()); } // Everything that's left as a child is the tab's content. var tabContent = element.contents().remove(); return function postLink(scope, element, attr, ctrls) { var tabItemCtrl = ctrls[0]; // Controller for THIS tabItemCtrl var tabsCtrl = ctrls[1]; // Controller for ALL tabs transcludeTabContent(); configureAria(); var detachRippleFn = $mdInkRipple.attachTabBehavior(scope, element, { colorElement: tabsCtrl.inkBarElement }); tabsCtrl.add(tabItemCtrl); scope.$on('$destroy', function() { detachRippleFn(); tabsCtrl.remove(tabItemCtrl); }); if (!angular.isDefined(attr.ngClick)) { element.on('click', defaultClickListener); } element.on('keydown', keydownListener); scope.onSwipe = onSwipe; if (angular.isNumber(scope.$parent.$index)) { watchNgRepeatIndex(); } if (angular.isDefined(attr.mdActive)) { watchActiveAttribute(); } watchDisabled(); function transcludeTabContent() { // Clone the label we found earlier, and $compile and append it var label = tabLabel.clone(); element.append(label); $compile(label)(scope.$parent); // Clone the content we found earlier, and mark it for later placement into // the proper content area. tabItemCtrl.content = tabContent.clone(); } //defaultClickListener isn't applied if the user provides an ngClick expression. function defaultClickListener() { scope.$apply(function() { tabsCtrl.select(tabItemCtrl); tabsCtrl.focus(tabItemCtrl); }); } function keydownListener(ev) { if (ev.keyCode == $mdConstant.KEY_CODE.SPACE || ev.keyCode == $mdConstant.KEY_CODE.ENTER ) { // Fire the click handler to do normal selection if space is pressed element.triggerHandler('click'); ev.preventDefault(); } else if (ev.keyCode === $mdConstant.KEY_CODE.LEFT_ARROW) { scope.$evalAsync(function() { tabsCtrl.focus(tabsCtrl.previous(tabItemCtrl)); }); } else if (ev.keyCode === $mdConstant.KEY_CODE.RIGHT_ARROW) { scope.$evalAsync(function() { tabsCtrl.focus(tabsCtrl.next(tabItemCtrl)); }); } } function onSwipe(ev) { scope.$apply(function() { if (ev.type === 'swipeleft') { tabsCtrl.select(tabsCtrl.next()); } else { tabsCtrl.select(tabsCtrl.previous()); } }); } // If tabItemCtrl is part of an ngRepeat, move the tabItemCtrl in our internal array // when its $index changes function watchNgRepeatIndex() { // The tabItemCtrl has an isolate scope, so we watch the $index on the parent. scope.$watch('$parent.$index', function $indexWatchAction(newIndex) { tabsCtrl.move(tabItemCtrl, newIndex); }); } function watchActiveAttribute() { var unwatch = scope.$parent.$watch('!!(' + attr.mdActive + ')', activeWatchAction); scope.$on('$destroy', unwatch); function activeWatchAction(isActive) { var isSelected = tabsCtrl.selected() === tabItemCtrl; if (isActive && !isSelected) { tabsCtrl.select(tabItemCtrl); } else if (!isActive && isSelected) { tabsCtrl.deselect(tabItemCtrl); } } } function watchDisabled() { scope.$watch(tabItemCtrl.isDisabled, disabledWatchAction); function disabledWatchAction(isDisabled) { element.attr('aria-disabled', isDisabled); // Auto select `next` tab when disabled var isSelected = (tabsCtrl.selected() === tabItemCtrl); if (isSelected && isDisabled) { tabsCtrl.select(tabsCtrl.next() || tabsCtrl.previous()); } } } function configureAria() { // Link together the content area and tabItemCtrl with an id var tabId = attr.id || ('tab_' + $mdUtil.nextUid()); element.attr({ id: tabId, role: 'tab', tabIndex: -1 //this is also set on select/deselect in tabItemCtrl }); // Only setup the contentContainer's aria attributes if tab content is provided if (tabContent.length) { var tabContentId = 'content_' + tabId; if (!element.attr('aria-controls')) { element.attr('aria-controls', tabContentId); } tabItemCtrl.contentContainer.attr({ id: tabContentId, role: 'tabpanel', 'aria-labelledby': tabId }); } } }; } } MdTabDirective.$inject = ["$mdInkRipple", "$compile", "$mdAria", "$mdUtil", "$mdConstant"]; })(); (function() { 'use strict'; angular.module('material.components.tabs') .controller('$mdTabs', MdTabsController); function MdTabsController($scope, $element, $mdUtil) { var tabsList = $mdUtil.iterator([], false); var self = this; // Properties self.$element = $element; self.scope = $scope; // The section containing the tab content $elements self.contentArea = angular.element($element[0].querySelector('.md-tabs-content')); // Methods from iterator self.inRange = tabsList.inRange; self.indexOf = tabsList.indexOf; self.itemAt = tabsList.itemAt; self.count = tabsList.count; self.selected = selected; self.add = add; self.remove = remove; self.move = move; self.select = select; self.focus = focus; self.deselect = deselect; self.next = next; self.previous = previous; $scope.$on('$destroy', function() { self.deselect(self.selected()); for (var i = tabsList.count() - 1; i >= 0; i--) { self.remove(tabsList[i], true); } }); // Get the selected tab function selected() { return self.itemAt($scope.selectedIndex); } // Add a new tab. // Returns a method to remove the tab from the list. function add(tab, index) { tabsList.add(tab, index); tab.onAdd(self.contentArea); // Select the new tab if we don't have a selectedIndex, or if the // selectedIndex we've been waiting for is this tab if ($scope.selectedIndex === -1 || !angular.isNumber($scope.selectedIndex) || $scope.selectedIndex === self.indexOf(tab)) { self.select(tab); } $scope.$broadcast('$mdTabsChanged'); } function remove(tab, noReselect) { if (!tabsList.contains(tab)) return; if (noReselect) { // do nothing } else if (self.selected() === tab) { if (tabsList.count() > 1) { self.select(self.previous() || self.next()); } else { self.deselect(tab); } } tabsList.remove(tab); tab.onRemove(); $scope.$broadcast('$mdTabsChanged'); } // Move a tab (used when ng-repeat order changes) function move(tab, toIndex) { var isSelected = self.selected() === tab; tabsList.remove(tab); tabsList.add(tab, toIndex); if (isSelected) self.select(tab); $scope.$broadcast('$mdTabsChanged'); } function select(tab) { if (!tab || tab.isSelected || tab.isDisabled()) return; if (!tabsList.contains(tab)) return; self.deselect(self.selected()); $scope.selectedIndex = self.indexOf(tab); tab.isSelected = true; tab.onSelect(); } function focus(tab) { // this variable is $watch'd by pagination self.tabToFocus = tab; } function deselect(tab) { if (!tab || !tab.isSelected) return; if (!tabsList.contains(tab)) return; $scope.selectedIndex = -1; tab.isSelected = false; tab.onDeselect(); } function next(tab, filterFn) { return tabsList.next(tab || self.selected(), filterFn || isTabEnabled); } function previous(tab, filterFn) { return tabsList.previous(tab || self.selected(), filterFn || isTabEnabled); } function isTabEnabled(tab) { return tab && !tab.isDisabled(); } } MdTabsController.$inject = ["$scope", "$element", "$mdUtil"]; })(); (function() { 'use strict'; angular.module('material.components.tabs') .directive('mdTabs', TabsDirective); /** * @ngdoc directive * @name mdTabs * @module material.components.tabs * * @restrict E * * @description * The `<md-tabs>` directive serves as the container for 1..n `<md-tab>` child directives to produces a Tabs components. * In turn, the nested `<md-tab>` directive is used to specify a tab label for the **header button** and a [optional] tab view * content that will be associated with each tab button. * * Below is the markup for its simplest usage: * * <hljs lang="html"> * <md-tabs> * <md-tab label="Tab #1"></md-tab> * <md-tab label="Tab #2"></md-tab> * <md-tab label="Tab #3"></md-tab> * <md-tabs> * </hljs> * * Tabs supports three (3) usage scenarios: * * 1. Tabs (buttons only) * 2. Tabs with internal view content * 3. Tabs with external view content * * **Tab-only** support is useful when tab buttons are used for custom navigation regardless of any other components, content, or views. * **Tabs with internal views** are the traditional usages where each tab has associated view content and the view switching is managed internally by the Tabs component. * **Tabs with external view content** is often useful when content associated with each tab is independently managed and data-binding notifications announce tab selection changes. * * > As a performance bonus, if the tab content is managed internally then the non-active (non-visible) tab contents are temporarily disconnected from the `$scope.$digest()` processes; which restricts and optimizes DOM updates to only the currently active tab. * * Additional features also include: * * * Content can include any markup. * * If a tab is disabled while active/selected, then the next tab will be auto-selected. * * If the currently active tab is the last tab, then next() action will select the first tab. * * Any markup (other than **`<md-tab>`** tags) will be transcluded into the tab header area BEFORE the tab buttons. * * @param {integer=} md-selected Index of the active/selected tab * @param {boolean=} md-no-ink If present, disables ink ripple effects. * @param {boolean=} md-no-bar If present, disables the selection ink bar. * @param {string=} md-align-tabs Attribute to indicate position of tab buttons: bottom or top; default is `top` * * @usage * <hljs lang="html"> * <md-tabs md-selected="selectedIndex" > * <img ng-src="img/angular.png" class="centered"> * * <md-tab * ng-repeat="tab in tabs | orderBy:predicate:reversed" * md-on-select="onTabSelected(tab)" * md-on-deselect="announceDeselected(tab)" * disabled="tab.disabled" > * * <md-tab-label> * {{tab.title}} * <img src="img/removeTab.png" * ng-click="removeTab(tab)" * class="delete" > * </md-tab-label> * * {{tab.content}} * * </md-tab> * * </md-tabs> * </hljs> * */ function TabsDirective($parse, $mdTheming) { return { restrict: 'E', controller: '$mdTabs', require: 'mdTabs', transclude: true, scope: { selectedIndex: '=?mdSelected' }, template: '<section class="md-header" ' + 'ng-class="{\'md-paginating\': pagination.active}">' + '<button class="md-paginator md-prev" ' + 'ng-if="pagination.active && pagination.hasPrev" ' + 'ng-click="pagination.clickPrevious()" ' + 'aria-hidden="true">' + '</button>' + // overflow: hidden container when paginating '<div class="md-header-items-container" md-tabs-pagination>' + // flex container for <md-tab> elements '<div class="md-header-items">' + '<md-tabs-ink-bar></md-tabs-ink-bar>' + '<md-tabs-ink-bar class="md-ink-bar-delayed"></md-tabs-ink-bar>' + '</div>' + '</div>' + '<button class="md-paginator md-next" ' + 'ng-if="pagination.active && pagination.hasNext" ' + 'ng-click="pagination.clickNext()" ' + 'aria-hidden="true">' + '</button>' + '</section>' + '<section class="md-tabs-content"></section>', link: postLink }; function postLink(scope, element, attr, tabsCtrl, transclude) { $mdTheming(element); configureAria(); watchSelected(); transclude(scope.$parent, function(clone) { angular.element(element[0].querySelector('.md-header-items')).append(clone); }); function configureAria() { element.attr({ role: 'tablist' }); } function watchSelected() { scope.$watch('selectedIndex', function watchSelectedIndex(newIndex, oldIndex) { // Note: if the user provides an invalid newIndex, all tabs will be deselected // and the associated view will be hidden. tabsCtrl.deselect( tabsCtrl.itemAt(oldIndex) ); if (tabsCtrl.inRange(newIndex)) { var newTab = tabsCtrl.itemAt(newIndex); // If the newTab is disabled, find an enabled one to go to. if (newTab && newTab.isDisabled()) { newTab = newIndex > oldIndex ? tabsCtrl.next(newTab) : tabsCtrl.previous(newTab); } tabsCtrl.select(newTab); } }); } } } TabsDirective.$inject = ["$parse", "$mdTheming"]; })();
{'content_hash': '5efee45549405755df5ba6cacd7737aa', 'timestamp': '', 'source': 'github', 'line_count': 896, 'max_line_length': 260, 'avg_line_length': 30.428571428571427, 'alnum_prop': 0.6251833920187794, 'repo_name': 'ChrisBoesch/docker-code-verifier', 'id': '99ae9dc0b474a0c9db7919163516e786794c214d', 'size': '27264', 'binary': False, 'copies': '18', 'ref': 'refs/heads/master', 'path': 'server/www/console/vendor/angular-material/modules/js/tabs/tabs.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '7191'}, {'name': 'JavaScript', 'bytes': '15406'}, {'name': 'Makefile', 'bytes': '6401'}, {'name': 'Nginx', 'bytes': '1994'}, {'name': 'Python', 'bytes': '12233'}, {'name': 'Shell', 'bytes': '17830'}]}
package com.twitter.finagle.factory import com.twitter.conversions.time._ import com.twitter.finagle._ import com.twitter.util.{Future, Time, Await} import org.junit.runner.RunWith import org.scalatest.{FunSuite, Tag} import org.scalatest.junit.JUnitRunner import org.scalatest.mock.MockitoSugar import scala.collection.JavaConverters._ @RunWith(classOf[JUnitRunner]) class ServiceFactoryCacheTest extends FunSuite with MockitoSugar { override def test(testName: String, testTags: Tag*)(f: => Unit) { super.test(testName, testTags:_*) { factories = Map.empty news = Map.empty } } var factories: Map[Int, Int] = Map.empty var news: Map[Int, Int] = Map.empty case class SF(i: Int) extends ServiceFactory[String, String] { assert(!(factories contains i)) factories += (i -> 0) news += (i -> (1+news.getOrElse(i, 0))) def apply(conn: ClientConnection) = Future.value(new Service[String, String] { factories = factories + (i -> (factories(i)+1)) def apply(req: String) = Future.value(i.toString) override def close(deadline: Time) = { factories += (i -> (factories(i) - 1)) Future.Done } }) def close(deadline: Time) = { factories -= i Future.Done } } case class exceptingSF(i: Int) extends ServiceFactory[String, String] { def apply(conn: ClientConnection) = Future.exception(new Exception("oh no")) def close(deadline: Time) = Future.Done } test("cache, evict") (Time.withCurrentTimeFrozen { tc => val newFactory: Int => ServiceFactory[String, String] = { i => SF(i) } val cache = new ServiceFactoryCache[Int, String, String](newFactory, maxCacheSize=2) assert(factories.isEmpty) val s1 = Await.result(cache(1, ClientConnection.nil)) assert(factories === Map(1->1)) val s2 = Await.result(cache(2, ClientConnection.nil)) assert(factories === Map(1->1, 2->1)) val s3 = Await.result(cache(3, ClientConnection.nil)) assert(factories === Map(1->1, 2->1, 3->1)) Await.result(s3.close()) assert(factories === Map(1->1, 2->1)) Await.result(s2.close()) tc.advance(1.second) assert(factories === Map(1->1, 2->0)) Await.result(s1.close()) tc.advance(1.second) assert(factories === Map(1->0, 2->0)) assert(news === Map(1->1, 2->1, 3->1)) val s3x = Await.result(cache(3, ClientConnection.nil)) assert(factories === Map(1->0, 3->1)) assert(news === Map(1->1, 2->1, 3->2)) val s1x, s1y = Await.result(cache(1, ClientConnection.nil)) assert(factories === Map(1->2, 3->1)) assert(news === Map(1->1, 2->1, 3->2)) val s2x = Await.result(cache(2, ClientConnection.nil)) assert(factories === Map(1->2, 3->1, 2->1)) assert(news === Map(1->1, 2->2, 3->2)) }) }
{'content_hash': '3a591e7905529f427605786e5c1b44b6', 'timestamp': '', 'source': 'github', 'line_count': 90, 'max_line_length': 88, 'avg_line_length': 31.022222222222222, 'alnum_prop': 0.6386103151862464, 'repo_name': 'rojanu/finagle', 'id': '182f1aa9d699e4e560e1dd4b630fbb3a7e5659c8', 'size': '2792', 'binary': False, 'copies': '15', 'ref': 'refs/heads/master', 'path': 'finagle-core/src/test/scala/com/twitter/finagle/factory/ServiceFactoryCacheTest.scala', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '4834'}, {'name': 'Java', 'bytes': '700045'}, {'name': 'Python', 'bytes': '37122'}, {'name': 'Ruby', 'bytes': '24870'}, {'name': 'Scala', 'bytes': '3661478'}, {'name': 'Shell', 'bytes': '10602'}, {'name': 'Thrift', 'bytes': '14519'}]}
package net.dontdrinkandroot.example.angularrestspringsecurity.dao.accesstoken; import net.dontdrinkandroot.example.angularrestspringsecurity.dao.JpaDao; import net.dontdrinkandroot.example.angularrestspringsecurity.entity.AccessToken; import org.springframework.transaction.annotation.Transactional; import javax.persistence.NoResultException; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; /** * @author Philip Washington Sorst <[email protected]> */ public class JpaAccessTokenDao extends JpaDao<AccessToken, Long> implements AccessTokenDao { public JpaAccessTokenDao() { super(AccessToken.class); } @Override @Transactional(readOnly = true, noRollbackFor = NoResultException.class) public AccessToken findByToken(String accessTokenString) { CriteriaBuilder builder = this.getEntityManager().getCriteriaBuilder(); CriteriaQuery<AccessToken> query = builder.createQuery(this.entityClass); Root<AccessToken> root = query.from(this.entityClass); query.where(builder.equal(root.get("token"), accessTokenString)); try { return this.getEntityManager().createQuery(query).getSingleResult(); } catch (NoResultException e) { return null; } } }
{'content_hash': 'e36feac0c496f6483c3660e1533deecb', 'timestamp': '', 'source': 'github', 'line_count': 37, 'max_line_length': 90, 'avg_line_length': 36.67567567567568, 'alnum_prop': 0.7546057479734709, 'repo_name': 'philipsorst/angular-rest-springsecurity', 'id': '414e16de202e910d96929adc2cd292edaa333671', 'size': '1357', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/net/dontdrinkandroot/example/angularrestspringsecurity/dao/accesstoken/JpaAccessTokenDao.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '228'}, {'name': 'HTML', 'bytes': '6566'}, {'name': 'Java', 'bytes': '29465'}, {'name': 'JavaScript', 'bytes': '6378'}]}
package quasar.impl.storage import slamdata.Predef._ final case class AntiEntropyStoreConfig( adTimeoutMillis: Long, purgeTimeoutMillis: Long, updateBroadcastMillis: Long, updateBroadcastBatch: Int, tombstoneLiveForMillis: Long, updateRequestLimit: Int, updateLimit: Int, adLimit: Int) object AntiEntropyStoreConfig { val default: AntiEntropyStoreConfig = AntiEntropyStoreConfig( adTimeoutMillis = 300L, purgeTimeoutMillis = 1000L, updateBroadcastMillis = 100L, updateBroadcastBatch = 100, tombstoneLiveForMillis = 300000L, updateRequestLimit = 128, updateLimit = 128, adLimit = 128) }
{'content_hash': '0de77163c2d9913ddf9c72eaffd45ce8', 'timestamp': '', 'source': 'github', 'line_count': 27, 'max_line_length': 63, 'avg_line_length': 23.74074074074074, 'alnum_prop': 0.7581903276131046, 'repo_name': 'slamdata/quasar', 'id': '857446b52aa1fd797785eb034e8599b0b231bf11', 'size': '1244', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'impl/src/main/scala/quasar/impl/storage/AntiEntropyStoreConfig.scala', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '857'}, {'name': 'Scala', 'bytes': '2474240'}, {'name': 'Shell', 'bytes': '24105'}]}
using System; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Grpc.Core.Utils; namespace Grpc.Core.Internal { /// <summary> /// grpc_server_credentials from <c>grpc/grpc_security.h</c> /// </summary> internal class ServerCredentialsSafeHandle : SafeHandleZeroIsInvalid { static readonly NativeMethods Native = NativeMethods.Get(); private ServerCredentialsSafeHandle() { } public static ServerCredentialsSafeHandle CreateSslCredentials(string pemRootCerts, string[] keyCertPairCertChainArray, string[] keyCertPairPrivateKeyArray, SslClientCertificateRequestType clientCertificateRequest) { GrpcPreconditions.CheckArgument(keyCertPairCertChainArray.Length == keyCertPairPrivateKeyArray.Length); return Native.grpcsharp_ssl_server_credentials_create(pemRootCerts, keyCertPairCertChainArray, keyCertPairPrivateKeyArray, new UIntPtr((ulong)keyCertPairCertChainArray.Length), clientCertificateRequest); } protected override bool ReleaseHandle() { Native.grpcsharp_server_credentials_release(handle); return true; } } }
{'content_hash': '8c9e529ce95d954665c3425cf6178260', 'timestamp': '', 'source': 'github', 'line_count': 35, 'max_line_length': 222, 'avg_line_length': 40.51428571428571, 'alnum_prop': 0.6297602256699577, 'repo_name': 'mehrdada/grpc', 'id': '5f8c95c4ea6b3706cab9dd6abf86b08c74dc92b1', 'size': '2056', 'binary': False, 'copies': '10', 'ref': 'refs/heads/master', 'path': 'src/csharp/Grpc.Core/Internal/ServerCredentialsSafeHandle.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '31730'}, {'name': 'C', 'bytes': '1660935'}, {'name': 'C#', 'bytes': '1876184'}, {'name': 'C++', 'bytes': '30543571'}, {'name': 'CMake', 'bytes': '619730'}, {'name': 'CSS', 'bytes': '1519'}, {'name': 'DTrace', 'bytes': '147'}, {'name': 'Dockerfile', 'bytes': '153062'}, {'name': 'Go', 'bytes': '27069'}, {'name': 'HTML', 'bytes': '14'}, {'name': 'Java', 'bytes': '6907'}, {'name': 'JavaScript', 'bytes': '52923'}, {'name': 'M4', 'bytes': '46807'}, {'name': 'Makefile', 'bytes': '1144385'}, {'name': 'Objective-C', 'bytes': '435838'}, {'name': 'Objective-C++', 'bytes': '37596'}, {'name': 'PHP', 'bytes': '468803'}, {'name': 'Python', 'bytes': '2716831'}, {'name': 'Ruby', 'bytes': '988563'}, {'name': 'Shell', 'bytes': '399606'}, {'name': 'Swift', 'bytes': '3516'}, {'name': 'XSLT', 'bytes': '9673'}]}
//===----------------------------------------------------------------------===// // // Peloton // // transaction_context.h // // Identification: src/include/concurrency/transaction_context.h // // Copyright (c) 2015-16, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #pragma once #include <atomic> #include <map> #include <unordered_map> #include <unordered_set> #include <vector> #include "catalog/catalog_cache.h" #include "common/exception.h" #include "common/item_pointer.h" #include "common/printable.h" #include "common/internal_types.h" namespace peloton { namespace trigger { class TriggerSet; class TriggerData; } // namespace trigger namespace concurrency { //===--------------------------------------------------------------------===// // TransactionContext //===--------------------------------------------------------------------===// /** * @brief Class for transaction context. */ class TransactionContext : public Printable { TransactionContext(TransactionContext const &) = delete; public: TransactionContext(const size_t thread_id, const IsolationLevelType isolation, const cid_t &read_id); TransactionContext(const size_t thread_id, const IsolationLevelType isolation, const cid_t &read_id, const cid_t &commit_id); /** * @brief Destroys the object. */ ~TransactionContext() = default; private: void Init(const size_t thread_id, const IsolationLevelType isolation, const cid_t &read_id) { Init(thread_id, isolation, read_id, read_id); } void Init(const size_t thread_id, const IsolationLevelType isolation, const cid_t &read_id, const cid_t &commit_id); public: //===--------------------------------------------------------------------===// // Mutators and Accessors //===--------------------------------------------------------------------===// /** * @brief Gets the thread identifier. * * @return The thread identifier. */ inline size_t GetThreadId() const { return thread_id_; } /** * @brief Gets the transaction identifier. * * @return The transaction identifier. */ inline txn_id_t GetTransactionId() const { return txn_id_; } /** * @brief Gets the read identifier. * * @return The read identifier. */ inline cid_t GetReadId() const { return read_id_; } /** * @brief Gets the commit identifier. * * @return The commit identifier. */ inline cid_t GetCommitId() const { return commit_id_; } /** * @brief Gets the epoch identifier. * * @return The epoch identifier. */ inline eid_t GetEpochId() const { return epoch_id_; } /** * @brief Gets the timestamp. * * @return The timestamp. */ inline uint64_t GetTimestamp() const { return timestamp_; } /** * @brief Gets the query strings. * * @return The query strings. */ inline const std::vector<std::string>& GetQueryStrings() const { return query_strings_; } /** * @brief Sets the commit identifier. * * @param[in] commit_id The commit identifier */ inline void SetCommitId(const cid_t commit_id) { commit_id_ = commit_id; } /** * @brief Sets the epoch identifier. * * @param[in] epoch_id The epoch identifier */ inline void SetEpochId(const eid_t epoch_id) { epoch_id_ = epoch_id; } /** * @brief Sets the timestamp. * * @param[in] timestamp The timestamp */ inline void SetTimestamp(const uint64_t timestamp) { timestamp_ = timestamp; } /** * @brief Adds a query string. * * @param[in] query_string The query string */ inline void AddQueryString(const char* query_string) { query_strings_.push_back(std::string(query_string)); } void RecordCreate(oid_t database_oid, oid_t table_oid, oid_t index_oid) { rw_object_set_.push_back(std::make_tuple(database_oid, table_oid, index_oid, DDLType::CREATE)); } void RecordDrop(oid_t database_oid, oid_t table_oid, oid_t index_oid) { rw_object_set_.push_back(std::make_tuple(database_oid, table_oid, index_oid, DDLType::DROP)); } void RecordReadOwn(const ItemPointer &); void RecordUpdate(const ItemPointer &); void RecordInsert(const ItemPointer &); /** * @brief Delete the record. * * @param[in] <unnamed> The logical physical location of the record * @return true if INS_DEL, false if DELETE */ bool RecordDelete(const ItemPointer &); RWType GetRWType(const ItemPointer &); /** * @brief Adds on commit trigger. * * @param trigger_data The trigger data */ void AddOnCommitTrigger(trigger::TriggerData &trigger_data); void ExecOnCommitTriggers(); /** * @brief Determines if in rw set. * * @param[in] location The location * * @return True if in rw set, False otherwise. */ bool IsInRWSet(const ItemPointer &location) { return (rw_set_.find(location) != rw_set_.end()); } /** * @brief Gets the read write set. * * @return The read write set. */ inline const ReadWriteSet &GetReadWriteSet() const { return rw_set_; } inline const CreateDropSet &GetCreateDropSet() { return rw_object_set_; } /** * @brief Gets the gc set pointer. * * @return The gc set pointer. */ inline std::shared_ptr<GCSet> GetGCSetPtr() { return gc_set_; } /** * @brief Gets the gc object set pointer. * * @return The gc object set pointer. */ inline std::shared_ptr<GCObjectSet> GetGCObjectSetPtr() { return gc_object_set_; } /** * @brief Determines if gc set empty. * * @return True if gc set empty, False otherwise. */ inline bool IsGCSetEmpty() { return gc_set_->size() == 0; } /** * @brief Determines if gc object set empty. * * @return True if gc object set empty, False otherwise. */ inline bool IsGCObjectSetEmpty() { return gc_object_set_->size() == 0; } /** * @brief Get a string representation for debugging. * * @return The information. */ const std::string GetInfo() const; /** * Set result and status. * * @param[in] result The result */ inline void SetResult(ResultType result) { result_ = result; } /** * Get result and status. * * @return The result. */ inline ResultType GetResult() const { return result_; } /** * @brief Determines if read only. * * @return True if read only, False otherwise. */ bool IsReadOnly() const { return read_only_; } /** * @brief mark this context as read only * */ void SetReadOnly() { read_only_ = true; } /** * @brief Gets the isolation level. * * @return The isolation level. */ inline IsolationLevelType GetIsolationLevel() const { return isolation_level_; } /** cache for table catalog objects */ catalog::CatalogCache catalog_cache; private: //===--------------------------------------------------------------------===// // Data members //===--------------------------------------------------------------------===// /** transaction id */ txn_id_t txn_id_; /** id of thread creating this transaction */ size_t thread_id_; /** * read id * this id determines which tuple versions the transaction can access. */ cid_t read_id_; /** * commit id * this id determines the id attached to the tuple version written by the * transaction. */ cid_t commit_id_; /** * epoch id can be extracted from read id. * GC manager uses this id to check whether a version is still visible. */ eid_t epoch_id_; /** * vector of strings to log at the end of the transaction * populated only if the indextuner is running */ std::vector<std::string> query_strings_; /** timestamp when the transaction began */ uint64_t timestamp_; ReadWriteSet rw_set_; CreateDropSet rw_object_set_; /** * this set contains data location that needs to be gc'd in the transaction. */ std::shared_ptr<GCSet> gc_set_; std::shared_ptr<GCObjectSet> gc_object_set_; /** result of the transaction */ ResultType result_ = ResultType::SUCCESS; IsolationLevelType isolation_level_; bool is_written_; std::unique_ptr<trigger::TriggerSet> on_commit_triggers_; /** one default transaction is NOT 'read only' unless it is marked 'read only' explicitly*/ bool read_only_ = false; }; } // namespace concurrency } // namespace peloton
{'content_hash': '6fbed153dfa5b5a557514b0b3d3f6af8', 'timestamp': '', 'source': 'github', 'line_count': 348, 'max_line_length': 93, 'avg_line_length': 25.221264367816094, 'alnum_prop': 0.5761649766435001, 'repo_name': 'cmu-db/peloton', 'id': '511e0bd38f7477800a377ef7b7efe63ae76f69ad', 'size': '8777', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/include/concurrency/transaction_context.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '45917'}, {'name': 'C++', 'bytes': '7049996'}, {'name': 'CMake', 'bytes': '137658'}, {'name': "Cap'n Proto", 'bytes': '362'}, {'name': 'Dockerfile', 'bytes': '3104'}, {'name': 'Java', 'bytes': '76998'}, {'name': 'PLpgSQL', 'bytes': '5855'}, {'name': 'Python', 'bytes': '112928'}, {'name': 'Ruby', 'bytes': '1278'}, {'name': 'Shell', 'bytes': '22467'}]}
!function ($) { "use strict"; // jshint ;_; /* MODAL CLASS DEFINITION * ====================== */ var Modal = function (content, options) { this.options = options this.$element = $(content) .delegate('[data-dismiss="modal"]', 'click.dismiss.modal', $.proxy(this.hide, this)) } Modal.prototype = { constructor: Modal, toggle: function () { return this[!this.isShown ? 'show' : 'hide']() }, show: function () { var that = this , e = $.Event('show') this.$element.trigger(e) if (this.isShown || e.isDefaultPrevented()) return $('body').addClass('modal-open') this.isShown = true escape.call(this) backdrop.call(this, function () { var transition = $.support.transition && that.$element.hasClass('fade') if (!that.$element.parent().length) { that.$element.appendTo(document.body) //don't move modals dom position } that.$element .show() if (transition) { that.$element[0].offsetWidth // force reflow } that.$element.addClass('in') transition ? that.$element.one($.support.transition.end, function () { that.$element.trigger('shown') }) : that.$element.trigger('shown') }) }, hide: function (e) { e && e.preventDefault() var that = this e = $.Event('hide') this.$element.trigger(e) if (!this.isShown || e.isDefaultPrevented()) return this.isShown = false $('body').removeClass('modal-open') escape.call(this) this.$element.removeClass('in') $.support.transition && this.$element.hasClass('fade') ? hideWithTransition.call(this) : hideModal.call(this) } } /* MODAL PRIVATE METHODS * ===================== */ function hideWithTransition() { var that = this , timeout = setTimeout(function () { that.$element.off($.support.transition.end) hideModal.call(that) }, 500) this.$element.one($.support.transition.end, function () { clearTimeout(timeout) hideModal.call(that) }) } function hideModal(that) { this.$element .hide() .trigger('hidden') backdrop.call(this) } function backdrop(callback) { var that = this , animate = this.$element.hasClass('fade') ? 'fade' : '' if (this.isShown && this.options.backdrop) { var doAnimate = $.support.transition && animate this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />') .appendTo(document.body) if (this.options.backdrop != 'static') { this.$backdrop.click($.proxy(this.hide, this)) } if (doAnimate) this.$backdrop[0].offsetWidth // force reflow this.$backdrop.addClass('in') doAnimate ? this.$backdrop.one($.support.transition.end, callback) : callback() } else if (!this.isShown && this.$backdrop) { this.$backdrop.removeClass('in') $.support.transition && this.$element.hasClass('fade') ? this.$backdrop.one($.support.transition.end, $.proxy(removeBackdrop, this)) : removeBackdrop.call(this) } else if (callback) { callback() } } function removeBackdrop() { this.$backdrop.remove() this.$backdrop = null } function escape() { var that = this if (this.isShown && this.options.keyboard) { $(document).on('keyup.dismiss.modal', function (e) { e.which == 27 && that.hide() }) } else if (!this.isShown) { $(document).off('keyup.dismiss.modal') } } /* MODAL PLUGIN DEFINITION * ======================= */ $.fn.modal = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('modal') , options = $.extend({}, $.fn.modal.defaults, $this.data(), typeof option == 'object' && option) if (!data) $this.data('modal', (data = new Modal(this, options))) if (typeof option == 'string') data[option]() else if (options.show) data.show() }) } $.fn.modal.defaults = { backdrop: true, keyboard: true, show: true } $.fn.modal.Constructor = Modal /* MODAL DATA-API * ============== */ $(function () { $('body').on('click.modal.data-api', '[data-toggle="modal"]', function (e) { var $this = $(this), href , $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7 , option = $target.data('modal') ? 'toggle' : $.extend({}, $target.data(), $this.data()) e.preventDefault() $target.modal(option) }) }) }(window.jQuery);
{'content_hash': '8c1915261ff7a8cd73f3ef800b40fd76', 'timestamp': '', 'source': 'github', 'line_count': 195, 'max_line_length': 141, 'avg_line_length': 27.907692307692308, 'alnum_prop': 0.4805218669606762, 'repo_name': 'Elephant418/Staq', 'id': '2f1bd6dadc6b5caf05ba5b65b42bef90833b5346', 'size': '6304', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Staq/App/BackOffice/public/twbootstrap/bootstrap-modal.js', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '384'}, {'name': 'CSS', 'bytes': '20933'}, {'name': 'HTML', 'bytes': '18860'}, {'name': 'JavaScript', 'bytes': '4197'}, {'name': 'PHP', 'bytes': '188178'}]}
package org.skife.jdbi.v2; import org.junit.Test; import org.skife.jdbi.v2.tweak.Argument; import java.math.BigDecimal; import java.util.HashMap; import java.util.Map; import static org.hamcrest.CoreMatchers.instanceOf; import static org.junit.Assert.assertThat; public class TestMapArguments { @Test public void testBind() throws Exception { Map<String, Object> args = new HashMap<String, Object>(); args.put("foo", BigDecimal.ONE); Foreman foreman = new Foreman(); StatementContext ctx = new ConcreteStatementContext(new HashMap<String, Object>()); MapArguments mapArguments = new MapArguments(foreman, ctx, args); Argument argument = mapArguments.find("foo"); assertThat(argument, instanceOf(BigDecimalArgument.class)); } @Test public void testNullBinding() throws Exception { Map<String, Object> args = new HashMap<String, Object>(); args.put("foo", null); Foreman foreman = new Foreman(); StatementContext ctx = new ConcreteStatementContext(new HashMap<String, Object>()); MapArguments mapArguments = new MapArguments(foreman, ctx, args); Argument argument = mapArguments.find("foo"); assertThat(argument, instanceOf(ObjectArgument.class)); } }
{'content_hash': '51c570ecf05792961011682efe7f2295', 'timestamp': '', 'source': 'github', 'line_count': 40, 'max_line_length': 91, 'avg_line_length': 32.525, 'alnum_prop': 0.6917755572636434, 'repo_name': 'BernhardBln/jdbi', 'id': '25542a06762e8203376a1e468446fdc19a359966', 'size': '1908', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'src/test/java/org/skife/jdbi/v2/TestMapArguments.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'GAP', 'bytes': '1920'}, {'name': 'HTML', 'bytes': '48847'}, {'name': 'Java', 'bytes': '1036126'}]}
YUI.add('yui2-yahoo', function(Y) { /** * The YAHOO object is the single global object used by YUI Library. It * contains utility function for setting up namespaces, inheritance, and * logging. YAHOO.util, YAHOO.widget, and YAHOO.example are namespaces * created automatically for and used by the library. * @module yahoo * @title YAHOO Global */ /** * YAHOO_config is not included as part of the library. Instead it is an * object that can be defined by the implementer immediately before * including the YUI library. The properties included in this object * will be used to configure global properties needed as soon as the * library begins to load. * @class YAHOO_config * @static */ /** * A reference to a function that will be executed every time a YAHOO module * is loaded. As parameter, this function will receive the version * information for the module. See <a href="YAHOO.env.html#getVersion"> * YAHOO.env.getVersion</a> for the description of the version data structure. * @property listener * @type Function * @static * @default undefined */ /** * Set to true if the library will be dynamically loaded after window.onload. * Defaults to false * @property injecting * @type boolean * @static * @default undefined */ /** * Instructs the yuiloader component to dynamically load yui components and * their dependencies. See the yuiloader documentation for more information * about dynamic loading * @property load * @static * @default undefined * @see yuiloader */ /** * Forces the use of the supplied locale where applicable in the library * @property locale * @type string * @static * @default undefined */ if (typeof YAHOO == "undefined" || !YAHOO) { /** * The YAHOO global namespace object. If YAHOO is already defined, the * existing YAHOO object will not be overwritten so that defined * namespaces are preserved. * @class YAHOO * @static */ var YAHOO = {}; } /** * Returns the namespace specified and creates it if it doesn't exist * <pre> * YAHOO.namespace("property.package"); * YAHOO.namespace("YAHOO.property.package"); * </pre> * Either of the above would create YAHOO.property, then * YAHOO.property.package * * Be careful when naming packages. Reserved words may work in some browsers * and not others. For instance, the following will fail in Safari: * <pre> * YAHOO.namespace("really.long.nested.namespace"); * </pre> * This fails because "long" is a future reserved word in ECMAScript * * For implementation code that uses YUI, do not create your components * in the namespaces defined by YUI ( * <code>YAHOO.util</code>, * <code>YAHOO.widget</code>, * <code>YAHOO.lang</code>, * <code>YAHOO.tool</code>, * <code>YAHOO.example</code>, * <code>YAHOO.env</code>) -- create your own namespace (e.g., 'companyname'). * * @method namespace * @static * @param {String*} arguments 1-n namespaces to create * @return {Object} A reference to the last namespace object created */ YAHOO.namespace = function() { var a=arguments, o=null, i, j, d; for (i=0; i<a.length; i=i+1) { d=(""+a[i]).split("."); o=YAHOO; // YAHOO is implied, so it is ignored if it is included for (j=(d[0] == "YAHOO") ? 1 : 0; j<d.length; j=j+1) { o[d[j]]=o[d[j]] || {}; o=o[d[j]]; } } return o; }; /** * Uses YAHOO.widget.Logger to output a log message, if the widget is * available. * Note: LogReader adds the message, category, and source to the DOM as HTML. * * @method log * @static * @param {HTML} msg The message to log. * @param {HTML} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt) * @param {HTML} src The source of the the message (opt) * @return {Boolean} True if the log operation was successful. */ YAHOO.log = function(msg, cat, src) { var l=YAHOO.widget.Logger; if(l && l.log) { return l.log(msg, cat, src); } else { return false; } }; /** * Registers a module with the YAHOO object * @method register * @static * @param {String} name the name of the module (event, slider, etc) * @param {Function} mainClass a reference to class in the module. This * class will be tagged with the version info * so that it will be possible to identify the * version that is in use when multiple versions * have loaded * @param {Object} data metadata object for the module. Currently it * is expected to contain a "version" property * and a "build" property at minimum. */ YAHOO.register = function(name, mainClass, data) { var mods = YAHOO.env.modules, m, v, b, ls, i; if (!mods[name]) { mods[name] = { versions:[], builds:[] }; } m = mods[name]; v = data.version; b = data.build; ls = YAHOO.env.listeners; m.name = name; m.version = v; m.build = b; m.versions.push(v); m.builds.push(b); m.mainClass = mainClass; // fire the module load listeners for (i=0;i<ls.length;i=i+1) { ls[i](m); } // label the main class if (mainClass) { mainClass.VERSION = v; mainClass.BUILD = b; } else { YAHOO.log("mainClass is undefined for module " + name, "warn"); } }; /** * YAHOO.env is used to keep track of what is known about the YUI library and * the browsing environment * @class YAHOO.env * @static */ YAHOO.env = YAHOO.env || { /** * Keeps the version info for all YUI modules that have reported themselves * @property modules * @type Object[] */ modules: [], /** * List of functions that should be executed every time a YUI module * reports itself. * @property listeners * @type Function[] */ listeners: [] }; /** * Returns the version data for the specified module: * <dl> * <dt>name:</dt> <dd>The name of the module</dd> * <dt>version:</dt> <dd>The version in use</dd> * <dt>build:</dt> <dd>The build number in use</dd> * <dt>versions:</dt> <dd>All versions that were registered</dd> * <dt>builds:</dt> <dd>All builds that were registered.</dd> * <dt>mainClass:</dt> <dd>An object that was was stamped with the * current version and build. If * mainClass.VERSION != version or mainClass.BUILD != build, * multiple versions of pieces of the library have been * loaded, potentially causing issues.</dd> * </dl> * * @method getVersion * @static * @param {String} name the name of the module (event, slider, etc) * @return {Object} The version info */ YAHOO.env.getVersion = function(name) { return YAHOO.env.modules[name] || null; }; /** * Do not fork for a browser if it can be avoided. Use feature detection when * you can. Use the user agent as a last resort. YAHOO.env.ua stores a version * number for the browser engine, 0 otherwise. This value may or may not map * to the version number of the browser using the engine. The value is * presented as a float so that it can easily be used for boolean evaluation * as well as for looking for a particular range of versions. Because of this, * some of the granularity of the version info may be lost (e.g., Gecko 1.8.0.9 * reports 1.8). * @class YAHOO.env.ua * @static */ /** * parses a user agent string (or looks for one in navigator to parse if * not supplied). * @method parseUA * @since 2.9.0 * @static */ YAHOO.env.parseUA = function(agent) { var numberify = function(s) { var c = 0; return parseFloat(s.replace(/\./g, function() { return (c++ == 1) ? '' : '.'; })); }, nav = navigator, o = { /** * Internet Explorer version number or 0. Example: 6 * @property ie * @type float * @static */ ie: 0, /** * Opera version number or 0. Example: 9.2 * @property opera * @type float * @static */ opera: 0, /** * Gecko engine revision number. Will evaluate to 1 if Gecko * is detected but the revision could not be found. Other browsers * will be 0. Example: 1.8 * <pre> * Firefox 1.0.0.4: 1.7.8 <-- Reports 1.7 * Firefox 1.5.0.9: 1.8.0.9 <-- 1.8 * Firefox 2.0.0.3: 1.8.1.3 <-- 1.81 * Firefox 3.0 <-- 1.9 * Firefox 3.5 <-- 1.91 * </pre> * @property gecko * @type float * @static */ gecko: 0, /** * AppleWebKit version. KHTML browsers that are not WebKit browsers * will evaluate to 1, other browsers 0. Example: 418.9 * <pre> * Safari 1.3.2 (312.6): 312.8.1 <-- Reports 312.8 -- currently the * latest available for Mac OSX 10.3. * Safari 2.0.2: 416 <-- hasOwnProperty introduced * Safari 2.0.4: 418 <-- preventDefault fixed * Safari 2.0.4 (419.3): 418.9.1 <-- One version of Safari may run * different versions of webkit * Safari 2.0.4 (419.3): 419 <-- Tiger installations that have been * updated, but not updated * to the latest patch. * Webkit 212 nightly: 522+ <-- Safari 3.0 precursor (with native * SVG and many major issues fixed). * Safari 3.0.4 (523.12) 523.12 <-- First Tiger release - automatic * update from 2.x via the 10.4.11 OS patch. * Webkit nightly 1/2008:525+ <-- Supports DOMContentLoaded event. * yahoo.com user agent hack removed. * </pre> * http://en.wikipedia.org/wiki/Safari_version_history * @property webkit * @type float * @static */ webkit: 0, /** * Chrome will be detected as webkit, but this property will also * be populated with the Chrome version number * @property chrome * @type float * @static */ chrome: 0, /** * The mobile property will be set to a string containing any relevant * user agent information when a modern mobile browser is detected. * Currently limited to Safari on the iPhone/iPod Touch, Nokia N-series * devices with the WebKit-based browser, and Opera Mini. * @property mobile * @type string * @static */ mobile: null, /** * Adobe AIR version number or 0. Only populated if webkit is detected. * Example: 1.0 * @property air * @type float */ air: 0, /** * Detects Apple iPad's OS version * @property ipad * @type float * @static */ ipad: 0, /** * Detects Apple iPhone's OS version * @property iphone * @type float * @static */ iphone: 0, /** * Detects Apples iPod's OS version * @property ipod * @type float * @static */ ipod: 0, /** * General truthy check for iPad, iPhone or iPod * @property ios * @type float * @static */ ios: null, /** * Detects Googles Android OS version * @property android * @type float * @static */ android: 0, /** * Detects Palms WebOS version * @property webos * @type float * @static */ webos: 0, /** * Google Caja version number or 0. * @property caja * @type float */ caja: nav && nav.cajaVersion, /** * Set to true if the page appears to be in SSL * @property secure * @type boolean * @static */ secure: false, /** * The operating system. Currently only detecting windows or macintosh * @property os * @type string * @static */ os: null }, ua = agent || (navigator && navigator.userAgent), loc = window && window.location, href = loc && loc.href, m; o.secure = href && (href.toLowerCase().indexOf("https") === 0); if (ua) { if ((/windows|win32/i).test(ua)) { o.os = 'windows'; } else if ((/macintosh/i).test(ua)) { o.os = 'macintosh'; } else if ((/rhino/i).test(ua)) { o.os = 'rhino'; } // Modern KHTML browsers should qualify as Safari X-Grade if ((/KHTML/).test(ua)) { o.webkit = 1; } // Modern WebKit browsers are at least X-Grade m = ua.match(/AppleWebKit\/([^\s]*)/); if (m && m[1]) { o.webkit = numberify(m[1]); // Mobile browser check if (/ Mobile\//.test(ua)) { o.mobile = 'Apple'; // iPhone or iPod Touch m = ua.match(/OS ([^\s]*)/); if (m && m[1]) { m = numberify(m[1].replace('_', '.')); } o.ios = m; o.ipad = o.ipod = o.iphone = 0; m = ua.match(/iPad|iPod|iPhone/); if (m && m[0]) { o[m[0].toLowerCase()] = o.ios; } } else { m = ua.match(/NokiaN[^\/]*|Android \d\.\d|webOS\/\d\.\d/); if (m) { // Nokia N-series, Android, webOS, ex: NokiaN95 o.mobile = m[0]; } if (/webOS/.test(ua)) { o.mobile = 'WebOS'; m = ua.match(/webOS\/([^\s]*);/); if (m && m[1]) { o.webos = numberify(m[1]); } } if (/ Android/.test(ua)) { o.mobile = 'Android'; m = ua.match(/Android ([^\s]*);/); if (m && m[1]) { o.android = numberify(m[1]); } } } m = ua.match(/Chrome\/([^\s]*)/); if (m && m[1]) { o.chrome = numberify(m[1]); // Chrome } else { m = ua.match(/AdobeAIR\/([^\s]*)/); if (m) { o.air = m[0]; // Adobe AIR 1.0 or better } } } if (!o.webkit) { // not webkit // @todo check Opera/8.01 (J2ME/MIDP; Opera Mini/2.0.4509/1316; fi; U; ssr) m = ua.match(/Opera[\s\/]([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); m = ua.match(/Version\/([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); // opera 10+ } m = ua.match(/Opera Mini[^;]*/); if (m) { o.mobile = m[0]; // ex: Opera Mini/2.0.4509/1316 } } else { // not opera or webkit m = ua.match(/MSIE\s([^;]*)/); if (m && m[1]) { o.ie = numberify(m[1]); } else { // not opera, webkit, or ie m = ua.match(/Gecko\/([^\s]*)/); if (m) { o.gecko = 1; // Gecko detected, look for revision m = ua.match(/rv:([^\s\)]*)/); if (m && m[1]) { o.gecko = numberify(m[1]); } } } } } } return o; }; YAHOO.env.ua = YAHOO.env.parseUA(); /* * Initializes the global by creating the default namespaces and applying * any new configuration information that is detected. This is the setup * for env. * @method init * @static * @private */ (function() { YAHOO.namespace("util", "widget", "example"); /*global YAHOO_config*/ if ("undefined" !== typeof YAHOO_config) { var l=YAHOO_config.listener, ls=YAHOO.env.listeners,unique=true, i; if (l) { // if YAHOO is loaded multiple times we need to check to see if // this is a new config object. If it is, add the new component // load listener to the stack for (i=0; i<ls.length; i++) { if (ls[i] == l) { unique = false; break; } } if (unique) { ls.push(l); } } } })(); /** * Provides the language utilites and extensions used by the library * @class YAHOO.lang */ YAHOO.lang = YAHOO.lang || {}; (function() { var L = YAHOO.lang, OP = Object.prototype, ARRAY_TOSTRING = '[object Array]', FUNCTION_TOSTRING = '[object Function]', OBJECT_TOSTRING = '[object Object]', NOTHING = [], HTML_CHARS = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#x27;', '/': '&#x2F;', '`': '&#x60;' }, // ADD = ["toString", "valueOf", "hasOwnProperty"], ADD = ["toString", "valueOf"], OB = { /** * Determines wheather or not the provided object is an array. * @method isArray * @param {any} o The object being testing * @return {boolean} the result */ isArray: function(o) { return OP.toString.apply(o) === ARRAY_TOSTRING; }, /** * Determines whether or not the provided object is a boolean * @method isBoolean * @param {any} o The object being testing * @return {boolean} the result */ isBoolean: function(o) { return typeof o === 'boolean'; }, /** * Determines whether or not the provided object is a function. * Note: Internet Explorer thinks certain functions are objects: * * var obj = document.createElement("object"); * YAHOO.lang.isFunction(obj.getAttribute) // reports false in IE * * var input = document.createElement("input"); // append to body * YAHOO.lang.isFunction(input.focus) // reports false in IE * * You will have to implement additional tests if these functions * matter to you. * * @method isFunction * @param {any} o The object being testing * @return {boolean} the result */ isFunction: function(o) { return (typeof o === 'function') || OP.toString.apply(o) === FUNCTION_TOSTRING; }, /** * Determines whether or not the provided object is null * @method isNull * @param {any} o The object being testing * @return {boolean} the result */ isNull: function(o) { return o === null; }, /** * Determines whether or not the provided object is a legal number * @method isNumber * @param {any} o The object being testing * @return {boolean} the result */ isNumber: function(o) { return typeof o === 'number' && isFinite(o); }, /** * Determines whether or not the provided object is of type object * or function * @method isObject * @param {any} o The object being testing * @return {boolean} the result */ isObject: function(o) { return (o && (typeof o === 'object' || L.isFunction(o))) || false; }, /** * Determines whether or not the provided object is a string * @method isString * @param {any} o The object being testing * @return {boolean} the result */ isString: function(o) { return typeof o === 'string'; }, /** * Determines whether or not the provided object is undefined * @method isUndefined * @param {any} o The object being testing * @return {boolean} the result */ isUndefined: function(o) { return typeof o === 'undefined'; }, /** * IE will not enumerate native functions in a derived object even if the * function was overridden. This is a workaround for specific functions * we care about on the Object prototype. * @property _IEEnumFix * @param {Function} r the object to receive the augmentation * @param {Function} s the object that supplies the properties to augment * @static * @private */ _IEEnumFix: (YAHOO.env.ua.ie) ? function(r, s) { var i, fname, f; for (i=0;i<ADD.length;i=i+1) { fname = ADD[i]; f = s[fname]; if (L.isFunction(f) && f!=OP[fname]) { r[fname]=f; } } } : function(){}, /** * <p> * Returns a copy of the specified string with special HTML characters * escaped. The following characters will be converted to their * corresponding character entities: * <code>&amp; &lt; &gt; &quot; &#x27; &#x2F; &#x60;</code> * </p> * * <p> * This implementation is based on the * <a href="http://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet">OWASP * HTML escaping recommendations</a>. In addition to the characters * in the OWASP recommendation, we also escape the <code>&#x60;</code> * character, since IE interprets it as an attribute delimiter when used in * innerHTML. * </p> * * @method escapeHTML * @param {String} html String to escape. * @return {String} Escaped string. * @static * @since 2.9.0 */ escapeHTML: function (html) { return html.replace(/[&<>"'\/`]/g, function (match) { return HTML_CHARS[match]; }); }, /** * Utility to set up the prototype, constructor and superclass properties to * support an inheritance strategy that can chain constructors and methods. * Static members will not be inherited. * * @method extend * @static * @param {Function} subc the object to modify * @param {Function} superc the object to inherit * @param {Object} overrides additional properties/methods to add to the * subclass prototype. These will override the * matching items obtained from the superclass * if present. */ extend: function(subc, superc, overrides) { if (!superc||!subc) { throw new Error("extend failed, please check that " + "all dependencies are included."); } var F = function() {}, i; F.prototype=superc.prototype; subc.prototype=new F(); subc.prototype.constructor=subc; subc.superclass=superc.prototype; if (superc.prototype.constructor == OP.constructor) { superc.prototype.constructor=superc; } if (overrides) { for (i in overrides) { if (L.hasOwnProperty(overrides, i)) { subc.prototype[i]=overrides[i]; } } L._IEEnumFix(subc.prototype, overrides); } }, /** * Applies all properties in the supplier to the receiver if the * receiver does not have these properties yet. Optionally, one or * more methods/properties can be specified (as additional * parameters). This option will overwrite the property if receiver * has it already. If true is passed as the third parameter, all * properties will be applied and _will_ overwrite properties in * the receiver. * * @method augmentObject * @static * @since 2.3.0 * @param {Function} r the object to receive the augmentation * @param {Function} s the object that supplies the properties to augment * @param {String*|boolean} arguments zero or more properties methods * to augment the receiver with. If none specified, everything * in the supplier will be used unless it would * overwrite an existing property in the receiver. If true * is specified as the third parameter, all properties will * be applied and will overwrite an existing property in * the receiver */ augmentObject: function(r, s) { if (!s||!r) { throw new Error("Absorb failed, verify dependencies."); } var a=arguments, i, p, overrideList=a[2]; if (overrideList && overrideList!==true) { // only absorb the specified properties for (i=2; i<a.length; i=i+1) { r[a[i]] = s[a[i]]; } } else { // take everything, overwriting only if the third parameter is true for (p in s) { if (overrideList || !(p in r)) { r[p] = s[p]; } } L._IEEnumFix(r, s); } return r; }, /** * Same as YAHOO.lang.augmentObject, except it only applies prototype properties * @see YAHOO.lang.augmentObject * @method augmentProto * @static * @param {Function} r the object to receive the augmentation * @param {Function} s the object that supplies the properties to augment * @param {String*|boolean} arguments zero or more properties methods * to augment the receiver with. If none specified, everything * in the supplier will be used unless it would overwrite an existing * property in the receiver. if true is specified as the third * parameter, all properties will be applied and will overwrite an * existing property in the receiver */ augmentProto: function(r, s) { if (!s||!r) { throw new Error("Augment failed, verify dependencies."); } //var a=[].concat(arguments); var a=[r.prototype,s.prototype], i; for (i=2;i<arguments.length;i=i+1) { a.push(arguments[i]); } L.augmentObject.apply(this, a); return r; }, /** * Returns a simple string representation of the object or array. * Other types of objects will be returned unprocessed. Arrays * are expected to be indexed. Use object notation for * associative arrays. * @method dump * @since 2.3.0 * @param o {Object} The object to dump * @param d {int} How deep to recurse child objects, default 3 * @return {String} the dump result */ dump: function(o, d) { var i,len,s=[],OBJ="{...}",FUN="f(){...}", COMMA=', ', ARROW=' => '; // Cast non-objects to string // Skip dates because the std toString is what we want // Skip HTMLElement-like objects because trying to dump // an element will cause an unhandled exception in FF 2.x if (!L.isObject(o)) { return o + ""; } else if (o instanceof Date || ("nodeType" in o && "tagName" in o)) { return o; } else if (L.isFunction(o)) { return FUN; } // dig into child objects the depth specifed. Default 3 d = (L.isNumber(d)) ? d : 3; // arrays [1, 2, 3] if (L.isArray(o)) { s.push("["); for (i=0,len=o.length;i<len;i=i+1) { if (L.isObject(o[i])) { s.push((d > 0) ? L.dump(o[i], d-1) : OBJ); } else { s.push(o[i]); } s.push(COMMA); } if (s.length > 1) { s.pop(); } s.push("]"); // objects {k1 => v1, k2 => v2} } else { s.push("{"); for (i in o) { if (L.hasOwnProperty(o, i)) { s.push(i + ARROW); if (L.isObject(o[i])) { s.push((d > 0) ? L.dump(o[i], d-1) : OBJ); } else { s.push(o[i]); } s.push(COMMA); } } if (s.length > 1) { s.pop(); } s.push("}"); } return s.join(""); }, /** * Does variable substitution on a string. It scans through the string * looking for expressions enclosed in { } braces. If an expression * is found, it is used a key on the object. If there is a space in * the key, the first word is used for the key and the rest is provided * to an optional function to be used to programatically determine the * value (the extra information might be used for this decision). If * the value for the key in the object, or what is returned from the * function has a string value, number value, or object value, it is * substituted for the bracket expression and it repeats. If this * value is an object, it uses the Object's toString() if this has * been overridden, otherwise it does a shallow dump of the key/value * pairs. * * By specifying the recurse option, the string is rescanned after * every replacement, allowing for nested template substitutions. * The side effect of this option is that curly braces in the * replacement content must be encoded. * * @method substitute * @since 2.3.0 * @param s {String} The string that will be modified. * @param o {Object} An object containing the replacement values * @param f {Function} An optional function that can be used to * process each match. It receives the key, * value, and any extra metadata included with * the key inside of the braces. * @param recurse {boolean} default true - if not false, the replaced * string will be rescanned so that nested substitutions are possible. * @return {String} the substituted string */ substitute: function (s, o, f, recurse) { var i, j, k, key, v, meta, saved=[], token, lidx=s.length, DUMP='dump', SPACE=' ', LBRACE='{', RBRACE='}', dump, objstr; for (;;) { i = s.lastIndexOf(LBRACE, lidx); if (i < 0) { break; } j = s.indexOf(RBRACE, i); if (i + 1 > j) { break; } //Extract key and meta info token = s.substring(i + 1, j); key = token; meta = null; k = key.indexOf(SPACE); if (k > -1) { meta = key.substring(k + 1); key = key.substring(0, k); } // lookup the value v = o[key]; // if a substitution function was provided, execute it if (f) { v = f(key, v, meta); } if (L.isObject(v)) { if (L.isArray(v)) { v = L.dump(v, parseInt(meta, 10)); } else { meta = meta || ""; // look for the keyword 'dump', if found force obj dump dump = meta.indexOf(DUMP); if (dump > -1) { meta = meta.substring(4); } objstr = v.toString(); // use the toString if it is not the Object toString // and the 'dump' meta info was not found if (objstr === OBJECT_TOSTRING || dump > -1) { v = L.dump(v, parseInt(meta, 10)); } else { v = objstr; } } } else if (!L.isString(v) && !L.isNumber(v)) { // This {block} has no replace string. Save it for later. v = "~-" + saved.length + "-~"; saved[saved.length] = token; // break; } s = s.substring(0, i) + v + s.substring(j + 1); if (recurse === false) { lidx = i-1; } } // restore saved {block}s for (i=saved.length-1; i>=0; i=i-1) { s = s.replace(new RegExp("~-" + i + "-~"), "{" + saved[i] + "}", "g"); } return s; }, /** * Returns a string without any leading or trailing whitespace. If * the input is not a string, the input will be returned untouched. * @method trim * @since 2.3.0 * @param s {string} the string to trim * @return {string} the trimmed string */ trim: function(s){ try { return s.replace(/^\s+|\s+$/g, ""); } catch(e) { return s; } }, /** * Returns a new object containing all of the properties of * all the supplied objects. The properties from later objects * will overwrite those in earlier objects. * @method merge * @since 2.3.0 * @param arguments {Object*} the objects to merge * @return the new merged object */ merge: function() { var o={}, a=arguments, l=a.length, i; for (i=0; i<l; i=i+1) { L.augmentObject(o, a[i], true); } return o; }, /** * Executes the supplied function in the context of the supplied * object 'when' milliseconds later. Executes the function a * single time unless periodic is set to true. * @method later * @since 2.4.0 * @param when {int} the number of milliseconds to wait until the fn * is executed * @param o the context object * @param fn {Function|String} the function to execute or the name of * the method in the 'o' object to execute * @param data [Array] data that is provided to the function. This accepts * either a single item or an array. If an array is provided, the * function is executed with one parameter for each array item. If * you need to pass a single array parameter, it needs to be wrapped in * an array [myarray] * @param periodic {boolean} if true, executes continuously at supplied * interval until canceled * @return a timer object. Call the cancel() method on this object to * stop the timer. */ later: function(when, o, fn, data, periodic) { when = when || 0; o = o || {}; var m=fn, d=data, f, r; if (L.isString(fn)) { m = o[fn]; } if (!m) { throw new TypeError("method undefined"); } if (!L.isUndefined(data) && !L.isArray(d)) { d = [data]; } f = function() { m.apply(o, d || NOTHING); }; r = (periodic) ? setInterval(f, when) : setTimeout(f, when); return { interval: periodic, cancel: function() { if (this.interval) { clearInterval(r); } else { clearTimeout(r); } } }; }, /** * A convenience method for detecting a legitimate non-null value. * Returns false for null/undefined/NaN, true for other values, * including 0/false/'' * @method isValue * @since 2.3.0 * @param o {any} the item to test * @return {boolean} true if it is not null/undefined/NaN || false */ isValue: function(o) { // return (o || o === false || o === 0 || o === ''); // Infinity fails return (L.isObject(o) || L.isString(o) || L.isNumber(o) || L.isBoolean(o)); } }; /** * Determines whether or not the property was added * to the object instance. Returns false if the property is not present * in the object, or was inherited from the prototype. * This abstraction is provided to enable hasOwnProperty for Safari 1.3.x. * There is a discrepancy between YAHOO.lang.hasOwnProperty and * Object.prototype.hasOwnProperty when the property is a primitive added to * both the instance AND prototype with the same value: * <pre> * var A = function() {}; * A.prototype.foo = 'foo'; * var a = new A(); * a.foo = 'foo'; * alert(a.hasOwnProperty('foo')); // true * alert(YAHOO.lang.hasOwnProperty(a, 'foo')); // false when using fallback * </pre> * @method hasOwnProperty * @param {any} o The object being testing * @param prop {string} the name of the property to test * @return {boolean} the result */ L.hasOwnProperty = (OP.hasOwnProperty) ? function(o, prop) { return o && o.hasOwnProperty && o.hasOwnProperty(prop); } : function(o, prop) { return !L.isUndefined(o[prop]) && o.constructor.prototype[prop] !== o[prop]; }; // new lang wins OB.augmentObject(L, OB, true); /* * An alias for <a href="YAHOO.lang.html">YAHOO.lang</a> * @class YAHOO.util.Lang */ YAHOO.util.Lang = L; /** * Same as YAHOO.lang.augmentObject, except it only applies prototype * properties. This is an alias for augmentProto. * @see YAHOO.lang.augmentObject * @method augment * @static * @param {Function} r the object to receive the augmentation * @param {Function} s the object that supplies the properties to augment * @param {String*|boolean} arguments zero or more properties methods to * augment the receiver with. If none specified, everything * in the supplier will be used unless it would * overwrite an existing property in the receiver. if true * is specified as the third parameter, all properties will * be applied and will overwrite an existing property in * the receiver */ L.augment = L.augmentProto; /** * An alias for <a href="YAHOO.lang.html#augment">YAHOO.lang.augment</a> * @for YAHOO * @method augment * @static * @param {Function} r the object to receive the augmentation * @param {Function} s the object that supplies the properties to augment * @param {String*} arguments zero or more properties methods to * augment the receiver with. If none specified, everything * in the supplier will be used unless it would * overwrite an existing property in the receiver */ YAHOO.augment = L.augmentProto; /** * An alias for <a href="YAHOO.lang.html#extend">YAHOO.lang.extend</a> * @method extend * @static * @param {Function} subc the object to modify * @param {Function} superc the object to inherit * @param {Object} overrides additional properties/methods to add to the * subclass prototype. These will override the * matching items obtained from the superclass if present. */ YAHOO.extend = L.extend; })(); YAHOO.register("yahoo", YAHOO, {version: "2.9.0", build: "2800"}); Y.YUI2 = YAHOO; }, '2.9.0' ,{});
{'content_hash': '8e5a51ea15cac2ff43e91bfb2e21ea71', 'timestamp': '', 'source': 'github', 'line_count': 1228, 'max_line_length': 103, 'avg_line_length': 32.09609120521173, 'alnum_prop': 0.532678743593647, 'repo_name': 'miguelhidrogo/moodle_auth_cors', 'id': '3fbec05565035f77269fb89f4d71dbc654829616', 'size': '39568', 'binary': False, 'copies': '1084', 'ref': 'refs/heads/master', 'path': 'lib/yuilib/2in3/2.9.0/build/yui2-yahoo/yui2-yahoo.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ActionScript', 'bytes': '1205'}, {'name': 'CSS', 'bytes': '1250739'}, {'name': 'Cucumber', 'bytes': '1573954'}, {'name': 'HTML', 'bytes': '418957'}, {'name': 'Java', 'bytes': '14870'}, {'name': 'JavaScript', 'bytes': '12201919'}, {'name': 'PHP', 'bytes': '66948375'}, {'name': 'PLSQL', 'bytes': '4867'}, {'name': 'Perl', 'bytes': '20769'}, {'name': 'XSLT', 'bytes': '33489'}]}
package mcjty.rftools.blocks.screens.modules; import io.netty.buffer.ByteBuf; import mcjty.rftools.RFTools; import mcjty.rftools.api.screens.data.IModuleDataContents; public class ScreenModuleHelper { public static final double SMOOTHING = 0.5; private boolean showdiff = false; private long prevMillis = 0; private long prevContents = 0; private long lastPerTick = 0; public static class ModuleDataContents implements IModuleDataContents { public static final String ID = RFTools.MODID + ":contents"; private final long contents; private final long maxContents; private final long lastPerTick; @Override public String getId() { return ID; } public ModuleDataContents(long contents, long maxContents, long lastPerTick) { this.contents = contents; this.maxContents = maxContents; this.lastPerTick = lastPerTick; } public ModuleDataContents(ByteBuf buf) { contents = buf.readLong(); maxContents = buf.readLong(); lastPerTick = buf.readLong(); } @Override public long getContents() { return contents; } @Override public long getMaxContents() { return maxContents; } @Override public long getLastPerTick() { return lastPerTick; } @Override public void writeToBuf(ByteBuf buf) { buf.writeLong(contents); buf.writeLong(maxContents); buf.writeLong(lastPerTick); } } public IModuleDataContents getContentsValue(long millis, long contents, long maxContents) { if (showdiff) { if (prevMillis == 0) { prevMillis = millis; prevContents = contents; return new ModuleDataContents(contents, maxContents, lastPerTick); } else { if (millis > prevMillis + 500) { long diffEnergy = contents - prevContents; long diff = millis - prevMillis; int ticks = (int) (diff * 20 / 1000); if (ticks == 0) { ticks = 1; } long measurement = diffEnergy / ticks; lastPerTick = (long) ((lastPerTick * SMOOTHING) + (measurement * (1.0 - SMOOTHING))); prevMillis = millis; prevContents = contents; } return new ModuleDataContents(contents, maxContents, lastPerTick); } } else { return new ModuleDataContents(contents, maxContents, 0L); } } public void setShowdiff(boolean showdiff) { this.showdiff = showdiff; } }
{'content_hash': '34f9a49b3ea8466240791afaa4bcc9f5', 'timestamp': '', 'source': 'github', 'line_count': 94, 'max_line_length': 105, 'avg_line_length': 30.404255319148938, 'alnum_prop': 0.5598320503848845, 'repo_name': 'McJty/RFTools', 'id': '50019c26c708cebf5e1765c66fc851e43afe5bf2', 'size': '2858', 'binary': False, 'copies': '1', 'ref': 'refs/heads/1.12', 'path': 'src/main/java/mcjty/rftools/blocks/screens/modules/ScreenModuleHelper.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '2868355'}]}
import { spreadFrom } from "../fp"; export = spreadFrom;
{'content_hash': '5c40537b6370f4267e28cd248444f229', 'timestamp': '', 'source': 'github', 'line_count': 2, 'max_line_length': 35, 'avg_line_length': 28.5, 'alnum_prop': 0.6666666666666666, 'repo_name': 'jpoeng/jpoeng.github.io', 'id': '7eb840b036d645f45d0a737c7b5f721039bb4ba4', 'size': '57', 'binary': False, 'copies': '133', 'ref': 'refs/heads/master', 'path': 'node_modules/@types/lodash/fp/spreadFrom.d.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '5765'}, {'name': 'HTML', 'bytes': '53947'}, {'name': 'JavaScript', 'bytes': '1885'}, {'name': 'PHP', 'bytes': '9773'}]}
package jsky.catalog; import jsky.coords.DMS; import jsky.coords.HMS; import jsky.util.gui.DialogUtil; import java.io.Serializable; /** * This utility class provides a method to scan specially formatted * values from a string and return an object of the correct type. */ public class FieldFormat { /** * Return an object for the given field description by parsing the given string. * * @param fieldDesc describes the field * @param s the value in string format * @return an object of the given class, or null if it could not be parsed */ public static Serializable getValue(FieldDesc fieldDesc, String s) { Class<?> c = fieldDesc.getFieldClass(); s = s.trim(); if (c == String.class) return s; if (s.equals("")) return null; if (c == Double.class || c == Float.class) { if (fieldDesc.isRA()) { HMS hms = new HMS(s); if (c == Double.class) return hms.getVal(); else return (float) hms.getVal(); } else if (fieldDesc.isDec()) { DMS dms = new DMS(s); if (c == Double.class) return dms.getVal(); else return (float) dms.getVal(); } } try { if (c == Double.class) { return new Double(s); } if (c == Float.class) { return new Float(s); } if (c == Integer.class) return new Integer(s); if (c == Boolean.class) return Boolean.getBoolean(s); } catch (NumberFormatException e) { DialogUtil.error("Invalid query syntax: " + s + ", expected a single value"); } return null; } /** * Return a ValueRange object representing a range of values for the given * field by parsing the given string. * * @param fieldDesc describes the field * @param s the value range in string format, which may be encoded as two * values: "min max", as one value: "value" (For numerical types, * tests for equality, for Strings, the start of the string). The * symbols ">", or "<" may be used in the string for numerical types, * to indicate that the value should be greater than or less than * the (noninclusive) given values, for example: ">0.0 <1.0". * If there are two values, they should be separated by a single space * and the first value should be the minimum value (inclusive, * unless ">" was specified). * @return a ValueRange object representing the range of values, or null if they * could not be parsed */ public static ValueRange getValueRange(FieldDesc fieldDesc, String s) { Class<?> c = fieldDesc.getFieldClass(); s = s.trim(); if (c == String.class) return new ValueRange(s); // look for two values separated by a space, or a single value (test for equality) String[] ar = s.split(" ", 2); boolean oneVal = false; // true if only one value was specified if (ar.length == 1) { ar = new String[2]; ar[0] = ar[1] = s; oneVal = true; } // check for <, >, symbols and set inclusive flags boolean[] inclusive = new boolean[2]; boolean insertMin = false, insertMax = false; // XXX error handling?) for (int i = 0; i < 2; i++) { inclusive[i] = true; if (ar[i].startsWith(">")) { if (ar[i].startsWith(">=")) { ar[i] = ar[i].substring(2); } else { inclusive[i] = false; ar[i] = ar[i].substring(1); } if (oneVal) { // x > value insertMax = true; break; } } else if (ar[i].startsWith("<")) { if (ar[i].startsWith("<=")) { ar[i] = ar[i].substring(2); } else { inclusive[i] = false; ar[i] = ar[i].substring(1); } if (oneVal) { // x < value insertMin = true; ar[1] = ar[0]; break; } } } try { if (c == Double.class) { if (insertMin) ar[0] = Double.toString(Double.MIN_VALUE); else if (insertMax) ar[1] = Double.toString(Double.MAX_VALUE); return new ValueRange(new Double(ar[0]), inclusive[0], new Double(ar[1]), inclusive[1]); } if (c == Float.class) { if (insertMin) ar[0] = Float.toString(Float.MIN_VALUE); else if (insertMax) ar[1] = Float.toString(Float.MAX_VALUE); return new ValueRange(new Float(ar[0]), inclusive[0], new Float(ar[1]), inclusive[1]); } if (c == Integer.class) { if (insertMin) ar[0] = Integer.toString(Integer.MIN_VALUE); else if (insertMax) ar[1] = Integer.toString(Integer.MAX_VALUE); return new ValueRange(new Integer(ar[0]), inclusive[0], new Integer(ar[1]), inclusive[1]); } } catch (NumberFormatException e) { DialogUtil.error("Invalid query syntax: " + s + ", expected: a value or value range expression (min max, >min, <=max, ...)"); } return null; } }
{'content_hash': '26eb4762fd0f4f54a7f42594d3616228', 'timestamp': '', 'source': 'github', 'line_count': 165, 'max_line_length': 137, 'avg_line_length': 36.012121212121215, 'alnum_prop': 0.4786267250084147, 'repo_name': 'arturog8m/ocs', 'id': '0a92789c11cdbaa03ac8067a28c6c85a35e0cfa9', 'size': '5942', 'binary': False, 'copies': '9', 'ref': 'refs/heads/develop', 'path': 'bundle/edu.gemini.catalog/src/main/java/jsky/catalog/FieldFormat.java', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '7919'}, {'name': 'HTML', 'bytes': '490242'}, {'name': 'Java', 'bytes': '14504312'}, {'name': 'JavaScript', 'bytes': '7962'}, {'name': 'Scala', 'bytes': '4967047'}, {'name': 'Shell', 'bytes': '4989'}, {'name': 'Tcl', 'bytes': '2841'}]}
 #region Using Directives using System; #endregion namespace MvvmFramework.Samples.Uwp.Models { /// <summary> /// Represents a single item on the todo list of the user. /// </summary> public class TodoListItem { #region Public Properties /// <summary> /// Gets or sets the unique identifier of the <see cref="TodoListItem"/>, which is a global unique ID. /// </summary> public string Id { get; set; } = Guid.NewGuid().ToString(); /// <summary> /// Gets or sets the title of the <see cref="TodoListItem"/>. /// </summary> public string Title { get; set; } /// <summary> /// Gets or sets a detailed description of the <see cref="TodoListItem"/>, which contains the steps to finish it. /// </summary> public string Description { get; set; } /// <summary> /// Gets or sets a value that determines whether the <see cref="TodoListItem"/> has already been finished an can therefore be removed from the todo list. /// </summary> public bool IsFinished { get; set; } #endregion } }
{'content_hash': '90964f6cb0f0cbca783ae48f7eb86d2c', 'timestamp': '', 'source': 'github', 'line_count': 39, 'max_line_length': 161, 'avg_line_length': 29.46153846153846, 'alnum_prop': 0.5953002610966057, 'repo_name': 'lecode-official/mvvm-framework', 'id': '89f47dbcc887d143404d7f1758d507d0c8e7630b', 'size': '1151', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Samples/MvvmFramework.Samples.Uwp/Models/TodoListItem.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '483517'}, {'name': 'PowerShell', 'bytes': '358'}]}
Library Overview ================================= QualtricsAPI is a lightweight Python library for the Qualtrics Web API. With the Qualtrics you get access to ingest and upload data provided by the Qualtrics platform. Python Package Installer: ################################################# The installation of this package is pretty straight forward. To install this package run pip install in your terminal. :: $ pip install QualtricsAPI
{'content_hash': 'be4f29ccbecbac50a3e39ed3a1b7b531', 'timestamp': '', 'source': 'github', 'line_count': 12, 'max_line_length': 118, 'avg_line_length': 37.583333333333336, 'alnum_prop': 0.656319290465632, 'repo_name': 'Jaseibert/QualtricsAPI', 'id': '5a039657f85a8be703605dc9785ee668303ce5d3', 'size': '451', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'docs/source/installation.rst', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Python', 'bytes': '397950'}]}
<?php namespace ZendTest\Application; use Zend\Application\ResourceBroker, Zend\Application\ResourceLoader, Zend\Application\Application, Zend\Application\Bootstrap; /** * @category Zend * @package Zend_Application * @subpackage UnitTests * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Application */ class ResourceBrokerTest extends \PHPUnit_Framework_TestCase { public function setUp() { $this->broker = new ResourceBroker(); $this->application = new Application('testing', array()); $this->bootstrap = new Bootstrap($this->application); } public function testBootstrapIsUndefinedByDefault() { $this->assertNull($this->broker->getBootstrap()); } public function testCanSetBootstrap() { $this->broker->setBootstrap($this->bootstrap); $this->assertSame($this->bootstrap, $this->broker->getBootstrap()); } public function testNoBootstrapInjectedInResourceIfNotInjectedInBroker() { $this->broker->registerSpec('view'); $view = $this->broker->load('view'); $this->assertInstanceOf('Zend\Application\Resource\View', $view); $this->assertNull($view->getBootstrap()); } public function testBootstrapInjectedInResourceIfInjectedInBroker() { $this->broker->setBootstrap($this->bootstrap); $this->broker->registerSpec('view'); $view = $this->broker->load('view'); $this->assertInstanceOf('Zend\Application\Resource\View', $view); $this->assertSame($this->bootstrap, $view->getBootstrap()); } public function testExceptionIsRaisedIfLoadedPluginIsNotAnApplicationResource() { $this->broker->getClassLoader()->registerPlugin('view', 'Zend\View\PhpRenderer'); $this->setExpectedException('InvalidArgumentException', 'must implement'); $view = $this->broker->load('view'); } }
{'content_hash': '7f845d10992904e98987a665eb5d4b28', 'timestamp': '', 'source': 'github', 'line_count': 62, 'max_line_length': 89, 'avg_line_length': 33.04838709677419, 'alnum_prop': 0.6676427525622255, 'repo_name': 'dineshkummarc/zf2', 'id': '9682b06ff1764bc78a638cce8357d12ad341a028', 'size': '2751', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'modules/ZendFramework1Mvc/tests/Zend/Application/ResourceBrokerTest.php', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []}
var gulp = require("gulp"); var watch = require("gulp-watch"); var fs = require("fs-extra"); var path = require("path"); var glob = require("glob"); var batch = require("gulp-batch"); gulp.task("rules", () => { let code = ""; let names = []; glob.sync("./src/rules/*").sort().forEach((filepath, index) => { let name = `rule_${index}`; names.push(name); code += `import ${name} from "${filepath.replace("src/", "")}";\n`; }); code += `\nexport { ${names.join(", ")} };`; fs.writeFileSync("./src/rules.es6.js", code, {enc: "uf8"}); return; }); let getTestFilePath = filepath => filepath .replace("./src/", "./test/") .replace(".es6", ""); gulp.task("build-tests", () => { glob.sync("./src/**/*.es6.js") .filter((filepath) => { return !fs.existsSync(getTestFilePath(filepath)); }).forEach((filepath) => { let filename = path.basename(filepath); let functionName = filename.split(".")[0]; let testCode = `import "babel-polyfill"; import ${functionName} from ".${filepath}"; import assert from "assert"; import jsdom from "mocha-jsdom"; describe("${functionName}", () => { jsdom(); it("is a function", (done) => { assert(typeof ${functionName} === "function"); done(); }); });`; fs.writeFileSync(getTestFilePath(filepath), testCode, {encoding: "utf8"}); }); return; }); gulp.task("watch-rules", () => { watch(["./rules/**/*.json"], batch((events, done) => { gulp.start("rules", done); })); }); gulp.task("watch", ["watch-src"]);
{'content_hash': 'e69b7234c5d62a6fea3210fdc9353910', 'timestamp': '', 'source': 'github', 'line_count': 55, 'max_line_length': 78, 'avg_line_length': 27.563636363636363, 'alnum_prop': 0.5778364116094987, 'repo_name': 'lagora/proc.edu.ria', 'id': '943abc7cf8f775e0703f5e526753b36cc70eb8a5', 'size': '1516', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'gulpfile.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '343'}, {'name': 'HTML', 'bytes': '269'}, {'name': 'JavaScript', 'bytes': '20751'}]}
import unittest import cerebro.nlp as n class TestParser(unittest.TestCase): def setUp(self): self.obj = n.DataSetParser(n.DATA_SET_PATH) self.obj.parse() def test_parse(self): self.assertIsNotNone(self.obj.path) self.assertIsNotNone(self.obj.df) def test_column_data(self): temp = self.obj.get_column_data(n.COLUMN_LABEL) self.assertEqual(len(temp), 29)
{'content_hash': '454ded5677ee5a06f3179ceb56bb3fb7', 'timestamp': '', 'source': 'github', 'line_count': 18, 'max_line_length': 55, 'avg_line_length': 23.38888888888889, 'alnum_prop': 0.6555819477434679, 'repo_name': 'Le-Bot/cerebro', 'id': 'd7cedd9224423ce4260ed0e6b4e477752b9c0160', 'size': '421', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'cerebro/tests/nlp/test_parser.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Python', 'bytes': '15172'}]}
#ifndef FLOW_TABLE_H #define FLOW_TABLE_H 1 #include <linux/kernel.h> #include <linux/netlink.h> #include <linux/openvswitch.h> #include <linux/spinlock.h> #include <linux/types.h> #include <linux/rcupdate.h> #include <linux/if_ether.h> #include <linux/in6.h> #include <linux/jiffies.h> #include <linux/time.h> #include <linux/flex_array.h> #include <net/inet_ecn.h> #include <net/ip_tunnels.h> #include "flow.h" struct table_instance { struct flex_array *buckets; unsigned int n_buckets; struct rcu_head rcu; int node_ver; u32 hash_seed; bool keep_flows; }; struct flow_table { struct table_instance __rcu *ti; struct list_head mask_list; unsigned long last_rehash; unsigned int count; }; int ovs_flow_init(void); void ovs_flow_exit(void); struct sw_flow *ovs_flow_alloc(bool percpu_stats); void ovs_flow_free(struct sw_flow *, bool deferred); int ovs_flow_tbl_init(struct flow_table *); int ovs_flow_tbl_count(struct flow_table *table); void ovs_flow_tbl_destroy(struct flow_table *table, bool deferred); int ovs_flow_tbl_flush(struct flow_table *flow_table); int ovs_flow_tbl_insert(struct flow_table *table, struct sw_flow *flow, struct sw_flow_mask *mask); void ovs_flow_tbl_remove(struct flow_table *table, struct sw_flow *flow); int ovs_flow_tbl_num_masks(const struct flow_table *table); struct sw_flow *ovs_flow_tbl_dump_next(struct table_instance *table, u32 *bucket, u32 *idx); struct sw_flow *ovs_flow_tbl_lookup_stats(struct flow_table *, const struct sw_flow_key *, u32 *n_mask_hit); struct sw_flow *ovs_flow_tbl_lookup(struct flow_table *, const struct sw_flow_key *); bool ovs_flow_cmp_unmasked_key(const struct sw_flow *flow, struct sw_flow_match *match); void ovs_flow_mask_key(struct sw_flow_key *dst, const struct sw_flow_key *src, const struct sw_flow_mask *mask); #endif /* flow_table.h */
{'content_hash': 'e19db0e59dd489eb0f76c9215032d65c', 'timestamp': '', 'source': 'github', 'line_count': 67, 'max_line_length': 78, 'avg_line_length': 28.253731343283583, 'alnum_prop': 0.7105124141574221, 'repo_name': 'lokeshjindal15/pd-gem5', 'id': 'baaeb101924d81a4beb373be93e07287ed9be020', 'size': '2599', 'binary': False, 'copies': '266', 'ref': 'refs/heads/master', 'path': 'kernel_dvfs/linux-linaro-tracking-gem5/net/openvswitch/flow_table.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Assembly', 'bytes': '10138943'}, {'name': 'Awk', 'bytes': '19269'}, {'name': 'C', 'bytes': '469972635'}, {'name': 'C++', 'bytes': '18163034'}, {'name': 'CMake', 'bytes': '2202'}, {'name': 'Clojure', 'bytes': '333'}, {'name': 'Emacs Lisp', 'bytes': '1969'}, {'name': 'Groff', 'bytes': '63956'}, {'name': 'HTML', 'bytes': '136898'}, {'name': 'Hack', 'bytes': '2489'}, {'name': 'Java', 'bytes': '3096'}, {'name': 'Jupyter Notebook', 'bytes': '1231954'}, {'name': 'Lex', 'bytes': '59257'}, {'name': 'M4', 'bytes': '52982'}, {'name': 'Makefile', 'bytes': '1453704'}, {'name': 'Objective-C', 'bytes': '1315749'}, {'name': 'Perl', 'bytes': '716374'}, {'name': 'Perl6', 'bytes': '3727'}, {'name': 'Protocol Buffer', 'bytes': '3246'}, {'name': 'Python', 'bytes': '4102365'}, {'name': 'Scilab', 'bytes': '21433'}, {'name': 'Shell', 'bytes': '512873'}, {'name': 'SourcePawn', 'bytes': '4687'}, {'name': 'UnrealScript', 'bytes': '10556'}, {'name': 'Visual Basic', 'bytes': '2884'}, {'name': 'XS', 'bytes': '1239'}, {'name': 'Yacc', 'bytes': '121715'}]}
var menu = new Vue({ el: '#menu', data: { layer: 'raster', showGraph: false, isochroneRadius: 600, showSpt: false, isochronePoint: undefined }, methods: { changeLayer: function (event) { this.showGraph = false; setGHMvtVisible(map, false); removeIsoLayers(); setLayer(map, event.target.id); }, toggleGHMvt: function (event) { setGHMvtVisible(map, event.target.checked); }, updateIsochrone: function (event) { if (!this.isochronePoint) return; var coordinates = this.isochronePoint.split(',') .map(item => item.trim()) .map(parseFloat); if (coordinates.length != 2) { console.error('invalid point: ' + this.isochronePoint); } else { _updateIsochrone({ lng: coordinates[1], lat: coordinates[0] }); } } } }); var mapTilerKey = 'ADD_YOUR_KEY_HERE'; var rasterStyle = { 'version': 8, 'sources': { 'raster-tiles-source': { 'type': 'raster', 'tiles': [ 'https://a.tile.openstreetmap.de/{z}/{x}/{y}.png', 'https://b.tile.openstreetmap.de/{z}/{x}/{y}.png', 'https://c.tile.openstreetmap.de/{z}/{x}/{y}.png' ] } }, 'layers': [ { 'id': 'raster-tiles', 'type': 'raster', 'source': 'raster-tiles-source' } ] }; var vectorStyle = 'https://api.maptiler.com/maps/basic/style.json?key=' + mapTilerKey; fetch('/info') .then(response => response.json()) .then(json => _drawMap(json.bbox)) .catch(e => console.error('Could not receive bbox from GH server', e)); // the mapbox map object used in various places here var map; function _drawMap(bbox) { map = new mapboxgl.Map({ container: 'map', style: rasterStyle, }); map.fitBounds([ [bbox[0], bbox[1]], [bbox[2], bbox[3]] ], { animate: false, padding: 50 }); map.on('style.load', function addGHMvt() { // add GraphHopper vector tiles of road network. this is also called when we change the style map.addSource('gh-mvt', { type: 'vector', tiles: ['http://' + window.location.host + '/mvt/{z}/{x}/{y}.mvt?details=road_class'] }); var boundsPolygon = [[bbox[0], bbox[1]], [bbox[2], bbox[1]], [bbox[2], bbox[3]], [bbox[0], bbox[3]], [bbox[0], bbox[1]]]; map.addLayer({ 'id': 'gh-bounds', 'type': 'line', 'source': { 'type': 'geojson', 'data': { 'type': 'Feature', 'geometry': { 'type': 'Polygon', 'coordinates': [boundsPolygon] } } }, 'layout': {}, 'paint': { 'line-color': 'grey', 'line-width': 1.5 } }, getFirstSymbolLayer(map)); map.addLayer({ 'id': 'gh', 'type': 'line', 'source': 'gh-mvt', 'source-layer': 'roads', 'paint': { 'line-color': [ 'match', ['get', 'road_class'], 'motorway', 'red', 'primary', 'orange', 'trunk', 'orange', 'secondary', 'yellow', /*other*/ 'grey' ] }, 'layout': { 'visibility': 'none' } // we make sure the map labels stay on top }, getFirstSymbolLayer(map)); }); map.on('click', function (e) { _updateIsochrone(e.lngLat); }); } function _updateIsochrone(lngLat) { menu.isochronePoint = lngLat.lat.toFixed(6) + "," + lngLat.lng.toFixed(6); if (menu.showSpt) fetchAndDrawSPT(lngLat); else fetchAndDrawIsoline(lngLat); } function fetchAndDrawSPT(point) { // fetch GraphHopper isochrone and draw on map var counter = 0; var coordinates = []; var radius = menu.isochroneRadius; Papa.parse("http://" + window.location.host + "/spt?profile=car&point=" + point.lat + "," + point.lng + "&columns=prev_longitude,prev_latitude,longitude,latitude,distance,time&time_limit=" + radius, { download: true, worker: true, step: function (results) { var d = results.data; // skip the first line (column names) and the second (root node) if (counter > 1) coordinates.push([[parseFloat(d[0]), parseFloat(d[1])], [parseFloat(d[2]), parseFloat(d[3])]]); counter++; }, complete: function () { var geojson = { 'type': 'FeatureCollection', 'features': [ { 'type': 'Feature', 'geometry': { 'type': 'MultiLineString', 'coordinates': coordinates } } ] }; drawIsoLayer(geojson, coordinates); }, error: function (e) { console.error('error when trying to show SPT', e); } }); } function fetchAndDrawIsoline(point) { var radius = menu.isochroneRadius; fetch("/isochrone?profile=car&point=" + point.lat + "," + point.lng + "&time_limit=" + radius) .then(response => response.json()) .then(data => { console.log('isoline took: ' + data.info.took + 'ms'); // since we do not use the buckets parameter there is always just one polygon drawIsoLayer(data.polygons[0], undefined) }) .catch(e => { console.error('error when trying to show isoline', e) }); } function drawIsoLayer(geojson, coordinates) { removeIsoLayers(); var source = map.getSource('isochrone'); if (!source) { map.addSource('isochrone', { 'type': 'geojson', 'data': geojson }); } else { source.setData(geojson); } map.addLayer({ 'id': 'isochrone-layer', 'type': 'line', 'source': 'isochrone', 'paint': { 'line-color': '#0000e1' } }, getFirstSymbolLayer(map)); } function removeIsoLayers() { if (map.getLayer('isochrone-layer')) { map.removeLayer('isochrone-layer'); } } function setLayer(map, layerId) { if (layerId == 'vector') { map.setStyle(vectorStyle); } else if (layerId == 'raster') { map.setStyle(rasterStyle); } } function setGHMvtVisible(map, visible) { if (visible) { map.setLayoutProperty('gh', 'visibility', 'visible'); } else { map.setLayoutProperty('gh', 'visibility', 'none'); } } function getFirstSymbolLayer(map) { var layers = map.getStyle().layers; // Find the index of the first symbol layer in the map style for (var i = 0; i < layers.length; i++) { if (layers[i].type === 'symbol') { return layers[i].id; } } }
{'content_hash': '9255ac6a49f81124dadacccb659c400d', 'timestamp': '', 'source': 'github', 'line_count': 241, 'max_line_length': 204, 'avg_line_length': 30.522821576763487, 'alnum_prop': 0.48355084284937466, 'repo_name': 'routexl/graphhopper', 'id': 'be1142f29f1c73c8221968fd533bac2157f92a64', 'size': '8160', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'web-bundle/src/main/resources/com/graphhopper/maps/isochrone/index.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '34062'}, {'name': 'HTML', 'bytes': '17227'}, {'name': 'Java', 'bytes': '5443247'}, {'name': 'JavaScript', 'bytes': '355684'}, {'name': 'Shell', 'bytes': '19811'}]}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_79) on Mon Jun 29 06:45:49 CEST 2015 --> <title>ColorMapper (Apache Ant API)</title> <meta name="date" content="2015-06-29"> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="ColorMapper (Apache Ant API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../../org/apache/tools/ant/types/optional/image/BasicShape.html" title="class in org.apache.tools.ant.types.optional.image"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../../../org/apache/tools/ant/types/optional/image/Draw.html" title="class in org.apache.tools.ant.types.optional.image"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/apache/tools/ant/types/optional/image/ColorMapper.html" target="_top">Frames</a></li> <li><a href="ColorMapper.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field_summary">Field</a>&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field_detail">Field</a>&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">org.apache.tools.ant.types.optional.image</div> <h2 title="Class ColorMapper" class="title">Class ColorMapper</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>org.apache.tools.ant.types.optional.image.ColorMapper</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>public final class <span class="strong">ColorMapper</span> extends java.lang.Object</pre> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../../../org/apache/tools/ant/taskdefs/optional/image/Image.html" title="class in org.apache.tools.ant.taskdefs.optional.image"><code>Image</code></a></dd></dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- =========== FIELD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="field_summary"> <!-- --> </a> <h3>Field Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation"> <caption><span>Fields</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>static java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/apache/tools/ant/types/optional/image/ColorMapper.html#COLOR_BLACK">COLOR_BLACK</a></strong></code> <div class="block">black string</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/apache/tools/ant/types/optional/image/ColorMapper.html#COLOR_BLUE">COLOR_BLUE</a></strong></code> <div class="block">blue string</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/apache/tools/ant/types/optional/image/ColorMapper.html#COLOR_CYAN">COLOR_CYAN</a></strong></code> <div class="block">cyan string</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/apache/tools/ant/types/optional/image/ColorMapper.html#COLOR_DARKGRAY">COLOR_DARKGRAY</a></strong></code> <div class="block">black string</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/apache/tools/ant/types/optional/image/ColorMapper.html#COLOR_DARKGREY">COLOR_DARKGREY</a></strong></code> <div class="block">darkgrey string</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/apache/tools/ant/types/optional/image/ColorMapper.html#COLOR_GRAY">COLOR_GRAY</a></strong></code> <div class="block">gray string</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/apache/tools/ant/types/optional/image/ColorMapper.html#COLOR_GREEN">COLOR_GREEN</a></strong></code> <div class="block">green string</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/apache/tools/ant/types/optional/image/ColorMapper.html#COLOR_GREY">COLOR_GREY</a></strong></code> <div class="block">grey string</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/apache/tools/ant/types/optional/image/ColorMapper.html#COLOR_LIGHTGRAY">COLOR_LIGHTGRAY</a></strong></code> <div class="block">lightgray string</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/apache/tools/ant/types/optional/image/ColorMapper.html#COLOR_LIGHTGREY">COLOR_LIGHTGREY</a></strong></code> <div class="block">lightgrey string</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/apache/tools/ant/types/optional/image/ColorMapper.html#COLOR_MAGENTA">COLOR_MAGENTA</a></strong></code> <div class="block">magenta string</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/apache/tools/ant/types/optional/image/ColorMapper.html#COLOR_ORANGE">COLOR_ORANGE</a></strong></code> <div class="block">orange string</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/apache/tools/ant/types/optional/image/ColorMapper.html#COLOR_PINK">COLOR_PINK</a></strong></code> <div class="block">pink string</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/apache/tools/ant/types/optional/image/ColorMapper.html#COLOR_RED">COLOR_RED</a></strong></code> <div class="block">reg string</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/apache/tools/ant/types/optional/image/ColorMapper.html#COLOR_WHITE">COLOR_WHITE</a></strong></code> <div class="block">white string</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/apache/tools/ant/types/optional/image/ColorMapper.html#COLOR_YELLOW">COLOR_YELLOW</a></strong></code> <div class="block">yellow string</div> </td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>static java.awt.Color</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/apache/tools/ant/types/optional/image/ColorMapper.html#getColorByName(java.lang.String)">getColorByName</a></strong>(java.lang.String&nbsp;colorName)</code> <div class="block">Convert a color name to a color value.</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ FIELD DETAIL =========== --> <ul class="blockList"> <li class="blockList"><a name="field_detail"> <!-- --> </a> <h3>Field Detail</h3> <a name="COLOR_BLACK"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>COLOR_BLACK</h4> <pre>public static final&nbsp;java.lang.String COLOR_BLACK</pre> <div class="block">black string</div> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../../../constant-values.html#org.apache.tools.ant.types.optional.image.ColorMapper.COLOR_BLACK">Constant Field Values</a></dd></dl> </li> </ul> <a name="COLOR_BLUE"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>COLOR_BLUE</h4> <pre>public static final&nbsp;java.lang.String COLOR_BLUE</pre> <div class="block">blue string</div> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../../../constant-values.html#org.apache.tools.ant.types.optional.image.ColorMapper.COLOR_BLUE">Constant Field Values</a></dd></dl> </li> </ul> <a name="COLOR_CYAN"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>COLOR_CYAN</h4> <pre>public static final&nbsp;java.lang.String COLOR_CYAN</pre> <div class="block">cyan string</div> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../../../constant-values.html#org.apache.tools.ant.types.optional.image.ColorMapper.COLOR_CYAN">Constant Field Values</a></dd></dl> </li> </ul> <a name="COLOR_DARKGRAY"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>COLOR_DARKGRAY</h4> <pre>public static final&nbsp;java.lang.String COLOR_DARKGRAY</pre> <div class="block">black string</div> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../../../constant-values.html#org.apache.tools.ant.types.optional.image.ColorMapper.COLOR_DARKGRAY">Constant Field Values</a></dd></dl> </li> </ul> <a name="COLOR_GRAY"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>COLOR_GRAY</h4> <pre>public static final&nbsp;java.lang.String COLOR_GRAY</pre> <div class="block">gray string</div> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../../../constant-values.html#org.apache.tools.ant.types.optional.image.ColorMapper.COLOR_GRAY">Constant Field Values</a></dd></dl> </li> </ul> <a name="COLOR_LIGHTGRAY"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>COLOR_LIGHTGRAY</h4> <pre>public static final&nbsp;java.lang.String COLOR_LIGHTGRAY</pre> <div class="block">lightgray string</div> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../../../constant-values.html#org.apache.tools.ant.types.optional.image.ColorMapper.COLOR_LIGHTGRAY">Constant Field Values</a></dd></dl> </li> </ul> <a name="COLOR_DARKGREY"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>COLOR_DARKGREY</h4> <pre>public static final&nbsp;java.lang.String COLOR_DARKGREY</pre> <div class="block">darkgrey string</div> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../../../constant-values.html#org.apache.tools.ant.types.optional.image.ColorMapper.COLOR_DARKGREY">Constant Field Values</a></dd></dl> </li> </ul> <a name="COLOR_GREY"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>COLOR_GREY</h4> <pre>public static final&nbsp;java.lang.String COLOR_GREY</pre> <div class="block">grey string</div> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../../../constant-values.html#org.apache.tools.ant.types.optional.image.ColorMapper.COLOR_GREY">Constant Field Values</a></dd></dl> </li> </ul> <a name="COLOR_LIGHTGREY"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>COLOR_LIGHTGREY</h4> <pre>public static final&nbsp;java.lang.String COLOR_LIGHTGREY</pre> <div class="block">lightgrey string</div> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../../../constant-values.html#org.apache.tools.ant.types.optional.image.ColorMapper.COLOR_LIGHTGREY">Constant Field Values</a></dd></dl> </li> </ul> <a name="COLOR_GREEN"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>COLOR_GREEN</h4> <pre>public static final&nbsp;java.lang.String COLOR_GREEN</pre> <div class="block">green string</div> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../../../constant-values.html#org.apache.tools.ant.types.optional.image.ColorMapper.COLOR_GREEN">Constant Field Values</a></dd></dl> </li> </ul> <a name="COLOR_MAGENTA"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>COLOR_MAGENTA</h4> <pre>public static final&nbsp;java.lang.String COLOR_MAGENTA</pre> <div class="block">magenta string</div> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../../../constant-values.html#org.apache.tools.ant.types.optional.image.ColorMapper.COLOR_MAGENTA">Constant Field Values</a></dd></dl> </li> </ul> <a name="COLOR_ORANGE"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>COLOR_ORANGE</h4> <pre>public static final&nbsp;java.lang.String COLOR_ORANGE</pre> <div class="block">orange string</div> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../../../constant-values.html#org.apache.tools.ant.types.optional.image.ColorMapper.COLOR_ORANGE">Constant Field Values</a></dd></dl> </li> </ul> <a name="COLOR_PINK"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>COLOR_PINK</h4> <pre>public static final&nbsp;java.lang.String COLOR_PINK</pre> <div class="block">pink string</div> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../../../constant-values.html#org.apache.tools.ant.types.optional.image.ColorMapper.COLOR_PINK">Constant Field Values</a></dd></dl> </li> </ul> <a name="COLOR_RED"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>COLOR_RED</h4> <pre>public static final&nbsp;java.lang.String COLOR_RED</pre> <div class="block">reg string</div> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../../../constant-values.html#org.apache.tools.ant.types.optional.image.ColorMapper.COLOR_RED">Constant Field Values</a></dd></dl> </li> </ul> <a name="COLOR_WHITE"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>COLOR_WHITE</h4> <pre>public static final&nbsp;java.lang.String COLOR_WHITE</pre> <div class="block">white string</div> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../../../constant-values.html#org.apache.tools.ant.types.optional.image.ColorMapper.COLOR_WHITE">Constant Field Values</a></dd></dl> </li> </ul> <a name="COLOR_YELLOW"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>COLOR_YELLOW</h4> <pre>public static final&nbsp;java.lang.String COLOR_YELLOW</pre> <div class="block">yellow string</div> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../../../constant-values.html#org.apache.tools.ant.types.optional.image.ColorMapper.COLOR_YELLOW">Constant Field Values</a></dd></dl> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="getColorByName(java.lang.String)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>getColorByName</h4> <pre>public static&nbsp;java.awt.Color&nbsp;getColorByName(java.lang.String&nbsp;colorName)</pre> <div class="block">Convert a color name to a color value.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>colorName</code> - a string repr of the color.</dd> <dt><span class="strong">Returns:</span></dt><dd>the color value.</dd><dt><span class="strong">To do:</span></dt> <dd>refactor to use an EnumeratedAttribute (maybe?)</dd></dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../../org/apache/tools/ant/types/optional/image/BasicShape.html" title="class in org.apache.tools.ant.types.optional.image"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../../../org/apache/tools/ant/types/optional/image/Draw.html" title="class in org.apache.tools.ant.types.optional.image"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/apache/tools/ant/types/optional/image/ColorMapper.html" target="_top">Frames</a></li> <li><a href="ColorMapper.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field_summary">Field</a>&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field_detail">Field</a>&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{'content_hash': 'bd7b227bd06007bad207c15669809c7a', 'timestamp': '', 'source': 'github', 'line_count': 522, 'max_line_length': 235, 'avg_line_length': 39.701149425287355, 'alnum_prop': 0.6436498745415943, 'repo_name': 'p4datasystems/CarnotDE', 'id': '0ea253e0d2e460ee4b6ef25da7855e04c9ec9150', 'size': '20724', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'WDB/ext/apache-ant-1.9.6/manual/api/org/apache/tools/ant/types/optional/image/ColorMapper.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '44495'}, {'name': 'CSS', 'bytes': '96083'}, {'name': 'HTML', 'bytes': '45806649'}, {'name': 'Java', 'bytes': '1495890'}, {'name': 'JavaScript', 'bytes': '11934'}, {'name': 'Perl', 'bytes': '19743'}, {'name': 'Python', 'bytes': '6670'}, {'name': 'Shell', 'bytes': '40496'}, {'name': 'XSLT', 'bytes': '462294'}]}
/* Theme Name: EaseCloud Template Theme URI: http://www.easecloud.cn Author: 逸云科技 Author URI: http://www.easecloud.cn Description: 逸云科技 WordPress 模板 Version: 2.0 License: GNU General Public License v2 or later License URI: http://www.gnu.org/licenses/gpl-2.0.html Tags: white Text Domain: easecloud 逸云科技内部 WordPress 模板,用于快速引入所有常用的组件以及自定义函数,加速模板开发效率。 */ img { max-width: 100%; } a { text-decoration: none; color: inherit; } strong { font-weight: bold; } em { font-style: italic; } del { text-decoration: line-through; } input { font-size: inherit; color: inherit; } .text-left { text-align: left; } .text-right { text-align: right; } .text-center { text-align: center; } .pull-left, .alignleft { float: left; } .pull-right, .alignright { float: right; } .aligncenter { margin-left: auto; margin-right: auto; } .clearfix { clear: both; zoom: 1; } .clearfix::before { content: ""; display: table; } .clearfix::after { content: ""; display: table; clear: both; } .float-wrapper { display: inline-block; width: 100%; zoom: 1; } .nowrap { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .circle { border-radius: 9999px; -webkit-border-radius: 9999px; -moz-border-radius: 9999px; } .wp-caption, .wp-caption-text, .sticky, .gallery-caption, .sticky, .gallery-caption, .bypostauthor { font-size: 1em; }
{'content_hash': '55bbc2d4d45d6537a4b225219ddcf29b', 'timestamp': '', 'source': 'github', 'line_count': 92, 'max_line_length': 53, 'avg_line_length': 14.967391304347826, 'alnum_prop': 0.6761074800290486, 'repo_name': 'nutto/resource', 'id': '4f3cb28d1817ca7d03c8e40f3ff965d431d80466', 'size': '1475', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'wordpress-template/wp-content/themes/mytheme/style.css', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '19674'}, {'name': 'HTML', 'bytes': '3307'}, {'name': 'JavaScript', 'bytes': '49401'}, {'name': 'PHP', 'bytes': '38272'}, {'name': 'TypeScript', 'bytes': '180'}]}
using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices.WindowsRuntime; using System.Runtime.InteropServices; using System.Threading.Tasks; using System.Threading; using Windows.Foundation; using Windows.Storage.Streams; namespace System.IO { /// <summary> /// A <code>Stream</code> used to wrap a Windows Runtime stream to expose it as a managed steam. /// </summary> internal class WinRtToNetFxStreamAdapter : Stream, IDisposable { #region Construction internal static WinRtToNetFxStreamAdapter Create(object windowsRuntimeStream) { if (windowsRuntimeStream == null) throw new ArgumentNullException(nameof(windowsRuntimeStream)); bool canRead = windowsRuntimeStream is IInputStream; bool canWrite = windowsRuntimeStream is IOutputStream; bool canSeek = windowsRuntimeStream is IRandomAccessStream; if (!canRead && !canWrite && !canSeek) throw new ArgumentException(SR.Argument_ObjectMustBeWinRtStreamToConvertToNetFxStream); // Proactively guard against a non-conforming curstomer implementations: if (canSeek) { IRandomAccessStream iras = (IRandomAccessStream)windowsRuntimeStream; if (!canRead && iras.CanRead) throw new ArgumentException(SR.Argument_InstancesImplementingIRASThatCanReadMustImplementIIS); if (!canWrite && iras.CanWrite) throw new ArgumentException(SR.Argument_InstancesImplementingIRASThatCanWriteMustImplementIOS); if (!iras.CanRead) canRead = false; if (!iras.CanWrite) canWrite = false; } if (!canRead && !canWrite) throw new ArgumentException(SR.Argument_WinRtStreamCannotReadOrWrite); return new WinRtToNetFxStreamAdapter(windowsRuntimeStream, canRead, canWrite, canSeek); } private WinRtToNetFxStreamAdapter(object winRtStream, bool canRead, bool canWrite, bool canSeek) { Debug.Assert(winRtStream != null); Debug.Assert(winRtStream is IInputStream || winRtStream is IOutputStream || winRtStream is IRandomAccessStream); Debug.Assert((canSeek && (winRtStream is IRandomAccessStream)) || (!canSeek && !(winRtStream is IRandomAccessStream))); Debug.Assert((canRead && (winRtStream is IInputStream)) || (!canRead && ( !(winRtStream is IInputStream) || (winRtStream is IRandomAccessStream && !((IRandomAccessStream)winRtStream).CanRead) )) ); Debug.Assert((canWrite && (winRtStream is IOutputStream)) || (!canWrite && ( !(winRtStream is IOutputStream) || (winRtStream is IRandomAccessStream && !((IRandomAccessStream)winRtStream).CanWrite) )) ); _winRtStream = winRtStream; _canRead = canRead; _canWrite = canWrite; _canSeek = canSeek; } #endregion Construction #region Instance variables private byte[] _oneByteBuffer = null; private bool _leaveUnderlyingStreamOpen = true; private object _winRtStream; private readonly bool _canRead; private readonly bool _canWrite; private readonly bool _canSeek; #endregion Instance variables #region Tools and Helpers /// <summary> /// We keep tables for mappings between managed and WinRT streams to make sure to always return the same adapter for a given underlying stream. /// However, in order to avoid global locks on those tables, several instances of this type may be created and then can race to be entered /// into the appropriate map table. All except for the winning instances will be thrown away. However, we must ensure that when the losers are /// finalized, the do not dispose the underlying stream. To ensure that, we must call this method on the winner to notify it that it is safe to /// dispose the underlying stream. /// </summary> internal void SetWonInitializationRace() { _leaveUnderlyingStreamOpen = false; } public TWinRtStream GetWindowsRuntimeStream<TWinRtStream>() where TWinRtStream : class { object wrtStr = _winRtStream; if (wrtStr == null) return null; Debug.Assert(wrtStr is TWinRtStream, $"Attempted to get the underlying WinRT stream typed as \"{typeof(TWinRtStream)}\", " + $"but the underlying WinRT stream cannot be cast to that type. Its actual type is \"{wrtStr.GetType()}\"."); return wrtStr as TWinRtStream; } private byte[] OneByteBuffer { get { byte[] obb = _oneByteBuffer; if (obb == null) // benign race for multiple init _oneByteBuffer = obb = new byte[1]; return obb; } } #if DEBUG private static void AssertValidStream(object winRtStream) { Debug.Assert(winRtStream != null, "This to-NetFx Stream adapter must not be disposed and the underlying WinRT stream must be of compatible type for this operation"); } #endif // DEBUG private TWinRtStream EnsureNotDisposed<TWinRtStream>() where TWinRtStream : class { object wrtStr = _winRtStream; if (wrtStr == null) throw new ObjectDisposedException(SR.ObjectDisposed_CannotPerformOperation); return (wrtStr as TWinRtStream); } private void EnsureNotDisposed() { if (_winRtStream == null) throw new ObjectDisposedException(SR.ObjectDisposed_CannotPerformOperation); } private void EnsureCanRead() { if (!_canRead) throw new NotSupportedException(SR.NotSupported_CannotReadFromStream); } private void EnsureCanWrite() { if (!_canWrite) throw new NotSupportedException(SR.NotSupported_CannotWriteToStream); } #endregion Tools and Helpers #region Simple overrides protected override void Dispose(bool disposing) { // WinRT streams should implement IDisposable (IClosable in WinRT), but let's be defensive: if (disposing && _winRtStream != null && !_leaveUnderlyingStreamOpen) { IDisposable disposableWinRtStream = _winRtStream as IDisposable; // benign race on winRtStream if (disposableWinRtStream != null) disposableWinRtStream.Dispose(); } _winRtStream = null; base.Dispose(disposing); } public override bool CanRead { [Pure] get { return (_canRead && _winRtStream != null); } } public override bool CanWrite { [Pure] get { return (_canWrite && _winRtStream != null); } } public override bool CanSeek { [Pure] get { return (_canSeek && _winRtStream != null); } } #endregion Simple overrides #region Length and Position functions public override long Length { get { IRandomAccessStream wrtStr = EnsureNotDisposed<IRandomAccessStream>(); if (!_canSeek) throw new NotSupportedException(SR.NotSupported_CannotUseLength_StreamNotSeekable); #if DEBUG AssertValidStream(wrtStr); #endif // DEBUG ulong size = wrtStr.Size; // These are over 8000 PetaBytes, we do not expect this to happen. However, let's be defensive: if (size > (ulong)long.MaxValue) throw new IOException(SR.IO_UnderlyingWinRTStreamTooLong_CannotUseLengthOrPosition); return unchecked((long)size); } } public override long Position { get { IRandomAccessStream wrtStr = EnsureNotDisposed<IRandomAccessStream>(); if (!_canSeek) throw new NotSupportedException(SR.NotSupported_CannotUsePosition_StreamNotSeekable); #if DEBUG AssertValidStream(wrtStr); #endif // DEBUG ulong pos = wrtStr.Position; // These are over 8000 PetaBytes, we do not expect this to happen. However, let's be defensive: if (pos > (ulong)long.MaxValue) throw new IOException(SR.IO_UnderlyingWinRTStreamTooLong_CannotUseLengthOrPosition); return unchecked((long)pos); } set { if (value < 0) throw new ArgumentOutOfRangeException("Position", SR.ArgumentOutOfRange_IO_CannotSeekToNegativePosition); IRandomAccessStream wrtStr = EnsureNotDisposed<IRandomAccessStream>(); if (!_canSeek) throw new NotSupportedException(SR.NotSupported_CannotUsePosition_StreamNotSeekable); #if DEBUG AssertValidStream(wrtStr); #endif // DEBUG wrtStr.Seek(unchecked((ulong)value)); } } public override long Seek(long offset, SeekOrigin origin) { IRandomAccessStream wrtStr = EnsureNotDisposed<IRandomAccessStream>(); if (!_canSeek) throw new NotSupportedException(SR.NotSupported_CannotSeekInStream); #if DEBUG AssertValidStream(wrtStr); #endif // DEBUG switch (origin) { case SeekOrigin.Begin: { Position = offset; return offset; } case SeekOrigin.Current: { long curPos = Position; if (long.MaxValue - curPos < offset) throw new IOException(SR.IO_CannotSeekBeyondInt64MaxValue); long newPos = curPos + offset; if (newPos < 0) throw new IOException(SR.ArgumentOutOfRange_IO_CannotSeekToNegativePosition); Position = newPos; return newPos; } case SeekOrigin.End: { ulong size = wrtStr.Size; long newPos; if (size > (ulong)long.MaxValue) { if (offset >= 0) throw new IOException(SR.IO_CannotSeekBeyondInt64MaxValue); Debug.Assert(offset < 0); ulong absOffset = (offset == long.MinValue) ? ((ulong)long.MaxValue) + 1 : (ulong)(-offset); Debug.Assert(absOffset <= size); ulong np = size - absOffset; if (np > (ulong)long.MaxValue) throw new IOException(SR.IO_CannotSeekBeyondInt64MaxValue); newPos = (long)np; } else { Debug.Assert(size <= (ulong)long.MaxValue); long s = unchecked((long)size); if (long.MaxValue - s < offset) throw new IOException(SR.IO_CannotSeekBeyondInt64MaxValue); newPos = s + offset; if (newPos < 0) throw new IOException(SR.ArgumentOutOfRange_IO_CannotSeekToNegativePosition); } Position = newPos; return newPos; } default: { throw new ArgumentException(SR.Argument_InvalidSeekOrigin, nameof(origin)); } } } public override void SetLength(long value) { if (value < 0) throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_CannotResizeStreamToNegative); IRandomAccessStream wrtStr = EnsureNotDisposed<IRandomAccessStream>(); if (!_canSeek) throw new NotSupportedException(SR.NotSupported_CannotSeekInStream); EnsureCanWrite(); #if DEBUG AssertValidStream(wrtStr); #endif // DEBUG wrtStr.Size = unchecked((ulong)value); // If the length is set to a value < that the current position, then we need to set the position to that value // Because we can't directly set the position, we are going to seek to it. if (wrtStr.Size < wrtStr.Position) wrtStr.Seek(unchecked((ulong)value)); } #endregion Length and Position functions #region Reading private IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state, bool usedByBlockingWrapper) { // This method is somewhat tricky: We could consider just calling ReadAsync (recall that Task implements IAsyncResult). // It would be OK for cases where BeginRead is invoked directly by the public user. // However, in cases where it is invoked by Read to achieve a blocking (synchronous) IO operation, the ReadAsync-approach may deadlock: // // The sync-over-async IO operation will be doing a blocking wait on the completion of the async IO operation assuming that // a wait handle would be signalled by the completion handler. Recall that the IAsyncInfo representing the IO operation may // not be free-threaded and not "free-marshalled"; it may also belong to an ASTA compartment because the underlying WinRT // stream lives in an ASTA compartment. The completion handler is invoked on a pool thread, i.e. in MTA. // That handler needs to fetch the results from the async IO operation, which requires a cross-compartment call from MTA into ASTA. // But because the ASTA thread is busy waiting this call will deadlock. // (Recall that although WaitOne pumps COM, ASTA specifically schedules calls on the outermost ?idle? pump only.) // // The solution is to make sure that: // - In cases where main thread is waiting for the async IO to complete: // Fetch results on the main thread after it has been signalled by the completion callback. // - In cases where main thread is not waiting for the async IO to complete: // Fetch results in the completion callback. // // But the Task-plumbing around IAsyncInfo.AsTask *always* fetches results in the completion handler because it has // no way of knowing whether or not someone is waiting. So, instead of using ReadAsync here we implement our own IAsyncResult // and our own completion handler which can behave differently according to whether it is being used by a blocking IO // operation wrapping a BeginRead/EndRead pair, or by an actual async operation based on the old Begin/End pattern. if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count)); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InsufficientSpaceInTargetBuffer); IInputStream wrtStr = EnsureNotDisposed<IInputStream>(); EnsureCanRead(); #if DEBUG AssertValidStream(wrtStr); #endif // DEBUG IBuffer userBuffer = buffer.AsBuffer(offset, count); IAsyncOperationWithProgress<IBuffer, uint> asyncReadOperation = wrtStr.ReadAsync(userBuffer, unchecked((uint)count), InputStreamOptions.Partial); StreamReadAsyncResult asyncResult = new StreamReadAsyncResult(asyncReadOperation, userBuffer, callback, state, processCompletedOperationInCallback: !usedByBlockingWrapper); // The StreamReadAsyncResult will set a private instance method to act as a Completed handler for asyncOperation. // This will cause a CCW to be created for the delegate and the delegate has a reference to its target, i.e. to // asyncResult, so asyncResult will not be collected. If we loose the entire AppDomain, then asyncResult and its CCW // will be collected but the stub will remain and the callback will fail gracefully. The underlying buffer is the only // item to which we expose a direct pointer and this is properly pinned using a mechanism similar to Overlapped. return asyncResult; } public override int EndRead(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException(nameof(asyncResult)); EnsureNotDisposed(); EnsureCanRead(); StreamOperationAsyncResult streamAsyncResult = asyncResult as StreamOperationAsyncResult; if (streamAsyncResult == null) throw new ArgumentException(SR.Argument_UnexpectedAsyncResult, nameof(asyncResult)); streamAsyncResult.Wait(); try { // If the async result did NOT process the async IO operation in its completion handler (i.e. check for errors, // cache results etc), then we need to do that processing now. This is to allow blocking-over-async IO operations. // See the big comment in BeginRead for details. if (!streamAsyncResult.ProcessCompletedOperationInCallback) streamAsyncResult.ProcessCompletedOperation(); // Rethrow errors caught in the completion callback, if any: if (streamAsyncResult.HasError) { streamAsyncResult.CloseStreamOperation(); streamAsyncResult.ThrowCachedError(); } // Done: long bytesCompleted = streamAsyncResult.BytesCompleted; Debug.Assert(bytesCompleted <= unchecked((long)int.MaxValue)); return (int)bytesCompleted; } finally { // Closing multiple times is Ok. streamAsyncResult.CloseStreamOperation(); } } public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count)); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InsufficientSpaceInTargetBuffer); EnsureNotDisposed(); EnsureCanRead(); // If already cancelled, bail early: cancellationToken.ThrowIfCancellationRequested(); // State is Ok. Do the actual read: return ReadAsyncInternal(buffer, offset, count, cancellationToken); } public override int Read(byte[] buffer, int offset, int count) { // Arguments validation and not-disposed validation are done in BeginRead. IAsyncResult asyncResult = BeginRead(buffer, offset, count, null, null, usedByBlockingWrapper: true); int bytesRead = EndRead(asyncResult); return bytesRead; } public override int ReadByte() { // EnsureNotDisposed will be called in Read->BeginRead. byte[] oneByteArray = OneByteBuffer; if (0 == Read(oneByteArray, 0, 1)) return -1; int value = oneByteArray[0]; return value; } #endregion Reading #region Writing public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { return BeginWrite(buffer, offset, count, callback, state, usedByBlockingWrapper: false); } private IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state, bool usedByBlockingWrapper) { // See the large comment in BeginRead about why we are not using this.WriteAsync, // and instead using a custom implementation of IAsyncResult. if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count)); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset); IOutputStream wrtStr = EnsureNotDisposed<IOutputStream>(); EnsureCanWrite(); #if DEBUG AssertValidStream(wrtStr); #endif // DEBUG IBuffer asyncWriteBuffer = buffer.AsBuffer(offset, count); IAsyncOperationWithProgress<uint, uint> asyncWriteOperation = wrtStr.WriteAsync(asyncWriteBuffer); StreamWriteAsyncResult asyncResult = new StreamWriteAsyncResult(asyncWriteOperation, callback, state, processCompletedOperationInCallback: !usedByBlockingWrapper); // The StreamReadAsyncResult will set a private instance method to act as a Completed handler for asyncOperation. // This will cause a CCW to be created for the delegate and the delegate has a reference to its target, i.e. to // asyncResult, so asyncResult will not be collected. If we loose the entire AppDomain, then asyncResult and its CCW // will be collected but the stub will remain and the callback will fail gracefully. The underlying buffer if the only // item to which we expose a direct pointer and this is properly pinned using a mechanism similar to Overlapped. return asyncResult; } public override void EndWrite(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException(nameof(asyncResult)); EnsureNotDisposed(); EnsureCanWrite(); StreamOperationAsyncResult streamAsyncResult = asyncResult as StreamOperationAsyncResult; if (streamAsyncResult == null) throw new ArgumentException(SR.Argument_UnexpectedAsyncResult, nameof(asyncResult)); streamAsyncResult.Wait(); try { // If the async result did NOT process the async IO operation in its completion handler (i.e. check for errors, // cache results etc), then we need to do that processing now. This is to allow blocking-over-async IO operations. // See the big comment in BeginWrite for details. if (!streamAsyncResult.ProcessCompletedOperationInCallback) streamAsyncResult.ProcessCompletedOperation(); // Rethrow errors caught in the completion callback, if any: if (streamAsyncResult.HasError) { streamAsyncResult.CloseStreamOperation(); streamAsyncResult.ThrowCachedError(); } } finally { // Closing multiple times is Ok. streamAsyncResult.CloseStreamOperation(); } } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count)); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset); IOutputStream wrtStr = EnsureNotDisposed<IOutputStream>(); EnsureCanWrite(); #if DEBUG AssertValidStream(wrtStr); #endif // DEBUG // If already cancelled, bail early: cancellationToken.ThrowIfCancellationRequested(); IBuffer asyncWriteBuffer = buffer.AsBuffer(offset, count); IAsyncOperationWithProgress<uint, uint> asyncWriteOperation = wrtStr.WriteAsync(asyncWriteBuffer); Task asyncWriteTask = asyncWriteOperation.AsTask(cancellationToken); // The underlying IBuffer is the only object to which we expose a direct pointer to native, // and that is properly pinned using a mechanism similar to Overlapped. return asyncWriteTask; } public override void Write(byte[] buffer, int offset, int count) { // Arguments validation and not-disposed validation are done in BeginWrite. IAsyncResult asyncResult = BeginWrite(buffer, offset, count, null, null, usedByBlockingWrapper: true); EndWrite(asyncResult); } public override void WriteByte(byte value) { // EnsureNotDisposed will be called in Write->BeginWrite. byte[] oneByteArray = OneByteBuffer; oneByteArray[0] = value; Write(oneByteArray, 0, 1); } #endregion Writing #region Flushing public override void Flush() { // See the large comment in BeginRead about why we are not using this.FlushAsync, // and instead using a custom implementation of IAsyncResult. IOutputStream wrtStr = EnsureNotDisposed<IOutputStream>(); // Calling Flush in a non-writable stream is a no-op, not an error: if (!_canWrite) return; #if DEBUG AssertValidStream(wrtStr); #endif // DEBUG IAsyncOperation<bool> asyncFlushOperation = wrtStr.FlushAsync(); StreamFlushAsyncResult asyncResult = new StreamFlushAsyncResult(asyncFlushOperation, processCompletedOperationInCallback: false); asyncResult.Wait(); try { // We got signaled, so process the async Flush operation back on this thread: // (This is to allow blocking-over-async IO operations. See the big comment in BeginRead for details.) asyncResult.ProcessCompletedOperation(); // Rethrow errors cached by the async result, if any: if (asyncResult.HasError) { asyncResult.CloseStreamOperation(); asyncResult.ThrowCachedError(); } } finally { // Closing multiple times is Ok. asyncResult.CloseStreamOperation(); } } public override Task FlushAsync(CancellationToken cancellationToken) { IOutputStream wrtStr = EnsureNotDisposed<IOutputStream>(); // Calling Flush in a non-writable stream is a no-op, not an error: if (!_canWrite) return Task.CompletedTask; #if DEBUG AssertValidStream(wrtStr); #endif // DEBUG cancellationToken.ThrowIfCancellationRequested(); IAsyncOperation<bool> asyncFlushOperation = wrtStr.FlushAsync(); Task asyncFlushTask = asyncFlushOperation.AsTask(cancellationToken); return asyncFlushTask; } #endregion Flushing #region ReadAsyncInternal implementation // Moved it to the end while using Dev10 VS because it does not understand async and everything that follows looses intellisense. // Should move this code into the Reading regios once using Dev11 VS becomes the norm. private async Task<int> ReadAsyncInternal(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { Debug.Assert(buffer != null); Debug.Assert(offset >= 0); Debug.Assert(count >= 0); Debug.Assert(buffer.Length - offset >= count); Debug.Assert(_canRead); IInputStream wrtStr = EnsureNotDisposed<IInputStream>(); #if DEBUG AssertValidStream(wrtStr); #endif // DEBUG try { IBuffer userBuffer = buffer.AsBuffer(offset, count); IAsyncOperationWithProgress<IBuffer, uint> asyncReadOperation = wrtStr.ReadAsync(userBuffer, unchecked((uint)count), InputStreamOptions.Partial); IBuffer resultBuffer = await asyncReadOperation.AsTask(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); // If cancellationToken was cancelled until now, then we are currently propagating the corresponding cancellation exception. // (It will be correctly rethrown by the catch block below and overall we will return a cancelled task.) // But if the underlying operation managed to complete before it was cancelled, we want // the entire task to complete as well. This is ok as the continuation is very lightweight: if (resultBuffer == null) return 0; WinRtIOHelper.EnsureResultsInUserBuffer(userBuffer, resultBuffer); Debug.Assert(resultBuffer.Length <= unchecked((uint)int.MaxValue)); return (int)resultBuffer.Length; } catch (Exception ex) { // If the interop layer gave us an Exception, we assume that it hit a general/unknown case and wrap it into // an IOException as this is what Stream users expect. WinRtIOHelper.NativeExceptionToIOExceptionInfo(ex).Throw(); return 0; } } #endregion ReadAsyncInternal implementation } // class WinRtToNetFxStreamAdapter } // namespace // WinRtToNetFxStreamAdapter.cs
{'content_hash': '21397dfe545c7865aa8a8283f637787e', 'timestamp': '', 'source': 'github', 'line_count': 827, 'max_line_length': 159, 'avg_line_length': 38.851269649334945, 'alnum_prop': 0.5823529411764706, 'repo_name': 'wtgodbe/corefx', 'id': '796e65d2962a45a319cb055fd06d92397902736a', 'size': '32334', 'binary': False, 'copies': '22', 'ref': 'refs/heads/master', 'path': 'src/System.Runtime.WindowsRuntime/src/System/IO/WinRtToNetFxStreamAdapter.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': '1C Enterprise', 'bytes': '280724'}, {'name': 'ASP', 'bytes': '1687'}, {'name': 'Batchfile', 'bytes': '11027'}, {'name': 'C', 'bytes': '3803475'}, {'name': 'C#', 'bytes': '181225579'}, {'name': 'C++', 'bytes': '1521'}, {'name': 'CMake', 'bytes': '79434'}, {'name': 'DIGITAL Command Language', 'bytes': '26402'}, {'name': 'HTML', 'bytes': '653'}, {'name': 'Makefile', 'bytes': '13780'}, {'name': 'OpenEdge ABL', 'bytes': '137969'}, {'name': 'Perl', 'bytes': '3895'}, {'name': 'PowerShell', 'bytes': '192527'}, {'name': 'Python', 'bytes': '1535'}, {'name': 'Roff', 'bytes': '9422'}, {'name': 'Shell', 'bytes': '131260'}, {'name': 'TSQL', 'bytes': '96941'}, {'name': 'Visual Basic', 'bytes': '2135715'}, {'name': 'XSLT', 'bytes': '514720'}]}
package br.com.its.web.controller; import javax.ws.rs.Path; import org.springframework.stereotype.Controller; @Controller @Path("/example") public class ExampleController { }
{'content_hash': '3c9488fa235a4e50a9e9d72e5cfa3456', 'timestamp': '', 'source': 'github', 'line_count': 11, 'max_line_length': 49, 'avg_line_length': 16.272727272727273, 'alnum_prop': 0.7821229050279329, 'repo_name': 'ITSStartup/archetypewebappsmodule', 'id': 'c663f4dce703d55c542723c2c95f9a2a6d485b90', 'size': '265', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'src/main/resources/archetype-resources/webapps-web/src/main/java/br/com/its/web/controller/ExampleController.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '8620'}]}
using System; using System.Collections.Generic; using EnvDTE; using EnvDTE80; using Microsoft.SqlServer.TransactSql.ScriptDom; namespace Devvcat.SSMS { sealed class Executor { public readonly string CMD_QUERY_EXECUTE = "Query.Execute"; private Document document; private EditPoint oldAnchor; private EditPoint oldActivePoint; public Executor(DTE2 dte) { if (dte == null) throw new ArgumentNullException(nameof(dte)); document = dte.GetDocument(); SaveActiveAndAnchorPoints(); } private VirtualPoint GetCaretPoint() { var p = ((TextSelection)document.Selection).ActivePoint; return new VirtualPoint(p); } private string GetDocumentText() { var content = string.Empty; var selection = (TextSelection)document.Selection; if (!selection.IsEmpty) { content = selection.Text; } else { if (document.Object("TextDocument") is TextDocument doc) { content = doc.StartPoint.CreateEditPoint().GetText(doc.EndPoint); } } return content; } private void SaveActiveAndAnchorPoints() { var selection = (TextSelection)document.Selection; oldAnchor = selection.AnchorPoint.CreateEditPoint(); oldActivePoint = selection.ActivePoint.CreateEditPoint(); } private void RestoreActiveAndAnchorPoints() { var startPoint = new VirtualPoint(oldAnchor); var endPoint = new VirtualPoint(oldActivePoint); MakeSelection(startPoint, endPoint); } private void MakeSelection(VirtualPoint startPoint, VirtualPoint endPoint) { var selection = (TextSelection)document.Selection; selection.MoveToLineAndOffset(startPoint.Line, startPoint.LineCharOffset); selection.SwapAnchor(); selection.MoveToLineAndOffset(endPoint.Line, endPoint.LineCharOffset, true); } private bool ParseSqlFragments(string script, out TSqlScript sqlFragments) { IList<ParseError> errors; TSql140Parser parser = new TSql140Parser(true); using (System.IO.StringReader reader = new System.IO.StringReader(script)) { sqlFragments = parser.Parse(reader, out errors) as TSqlScript; } return errors.Count == 0; } private IList<TSqlStatement> GetInnerStatements(TSqlStatement statement) { List<TSqlStatement> list = new List<TSqlStatement>(); if (statement is BeginEndBlockStatement block) { list.AddRange(block.StatementList.Statements); } else if (statement is IfStatement ifBlock) { if (ifBlock.ThenStatement != null) { list.Add(ifBlock.ThenStatement); } if (ifBlock.ElseStatement != null) { list.Add(ifBlock.ElseStatement); } } else if (statement is WhileStatement whileBlock) { list.Add(whileBlock.Statement); } return list; } private bool IsCaretInsideStatement(TSqlStatement statement, VirtualPoint caret) { var ft = statement.ScriptTokenStream[statement.FirstTokenIndex]; var lt = statement.ScriptTokenStream[statement.LastTokenIndex]; if (caret.Line >= ft.Line && caret.Line <= lt.Line) { var isBeforeFirstToken = caret.Line == ft.Line && caret.LineCharOffset < ft.Column; var isAfterLastToken = caret.Line == lt.Line && caret.LineCharOffset > lt.Column + lt.Text.Length; if (!(isBeforeFirstToken || isAfterLastToken)) { return true; } } return false; } private TextBlock GetTextBlockFromStatement(TSqlStatement statement) { var ft = statement.ScriptTokenStream[statement.FirstTokenIndex]; var lt = statement.ScriptTokenStream[statement.LastTokenIndex]; return new TextBlock() { StartPoint = new VirtualPoint { Line = ft.Line, LineCharOffset = ft.Column }, EndPoint = new VirtualPoint { Line = lt.Line, LineCharOffset = lt.Column + lt.Text.Length } }; } private TextBlock FindCurrentStatement(IList<TSqlStatement> statements, VirtualPoint caret, ExecScope scope) { if (statements == null || statements.Count == 0) { return null; } foreach (var statement in statements) { if (scope == ExecScope.Inner) { IList<TSqlStatement> statementList = GetInnerStatements(statement); TextBlock currentStatement = FindCurrentStatement(statementList, caret, scope); if (currentStatement != null) { return currentStatement; } } if (IsCaretInsideStatement(statement, caret)) { return GetTextBlockFromStatement(statement); } } return null; } private void Exec() { document.DTE.ExecuteCommand(CMD_QUERY_EXECUTE); } private bool CanExecute() { try { var cmd = document.DTE.Commands.Item(CMD_QUERY_EXECUTE, -1); return cmd.IsAvailable; } catch { } return false; } public void ExecuteStatement(ExecScope scope = ExecScope.Block) { if (!CanExecute()) { return; } SaveActiveAndAnchorPoints(); if (!(document.Selection as TextSelection).IsEmpty) { Exec(); } else { var script = GetDocumentText(); var caretPoint = GetCaretPoint(); bool success = ParseSqlFragments(script, out TSqlScript sqlScript); if (success) { TextBlock currentStatement = null; foreach (var batch in sqlScript?.Batches) { currentStatement = FindCurrentStatement(batch.Statements, caretPoint, scope); if (currentStatement != null) { break; } } if (currentStatement != null) { // select the statement to be executed MakeSelection(currentStatement.StartPoint, currentStatement.EndPoint); // execute the statement Exec(); // restore selection RestoreActiveAndAnchorPoints(); } } else { // there are syntax errors // execute anyway to show the errors Exec(); } } } public class VirtualPoint { public int Line { get; set; } public int LineCharOffset { get; set; } public VirtualPoint() { Line = 1; LineCharOffset = 0; } public VirtualPoint(EnvDTE.TextPoint point) { Line = point.Line; LineCharOffset = point.LineCharOffset; } } public class TextBlock { public VirtualPoint StartPoint { get; set; } public VirtualPoint EndPoint { get; set; } } internal enum ExecScope { Block, Inner } } }
{'content_hash': 'b900e2a3d3c27ae6004438d80d9c6a79', 'timestamp': '', 'source': 'github', 'line_count': 293, 'max_line_length': 116, 'avg_line_length': 29.238907849829353, 'alnum_prop': 0.49655655421968015, 'repo_name': 'devvcat/ssms-executor', 'id': '9c85413b60699c37f84f8aca453465a9f73e7c59', 'size': '8569', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'SSMSExecutor/Executor.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '837'}, {'name': 'C#', 'bytes': '16701'}, {'name': 'Inno Setup', 'bytes': '7344'}]}
(function() { var Client, _, packageJson, request, util; request = require('request'); util = require('util'); packageJson = require('../package.json'); _ = require('lodash'); Client = (function() { Client.prototype.endpoint = 'https://metrics-api.librato.com/v1'; function Client(arg) { var email, requestOptions, simulate, token; email = arg.email, token = arg.token, simulate = arg.simulate, requestOptions = arg.requestOptions; if (!email || !token) { if (!simulate) { console.warn("librato-node metrics disabled: no email or token provided."); } } else { this._requestOptions = _.defaults(requestOptions || {}, { method: 'POST', uri: this.endpoint + "/metrics", headers: {} }); this._requestOptions.headers = _.defaults(this._requestOptions.headers, { authorization: 'Basic ' + new Buffer(email + ":" + token).toString('base64'), 'user-agent': "librato-rack/0.4.5 (compatible; librato-node/" + packageJson.version + ")" }); } } Client.prototype.send = function(json, cb) { var requestOptions; if (this._requestOptions == null) { return process.nextTick(cb); } requestOptions = _.extend({}, this._requestOptions, { json: json }); return request(requestOptions, function(err, res, body) { if (err != null) { return cb(err); } if (res.statusCode > 399 || ((body != null ? body.errors : void 0) != null)) { return cb(new Error("Error sending to Librato: " + (util.inspect(body, { depth: null })) + " (statusCode: " + res.statusCode + ")")); } return cb(null, body); }); }; return Client; })(); module.exports = Client; }).call(this); //# sourceMappingURL=client.js.map
{'content_hash': 'a78e58ab5c4f0211f6888ce21f6d53e0', 'timestamp': '', 'source': 'github', 'line_count': 64, 'max_line_length': 105, 'avg_line_length': 29.6875, 'alnum_prop': 0.5594736842105263, 'repo_name': 'prodatakey/librato-node', 'id': '7668bc4c8bfa5ab3c3af05bbdbb10cd47111a0b6', 'size': '1935', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/client.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CoffeeScript', 'bytes': '20646'}]}
/* This file is part of the WebKit open source project. This file has been generated by generate-bindings.pl. DO NOT MODIFY! This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #if ENABLE(SVG) #ifndef V8SVGAnimatedEnumeration_h #define V8SVGAnimatedEnumeration_h #include "SVGAnimatedEnumeration.h" #include "V8DOMWrapper.h" #include "WrapperTypeInfo.h" #include <wtf/text/StringHash.h> #include <v8.h> #include <wtf/HashMap.h> namespace WebCore { class V8SVGAnimatedEnumeration { public: static const bool hasDependentLifetime = true; static bool HasInstance(v8::Handle<v8::Value> value); static v8::Persistent<v8::FunctionTemplate> GetRawTemplate(); static v8::Persistent<v8::FunctionTemplate> GetTemplate(); static SVGAnimatedEnumeration* toNative(v8::Handle<v8::Object> object) { return reinterpret_cast<SVGAnimatedEnumeration*>(object->GetPointerFromInternalField(v8DOMWrapperObjectIndex)); } inline static v8::Handle<v8::Object> wrap(SVGAnimatedEnumeration*); static void derefObject(void*); static WrapperTypeInfo info; static const int internalFieldCount = v8DefaultWrapperInternalFieldCount + 0; private: static v8::Handle<v8::Object> wrapSlow(SVGAnimatedEnumeration*); }; v8::Handle<v8::Object> V8SVGAnimatedEnumeration::wrap(SVGAnimatedEnumeration* impl) { v8::Handle<v8::Object> wrapper = getDOMObjectMap().get(impl); if (!wrapper.IsEmpty()) return wrapper; return V8SVGAnimatedEnumeration::wrapSlow(impl); } inline v8::Handle<v8::Value> toV8(SVGAnimatedEnumeration* impl) { if (!impl) return v8::Null(); return V8SVGAnimatedEnumeration::wrap(impl); } inline v8::Handle<v8::Value> toV8(PassRefPtr< SVGAnimatedEnumeration > impl) { return toV8(impl.get()); } } #endif // V8SVGAnimatedEnumeration_h #endif // ENABLE(SVG)
{'content_hash': 'be498bd1c12015ac7135ef7cbca3dc90', 'timestamp': '', 'source': 'github', 'line_count': 76, 'max_line_length': 119, 'avg_line_length': 34.01315789473684, 'alnum_prop': 0.7369439071566731, 'repo_name': 'Treeeater/WebPermission', 'id': 'bfbfac9cb0c49989b1cebe57d960974b4e558c12', 'size': '2585', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src_chrome_Release_obj_global_intermediate_webkit/bindings/V8SVGAnimatedEnumeration.h', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'Assembly', 'bytes': '1301'}, {'name': 'C', 'bytes': '1820540'}, {'name': 'C++', 'bytes': '38574524'}, {'name': 'Java', 'bytes': '4882'}, {'name': 'JavaScript', 'bytes': '2238901'}, {'name': 'Objective-C', 'bytes': '1768529'}, {'name': 'PHP', 'bytes': '606'}, {'name': 'Perl', 'bytes': '699893'}, {'name': 'Prolog', 'bytes': '142937'}, {'name': 'Python', 'bytes': '131318'}, {'name': 'R', 'bytes': '290'}, {'name': 'Ruby', 'bytes': '3798'}, {'name': 'Shell', 'bytes': '52312'}]}
#ifndef AliAnalysisTaskSEXicPlus2XiPiPifromAODtracks_H #define AliAnalysisTaskSEXicPlus2XiPiPifromAODtracks_H /* $Id$ */ #include "TROOT.h" #include "TSystem.h" #include "AliAnalysisTaskSE.h" #include "AliAODEvent.h" #include "AliPID.h" #include "AliRDHFCuts.h" //jcho #include "AliRDHFCutsXicPlustoXiPiPifromAODtracks.h" /// \class AliAnalysisTaskSEXicPlus2XiPiPifromAODtracks class THnSparse; class TH1F; class TH2F; class TH3F; class TClonesArray; class AliAODRecoCascadeHF3Prong; class AliAODPidHF; class AliESDtrackCuts; class AliESDVertex; class AliAODMCParticle; class AliNormalizationCounter; class AliAnalysisTaskSEXicPlus2XiPiPifromAODtracks : public AliAnalysisTaskSE { public: enum ECandStatus {kGenLimAcc,kGenAccMother,kGenAccMother08,kGenAcc,kGenAcc08,kReco,kReco08,kRecoCuts,kRecoCuts08,kRecoPID,kRecoPID08}; AliAnalysisTaskSEXicPlus2XiPiPifromAODtracks(); AliAnalysisTaskSEXicPlus2XiPiPifromAODtracks(const Char_t* name, AliRDHFCutsXicPlustoXiPiPifromAODtracks* cuts, Bool_t writeVariableTree=kTRUE, Bool_t fillSparse=kFALSE, Bool_t HMTrigOn=kFALSE); virtual ~AliAnalysisTaskSEXicPlus2XiPiPifromAODtracks(); /// Implementation of interface methods virtual void UserCreateOutputObjects(); virtual void Init(); virtual void LocalInit() {Init();} virtual void UserExec(Option_t *option); virtual void Terminate(Option_t *option); void FillROOTObjects(AliAODRecoCascadeHF3Prong *xicobj, AliAODMCParticle *mcpart, AliAODMCParticle *mcdau1, AliAODMCParticle *mcdau2, AliAODMCParticle *mcdauxi, Int_t mcnused, Bool_t isXiC, Int_t checkOrigin); void MakeAnalysis(AliAODEvent *aod, TClonesArray *mcArray, AliAODMCHeader *mcHeader); /// set MC usage void SetMC(Bool_t theMCon) {fUseMCInfo = theMCon;} Bool_t GetMC() const {return fUseMCInfo;} void SetFillSignalOnly(Bool_t signalOnly) {fFillSignalOnly = signalOnly;} Bool_t GetFillSignalOnly() const {return fFillSignalOnly;} void SetFillBkgOnly(Bool_t bkgOnly) {fFillBkgOnly = bkgOnly;} Bool_t GetFillBkgOnly() const {return fFillBkgOnly;} void SetReconstructPrimVert(Bool_t a) { fReconstructPrimVert=a; } void SelectCascade( const AliVEvent *event,Int_t nCascades,Int_t &nSeleCasc, Bool_t *seleCascFlags); void SelectTrack( const AliVEvent *event, Int_t trkEntries, Int_t &nSeleTrks,Bool_t *seleFlags); void SelectTrackForUpgradeITS3( const AliVEvent *event, Int_t trkEntries, Int_t &nSeleTrks, Bool_t *seleFlags, TClonesArray *mcArray, AliAODMCHeader *mcHeader ); Bool_t SelectLikeSign(AliAODTrack *trk1, AliAODTrack *trk2); AliAODRecoCascadeHF3Prong* MakeCascadeHF3Prong(AliAODcascade *casc, AliAODTrack *trk1, AliAODTrack *trk2, AliAODEvent *aod, AliAODVertex *secvert, Double_t dispersion); void LoopOverGenParticles(TClonesArray *mcArray); Int_t CheckXic2XiPiPi(TClonesArray* arrayMC, AliAODMCParticle *mcPart, Int_t* arrayDauLab); void SetITS3UpgradeAnalysis(Bool_t isITS3Upgrade) {fIsXicPlusUpgradeITS3=isITS3Upgrade;} void SetRejFactorBkgUpgrade(Double_t rejFactor){fRejFactorBkgUpgrade=rejFactor;} // For HM analysis (Refer to Semileptonic Xic0)---------------------------- jcho void UseTrig_kINT7(void) { fUsekINT7 = kTRUE; } void UseTrig_kHMV0(void) { fUsekHMV0 = kTRUE; } void UseTrig_kHMSPD(void) { fUsekHMVSPD = kTRUE; } private: AliAnalysisTaskSEXicPlus2XiPiPifromAODtracks(const AliAnalysisTaskSEXicPlus2XiPiPifromAODtracks &source); AliAnalysisTaskSEXicPlus2XiPiPifromAODtracks& operator=(const AliAnalysisTaskSEXicPlus2XiPiPifromAODtracks& source); void DefineTreeVariables(); void DefineGeneralHistograms(); void DefineAnalysisHistograms(); AliAODVertex *CallPrimaryVertex(AliAODcascade *casc, AliAODTrack *trk1, AliAODTrack *trk2, AliAODEvent *evt); AliAODVertex* PrimaryVertex(const TObjArray *trkArray,AliVEvent *event); AliAODVertex* CallReconstructSecondaryVertex(AliAODTrack *trk1, AliAODTrack *trk2,Double_t &disp); AliAODVertex* ReconstructSecondaryVertex(TObjArray *trkArray, Double_t &dispersion,Bool_t useTRefArray=kTRUE); Bool_t fUseMCInfo; /// Use MC info Bool_t fFillSignalOnly; /// Fill only the signal in MC Bool_t fFillBkgOnly; /// Fill only the bkg in MC TList *fOutput; //!<! User output slot 1 // general histos TList *fOutputAll; //!<! User output slot 3 // Analysis histos TList *fListCuts; //!<! User output slot 2 // Cuts TH1F *fCEvents; /// Histogram to check selected events TH1F *fHTrigger; /// Histograms to check trigger TH1F *fHCentrality; /// histogram to check centrality TH1F *fHCentralSPD; ///jcho TH1F *fHNSPDTracklets; ///jcho AliRDHFCutsXicPlustoXiPiPifromAODtracks *fAnalCuts; /// Cuts - sent to output slot 2 AliRDHFCutsXicPlustoXiPiPifromAODtracks *fAnalCuts_HM; //jcho Bool_t fIsEventSelected; /// flag for event selected Bool_t fWriteVariableTree; /// flag to decide whether to write the candidate variables on a tree variables Bool_t fFillSparse; /// flag to decide whether fill the THnSparse Bool_t fHMTrigOn; /// jcho, flag for HM Trig check TTree *fVariablesTree; //!<! tree of the candidate variables after track selection on output slot 4 TTree *fEventTree; // jcho, Event variables tree Bool_t fReconstructPrimVert; /// Reconstruct primary vertex excluding candidate tracks Bool_t fIsMB; /// Is MB event Bool_t fIsSemi; /// is semi-central trigger event Bool_t fIsCent; /// is central trigger event Bool_t fIsINT7; /// is int7 trigger event Bool_t fIsEMC7; /// is emc7 trigger event Bool_t fIsHMV0; /// jcho Bool_t fIsHMSPD; /// jcho Float_t *fCandidateVariables; //!<! variables to be written to the tree Float_t *fEventTreeVariables; //jcho, Event variables to be written to the (event variables) tree AliAODVertex *fVtx1; /// primary vertex AliESDVertex *fV1; /// primary vertex Double_t fBzkG; /// magnetic field value [kG] Float_t fCentrality; /// centrality //--------------------- My histograms ------------------ THnSparse* fHistoXicMass; //!<! xic mass spectra THnSparse* fSparseXicMass; //!<! xic sparse to study cut variation TH3F* fHistoMCSpectrumAccXic; //!<! Spectrum of generated particles TH1F* fHistoDcaPi1Pi2; //!<! DCA between pions TH1F* fHistoDcaPi1Casc; //!<! DCA between pi and cascade TH1F* fHistoDcaPi2Casc; //!<! DCA between pi and cascade TH1F* fHistoLikeDecayLength; //!<! Decay length TH1F* fHistoLikeDecayLengthXY; //!<! Decay length in XY TH1F* fHistoXicCosPA; //!<! Xic cosine pointing angle TH1F* fHistoXiMass; //!<! mass of xi TH1F* fHistoCascDcaXiDaughters; //!<! DCA of xi daughgers TH1F* fHistoCascDcaV0Daughters; //!<! DCA of v0 daughters TH1F* fHistoCascDcaV0ToPrimVertex; //!<! DCA of v0 to primary vertex TH1F* fHistoCascDcaPosToPrimVertex; //!<! DCA of positive track to primary vertex TH1F* fHistoCascDcaNegToPrimVertex; //!<! DCA of negative track to primary vertex TH1F* fHistoCascDcaBachToPrimVertex; //!<! DCA of bachelor track to primary vertex TH1F* fHistoCascCosPAXiPrim; //!<! Cosine pointing angle of Xi to primary vertex TH1F* fHistoXiPt; //!<! Xi pt TH1F* fHistoPiPt; //!<! Pion pT TH1F* fHistoPid0; //!<! pion d0 TH1F* fHistonSigmaTPCpi; //!<! nSigma of TPC pion TH1F* fHistonSigmaTOFpi; //!<! nSigma of TOF pion TH1F* fHistoProbPion; //!<! Probability to be pion TH2F* fHistoXiMassvsPtRef1; //!<! Reference Xi mass spectra TH2F* fHistoXiMassvsPtRef2; //!<! Reference Xi mass spectra TH2F* fHistoXiMassvsPtRef3; //!<! Reference Xi mass spectra TH2F* fHistoXiMassvsPtRef4; //!<! Reference Xi mass spectra TH2F* fHistoXiMassvsPtRef5; //!<! Reference Xi mass spectra TH2F* fHistoXiMassvsPtRef6; //!<! Reference Xi mass spectra TH1F* fHistoPiPtRef; //!<! Reference pi spectra TH1F* fHistoPiEtaRef; //!<! Reference eta distribution of pi TH1F* fQAHistoNSelectedTracks; //!<! QA histo for number of selected tracks/event TH1F* fQAHistoNSelectedCasc; //!<! QA histo for number of selected Cascades/event TH1F* fQAHistoDCApi1pi2; //!<! QA histo for dca betwen two pions from XiC TH1F* fQAHistoAODPrimVertX; //!<! Coordinates of the primary vertex TH1F* fQAHistoAODPrimVertY; //!<! Coordinates of the primary vertex TH1F* fQAHistoAODPrimVertZ; //!<! Coordinates of the primary vertex TH1F* fQAHistoRecoPrimVertX; //!<! Coordinates of the reconstructed primary vertex without XiC decay tracks TH1F* fQAHistoRecoPrimVertY; //!<! Coordinates of the reconstructed primary vertex without XiC decay tracks TH1F* fQAHistoRecoPrimVertZ; //!<! Coordinates of the reconstructed primary vertex without XiC decay tracks TH1F* fQAHistoSecondaryVertexX; //!<! Coordinates of the reconstructed secondary vertex TH1F* fQAHistoSecondaryVertexY; //!<! Coordinates of the reconstructed secondary vertex TH1F* fQAHistoSecondaryVertexZ; //!<! Coordinates of the reconstructed secondary vertex TH1F* fQAHistoSecondaryVertexXY; //!<! Coordinates of the reconstructed secondary vertex AliNormalizationCounter *fCounter; //!<!Counter for normalization slot 4 Bool_t fIsXicPlusUpgradeITS3; ///flag to identify if the analysis is for the ITS3 upgrade Double_t fRejFactorBkgUpgrade; // rejection factor for background reconstruction in upgrade studies //---for Multiplicity dependent analysis--------------------// jcho AliNormalizationCounter *fCounter_MB_0to100 = nullptr; AliNormalizationCounter *fCounter_MB_0p1to30 = nullptr; AliNormalizationCounter *fCounter_MB_30to100 = nullptr; AliNormalizationCounter *fCounter_HMV0_0to0p1 = nullptr; AliNormalizationCounter *fCounter_HMV0_0to100 = nullptr; Float_t fNewCentrality = 9999; Float_t fCentralSPD = 9999; Float_t fNSPDTracklets = 9999; TH1F* hCentrality; //Centrality vector<UInt_t> fTargetTriggers; //jcho, Container for trigger bit UInt_t fEventTreeVarTrig = 0; //jcho, To write the trigger info. into the event tree Bool_t fUsekINT7 = kFALSE; Bool_t fUsekHMV0 = kFALSE; Bool_t fUsekHMVSPD = kFALSE; TH1F* fCentralityOfEvt; //jcho /// \cond CLASSIMP ClassDef(AliAnalysisTaskSEXicPlus2XiPiPifromAODtracks,15); /// class for Xic->Xipipi /// \endcond }; #endif
{'content_hash': '8ab2069a59789c13e53bb8f4b108fa6b', 'timestamp': '', 'source': 'github', 'line_count': 207, 'max_line_length': 211, 'avg_line_length': 53.63768115942029, 'alnum_prop': 0.6899036296496442, 'repo_name': 'rihanphys/AliPhysics', 'id': 'b9a54b3061528bac558dec64e91df73a124f7e96', 'size': '12167', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'PWGHF/vertexingHF/AliAnalysisTaskSEXicPlus2XiPiPifromAODtracks.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C', 'bytes': '91654361'}, {'name': 'C++', 'bytes': '190650723'}, {'name': 'CMake', 'bytes': '690540'}, {'name': 'CSS', 'bytes': '5189'}, {'name': 'Fortran', 'bytes': '176927'}, {'name': 'HTML', 'bytes': '34924'}, {'name': 'JavaScript', 'bytes': '3536'}, {'name': 'Makefile', 'bytes': '24994'}, {'name': 'Objective-C', 'bytes': '62560'}, {'name': 'Perl', 'bytes': '18619'}, {'name': 'Python', 'bytes': '797351'}, {'name': 'SWIG', 'bytes': '33320'}, {'name': 'Shell', 'bytes': '1127312'}, {'name': 'TeX', 'bytes': '392122'}]}
package com.intellij.codeInsight.javadoc; import com.intellij.psi.*; import com.intellij.util.ArrayUtil; import com.intellij.util.ReflectionUtil; import org.jetbrains.annotations.NotNull; import java.awt.*; /** * @author spleaner */ public class ColorUtil { private ColorUtil() { } public static String generatePreviewHtml(@NotNull final Color color) { return String.format("<div style=\"padding: 1px; width: 52px; height: 32px; background-color: #555555;\"><div style=\"width: 50px; height: 30px; background-color: #%s;\">&nbsp;</div></div>", com.intellij.ui.ColorUtil.toHex(color)); } @SuppressWarnings("UseJBColor") public static void appendColorPreview(final PsiVariable variable, final StringBuilder buffer) { final PsiExpression initializer = variable.getInitializer(); if (initializer != null) { final PsiType type = initializer.getType(); if (type != null && "java.awt.Color".equals(type.getCanonicalText())) { if (initializer instanceof PsiNewExpression) { final PsiExpressionList argumentList = ((PsiNewExpression) initializer).getArgumentList(); if (argumentList != null) { final PsiExpression[] expressions = argumentList.getExpressions(); int[] values = ArrayUtil.newIntArray(expressions.length); float[] values2 = new float[expressions.length]; int i = 0; int j = 0; final PsiConstantEvaluationHelper helper = JavaPsiFacade.getInstance(initializer.getProject()).getConstantEvaluationHelper(); for (final PsiExpression each : expressions) { final Object o = helper.computeConstantExpression(each); if (o instanceof Integer) { values[i] = ((Integer) o).intValue(); values[i] = values[i] > 255 && expressions.length > 1 ? 255 : values[i] < 0 ? 0 : values[i]; i++; } else if (o instanceof Float) { values2[j] = ((Float) o).floatValue(); values2[j] = values2[j] > 1 ? 1 : values2[j] < 0 ? 0 : values2[j]; j++; } } Color c = null; if (i == expressions.length) { switch (values.length) { case 1: c = new Color(values[0]); break; case 3: c = new Color(values[0], values[1], values[2]); break; case 4: c = new Color(values[0], values[1], values[2], values[3]); break; default: break; } } else if (j == expressions.length) { switch (values2.length) { case 3: c = new Color(values2[0], values2[1], values2[2]); break; case 4: c = new Color(values2[0], values2[1], values2[2], values2[3]); break; default: break; } } if (c != null) { buffer.append(generatePreviewHtml(c)); } } } else if (initializer instanceof PsiReferenceExpression) { final PsiReference reference = initializer.getReference(); if (reference != null) { final PsiElement psiElement = reference.resolve(); if (psiElement instanceof PsiField) { PsiField psiField = (PsiField)psiElement; final PsiClass psiClass = psiField.getContainingClass(); if (psiClass != null && "java.awt.Color".equals(psiClass.getQualifiedName())) { Color c = ReflectionUtil.getStaticFieldValue(Color.class, Color.class, psiField.getName()); if (c != null) { buffer.append(generatePreviewHtml(c)); } } } } } } } } }
{'content_hash': '1f9a019a0afd29267746ff559c99e27a', 'timestamp': '', 'source': 'github', 'line_count': 102, 'max_line_length': 235, 'avg_line_length': 38.98039215686274, 'alnum_prop': 0.540241448692153, 'repo_name': 'mglukhikh/intellij-community', 'id': '3a470ac5b4053e116653508f95caa6b39d0b72de', 'size': '4576', 'binary': False, 'copies': '18', 'ref': 'refs/heads/master', 'path': 'java/java-psi-impl/src/com/intellij/codeInsight/javadoc/ColorUtil.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'AMPL', 'bytes': '20665'}, {'name': 'AspectJ', 'bytes': '182'}, {'name': 'Batchfile', 'bytes': '60827'}, {'name': 'C', 'bytes': '211435'}, {'name': 'C#', 'bytes': '1264'}, {'name': 'C++', 'bytes': '197674'}, {'name': 'CMake', 'bytes': '1675'}, {'name': 'CSS', 'bytes': '201445'}, {'name': 'CoffeeScript', 'bytes': '1759'}, {'name': 'Erlang', 'bytes': '10'}, {'name': 'Groovy', 'bytes': '3243028'}, {'name': 'HLSL', 'bytes': '57'}, {'name': 'HTML', 'bytes': '1899088'}, {'name': 'J', 'bytes': '5050'}, {'name': 'Java', 'bytes': '165554704'}, {'name': 'JavaScript', 'bytes': '570364'}, {'name': 'Jupyter Notebook', 'bytes': '93222'}, {'name': 'Kotlin', 'bytes': '4611299'}, {'name': 'Lex', 'bytes': '147047'}, {'name': 'Makefile', 'bytes': '2352'}, {'name': 'NSIS', 'bytes': '51276'}, {'name': 'Objective-C', 'bytes': '27861'}, {'name': 'Perl', 'bytes': '903'}, {'name': 'Perl 6', 'bytes': '26'}, {'name': 'Protocol Buffer', 'bytes': '6680'}, {'name': 'Python', 'bytes': '25439881'}, {'name': 'Roff', 'bytes': '37534'}, {'name': 'Ruby', 'bytes': '1217'}, {'name': 'Scala', 'bytes': '11698'}, {'name': 'Shell', 'bytes': '66341'}, {'name': 'Smalltalk', 'bytes': '338'}, {'name': 'TeX', 'bytes': '25473'}, {'name': 'Thrift', 'bytes': '1846'}, {'name': 'TypeScript', 'bytes': '9469'}, {'name': 'Visual Basic', 'bytes': '77'}, {'name': 'XSLT', 'bytes': '113040'}]}
package volume import ( "fmt" "testing" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" "strings" ) func TestRecyclerSuccess(t *testing.T) { client := &mockRecyclerClient{} recycler := &api.Pod{ ObjectMeta: api.ObjectMeta{ Name: "recycler-test", Namespace: api.NamespaceDefault, }, Status: api.PodStatus{ Phase: api.PodSucceeded, }, } err := internalRecycleVolumeByWatchingPodUntilCompletion(recycler, client) if err != nil { t.Errorf("Unexpected error watching recycler pod: %+v", err) } if !client.deletedCalled { t.Errorf("Expected deferred client.Delete to be called on recycler pod") } } func TestRecyclerFailure(t *testing.T) { client := &mockRecyclerClient{} recycler := &api.Pod{ ObjectMeta: api.ObjectMeta{ Name: "recycler-test", Namespace: api.NamespaceDefault, }, Status: api.PodStatus{ Phase: api.PodFailed, Message: "foo", }, } err := internalRecycleVolumeByWatchingPodUntilCompletion(recycler, client) if err == nil { t.Fatalf("Expected pod failure but got nil error returned") } if err != nil { if !strings.Contains(err.Error(), "foo") { t.Errorf("Expected pod.Status.Message %s but got %s", recycler.Status.Message, err) } } if !client.deletedCalled { t.Errorf("Expected deferred client.Delete to be called on recycler pod") } } type mockRecyclerClient struct { pod *api.Pod deletedCalled bool } func (c *mockRecyclerClient) CreatePod(pod *api.Pod) (*api.Pod, error) { c.pod = pod return c.pod, nil } func (c *mockRecyclerClient) GetPod(name, namespace string) (*api.Pod, error) { if c.pod != nil { return c.pod, nil } else { return nil, fmt.Errorf("pod does not exist") } } func (c *mockRecyclerClient) DeletePod(name, namespace string) error { c.deletedCalled = true return nil } func (c *mockRecyclerClient) WatchPod(name, namespace, resourceVersion string, stopChannel chan struct{}) func() *api.Pod { return func() *api.Pod { return c.pod } } func TestCalculateTimeoutForVolume(t *testing.T) { pv := &api.PersistentVolume{ Spec: api.PersistentVolumeSpec{ Capacity: api.ResourceList{ api.ResourceName(api.ResourceStorage): resource.MustParse("500M"), }, }, } timeout := CalculateTimeoutForVolume(50, 30, pv) if timeout != 50 { t.Errorf("Expected 50 for timeout but got %v", timeout) } pv.Spec.Capacity[api.ResourceStorage] = resource.MustParse("2Gi") timeout = CalculateTimeoutForVolume(50, 30, pv) if timeout != 60 { t.Errorf("Expected 60 for timeout but got %v", timeout) } pv.Spec.Capacity[api.ResourceStorage] = resource.MustParse("150Gi") timeout = CalculateTimeoutForVolume(50, 30, pv) if timeout != 4500 { t.Errorf("Expected 4500 for timeout but got %v", timeout) } }
{'content_hash': 'eae6ff3e210881eaab295ddf42e24ded', 'timestamp': '', 'source': 'github', 'line_count': 116, 'max_line_length': 123, 'avg_line_length': 23.93103448275862, 'alnum_prop': 0.6974063400576369, 'repo_name': 'Smana/kubernetes', 'id': 'aaef904837e246d762faf519efdfa5f6c9863f9c', 'size': '3365', 'binary': False, 'copies': '12', 'ref': 'refs/heads/master', 'path': 'pkg/volume/util_test.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Go', 'bytes': '10654235'}, {'name': 'HTML', 'bytes': '1193991'}, {'name': 'Makefile', 'bytes': '16976'}, {'name': 'Nginx', 'bytes': '1013'}, {'name': 'Python', 'bytes': '63716'}, {'name': 'SaltStack', 'bytes': '37671'}, {'name': 'Shell', 'bytes': '906415'}]}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <title>matrix_major_storage.hpp File Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectlogo"><img alt="Logo" src="logo-mini.png"/></td> </tr> </tbody> </table> </div> <!-- Generated by Doxygen 1.7.5.1 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="files.html"><span>File&#160;List</span></a></li> </ul> </div> </div> <div class="header"> <div class="summary"> <a href="#func-members">Functions</a> </div> <div class="headertitle"> <div class="title">matrix_major_storage.hpp File Reference</div> </div> </div> <div class="contents"> <p><a href="a00057_source.html">Go to the source code of this file.</a></p> <table class="memberdecls"> <tr><td colspan="2"><h2><a name="func-members"></a> Functions</h2></td></tr> <tr><td class="memTemplParams" colspan="2">template&lt;typename T &gt; </td></tr> <tr><td class="memTemplItemLeft" align="right" valign="top">detail::tmat2x2&lt; T &gt;&#160;</td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00179.html#gaa188eb2ad0b0922f251bf1d0f4d85043">colMajor2</a> (detail::tvec2&lt; T &gt; const &amp;v1, detail::tvec2&lt; T &gt; const &amp;v2)</td></tr> <tr><td class="memTemplParams" colspan="2">template&lt;typename T &gt; </td></tr> <tr><td class="memTemplItemLeft" align="right" valign="top">detail::tmat2x2&lt; T &gt;&#160;</td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00179.html#gae5acce8fa0778cfa98fa7e7420114c94">colMajor2</a> (detail::tmat2x2&lt; T &gt; const &amp;m)</td></tr> <tr><td class="memTemplParams" colspan="2">template&lt;typename T &gt; </td></tr> <tr><td class="memTemplItemLeft" align="right" valign="top">detail::tmat3x3&lt; T &gt;&#160;</td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00179.html#ga025bcabc88eafc950e2f518939dc154e">colMajor3</a> (detail::tvec3&lt; T &gt; const &amp;v1, detail::tvec3&lt; T &gt; const &amp;v2, detail::tvec3&lt; T &gt; const &amp;v3)</td></tr> <tr><td class="memTemplParams" colspan="2">template&lt;typename T &gt; </td></tr> <tr><td class="memTemplItemLeft" align="right" valign="top">detail::tmat3x3&lt; T &gt;&#160;</td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00179.html#ga0766258f7e0ed0a64c38838011b8e4d8">colMajor3</a> (detail::tmat3x3&lt; T &gt; const &amp;m)</td></tr> <tr><td class="memTemplParams" colspan="2">template&lt;typename T &gt; </td></tr> <tr><td class="memTemplItemLeft" align="right" valign="top">detail::tmat4x4&lt; T &gt;&#160;</td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00179.html#ga8f5575ea47a559564dc3bd073082e475">colMajor4</a> (detail::tvec4&lt; T &gt; const &amp;v1, detail::tvec4&lt; T &gt; const &amp;v2, detail::tvec4&lt; T &gt; const &amp;v3, detail::tvec4&lt; T &gt; const &amp;v4)</td></tr> <tr><td class="memTemplParams" colspan="2">template&lt;typename T &gt; </td></tr> <tr><td class="memTemplItemLeft" align="right" valign="top">detail::tmat4x4&lt; T &gt;&#160;</td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00179.html#gad321af5ae6d151fd3752725b06c97154">colMajor4</a> (detail::tmat4x4&lt; T &gt; const &amp;m)</td></tr> <tr><td class="memTemplParams" colspan="2">template&lt;typename T &gt; </td></tr> <tr><td class="memTemplItemLeft" align="right" valign="top">detail::tmat2x2&lt; T &gt;&#160;</td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00179.html#ga7491478a44956d58b7e69aaed553cc6d">rowMajor2</a> (detail::tvec2&lt; T &gt; const &amp;v1, detail::tvec2&lt; T &gt; const &amp;v2)</td></tr> <tr><td class="memTemplParams" colspan="2">template&lt;typename T &gt; </td></tr> <tr><td class="memTemplItemLeft" align="right" valign="top">detail::tmat2x2&lt; T &gt;&#160;</td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00179.html#ga28d01bef195da95bb53cd4f92c2a682a">rowMajor2</a> (detail::tmat2x2&lt; T &gt; const &amp;m)</td></tr> <tr><td class="memTemplParams" colspan="2">template&lt;typename T &gt; </td></tr> <tr><td class="memTemplItemLeft" align="right" valign="top">detail::tmat3x3&lt; T &gt;&#160;</td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00179.html#ga68e32da2311bfb10a997b696f10c94e0">rowMajor3</a> (detail::tvec3&lt; T &gt; const &amp;v1, detail::tvec3&lt; T &gt; const &amp;v2, detail::tvec3&lt; T &gt; const &amp;v3)</td></tr> <tr><td class="memTemplParams" colspan="2">template&lt;typename T &gt; </td></tr> <tr><td class="memTemplItemLeft" align="right" valign="top">detail::tmat3x3&lt; T &gt;&#160;</td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00179.html#gac5ff8d95a98875264033a1e941b93139">rowMajor3</a> (detail::tmat3x3&lt; T &gt; const &amp;m)</td></tr> <tr><td class="memTemplParams" colspan="2">template&lt;typename T &gt; </td></tr> <tr><td class="memTemplItemLeft" align="right" valign="top">detail::tmat4x4&lt; T &gt;&#160;</td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00179.html#ga3b12b05239e6cfdab406281a8c3371fc">rowMajor4</a> (detail::tvec4&lt; T &gt; const &amp;v1, detail::tvec4&lt; T &gt; const &amp;v2, detail::tvec4&lt; T &gt; const &amp;v3, detail::tvec4&lt; T &gt; const &amp;v4)</td></tr> <tr><td class="memTemplParams" colspan="2">template&lt;typename T &gt; </td></tr> <tr><td class="memTemplItemLeft" align="right" valign="top">detail::tmat4x4&lt; T &gt;&#160;</td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00179.html#gaf60f42778d5018aee654d59d34ff720d">rowMajor4</a> (detail::tmat4x4&lt; T &gt; const &amp;m)</td></tr> </table> <hr/><a name="details" id="details"></a><h2>Detailed Description</h2> <div class="textblock"><p>OpenGL Mathematics (glm.g-truc.net) </p> <p>Copyright (c) 2005 - 2012 G-Truc Creation (www.g-truc.net) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:</p> <p>The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.</p> <p>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.</p> <p><a class="el" href="a00179.html">GLM_GTX_matrix_major_storage: Build matrix</a></p> <dl class="date"><dt><b>Date:</b></dt><dd>2006-04-19 / 2011-06-07 </dd></dl> <dl class="author"><dt><b>Author:</b></dt><dd>Christophe Riccio</dd></dl> <dl class="see"><dt><b>See also:</b></dt><dd><a class="el" href="a00139.html" title="The core of GLM, which implements exactly and only the GLSL specification to the degree possible...">GLM Core</a> (dependence) </dd> <dd> <a class="el" href="a00166.html" title="Min and max functions for 3 to 4 parameters.">GLM_GTX_extented_min_max: Extended min max</a> (dependence) </dd></dl> <p>Definition in file <a class="el" href="a00057_source.html">matrix_major_storage.hpp</a>.</p> </div></div> <hr class="footer"/><address class="footer"><small> Generated by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.7.5.1 </small></address> </body> </html>
{'content_hash': 'c4e2c5cff4dd419ee2268fa874da184a', 'timestamp': '', 'source': 'github', 'line_count': 110, 'max_line_length': 498, 'avg_line_length': 79.07272727272728, 'alnum_prop': 0.6949873534145781, 'repo_name': 'silencerh/Lab2Raytracer', 'id': '25f7fa5a4d576d3314f95288d5ccd84443576392', 'size': '8698', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'glm/doc/api-0.9.3/a00057.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C++', 'bytes': '1794341'}, {'name': 'CMake', 'bytes': '6584'}, {'name': 'CSS', 'bytes': '20294'}, {'name': 'HTML', 'bytes': '4427017'}, {'name': 'Python', 'bytes': '5531'}, {'name': 'XSLT', 'bytes': '27905'}]}