repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
kennywj/embarc_osp
include/arc/arc_xy_agu.h
<reponame>kennywj/embarc_osp<gh_stars>10-100 /* ------------------------------------------ * Copyright (c) 2018, Synopsys, Inc. All rights reserved. * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1) Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2) Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * 3) Neither the name of the Synopsys, 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * --------------------------------------------- */ #ifndef H_ARC_XY_AGU #define H_ARC_XY_AGU #ifndef __ASSEMBLY__ #ifdef __cplusplus extern "C" { #endif #define U0 % r32 #define U1 % r33 #define U2 % r34 #ifdef ARC_FEATURE_XCCM_PRESENT #define ARC_X_CCM __attribute__ ((section(".x_ccm"))) #else #define ARC_X_CCM #endif #ifdef ARC_FEATURE_YCCM_PRESENT #define ARC_Y_CCM __attribute__ ((section(".y_ccm"))) #else #define ARC_Y_CCM #endif #define US_EXPAND_MOD_NAME(reg_id) AUX_AGU_MOD ## reg_id #define US_EXPAND_OS_NAME(reg_id) AUX_AGU_OS ## reg_id #define US_EXPAND_AP_NAME(reg_id) AUX_AGU_AP ## reg_id #define ARC_AGU_MOD_SET(agu_mod, ptr_id, data_type, addressing) \ arc_aux_write(US_EXPAND_MOD_NAME(agu_mod), (uint32_t)(ptr_id | data_type | addressing)) #define ARC_AGU_OS_SET(os_id, offset) \ arc_aux_write(US_EXPAND_OS_NAME(os_id), (uint32_t)offset) #define ARC_AGU_AP_SET(ap_id, addr) \ arc_aux_write(US_EXPAND_AP_NAME(ap_id), (uint32_t)addr) #define ARC_AGU_MOD_GET(mod_id) arc_aux_read(US_EXPAND_MOD_NAME(mod_id)) #define ARC_AGU_OS_GET(os_id) arc_aux_read(US_EXPAND_MOD_NAME(os_id)) #define ARC_AGU_AP_GET(ap_id) arc_aux_read(US_EXPAND_AP_NAME(ap_id)) #define ARC_AGU_MOD_VW(x) ((x) << 4) #define ARC_AGU_MOD_FX(x) ((x) << 6) #define ARC_AGU_MOD_DIR(x) ((x) << 11) #define ARC_AGU_MOD_REV (1 << 12) #define ARC_AGU_MOD_REP (1 << 13) #define ARC_AGU_MOD_SC(x) ((x) << 14) #define ARC_AGU_MOD_OFFSET_REG(x) ((x) << 25) #define ARC_AGU_MOD_OFFSET_IMM(x) ((x) << 18) #define ARC_AGU_MOD_WRAP_REG(x) ((x) << 14) #define ARC_AGU_MOD_WRAP_IMM(x) ((x) << 14) #define ARC_AGU_MOD_OPC(x) ((x) << 29) #define ARC_AGU_DT_I32 (ARC_AGU_MOD_FX(11) | ARC_AGU_MOD_VW(2)) #define ARC_AGU_DT_I32_CAST_I16 (ARC_AGU_MOD_FX(8) | ARC_AGU_MOD_VW(2)) #define ARC_AGU_DT_I32_CAST_I8 (ARC_AGU_MOD_FX(4) | ARC_AGU_MOD_VW(2)) #define ARC_AGU_DT_I16 (ARC_AGU_MOD_FX(3) | ARC_AGU_MOD_VW(1)) #define ARC_AGU_DT_I16_CAST_I8 (ARC_AGU_MOD_FX(0) | ARC_AGU_MOD_VW(1)) #define ARC_AGU_DT_I8 (ARC_AGU_MOD_FX(7) | ARC_AGU_MOD_VW(0)) #define ARC_AGU_DT_V2I16 (ARC_AGU_MOD_FX(3) | ARC_AGU_MOD_VW(2)) #define ARC_AGU_DT_V2I16_REPLIC_I16 (ARC_AGU_MOD_FX(3) | ARC_AGU_MOD_VW(2) | ARC_AGU_MOD_REP) #define ARC_AGU_DT_V2I16_CAST_V2I8 (ARC_AGU_MOD_FX(0) | ARC_AGU_MOD_VW(2)) #define ARC_AGU_DT_V2I8 (ARC_AGU_MOD_FX(7) | ARC_AGU_MOD_VW(1)) #define ARC_AGU_DT_V2I8_REPLIC_I8 (ARC_AGU_MOD_FX(7) | ARC_AGU_MOD_VW(1) | ARC_AGU_MOD_REP) #define ARC_AGU_DT_V4I8 (ARC_AGU_MOD_FX(7) | ARC_AGU_MOD_VW(2)) #define ARC_AGU_DT_V4I8_REPLIC_I8 (ARC_AGU_MOD_FX(7) | ARC_AGU_MOD_VW(2) | ARC_AGU_MOD_REP) /* AGU addressing modes with scling factor macroses */ #define ARC_AGU_AD_INC_I32(offset) (ARC_AGU_MOD_OPC(1) | ARC_AGU_MOD_OFFSET_IMM(offset) | ARC_AGU_MOD_SC(2)) #define ARC_AGU_AD_DEC_I32(offset) (ARC_AGU_MOD_OPC(1) | ARC_AGU_MOD_OFFSET_IMM(offset) | ARC_AGU_MOD_SC(2) | ARC_AGU_MOD_DIR(1)) #define ARC_AGU_AD_INC_I32_REG(reg_id) (ARC_AGU_MOD_OPC(0) | ARC_AGU_MOD_OFFSET_REG(reg_id) | ARC_AGU_MOD_SC(2)) #define ARC_AGU_AD_DEC_I32_REG(reg_id) (ARC_AGU_MOD_OPC(0) | ARC_AGU_MOD_OFFSET_REG(reg_id) | ARC_AGU_MOD_SC(2) | ARC_AGU_MOD_DIR(1)) #define ARC_AGU_AD_BITREV_INC_I32(offset) (ARC_AGU_MOD_OPC(3) | ARC_AGU_MOD_OFFSET_IMM(offset) | ARC_AGU_MOD_SC(2)) #define ARC_AGU_AD_BITREV_DEC_I32(offset) (ARC_AGU_MOD_OPC(3) | ARC_AGU_MOD_OFFSET_IMM(offset) | ARC_AGU_MOD_SC(2) | ARC_AGU_MOD_DIR(1)) #define ARC_AGU_AD_BITREV_INC_I32_REG(reg_id) (ARC_AGU_MOD_OPC(2) | ARC_AGU_MOD_OFFSET_REG(reg_id) | ARC_AGU_MOD_SC(2)) #define ARC_AGU_AD_BITREV_DEC_I32_REG(reg_id) (ARC_AGU_MOD_OPC(2) | ARC_AGU_MOD_OFFSET_REG(reg_id) | ARC_AGU_MOD_SC(2) | ARC_AGU_MOD_DIR(1)) #define ARC_AGU_AD_INC_I16(offset) (ARC_AGU_MOD_OPC(1) | ARC_AGU_MOD_OFFSET_IMM(offset) | ARC_AGU_MOD_SC(1)) #define ARC_AGU_AD_DEC_I16(offset) (ARC_AGU_MOD_OPC(1) | ARC_AGU_MOD_OFFSET_IMM(offset) | ARC_AGU_MOD_SC(1) | ARC_AGU_MOD_DIR(1)) #define ARC_AGU_AD_INC_I16_REG(reg_id) (ARC_AGU_MOD_OPC(0) | ARC_AGU_MOD_OFFSET_REG(reg_id) | ARC_AGU_MOD_SC(1)) #define ARC_AGU_AD_DEC_I16_REG(reg_id) (ARC_AGU_MOD_OPC(0) | ARC_AGU_MOD_OFFSET_REG(reg_id) | ARC_AGU_MOD_SC(1) | ARC_AGU_MOD_DIR(1)) #define ARC_AGU_AD_BITREV_INC_I16(offset) (ARC_AGU_MOD_OPC(3) | ARC_AGU_MOD_OFFSET_IMM(offset) | ARC_AGU_MOD_SC(1)) #define ARC_AGU_AD_BITREV_DEC_I16(offset) (ARC_AGU_MOD_OPC(3) | ARC_AGU_MOD_OFFSET_IMM(offset) | ARC_AGU_MOD_SC(1) | ARC_AGU_MOD_DIR(1)) #define ARC_AGU_AD_BITREV_INC_I16_REG(reg_id) (ARC_AGU_MOD_OPC(2) | ARC_AGU_MOD_OFFSET_REG(reg_id) | ARC_AGU_MOD_SC(1)) #define ARC_AGU_AD_BITREV_DEC_I16_REG(reg_id) (ARC_AGU_MOD_OPC(2) | ARC_AGU_MOD_OFFSET_REG(reg_id) | ARC_AGU_MOD_SC(1) | ARC_AGU_MOD_DIR(1)) #define ARC_AGU_AD_INC_I8(offset) (ARC_AGU_MOD_OPC(1) | ARC_AGU_MOD_OFFSET_IMM(offset) | ARC_AGU_MOD_SC(0)) #define ARC_AGU_AD_DEC_I8(offset) (ARC_AGU_MOD_OPC(1) | ARC_AGU_MOD_OFFSET_IMM(offset) | ARC_AGU_MOD_SC(0) | ARC_AGU_MOD_DIR(1)) #define ARC_AGU_AD_INC_I8_REG(reg_id) (ARC_AGU_MOD_OPC(0) | ARC_AGU_MOD_OFFSET_REG(reg_id) | ARC_AGU_MOD_SC(0)) #define ARC_AGU_AD_DEC_I8_REG(reg_id) (ARC_AGU_MOD_OPC(0) | ARC_AGU_MOD_OFFSET_REG(reg_id) | ARC_AGU_MOD_SC(0) | ARC_AGU_MOD_DIR(1)) #define ARC_AGU_AD_BITREV_INC_I8(offset) (ARC_AGU_MOD_OPC(3) | ARC_AGU_MOD_OFFSET_IMM(offset) | ARC_AGU_MOD_SC(0)) #define ARC_AGU_AD_BITREV_DEC_I8(offset) (ARC_AGU_MOD_OPC(3) | ARC_AGU_MOD_OFFSET_IMM(offset) | ARC_AGU_MOD_SC(0) | ARC_AGU_MOD_DIR(1)) #define ARC_AGU_AD_BITREV_INC_I8_REG(reg_id) (ARC_AGU_MOD_OPC(2) | ARC_AGU_MOD_OFFSET_REG(reg_id) | ARC_AGU_MOD_SC(0)) #define ARC_AGU_AD_BITREV_DEC_I8_REG(reg_id) (ARC_AGU_MOD_OPC(2) | ARC_AGU_MOD_OFFSET_REG(reg_id) | ARC_AGU_MOD_SC(0) | ARC_AGU_MOD_DIR(1)) /****************************************************************************** * * AGU data types with type casting macroses for unsigned int data types * unsigned int data type assumes lsb aligned data conversion without sign extension * ******************************************************************************/ #define ARC_AGU_DT_UI32 ARC_AGU_DT_I32 #define ARC_AGU_DT_UI32_CAST_UI16 (ARC_AGU_MOD_FX(9) | ARC_AGU_MOD_VW(2)) #define ARC_AGU_DT_UI32_CAST_UI8 (ARC_AGU_MOD_FX(5) | ARC_AGU_MOD_VW(2)) #define ARC_AGU_DT_UI16 ARC_AGU_DT_I16 #define ARC_AGU_DT_UI16_CAST_UI8 (ARC_AGU_MOD_FX(1) | ARC_AGU_MOD_VW(1)) #define ARC_AGU_DT_UI8 ARC_AGU_DT_I8 #define ARC_AGU_DT_V2UI16 ARC_AGU_DT_V2I16 #define ARC_AGU_DT_V2UI16_REPLIC_UI16 ARC_AGU_DT_V2I16_REPLIC_I16 #define ARC_AGU_DT_V2UI16_CAST_V2UI8 (ARC_AGU_MOD_FX(1) | ARC_AGU_MOD_VW(2)) #define ARC_AGU_DT_V2UI8 ARC_AGU_DT_V2I8 #define ARC_AGU_DT_V2UI8_REPLIC_UI8 ARC_AGU_DT_V2I8_REPLIC_I8 #define ARC_AGU_DT_V4UI8 ARC_AGU_DT_V4I8 #define ARC_AGU_DT_V4UI8_REPLIC_UI8 ARC_AGU_DT_V4I8_REPLIC_I8 /* AGU addressing modes with scling factor macroses */ #define ARC_AGU_AD_INC_UI32(offset) ARC_AGU_AD_INC_I32(offset) #define ARC_AGU_AD_DEC_UI32(offset) ARC_AGU_AD_DEC_I32(offset) #define ARC_AGU_AD_INC_UI32_REG(reg_id) ARC_AGU_AD_INC_I32_REG(reg_id) #define ARC_AGU_AD_DEC_UI32_REG(reg_id) ARC_AGU_AD_DEC_I32_REG(reg_id) #define ARC_AGU_AD_BITREV_INC_UI32(offset) ARC_AGU_AD_BITREV_INC_I32(offset) #define ARC_AGU_AD_BITREV_DEC_UI32(offset) ARC_AGU_AD_BITREV_DEC_I32(offset) #define ARC_AGU_AD_BITREV_INC_UI32_REG(reg_id) ARC_AGU_AD_BITREV_INC_I32_REG(reg_id) #define ARC_AGU_AD_BITREV_DEC_UI32_REG(reg_id) ARC_AGU_AD_BITREV_DEC_I32_REG(reg_id) #define ARC_AGU_AD_INC_UI16(offset) ARC_AGU_AD_INC_I16(offset) #define ARC_AGU_AD_DEC_UI16(offset) ARC_AGU_AD_DEC_I16(offset) #define ARC_AGU_AD_INC_UI16_REG(reg_id) ARC_AGU_AD_INC_I16_REG(reg_id) #define ARC_AGU_AD_DEC_UI16_REG(reg_id) ARC_AGU_AD_DEC_I16_REG(reg_id) #define ARC_AGU_AD_BITREV_INC_UI16(offset) ARC_AGU_AD_BITREV_INC_I16(offset) #define ARC_AGU_AD_BITREV_DEC_UI16(offset) ARC_AGU_AD_BITREV_DEC_I16(offset) #define ARC_AGU_AD_BITREV_INC_UI16_REG(reg_id) ARC_AGU_AD_BITREV_INC_I16_REG(reg_id) #define ARC_AGU_AD_BITREV_DEC_UI16_REG(reg_id) ARC_AGU_AD_BITREV_DEC_I16_REG(reg_id) #define ARC_AGU_AD_INC_UI8(offset) ARC_AGU_AD_INC_I8(offset) #define ARC_AGU_AD_DEC_UI8(offset) ARC_AGU_AD_DEC_I8(offset) #define ARC_AGU_AD_INC_UI8_REG(reg_id) ARC_AGU_AD_INC_I8_REG(reg_id) #define ARC_AGU_AD_DEC_UI8_REG(reg_id) ARC_AGU_AD_DEC_I8_REG(reg_id) #define ARC_AGU_AD_BITREV_INC_UI8(offset) ARC_AGU_AD_BITREV_INC_I8(offset) #define ARC_AGU_AD_BITREV_DEC_UI8(offset) ARC_AGU_AD_BITREV_DEC_I8(offset) #define ARC_AGU_AD_BITREV_INC_UI8_REG(reg_id) ARC_AGU_AD_BITREV_INC_I8_REG(reg_id) #define ARC_AGU_AD_BITREV_DEC_UI8_REG(reg_id) ARC_AGU_AD_BITREV_DEC_I8_REG(reg_id) /****************************************************************************** * * AGU data types with type casting macroses for q.xx data types * q.xx data type assumes msb aligned data conversion * ******************************************************************************/ #define ARC_AGU_DT_Q31 ARC_AGU_DT_I32 #define ARC_AGU_DT_Q31_CAST_Q15 (ARC_AGU_MOD_FX(10) | ARC_AGU_MOD_VW(2)) #define ARC_AGU_DT_Q31_CAST_Q7 (ARC_AGU_MOD_FX(6) | ARC_AGU_MOD_VW(2)) #define ARC_AGU_DT_Q15 ARC_AGU_DT_I16 #define ARC_AGU_DT_Q15_CAST_Q7 (ARC_AGU_MOD_FX(2) | ARC_AGU_MOD_VW(1)) #define ARC_AGU_DT_Q7 ARC_AGU_DT_I8 #define ARC_AGU_DT_Q7_CAST_Q15 (ARC_AGU_MOD_FX(2) | ARC_AGU_MOD_VW(1)) // packing #define ARC_AGU_DT_V2Q15 ARC_AGU_DT_V2I16 #define ARC_AGU_DT_V2Q15_REPLIC_Q15 ARC_AGU_DT_V2I16_REPLIC_I16 #define ARC_AGU_DT_V2Q15_CAST_V2Q7 (ARC_AGU_MOD_FX(2) | ARC_AGU_MOD_VW(2)) #define ARC_AGU_DT_V2Q7 ARC_AGU_DT_V2I8 #define ARC_AGU_DT_V2Q7_REPLIC_Q7 ARC_AGU_DT_V2I8_REPLIC_I8 #define ARC_AGU_DT_V2Q7_CAST_V2Q15 (ARC_AGU_MOD_FX(2) | ARC_AGU_MOD_VW(2)) // packing #define ARC_AGU_DT_V4Q7 ARC_AGU_DT_V4I8 #define ARC_AGU_DT_V4Q7_REPLIC_Q7 ARC_AGU_DT_V4I8_REPLIC_I8 /* AGU addressing modes with scling factor macroses for q.xx data types */ #define ARC_AGU_AD_INC_Q31(offset) ARC_AGU_AD_INC_I32(offset) #define ARC_AGU_AD_DEC_Q31(offset) ARC_AGU_AD_DEC_I32(offset) #define ARC_AGU_AD_INC_Q31_REG(reg_id) ARC_AGU_AD_INC_I32_REG(reg_id) #define ARC_AGU_AD_DEC_Q31_REG(reg_id) ARC_AGU_AD_DEC_I32_REG(reg_id) #define ARC_AGU_AD_BITREV_INC_Q31(offset) ARC_AGU_AD_BITREV_INC_I32(offset) #define ARC_AGU_AD_BITREV_DEC_Q31(offset) ARC_AGU_AD_BITREV_DEC_I32(offset) #define ARC_AGU_AD_BITREV_INC_Q31_REG(reg_id) ARC_AGU_AD_BITREV_INC_I32_REG(reg_id) #define ARC_AGU_AD_BITREV_DEC_Q31_REG(reg_id) ARC_AGU_AD_BITREV_DEC_I32_REG(reg_id) #define ARC_AGU_AD_INC_Q15(offset) ARC_AGU_AD_INC_I16(offset) #define ARC_AGU_AD_DEC_Q15(offset) ARC_AGU_AD_DEC_I16(offset) #define ARC_AGU_AD_INC_Q15_REG(reg_id) ARC_AGU_AD_INC_I16_REG(reg_id) #define ARC_AGU_AD_DEC_Q15_REG(reg_id) ARC_AGU_AD_DEC_I16_REG(reg_id) #define ARC_AGU_AD_BITREV_INC_Q15(offset) ARC_AGU_AD_BITREV_INC_I16(offset) #define ARC_AGU_AD_BITREV_DEC_Q15(offset) ARC_AGU_AD_BITREV_DEC_I16(offset) #define ARC_AGU_AD_BITREV_INC_Q15_REG(reg_id) ARC_AGU_AD_BITREV_INC_I16_REG(reg_id) #define ARC_AGU_AD_BITREV_DEC_Q15_REG(reg_id) ARC_AGU_AD_BITREV_DEC_I16_REG(reg_id) #define ARC_AGU_AD_INC_Q7(offset) ARC_AGU_AD_INC_I8(offset) #define ARC_AGU_AD_DEC_Q7(offset) ARC_AGU_AD_DEC_I8(offset) #define ARC_AGU_AD_INC_Q7_REG(reg_id) ARC_AGU_AD_INC_I8_REG(reg_id) #define ARC_AGU_AD_DEC_Q7_REG(reg_id) ARC_AGU_AD_DEC_I8_REG(reg_id) #define ARC_AGU_AD_BITREV_INC_Q7(offset) ARC_AGU_AD_BITREV_INC_I8(offset) #define ARC_AGU_AD_BITREV_DEC_Q7(offset) ARC_AGU_AD_BITREV_DEC_I8(offset) #define ARC_AGU_AD_BITREV_INC_Q7_REG(reg_id) ARC_AGU_AD_BITREV_INC_I8_REG(reg_id) #define ARC_AGU_AD_BITREV_DEC_Q7_REG(reg_id) ARC_AGU_AD_BITREV_DEC_I8_REG(reg_id) /* AGU modificator for reverse vector elements (can be useful for Endian conversions) */ #define ARC_AGU_DT_VECTOR_REVERSE ARC_AGU_MOD_REV /* AGU wrapping modifiers */ #define ARC_AGU_AD_WRAP_INC_RR(inc_os_id, modulo_os_id) (ARC_AGU_MOD_OPC(4) | ARC_AGU_MOD_OFFSET_REG(inc_os_id) | ARC_AGU_MOD_WRAP_REG(modulo_os_id)) #define ARC_AGU_AD_WRAP_DEC_RR(dec_os_id, modulo_os_id) (ARC_AGU_MOD_OPC(4) | ARC_AGU_MOD_OFFSET_REG(dec_os_id) | ARC_AGU_MOD_WRAP_REG(modulo_os_id) | ARC_AGU_MOD_DIR(1)) #define ARC_AGU_AD_WRAP_INC_II(offset, modulo) (ARC_AGU_MOD_OPC(5) | ARC_AGU_MOD_OFFSET_IMM(offset) | ARC_AGU_MOD_WRAP_IMM(modulo)) #define ARC_AGU_AD_WRAP_DEC_II(offset, modulo) (ARC_AGU_MOD_OPC(5) | ARC_AGU_MOD_OFFSET_IMM(offset) | ARC_AGU_MOD_WRAP_IMM(modulo) | ARC_AGU_MOD_DIR(1)) #define ARC_AGU_AD_WRAP_INC_RI(dec_os_id, modulo) (ARC_AGU_MOD_OPC(6) | ARC_AGU_MOD_OFFSET_REG(dec_os_id) | ARC_AGU_MOD_WRAP_IMM(modulo)) #define ARC_AGU_AD_WRAP_DEC_RI(dec_os_id, modulo) (ARC_AGU_MOD_OPC(6) | ARC_AGU_MOD_OFFSET_REG(dec_os_id) | ARC_AGU_MOD_WRAP_IMM(modulo) | ARC_AGU_MOD_DIR(1)) /* Immediate Wrapping constants */ #define AGU_WRAP_IMM_2 0 #define AGU_WRAP_IMM_4 1 #define AGU_WRAP_IMM_8 2 #define AGU_WRAP_IMM_16 3 #define AGU_WRAP_IMM_32 4 #define AGU_WRAP_IMM_64 5 #define AGU_WRAP_IMM_128 6 #define AGU_WRAP_IMM_256 7 #define AGU_WRAP_IMM_512 8 #define AGU_WRAP_IMM_1024 9 #define AGU_WRAP_IMM_2048 10 #define AGU_WRAP_IMM_4096 11 #define AGU_WRAP_IMM_8192 12 #define AGU_WRAP_IMM_16384 13 #define AGU_WRAP_IMM_32768 14 #define AGU_WRAP_IMM_65536 15 /* push pop macros to follow calling conventions */ #define ARC_AGU_STORE_REGS(ap_num, mod_num, os_num) \ int32_t agu_temp_idx; \ uint32_t agu_temp_ap[ap_num]; \ uint32_t agu_temp_mod[mod_num]; \ uint32_t agu_temp_os[os_num]; \ int32_t agu_temp_ap_num = ap_num; \ int32_t agu_temp_mod_num = mod_num; \ int32_t agu_temp_os_num = os_num; \ for (agu_temp_idx = 0; agu_temp_idx < ap_num; agu_temp_idx++) agu_temp_ap[agu_temp_idx] = _lr(AGU_AUX_AP0 + agu_temp_idx); \ for (agu_temp_idx = 0; agu_temp_idx < mod_num; agu_temp_idx++) agu_temp_mod[agu_temp_idx] = _lr(AGU_AUX_MOD0 + agu_temp_idx); \ for (agu_temp_idx = 0; agu_temp_idx < os_num; agu_temp_idx++) agu_temp_os[agu_temp_idx] = _lr(AGU_AUX_OS0 + agu_temp_idx); {} #define ARC_AGU_RESTORE_REGS() \ for (agu_temp_idx = 0; agu_temp_idx < agu_temp_ap_num; agu_temp_idx++) _sr(agu_temp_ap[agu_temp_idx], AGU_AUX_AP0 + agu_temp_idx); \ for (agu_temp_idx = 0; agu_temp_idx < agu_temp_mod_num; agu_temp_idx++) _sr(agu_temp_mod[agu_temp_idx], AGU_AUX_MOD0 + agu_temp_idx); \ for (agu_temp_idx = 0; agu_temp_idx < agu_temp_os_num; agu_temp_idx++) _sr(agu_temp_os[agu_temp_idx], AGU_AUX_OS0 + agu_temp_idx); {} #ifdef __cplusplus } #endif #endif /* __ASSEMBLY__ */ #endif /* H_ARC_XY_AGU */
DayGitH/Python-Challenges
DailyProgrammer/DP20160408C.py
""" [2016-04-08] Challenge #261 [Hard] magic square dominoes https://www.reddit.com/r/dailyprogrammer/comments/4dwk7b/20160408_challenge_261_hard_magic_square_dominoes/ # Description An NxN magic square is an NxN grid of the numbers 1 through N^2 such that each row, column, and major diagonal adds up to M = N(N^(2)+1)/2. [See this week's Easy problem for an example.](https://www.reddit.com/r/dailyprogrammer/comments/4dccix/20160404_challenge_261_easy_verifying_3x3_magic/) For some even N, you will be given the numbers 1 through N^2 as N^(2)/2 pairs of numbers. You must produce an NxN magic square using the pairs of numbers like dominoes covering a grid. That is, your output is an NxN magic square such that, for each pair of numbers in the input, the two numbers in the pair are adjacent, either vertically or horizontally. The numbers can be swapped so that either one is on the top or left. For the input provided, there is guaranteed to be at least one magic square that can be formed this way. (In fact there must be at least eight such magic squares, given reflection and rotation.) Format the grid and input it into your function however you like. # Efficiency An acceptable solution to this problem must be significantly faster than brute force. (This is Hard, after all.) You don't need to get the optimal solution, but you should run your program to completion on at least one challenge input before submitting. Post your output for one of the challenge inputs along with your code (unless you're stuck and asking for help). Aim to finish one of the three 4x4 challenge inputs within a few minutes (my Python program takes about 11 seconds for all three). I have no idea how feasible the larger ones are. I started my program on a 6x6 input about 10 hours ago and it hasn't finished. But I'm guessing someone here will be more clever than me, so I generated inputs up to 16x16. Good luck! # Example input 1 9 2 10 3 6 4 14 5 11 7 15 8 16 12 13 # Example output 9 4 14 7 1 12 6 15 16 13 3 2 8 5 11 10 # Challenge inputs [Challenge inputs](http://pastebin.com/6dkYxvrM) """ def main(): pass if __name__ == "__main__": main()
Biyorne/learningcpp
random-test/main.cpp
#include <algorithm> #include <array> #include <cstdlib> #include <iostream> #include <random> #include <vector> #include "random.hpp" // Randomness - A lack of pattern and predictability. // Entropy - The randomness of a closed system. // True Randomness - Infinite entropy. // Pseudo Randomness - Zero entropy, but difficult for humans to predict. // Pseudo Random Number Generator - An algorithm that takes one number(seed) and gives you a // pseudo random result. It's limited by the number of bits in the values(size) and the number of // bits in the seed. // List of PRNG Algorithms (In order from lowest to highest quality) // The C Standard Library's rand() function. // Good enough that casual human users won't notice the pattern // So bad that no professional uses it anymore // Not good enough for encryption or statistical work // The Linear Congruential Generator (LCG) // The simplest, oldest and most well known // The quality varies depending on how you configure it // But still bad enough to be second on this list // Very fast // Still nowhere near good enough for encryption or statistical work // Subtract-With-Carry (SWC) // Just an improved version of LCG (but not a big one) // Not good enough for encryption or statistical work // The Mersenne Twister // It has great quality with a few nasty "gotchas" // Great speed // The biggest "gotcha" is that it's unreasonably bad with only slightly bad seeds. It NEEDS a good // seed. // What professionals use when randomness is not critical. // Still not good enough for encryption or statistics // Four Ways to get a seed (In order from worst to best) // Time (First used and worst possible) // Using time to generate a seed is tolerable for casual use (OS can give time in nanoseconds) // Human Interfaces // At best, high entropy but at worst, low entropy // Hardware // Specialized chunks of transistors that leverage unpredictable electron behavior // Operating Systems // Really just a combination of the three above // In general, combining multiple random sources does not add the entropy together. Usually, it // cancels them out. Picks from the best available options in the computer // Distribution // How likely some numbers are vs others to come out of the prng // Non-Uniformity // // True Randomness means that every number that can possibly be generated has the same chance of // being generated, but this is not always what you want. The way to define non-truly-random // behavior is with a probability distribution. Here are the most common examples: // // Uniform Distribution - Every number that can possibly be generated has an equal chance of // being generated. // // x Normal Distribution - Values in the center of the interval are more likely, creating a // classic bell-curve probability distribution. This is how you // could generate on the interval [1,100] where 50 is the most // likely. // // Exponential Distribution- If you count the number of times a coin toss lands 'heads' before // the first 'tails', then the chances of each count are: 0=50%, // 1=25%, 2=12.5%, and so on. Ths is an Exponential Distribution. // // (dozens of others...) // // The point: // - True Randomness is rarely what you want. // - If you want to eliminate duplicates or runs, then use a batch and remove process. // - All other situations where you want non-truly-random behavior can and should be defined with // a probability distribution. // The old C rand() way. #include <cstdlib> #include <ctime> void tenRandomNumbers_theOldCrandWay() { srand(static_cast<unsigned int>(time(nullptr))); for (int i(0); i < 10; ++i) { std::cout << (1 + (rand() % 4)) << std::endl; } } // Quick and dirty c++11 way // Not good enough for: encryption, statistics, unpredictability, if you need too many numbers or // need them too quickly #include <random> void tenRandomNumbers_quickAndDirtyCpp11Way() { // Decides where to get the seed from and gives us as many uints as we ask from it. std::random_device randomDevice; // Takes a small number of seeds and stretches it into however many the prng needs. //(note: this is the worst way to use seed_seq, but good enough for casual apps.) std::seed_seq seedSequence { randomDevice() }; // make the mt19937 PRNG and give it the seed (seed_seq) std::mt19937 engine; engine.seed(seedSequence); // this is both the distribution and the range limited over [1, 4] std::uniform_int_distribution<int> distribution(1, 4); for (int i(0); i < 10; ++i) { std::cout << distribution(engine) << std::endl; } } // Best possible use of mt19937 // yes we lose some entropy but this is still a kick ass mt19937 #include <array> #include <random> void tenRandomNumber_bestCpp11Way() { std::mt19937 engine; // create the the full state/seed from best seed sources std::random_device seedSource; std::array<unsigned int, engine.state_size> seedArray; std::generate(std::begin(seedArray), std::end(seedArray), std::ref(seedSource)); // put our perfect seed into seed_seq which makes no sense and loses entropy but we have to // because the engine only takes a seed_seq std::seed_seq seedSequence(std::begin(seedArray), std::end(seedArray)); engine.seed(seedSequence); std::uniform_int_distribution<int> dist { 1, 4 }; for (std::size_t i(0); i < 10; ++i) { std::cout << dist(engine) << std::endl; } } void diceRoller() { while (true) { std::cout << "How many sides?" << std::endl; int dieSideCount(0); std::cin >> dieSideCount; if (dieSideCount < 0) { return; } std::cout << "How many times?" << std::endl; std::size_t count(0); std::cin >> count; std::mt19937 engine; std::random_device seedSource; std::array<unsigned int, engine.state_size> seedArray; std::generate(std::begin(seedArray), std::end(seedArray), std::ref(seedSource)); std::seed_seq seedSequence(std::begin(seedArray), std::end(seedArray)); engine.seed(seedSequence); std::uniform_int_distribution<int> dist { 1, dieSideCount }; for (std::size_t i(0); i < count; ++i) { std::cout << count << "d" << dieSideCount << ": " << dist(engine) << std::endl; } } } void randomRollExamples() { Random random; std::cout << "1d6: " << random.rollInteger(1, 6) << std::endl; std::cout << "1d6: " << random.rollInteger(6, 1) << std::endl; std::cout << "1d6: " << random.rollInteger(6, 6) << std::endl; std::cout << "1d6: " << random.rollReal(1.0, 6.0) << std::endl; } int main(void) { // diceRoller(); // tenRandomNumbers_theOldCrandWay(); // tenRandomNumber_bestCpp11Way() // randomRollExamples(); Random random; for (int i(0); i < 10; ++i) { std::cout << random.rollInteger(10) << std::endl; std::cout << random.rollReal(10.0f) << std::endl; } char ignore('a'); std::cin >> ignore; return EXIT_SUCCESS; }
hendisantika/spring-ldap
core/src/test/java/org/springframework/ldap/transaction/compensating/manager/TransactionAwareContextSourceProxyTest.java
/* * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ldap.transaction.compensating.manager; import org.junit.Before; import org.junit.Test; import org.springframework.ldap.core.ContextSource; import org.springframework.ldap.core.DirContextProxy; import javax.naming.directory.DirContext; import javax.naming.ldap.LdapContext; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Tests for {@link TransactionAwareContextSourceProxy}. * * @author <NAME> */ public class TransactionAwareContextSourceProxyTest { private ContextSource contextSourceMock; private TransactionAwareContextSourceProxy tested; private LdapContext ldapContextMock; private DirContext dirContextMock; @Before public void setUp() throws Exception { contextSourceMock = mock(ContextSource.class); ldapContextMock = mock(LdapContext.class); dirContextMock = mock(DirContext.class); tested = new TransactionAwareContextSourceProxy(contextSourceMock); } @Test public void testGetReadWriteContext_LdapContext() { when(contextSourceMock.getReadWriteContext()).thenReturn(ldapContextMock); DirContext result = tested.getReadWriteContext(); assertNotNull("Result should not be null", result); assertTrue("Should be an LdapContext instance", result instanceof LdapContext); assertTrue("Should be a DirContextProxy instance", result instanceof DirContextProxy); } @Test public void testGetReadWriteContext_DirContext() { when(contextSourceMock.getReadWriteContext()).thenReturn(dirContextMock); DirContext result = tested.getReadWriteContext(); assertNotNull("Result should not be null", result); assertTrue("Should be a DirContext instance", result instanceof DirContext); assertFalse("Should not be an LdapContext instance", result instanceof LdapContext); assertTrue("Should be a DirContextProxy instance", result instanceof DirContextProxy); } @Test public void testGetReadOnlyContext_LdapContext() { when(contextSourceMock.getReadWriteContext()).thenReturn(ldapContextMock); DirContext result = tested.getReadOnlyContext(); assertNotNull("Result should not be null", result); assertTrue("Should be an LdapContext instance", result instanceof LdapContext); assertTrue("Should be a DirContextProxy instance", result instanceof DirContextProxy); } }
gordonturner/JEtsy
src/main/java/com/notronix/etsy/api/model/CartAssociations.java
package com.notronix.etsy.api.model; public enum CartAssociations { Shop, Listings, ShippingOptions }
MIDIculous/HISE
hi_sampler/sampler/ModulatorSamplerSound.cpp
<reponame>MIDIculous/HISE /* =========================================================================== * * This file is part of HISE. * Copyright 2016 <NAME> * * HISE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HISE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HISE. If not, see <http://www.gnu.org/licenses/>. * * Commercial licenses for using HISE in an closed source project are * available on request. Please visit the project's website to get more * information about commercial licensing: * * http://www.hise.audio/ * * HISE is based on the JUCE library, * which must be separately licensed for closed source applications: * * http://www.juce.com * * =========================================================================== */ namespace hise { using namespace juce; ModulatorSamplerSound::ModulatorSamplerSound(MainController* mc, StreamingSamplerSound *sound, int index_): ControlledObject(mc), index(index_), firstSound(sound), gain(1.0f), isMultiMicSound(false), centPitch(0), pitchFactor(1.0), maxRRGroup(1), rrGroup(1), normalizedPeak(-1.0f), isNormalized(false), upperVeloXFadeValue(0), lowerVeloXFadeValue(0), pan(0), purged(false), purgeChannels(0) { soundArray.add(firstSound.get()); setProperty(Pan, 0, dontSendNotification); } ModulatorSamplerSound::ModulatorSamplerSound(MainController* mc, StreamingSamplerSoundArray &soundArray_, int index_): ControlledObject(mc), index(index_), soundArray(soundArray_), firstSound(soundArray_.getFirst()), isMultiMicSound(true), gain(1.0f), centPitch(0), pitchFactor(1.0), maxRRGroup(1), rrGroup(1), normalizedPeak(-1.0f), isNormalized(false), upperVeloXFadeValue(0), lowerVeloXFadeValue(0), pan(0), purged(false), purgeChannels(0) { setProperty(Pan, 0, dontSendNotification); } ModulatorSamplerSound::~ModulatorSamplerSound() { getMainController()->getSampleManager().getModulatorSamplerSoundPool()->clearUnreferencedSamples(); firstSound = nullptr; soundArray.clear(); removeAllChangeListeners(); } String ModulatorSamplerSound::getPropertyName(Property p) { switch (p) { case ID: return "ID"; case FileName: return "FileName"; case RootNote: return "Root"; case KeyHigh: return "HiKey"; case KeyLow: return "LoKey"; case VeloLow: return "LoVel"; case VeloHigh: return "HiVel"; case RRGroup: return "RRGroup"; case Volume: return "Volume"; case Pan: return "Pan"; case Normalized: return "Normalized"; case Pitch: return "Pitch"; case SampleStart: return "SampleStart"; case SampleEnd: return "SampleEnd"; case SampleStartMod:return "SampleStartMod"; case LoopEnabled: return "LoopEnabled"; case LoopStart: return "LoopStart"; case LoopEnd: return "LoopEnd"; case LoopXFade: return "LoopXFade"; case UpperVelocityXFade: return "UpperVelocityXFade"; case LowerVelocityXFade: return "LowerVelocityXFade"; case SampleState: return "SampleState"; default: jassertfalse; return String(); } } bool ModulatorSamplerSound::isAsyncProperty(Property p) { return p >= SampleStart; } Range<int> ModulatorSamplerSound::getPropertyRange(Property p) const { auto s = soundArray.getFirst(); if (s == nullptr) return {}; switch (p) { case ID: return Range<int>(0, INT_MAX); case FileName: jassertfalse; return Range<int>(); case RootNote: return Range<int>(0, 127); case KeyHigh: return Range<int>((int)getProperty(KeyLow), 127); case KeyLow: return Range<int>(0, (int)getProperty(KeyHigh)); case VeloLow: return Range<int>(0, (int)getProperty(VeloHigh) - 1); case VeloHigh: return Range<int>((int)getProperty(VeloLow) + 1, 127); case Volume: return Range<int>(-100, 18); case Pan: return Range<int>(-100, 100); case Normalized: return Range<int>(0, 1); case RRGroup: return Range<int>(1, maxRRGroup); case Pitch: return Range<int>(-100, 100); case SampleStart: return firstSound->isLoopEnabled() ? Range<int>(0, jmin<int>((int)firstSound->getLoopStart() - (int)firstSound->getLoopCrossfade(), (int)(firstSound->getSampleEnd() - (int)firstSound->getSampleStartModulation()))) : Range<int>(0, (int)firstSound->getSampleEnd() - (int)firstSound->getSampleStartModulation()); case SampleEnd: { const int sampleStartMinimum = (int)(firstSound->getSampleStart() + firstSound->getSampleStartModulation()); const int upperLimit = (int)firstSound->getLengthInSamples(); if (firstSound->isLoopEnabled()) { const int lowerLimit = jmax<int>(sampleStartMinimum, (int)firstSound->getLoopEnd()); return Range<int>(lowerLimit, upperLimit); } else { const int lowerLimit = sampleStartMinimum; return Range<int>(lowerLimit, upperLimit); } } case SampleStartMod:return Range<int>(0, (int)firstSound->getSampleLength()); case LoopEnabled: return Range<int>(0, 1); case LoopStart: return Range<int>((int)firstSound->getSampleStart() + (int)firstSound->getLoopCrossfade(), (int)firstSound->getLoopEnd() - (int)firstSound->getLoopCrossfade()); case LoopEnd: return Range<int>((int)firstSound->getLoopStart() + (int)firstSound->getLoopCrossfade(), (int)firstSound->getSampleEnd()); case LoopXFade: return Range<int>(0, jmin<int>((int)(firstSound->getLoopStart() - firstSound->getSampleStart()), (int)firstSound->getLoopLength())); case UpperVelocityXFade: return Range < int >(0, (int)getProperty(VeloHigh) - ((int)getProperty(VeloLow) + lowerVeloXFadeValue)); case LowerVelocityXFade: return Range < int >(0, (int)getProperty(VeloHigh) - upperVeloXFadeValue - (int)getProperty(VeloLow)); case SampleState: return Range<int>(0, (int)StreamingSamplerSound::numSampleStates - 1); default: jassertfalse; return Range<int>(); } } String ModulatorSamplerSound::getPropertyAsString(Property p) const { auto s = soundArray.getFirst(); if (s == nullptr) return {}; switch (p) { case ID: return String(index); case FileName: return firstSound->getFileName(false); case RootNote: return MidiMessage::getMidiNoteName(rootNote, true, true, 3); case KeyHigh: return MidiMessage::getMidiNoteName(midiNotes.getHighestBit(), true, true, 3); case KeyLow: return MidiMessage::getMidiNoteName(midiNotes.findNextSetBit(0), true, true, 3); case VeloHigh: return String(velocityRange.getHighestBit()); case VeloLow: return String(velocityRange.findNextSetBit(0)); case RRGroup: return String(rrGroup); case Volume: return String(Decibels::gainToDecibels(gain.get()), 1) + " dB"; case Pan: return BalanceCalculator::getBalanceAsString(pan); case Normalized: return isNormalized ? "Enabled" : "Disabled"; case Pitch: return String(centPitch, 0) + " ct"; case SampleStart: return String(firstSound->getSampleStart()); case SampleEnd: return String(firstSound->getSampleEnd()); case SampleStartMod:return String(firstSound->getSampleStartModulation()); case LoopEnabled: return firstSound->isLoopEnabled() ? "Enabled" : "Disabled"; case LoopStart: return String(firstSound->getLoopStart()); case LoopEnd: return String(firstSound->getLoopEnd()); case LoopXFade: return String(firstSound->getLoopCrossfade()); case UpperVelocityXFade: return String(upperVeloXFadeValue); case LowerVelocityXFade: return String(lowerVeloXFadeValue); case SampleState: return firstSound->getSampleStateAsString(); default: jassertfalse; return String(); } } var ModulatorSamplerSound::getProperty(Property p) const { auto s = soundArray.getFirst(); if (s == nullptr) return {}; switch (p) { case ID: return var(index); case FileName: return var(firstSound->getFileName(true)); case RootNote: return var(rootNote); case KeyHigh: return var(midiNotes.getHighestBit()); case KeyLow: return var(midiNotes.findNextSetBit(0)); case VeloHigh: return var(velocityRange.getHighestBit()); case VeloLow: return var(velocityRange.findNextSetBit(0)); case RRGroup: return var(rrGroup); case Volume: return var(Decibels::gainToDecibels(gain.get())); case Pan: return var(pan); case Normalized: return var(isNormalized); case Pitch: return var(centPitch); case SampleStart: return var(firstSound->getSampleStart()); case SampleEnd: return var(firstSound->getSampleEnd()); case SampleStartMod:return var(firstSound->getSampleStartModulation()); case LoopEnabled: return var(firstSound->isLoopEnabled()); case LoopStart: return var(firstSound->getLoopStart()); case LoopEnd: return var(firstSound->getLoopEnd()); case LoopXFade: return var(firstSound->getLoopCrossfade()); case UpperVelocityXFade: return var(upperVeloXFadeValue); case LowerVelocityXFade: return var(lowerVeloXFadeValue); case SampleState: return var(isPurged()); default: jassertfalse; return var::undefined(); } } void ModulatorSamplerSound::setProperty(Property p, int newValue, NotificationType notifyEditor/*=sendNotification*/) { //ScopedLock sl(getLock()); if (enableAsyncPropertyChange && isAsyncProperty(p)) { ModulatorSamplerSound::Ptr refPtr = this; auto f = [refPtr, p, newValue, notifyEditor](Processor*) { if (refPtr != nullptr) { static_cast<ModulatorSamplerSound*>(refPtr.get())->setPreloadPropertyInternal(p, newValue); if(notifyEditor) static_cast<ModulatorSamplerSound*>(refPtr.get())->sendChangeMessage(); } return true; }; getMainController()->getKillStateHandler().killVoicesAndCall(getMainController()->getMainSynthChain(), f, MainController::KillStateHandler::TargetThread::SampleLoadingThread); } else { setPropertyInternal(p, newValue); if(notifyEditor) sendChangeMessage(); } } void ModulatorSamplerSound::toggleBoolProperty(ModulatorSamplerSound::Property p, NotificationType notifyEditor/*=sendNotification*/) { switch (p) { case Normalized: { isNormalized = !isNormalized; if (isNormalized) calculateNormalizedPeak(); break; } case LoopEnabled: { const bool wasEnabled = firstSound->isLoopEnabled(); FOR_EVERY_SOUND(setLoopEnabled(!wasEnabled)); break; } default: jassertfalse; break; } if(notifyEditor == sendNotification) sendChangeMessage(); } ValueTree ModulatorSamplerSound::exportAsValueTree() const { const ScopedLock sl(getLock()); ValueTree v("sample"); for (int i = ID; i < numProperties; i++) { Property p = (Property)i; v.setProperty(getPropertyName(p), getProperty(p), nullptr); } if (isMultiMicSound) { v.removeProperty(getPropertyName(FileName), nullptr); for (auto s: soundArray) { ValueTree fileChild("file"); fileChild.setProperty("FileName", s->getFileName(true), nullptr); v.addChild(fileChild, -1, nullptr); } } v.setProperty("NormalizedPeak", normalizedPeak, nullptr); if(firstSound.get()->isMonolithic()) { const int64 offset = firstSound->getMonolithOffset(); const int64 length = firstSound->getMonolithLength(); const double sampleRate = firstSound->getMonolithSampleRate(); v.setProperty("MonolithOffset", offset, nullptr); v.setProperty("MonolithLength", length, nullptr); v.setProperty("SampleRate", sampleRate, nullptr); } v.setProperty("Duplicate", firstSound->getReferenceCount() >= 3, nullptr); return v; } void ModulatorSamplerSound::restoreFromValueTree(const ValueTree &v) { const ScopedLock sl(getLock()); ScopedValueSetter<bool> svs(enableAsyncPropertyChange, false); normalizedPeak = v.getProperty("NormalizedPeak", -1.0f); for (int i = RootNote; i < numProperties; i++) // ID and filename must be passed to the constructor! { Property p = (Property)i; var x = v.getProperty(getPropertyName(p), var::undefined()); if (!x.isUndefined()) setProperty(p, x, dontSendNotification); } } void ModulatorSamplerSound::startPropertyChange(Property p, int newValue) { String x; x << getPropertyName(p) << ": " << getPropertyAsString(p) << " -> " << String(newValue); if (undoManager != nullptr) undoManager->beginNewTransaction(x); } void ModulatorSamplerSound::endPropertyChange(Property p, int startValue, int endValue) { String x; x << getPropertyName(p) << ": " << String(startValue) << " -> " << String(endValue); if (undoManager != nullptr) undoManager->setCurrentTransactionName(x); } void ModulatorSamplerSound::endPropertyChange(const String &actionName) { if (undoManager != nullptr) undoManager->setCurrentTransactionName(actionName); } void ModulatorSamplerSound::setPropertyWithUndo(Property p, var newValue) { if (undoManager != nullptr) { undoManager->perform(new PropertyChange(this, p, newValue)); } else setProperty(p, (int)newValue); } void ModulatorSamplerSound::openFileHandle() { FOR_EVERY_SOUND(openFileHandle()); } void ModulatorSamplerSound::closeFileHandle() { FOR_EVERY_SOUND(closeFileHandle()); } Range<int> ModulatorSamplerSound::getNoteRange() const { return Range<int>(midiNotes.findNextSetBit(0), midiNotes.getHighestBit() + 1); } Range<int> ModulatorSamplerSound::getVelocityRange() const { return Range<int>(velocityRange.findNextSetBit(0), velocityRange.getHighestBit() + 1); } float ModulatorSamplerSound::getPropertyVolume() const noexcept { return gain.get(); } double ModulatorSamplerSound::getPropertyPitch() const noexcept { return pitchFactor.load(); } void ModulatorSamplerSound::setMaxRRGroupIndex(int newGroupLimit) { maxRRGroup = newGroupLimit; // Not sure why this is here, remove it when nobody complains... // rrGroup = jmin(rrGroup, newGroupLimit); } void ModulatorSamplerSound::setMappingData(MappingData newData) { rootNote = newData.rootNote; velocityRange.clear(); velocityRange.setRange(newData.loVel, newData.hiVel - newData.loVel + 1, true); midiNotes.clear(); midiNotes.setRange(newData.loKey, newData.hiKey - newData.loKey + 1, true); rrGroup = newData.rrGroup; setProperty(SampleStart, newData.sampleStart, dontSendNotification); setProperty(SampleEnd, newData.sampleEnd, dontSendNotification); setProperty(SampleStartMod, newData.sampleStartMod, dontSendNotification); setProperty(LoopEnabled, newData.loopEnabled, dontSendNotification); setProperty(LoopStart, newData.loopStart, dontSendNotification); setProperty(LoopEnd, newData.loopEnd, dontSendNotification); setProperty(LoopXFade, newData.loopXFade, dontSendNotification); setProperty(Volume, newData.volume, dontSendNotification); setProperty(Pan, newData.pan, dontSendNotification); setProperty(Pitch, newData.pitch, dontSendNotification); } void ModulatorSamplerSound::calculateNormalizedPeak(bool forceScan /*= false*/) { if (forceScan || normalizedPeak < 0.0f) { float highestPeak = 0.0f; for (auto s: soundArray) { highestPeak = jmax<float>(highestPeak, s->calculatePeakValue()); } if (highestPeak != 0.0f) { normalizedPeak = 1.0f / highestPeak; } } } float ModulatorSamplerSound::getNormalizedPeak() const { return (isNormalized && normalizedPeak != -1.0f) ? normalizedPeak : 1.0f; } float ModulatorSamplerSound::getBalance(bool getRightChannelGain) const { return getRightChannelGain ? rightBalanceGain : leftBalanceGain; } void ModulatorSamplerSound::setVelocityXFade(int crossfadeLength, bool isUpperSound) { if (isUpperSound) lowerVeloXFadeValue = crossfadeLength; else upperVeloXFadeValue = crossfadeLength; } void ModulatorSamplerSound::setPurged(bool shouldBePurged) { purged = shouldBePurged; FOR_EVERY_SOUND(setPurged(shouldBePurged)); } void ModulatorSamplerSound::checkFileReference() { allFilesExist = true; FOR_EVERY_SOUND(checkFileReference()) for (auto s: soundArray) { if (s->isMissing()) { allFilesExist = false; break; } } } float ModulatorSamplerSound::getGainValueForVelocityXFade(int velocity) { if (upperVeloXFadeValue == 0 && lowerVeloXFadeValue == 0) return 1.0f; Range<int> upperRange = Range<int>(velocityRange.getHighestBit() - upperVeloXFadeValue, velocityRange.getHighestBit()); Range<int> lowerRange = Range<int>(velocityRange.findNextSetBit(0), velocityRange.findNextSetBit(0) + lowerVeloXFadeValue); float delta = 1.0f; if (upperRange.contains(velocity)) { delta = (float)(velocity - upperRange.getStart()) / (upperRange.getLength()); return Interpolator::interpolateLinear(1.0f, 0.0f, delta); } else if (lowerRange.contains(velocity)) { delta = (float)(velocity - lowerRange.getStart()) / (lowerRange.getLength()); return Interpolator::interpolateLinear(0.0f, 1.0f, delta); } else { return 1.0f; } } int ModulatorSamplerSound::getNumMultiMicSamples() const noexcept { return soundArray.size(); } bool ModulatorSamplerSound::isChannelPurged(int channelIndex) const { return purgeChannels[channelIndex]; } void ModulatorSamplerSound::setChannelPurged(int channelIndex, bool shouldBePurged) { if (purged) return; purgeChannels.setBit(channelIndex, shouldBePurged); if (auto s = soundArray[channelIndex]) { s->setPurged(shouldBePurged); } } bool ModulatorSamplerSound::preloadBufferIsNonZero() const noexcept { for (auto s: soundArray) { if (!s->isPurged() && s->getPreloadBuffer().getNumSamples() != 0) { return true; } } return false; } int ModulatorSamplerSound::getRRGroup() const { return rrGroup; } void ModulatorSamplerSound::selectSoundsBasedOnRegex(const String &regexWildcard, ModulatorSampler *sampler, SelectedItemSet<ModulatorSamplerSound::Ptr> &set) { bool subtractMode = false; bool addMode = false; String wildcard = regexWildcard; if (wildcard.startsWith("sub:")) { subtractMode = true; wildcard = wildcard.fromFirstOccurrenceOf("sub:", false, true); } else if (wildcard.startsWith("add:")) { addMode = true; wildcard = wildcard.fromFirstOccurrenceOf("add:", false, true); } else { set.deselectAll(); } try { std::regex reg(wildcard.toStdString()); ModulatorSampler::SoundIterator iter(sampler, false); while (auto sound = iter.getNextSound()) { const String name = sound->getPropertyAsString(Property::FileName); if (std::regex_search(name.toStdString(), reg)) { if (subtractMode) { set.deselect(sound.get()); } else { set.addToSelection(sound.get()); } } } } catch (std::regex_error e) { debugError(sampler, e.what()); } } void ModulatorSamplerSound::setPropertyInternal(Property p, int newValue) { switch (p) { case ID: jassertfalse; break; case FileName: jassertfalse; break; case RootNote: rootNote = newValue; break; case VeloHigh: { int low = jmin(velocityRange.findNextSetBit(0), newValue, 127); velocityRange.clear(); velocityRange.setRange(low, newValue - low + 1, true); break; } case VeloLow: { int high = jmax(velocityRange.getHighestBit(), newValue, 0); velocityRange.clear(); velocityRange.setRange(newValue, high - newValue + 1, true); break; } case KeyHigh: { int low = jmin(midiNotes.findNextSetBit(0), newValue, 127); midiNotes.clear(); midiNotes.setRange(low, newValue - low + 1, true); break; } case KeyLow: { int high = jmax(midiNotes.getHighestBit(), newValue, 0); midiNotes.clear(); midiNotes.setRange(newValue, high - newValue + 1, true); break; } case RRGroup: rrGroup = newValue; break; case Normalized: isNormalized = newValue == 1; if (isNormalized && normalizedPeak < 0.0f) calculateNormalizedPeak(); break; case Volume: { gain.set(Decibels::decibelsToGain((float)newValue)); break; } case Pan: { pan = (int)newValue; leftBalanceGain = BalanceCalculator::getGainFactorForBalance((float)newValue, true); rightBalanceGain = BalanceCalculator::getGainFactorForBalance((float)newValue, false); break; } case Pitch: { centPitch = newValue; pitchFactor.store(powf(2.0f, (float)centPitch / 1200.f)); break; }; case SampleStart: FOR_EVERY_SOUND(setSampleStart(newValue)); break; case SampleEnd: FOR_EVERY_SOUND(setSampleEnd(newValue)); break; case SampleStartMod: FOR_EVERY_SOUND(setSampleStartModulation(newValue)); break; case LoopEnabled: FOR_EVERY_SOUND(setLoopEnabled(newValue == 1.0f)); break; case LoopStart: FOR_EVERY_SOUND(setLoopStart(newValue)); break; case LoopEnd: FOR_EVERY_SOUND(setLoopEnd(newValue)); break; case LoopXFade: FOR_EVERY_SOUND(setLoopCrossfade(newValue)); break; case LowerVelocityXFade: lowerVeloXFadeValue = newValue; break; case UpperVelocityXFade: upperVeloXFadeValue = newValue; break; case SampleState: setPurged(newValue == 1.0f); break; default: jassertfalse; break; } } void ModulatorSamplerSound::setPreloadPropertyInternal(Property p, int newValue) { auto firstSampler = ProcessorHelpers::getFirstProcessorWithType<ModulatorSampler>(getMainController()->getMainSynthChain()); auto f = [this, p, newValue](Processor*)->bool { setPropertyInternal(p, newValue); return true; }; firstSampler->killAllVoicesAndCall(f); } // ==================================================================================================================== ModulatorSamplerSound::PropertyChange::PropertyChange(ModulatorSamplerSound *soundToChange, Property p, var newValue) : changedProperty(p), currentValue(newValue), sound(soundToChange), lastValue(soundToChange->getProperty(p)) { } bool ModulatorSamplerSound::PropertyChange::perform() { if (sound != nullptr) { auto s = dynamic_cast<ModulatorSamplerSound*>(sound.get()); s->setProperty(changedProperty, currentValue); return true; } else return false; } bool ModulatorSamplerSound::PropertyChange::undo() { if (sound != nullptr) { auto s = dynamic_cast<ModulatorSamplerSound*>(sound.get()); s->setProperty(changedProperty, lastValue); return true; } else return false; } // ==================================================================================================================== ModulatorSamplerSoundPool::ModulatorSamplerSoundPool(MainController *mc_) : mc(mc_), debugProcessor(nullptr), mainAudioProcessor(nullptr), updatePool(true), searchPool(true), forcePoolSearch(false), isCurrentlyLoading(false), asyncCleaner(*this) { } void ModulatorSamplerSoundPool::setDebugProcessor(Processor *p) { debugProcessor = p; } ModulatorSamplerSound * ModulatorSamplerSoundPool::addSound(const ValueTree &soundDescription, int index, bool forceReuse /*= false*/) { if (soundDescription.getNumChildren() > 1) { return addSoundWithMultiMic(soundDescription, index, forceReuse); } else { return addSoundWithSingleMic(soundDescription, index, forceReuse); } } bool ModulatorSamplerSoundPool::loadMonolithicData(const ValueTree &sampleMap, const Array<File>& monolithicFiles, OwnedArray<ModulatorSamplerSound> &sounds) { jassert(!mc->getMainSynthChain()->areVoicesActive()); clearUnreferencedMonoliths(); loadedMonoliths.add(new MonolithInfoToUse(monolithicFiles)); MonolithInfoToUse* hmaf = loadedMonoliths.getLast(); try { hmaf->fillMetadataInfo(sampleMap); } catch (StreamingSamplerSound::LoadingError l) { String x; x << "Error at loading sample " << l.fileName << ": " << l.errorDescription; mc->getDebugLogger().logMessage(x); #if USE_FRONTEND mc->sendOverlayMessage(DeactiveOverlay::State::CustomErrorMessage, x); #else debugError(mc->getMainSynthChain(), x); #endif return false; } for (int i = 0; i < sampleMap.getNumChildren(); i++) { ValueTree sample = sampleMap.getChild(i); if (sample.getNumChildren() == 0) { String fileName = sample.getProperty("FileName").toString().fromFirstOccurrenceOf("{PROJECT_FOLDER}", false, false); StreamingSamplerSound* sound = new StreamingSamplerSound(hmaf, 0, i); pool.add(sound); sounds.add(new ModulatorSamplerSound(mc, sound, i)); } else { StreamingSamplerSoundArray multiMicArray; for (int j = 0; j < sample.getNumChildren(); j++) { StreamingSamplerSound* sound = new StreamingSamplerSound(hmaf, j, i); pool.add(sound); multiMicArray.add(sound); } sounds.add(new ModulatorSamplerSound(mc, multiMicArray, i)); } } sendChangeMessage(); return true; } void ModulatorSamplerSoundPool::clearUnreferencedSamples() { asyncCleaner.triggerAsyncUpdate(); } void ModulatorSamplerSoundPool::clearUnreferencedSamplesInternal() { WeakStreamingSamplerSoundArray currentList; currentList.ensureStorageAllocated(pool.size()); for (int i = 0; i < pool.size(); i++) { if (pool[i].get() != nullptr) { currentList.add(pool[i]); } } pool.swapWith(currentList); if (updatePool) sendChangeMessage(); } int ModulatorSamplerSoundPool::getNumSoundsInPool() const noexcept { return pool.size(); } void ModulatorSamplerSoundPool::getMissingSamples(StreamingSamplerSoundArray &missingSounds) const { for (auto s: pool) { if (s != nullptr && s->isMissing()) { missingSounds.add(s); } } } class SampleResolver : public DialogWindowWithBackgroundThread { public: class HorizontalSpacer: public Component { public: HorizontalSpacer() { setSize(900, 2); } }; SampleResolver(ModulatorSamplerSoundPool *pool_, Processor *synthChain_): DialogWindowWithBackgroundThread("Sample Resolver"), pool(pool_), mainSynthChain(synthChain_) { pool->getMissingSamples(missingSounds); if (missingSounds.size() == 0) { addBasicComponents(false); } else { numMissingSounds = missingSounds.size(); remainingSounds = numMissingSounds; String textToShow = "Remaining missing sounds: " + String(remainingSounds) + " / " + String(numMissingSounds) + " missing sounds."; addCustomComponent(spacer = new HorizontalSpacer()); String fileNames = missingSounds[0]->getFileName(true); String path; if(ProjectHandler::isAbsolutePathCrossPlatform(fileNames)) { path = File(fileNames).getParentDirectory().getFullPathName(); } else path = fileNames; addTextEditor("fileNames", fileNames, "Filenames:"); addTextEditor("search", path, "Search for:"); addTextEditor("replace", path, "Replace with:"); addButton("Search in Finder", 5); addBasicComponents(true); showStatusMessage(textToShow); } }; void run() override { const String search = getTextEditorContents("search"); const String replace = getTextEditorContents("replace"); pool->setUpdatePool(false); int foundThisTime = 0; showStatusMessage("Replacing references"); try { const double numMissingSoundsDouble = (double)missingSounds.size(); for (int i = 0; i < missingSounds.size(); i++) { if (threadShouldExit()) return; setProgress(double(i) / numMissingSoundsDouble); auto sound = missingSounds[i]; String newFileName = sound->getFileName(true).replace(search, replace, true); String newFileNameSanitized = newFileName.replace("\\", "/"); if (File(newFileNameSanitized).existsAsFile()) { sound->replaceFileReference(newFileNameSanitized); foundThisTime++; missingSounds.remove(i--); } } } catch (StreamingSamplerSound::LoadingError e) { String x; x << "Error at loading sample " << e.fileName << ": " << e.errorDescription; mainSynthChain->getMainController()->getDebugLogger().logMessage(x); errorMessage = "There was an error at preloading."; return; } remainingSounds -= foundThisTime; showStatusMessage("Replacing references"); Processor::Iterator<ModulatorSampler> iter(mainSynthChain); int numSamplers = iter.getNumProcessors(); int index = 0; while (ModulatorSampler *s = iter.getNextProcessor()) { setProgress((double)index / (double)numSamplers); ModulatorSampler::SoundIterator sIter(s); while (auto sound = sIter.getNextSound()) { sound->checkFileReference(); } s->sendChangeMessage(); index++; } } void threadFinished() { if (errorMessage.isEmpty()) { PresetHandler::showMessageWindow("Missing Samples resolved", String(numMissingSounds - remainingSounds) + " out of " + String(numMissingSounds) + " were resolved.", PresetHandler::IconType::Info); } else { PresetHandler::showMessageWindow("Error", errorMessage, PresetHandler::IconType::Error); } pool->setUpdatePool(true); pool->sendChangeMessage(); } void resultButtonClicked(const String &name) override { if(name == "Search in Finder") { String file = getTextEditor("fileNames")->getText(); file.replace("\\", "/"); String fileName = file.fromLastOccurrenceOf("/", false, false); String pathName = file.upToLastOccurrenceOf("/", true, false); #if JUCE_WINDOWS String dialogName = "Explorer"; #else String dialogName = "Finder"; #endif PresetHandler::showMessageWindow("Search file", "Search for the sample:\n\n"+fileName +"\n\nPress OK to open the " + dialogName, PresetHandler::IconType::Info); FileChooser fc("Search sample location " + fileName); if(fc.browseForFileToOpen()) { File f = fc.getResult(); String newPath = f.getFullPathName().replaceCharacter('\\', '/').upToLastOccurrenceOf("/", true, false);; getTextEditor("search")->setText(pathName); getTextEditor("replace")->setText(newPath); } } }; private: StreamingSamplerSoundArray missingSounds; ScopedPointer<HorizontalSpacer> spacer; int remainingSounds; int numMissingSounds; String errorMessage; ModulatorSamplerSoundPool *pool; WeakReference<Processor> mainSynthChain; }; void ModulatorSamplerSoundPool::resolveMissingSamples(Component *childComponentOfMainEditor) { #if USE_BACKEND auto editor = dynamic_cast<BackendRootWindow*>(childComponentOfMainEditor); if (editor == nullptr) editor = GET_BACKEND_ROOT_WINDOW(childComponentOfMainEditor); SampleResolver *r = new SampleResolver(this, editor->getMainSynthChain()); r->setModalBaseWindowComponent(childComponentOfMainEditor); #else ignoreUnused(childComponentOfMainEditor); #endif } StringArray ModulatorSamplerSoundPool::getFileNameList() const { StringArray sa; for (int i = 0; i < pool.size(); i++) { sa.add(pool[i]->getFileName(true)); } return sa; } size_t ModulatorSamplerSoundPool::getMemoryUsageForAllSamples() const noexcept { if (mc->getSampleManager().isPreloading()) return 0; ScopedLock sl(mc->getSampleManager().getSamplerSoundLock()); size_t memoryUsage = 0; for (auto s : pool) { if (s == nullptr) continue; memoryUsage += s->getActualPreloadSize(); } return memoryUsage; } String ModulatorSamplerSoundPool::getTextForPoolTable(int columnId, int indexInPool) { #if USE_BACKEND if (auto s = pool[indexInPool]) { switch (columnId) { case SamplePoolTable::FileName: return s->getFileName(); case SamplePoolTable::Memory: return String((int)(s->getActualPreloadSize() / 1024)) + " kB"; case SamplePoolTable::State: return String(s->getSampleStateAsString()); case SamplePoolTable::References: return String(s->getReferenceCount()); default: jassertfalse; return ""; } } else { return "Invalid Index"; } #else ignoreUnused(columnId, indexInPool); return ""; #endif } void ModulatorSamplerSoundPool::increaseNumOpenFileHandles() { StreamingSamplerSoundPool::increaseNumOpenFileHandles(); if(updatePool) sendChangeMessage(); } void ModulatorSamplerSoundPool::decreaseNumOpenFileHandles() { StreamingSamplerSoundPool::decreaseNumOpenFileHandles(); if(updatePool) sendChangeMessage(); } bool ModulatorSamplerSoundPool::isFileBeingUsed(int poolIndex) { if (auto s = pool[poolIndex]) { return s->isOpened(); } return false; } int ModulatorSamplerSoundPool::getSoundIndexFromPool(int64 hashCode, int64 otherPossibleHashCode) { if (!searchPool) return -1; for (int i = 0; i < pool.size(); i++) { StreamingSamplerSound::Ptr s = pool[i].get(); if (s == nullptr) return -1; if (s->getHashCode() == hashCode) return i; if (otherPossibleHashCode != -1 && s->getHashCode() == otherPossibleHashCode) return i; } return -1; } ModulatorSamplerSound * ModulatorSamplerSoundPool::addSoundWithSingleMic(const ValueTree &soundDescription, int index, bool forceReuse /*= false*/) { String fileNameWildcard = soundDescription.getProperty(ModulatorSamplerSound::getPropertyName(ModulatorSamplerSound::FileName)); String fileName = GET_PROJECT_HANDLER(mc->getMainSynthChain()).getFilePath(fileNameWildcard, ProjectHandler::SubDirectories::Samples); if (forceReuse) { int64 hash = fileName.hashCode64(); int64 hashWildcard = fileNameWildcard.hashCode64(); int i = getSoundIndexFromPool(hash, hashWildcard); if (i != -1) { if(updatePool) sendChangeMessage(); return new ModulatorSamplerSound(mc, pool[i], index); } else { jassertfalse; return nullptr; } } else { static Identifier duplicate("Duplicate"); const bool isDuplicate = soundDescription.getProperty(duplicate, true); const bool searchThisSampleInPool = forcePoolSearch || isDuplicate; if(searchThisSampleInPool) { int64 hash = fileName.hashCode64(); int64 hashWildcard = fileNameWildcard.hashCode64(); int i = getSoundIndexFromPool(hash, hashWildcard); if (i != -1) { ModulatorSamplerSound *sound = new ModulatorSamplerSound(mc, pool[i], index); if(updatePool) sendChangeMessage(); return sound; } } StreamingSamplerSound::Ptr s = new StreamingSamplerSound(fileName, this); pool.add(s.get()); if(updatePool) sendChangeMessage(); return new ModulatorSamplerSound(mc, s, index); } } ModulatorSamplerSound * ModulatorSamplerSoundPool::addSoundWithMultiMic(const ValueTree &soundDescription, int index, bool forceReuse /*= false*/) { StreamingSamplerSoundArray multiMicArray; for (int i = 0; i < soundDescription.getNumChildren(); i++) { String fileNameWildcard = soundDescription.getChild(i).getProperty(ModulatorSamplerSound::getPropertyName(ModulatorSamplerSound::FileName)); String fileName = GET_PROJECT_HANDLER(mc->getMainSynthChain()).getFilePath(fileNameWildcard, ProjectHandler::SubDirectories::Samples); if (forceReuse) { int64 hash = fileName.hashCode64(); int64 hashWildcard = fileNameWildcard.hashCode64(); int j = getSoundIndexFromPool(hash, hashWildcard); jassert(j != -1); multiMicArray.add(pool[j]); if(updatePool) sendChangeMessage(); } else { static Identifier duplicate("Duplicate"); const bool isDuplicate = soundDescription.getProperty(duplicate, true); const bool searchThisSampleInPool = forcePoolSearch || isDuplicate; if (searchThisSampleInPool) { int64 hash = fileName.hashCode64(); int64 hashWildcard = fileNameWildcard.hashCode64(); int j = getSoundIndexFromPool(hash, hashWildcard); if (j != -1) { multiMicArray.add(pool[j]); continue; } else { StreamingSamplerSound::Ptr s = new StreamingSamplerSound(fileName, this); multiMicArray.add(s); pool.add(s.get()); continue; } } else { StreamingSamplerSound::Ptr s = new StreamingSamplerSound(fileName, this); multiMicArray.add(s); pool.add(s.get()); } } } if(updatePool) sendChangeMessage(); return new ModulatorSamplerSound(mc, multiMicArray, index); } bool ModulatorSamplerSoundPool::isPoolSearchForced() const { return forcePoolSearch; } void ModulatorSamplerSoundPool::clearUnreferencedMonoliths() { for (int i = 0; i < loadedMonoliths.size(); i++) { if (loadedMonoliths[i]->getReferenceCount() == 2) { loadedMonoliths.remove(i--); } } if(updatePool) sendChangeMessage(); } #define SET_IF_NOT_ZERO(field, x) if ((int)sound->getProperty(x) != 0) field = (int)sound->getProperty(x); void MappingData::fillOtherProperties(ModulatorSamplerSound* sound) { SET_IF_NOT_ZERO(volume, ModulatorSamplerSound::Volume); SET_IF_NOT_ZERO(pan, ModulatorSamplerSound::Pan); SET_IF_NOT_ZERO(pitch, ModulatorSamplerSound::Pitch); SET_IF_NOT_ZERO(sampleStart, ModulatorSamplerSound::SampleStart); SET_IF_NOT_ZERO(sampleEnd, ModulatorSamplerSound::SampleEnd); SET_IF_NOT_ZERO(sampleStartMod, ModulatorSamplerSound::SampleStartMod); // Skip the rest if the loop isn't enabled. if (!sound->getProperty(ModulatorSamplerSound::LoopEnabled)) return; SET_IF_NOT_ZERO(loopEnabled, ModulatorSamplerSound::LoopEnabled); SET_IF_NOT_ZERO(loopStart, ModulatorSamplerSound::LoopStart); SET_IF_NOT_ZERO(loopEnd, ModulatorSamplerSound::LoopEnd); SET_IF_NOT_ZERO(loopXFade, ModulatorSamplerSound::LoopXFade); } #undef SET_IF_NOT_ZERO } // namespace hise
consulo/consulo-groovy
groovy-psi/src/main/java/org/jetbrains/plugins/groovy/lang/psi/impl/search/GrSourceFilterScope.java
<reponame>consulo/consulo-groovy /* * Copyright 2000-2009 JetBrains s.r.o. * * 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 org.jetbrains.plugins.groovy.lang.psi.impl.search; import javax.annotation.Nonnull; import org.jetbrains.plugins.groovy.GroovyFileType; import com.intellij.openapi.roots.ProjectFileIndex; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.search.DelegatingGlobalSearchScope; import com.intellij.psi.search.GlobalSearchScope; /** * @author ilyas */ public class GrSourceFilterScope extends DelegatingGlobalSearchScope { private final ProjectFileIndex myIndex; public GrSourceFilterScope(@Nonnull final GlobalSearchScope delegate) { super(delegate, "groovy.sourceFilter"); myIndex = getProject() == null ? null : ProjectRootManager.getInstance(getProject()).getFileIndex(); } public boolean contains(@Nonnull final VirtualFile file) { return super.contains(file) && (myIndex == null || myIndex.isInSourceContent(file)) && GroovyFileType.GROOVY_FILE_TYPE == file.getFileType(); } }
fossabot/balm
lib/config/extras.js
const EXTRA_CONFIG = { excludes: [], includes: [] }; export default EXTRA_CONFIG;
anshupitlia-tw/twu-biblioteca-anshu
test/com/twu/biblioteca/menu_items/CheckoutBookMenuItemTest.java
<filename>test/com/twu/biblioteca/menu_items/CheckoutBookMenuItemTest.java package com.twu.biblioteca.menu_items; import com.twu.biblioteca.models.Library; import com.twu.biblioteca.helpers.LoginCaller; import com.twu.biblioteca.helpers.Messages; import com.twu.biblioteca.user_interface.UserInterface; import org.junit.Test; import static org.mockito.Mockito.*; public class CheckoutBookMenuItemTest { @Test public void shouldCheckoutABookAndDisplaySuccessfulCheckoutMessageIfSuccessfullyCheckedOut() { Library library = mock(Library.class); UserInterface userInterface = mock(UserInterface.class); Messages messages = mock(Messages.class); LoginCaller loginCaller = mock(LoginCaller.class); CheckoutBookMenuItem checkoutBook = new CheckoutBookMenuItem("Checkout A Book",library, userInterface, loginCaller, messages); when(loginCaller.callLoginViewForUser()).thenReturn(true); when(messages.getUXMessage("enter_book_name")).thenReturn("Enter the Book Name"); when(userInterface.getChoiceFromUser()).thenReturn("<NAME>"); when(library.checkOutBook("<NAME>")).thenReturn(true); when(messages.getUXMessage("successful_checkout")).thenReturn("Thank you! Enjoy the book"); checkoutBook.execute(); verify(userInterface, times(1)).printOnOutputStream("Thank you! Enjoy the book"); } @Test public void shouldTryToCheckOutABookAndDisplayUnSuccessfulCheckoutMessageIfNotFound() { Library library = mock(Library.class); UserInterface userInterface = mock(UserInterface.class); Messages messages = mock(Messages.class); LoginCaller loginCaller = mock(LoginCaller.class); CheckoutBookMenuItem checkoutBook = new CheckoutBookMenuItem("Checkout A Book",library, userInterface, loginCaller, messages); when(loginCaller.callLoginViewForUser()).thenReturn(true); when(messages.getUXMessage("enter_book_name")).thenReturn("Enter the Book Name"); when(userInterface.getChoiceFromUser()).thenReturn("<NAME>"); when(library.checkOutBook("<NAME>")).thenReturn(false); when(messages.getUXMessage("unsuccessful_checkout")).thenReturn("That book is not available. Please select a different book, or fix the spelling error"); checkoutBook.execute(); verify(userInterface, times(1)).printOnOutputStream("That book is not available. Please select a different book, or fix the spelling error"); } }
Hoommus/taskmaster
src/shell/line_editing/handlers_editing.c
<reponame>Hoommus/taskmaster /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* handlers_editing.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: vtarasiu <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/02/18 13:45:39 by vtarasiu #+# #+# */ /* Updated: 2019/05/06 15:53:17 by vtarasiu ### ########.fr */ /* */ /* ************************************************************************** */ #include "line_editing.h" #include "taskmaster_cli.h" void handle_backspace(union u_char key) { if (key.lng == K_BSP && g_shell->buffer->iterator > 0) { if ((g_shell->input_state > STATE_NON_INTERACTIVE) && buff_char_at_equals(g_shell->buffer->iterator - 1, "\n")) return ; handle_left((union u_char){K_LEFT}); buff_del_symbol(g_shell->buffer->iterator); tputs(tgetstr("dc", NULL), 1, &ft_putc); buffer_redraw(); } } void handle_del(union u_char key) { if (key.lng == K_DEL) { if (g_shell->buffer->iterator <= g_shell->buffer->size) tputs(tgetstr("dc", NULL), 1, &ft_putc); if (g_shell->buffer->iterator < g_shell->buffer->size) { buff_del_symbol(g_shell->buffer->iterator); buffer_redraw(); } } } void handle_home(union u_char key) { if (key.lng == K_HOME) { caret_move(g_shell->buffer->iterator, D_LEFT); g_shell->buffer->iterator = 0; } } void handle_end(union u_char key) { if (key.lng == K_END) { caret_move(g_shell->buffer->size - g_shell->buffer->iterator, D_RIGHT); g_shell->buffer->iterator = g_shell->buffer->size; } }
pyansys/ansys_corba
ansys_corba/omniORB/COS/CosNotification/__init__.py
# DO NOT EDIT THIS FILE! # # Python module CosNotification generated by omniidl import omniORB omniORB.updateModule("CosNotification") # ** 1. Stub files contributing to this module import CosNotification_idl # ** 2. Sub-modules # ** 3. End
uk-gov-mirror/hmrc.tariff-classification-frontend
app/controllers/v2/AttachmentsController.scala
/* * Copyright 2021 HM Revenue & Customs * * 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 controllers.v2 import javax.inject.{Inject, Singleton} import akka.stream.Materializer import config.AppConfig import controllers.{RenderCaseAction, RequestActions} import models._ import models.forms.RemoveAttachmentForm import models.viewmodels.CaseHeaderViewModel import play.api.data.Form import play.api.i18n.I18nSupport import play.api.mvc._ import service.CasesService import uk.gov.hmrc.play.bootstrap.frontend.controller.FrontendController import scala.concurrent.Future.successful import scala.concurrent.ExecutionContext @Singleton class AttachmentsController @Inject() ( verify: RequestActions, casesService: CasesService, mcc: MessagesControllerComponents, remove_attachment: views.html.v2.remove_attachment, implicit val appConfig: AppConfig, implicit val mat: Materializer )(implicit ec: ExecutionContext) extends FrontendController(mcc) with RenderCaseAction with I18nSupport { private lazy val removeAttachmentForm: Form[Boolean] = RemoveAttachmentForm.form override protected val config: AppConfig = appConfig override protected val caseService: CasesService = casesService def removeAttachment(reference: String, fileId: String, fileName: String): Action[AnyContent] = (verify.authenticated andThen verify.casePermissions(reference) andThen verify.mustHave( Permission.REMOVE_ATTACHMENTS )).async { implicit request => validateAndRenderView { c => val header = CaseHeaderViewModel.fromCase(c) successful(remove_attachment(header, removeAttachmentForm, fileId, fileName)) } } def confirmRemoveAttachment(reference: String, fileId: String, fileName: String): Action[AnyContent] = (verify.authenticated andThen verify.casePermissions(reference) andThen verify.mustHave( Permission.REMOVE_ATTACHMENTS )).async { implicit request => removeAttachmentForm .bindFromRequest() .fold( errors => validateAndRenderView { c => val header = CaseHeaderViewModel.fromCase(c) successful(remove_attachment(header, errors, fileId, fileName)) }, { case true => getCaseAndRespond( reference, caseService .removeAttachment(_, fileId) .map(_ => Redirect(controllers.routes.CaseController.attachmentsDetails(reference))) ) case _ => successful( Redirect(controllers.routes.CaseController.attachmentsDetails(reference)) ) } ) } }
rojasdiegopro/epitech-42sh
lib/parser_toolbox/src/range.c
<gh_stars>1-10 /* ** EPITECH PROJECT, 2020 ** parser_toolbox ** File description: ** ptb_characters */ #include <stdbool.h> #include "parser_toolbox/range.h" /* ** @DESCRIPTION ** Returns true if the val parameter falls between min and max ** Returns false otherwise. */ bool ptb_range(int val, int min, int max) { return (val >= min && val <= max); }
raycraft/MyBigApp_Discuz_Android
libs/AppUtils/src/com/youzu/android/framework/json/parser/AbstractJSONParser.java
<reponame>raycraft/MyBigApp_Discuz_Android package com.youzu.android.framework.json.parser; public abstract class AbstractJSONParser { }
4dn-dcic/fourfron
src/encoded/tests/test_upgrade_workflow.py
import pytest from snovault import UPGRADER pytestmark = [pytest.mark.setone, pytest.mark.working] @pytest.fixture def workflow_2(software, award, lab): return{ "schema_version": '2', "award": award['@id'], "lab": lab['@id'], "title": "some workflow", "name": "some workflow", "workflow_type": "Other", "steps": [ { "meta": { "software_used": software['@id'] } } ] } def test_workflow_convert_software_used_to_list_2( app, workflow_2, software): migrator = app.registry['upgrader'] value = migrator.upgrade('workflow', workflow_2, current_version='2', target_version='3') assert value['schema_version'] == '3' assert value['steps'][0]['meta']['software_used'] == [software['@id']] @pytest.fixture def workflow_3(software, award, lab): return { "arguments": [ { "argument_format": "chromsizes", "argument_type": "Input file", "workflow_argument_name": "chrsizes" }, { "argument_format": "pairs", "argument_type": "Input file", "workflow_argument_name": "input_pairs" }, { "argument_format": "pairs", "argument_type": "Input file", "workflow_argument_name": "input_pairs_index" }, { "argument_type": "parameter", "workflow_argument_name": "ncores" }, { "argument_type": "parameter", "workflow_argument_name": "binsize" }, { "argument_type": "parameter", "workflow_argument_name": "min_res" }, { "argument_type": "parameter", "workflow_argument_name": "normalization_type" }, { "argument_format": "pairs_px2", "argument_type": "Output processed file", "workflow_argument_name": "output_pairs_index" }, { "argument_format": "pairs", "argument_type": "Output processed file", "workflow_argument_name": "output_pairs" }, { "argument_format": "cool", "argument_type": "Output processed file", "workflow_argument_name": "out_cool" }, { "argument_format": "hic", "argument_type": "Output processed file", "workflow_argument_name": "output_hic" }, { "argument_format": "mcool", "argument_type": "Output processed file", "workflow_argument_name": "out_mcool" } ], "category": "merging + matrix generation", "data_types": [ "Hi-C" ], "description": "Hi-C processing part B revision 15", "award": award['@id'], "lab": lab['@id'], "name": "hi-c-processing-partb/15", "schema_version": "3", "steps": [ { "inputs": [ { "meta": { "argument_format": "pairs", "argument_type": "Input file" }, "name": "input_pairs", "source": [ { "name": "input_pairs" } ] }, { "meta": { "argument_type": "Input file" }, "name": "input_pairs_index", "source": [ { "name": "input_pairs_index" } ] } ], "meta": { "analysis_step_types": [ "file merging" ], "software_used": [ "/software/02d636b9-d82d-4da9-950c-2ca994a23547/" ] }, "name": "merge_pairs", "outputs": [ { "meta": { "argument_format": "pairs_px2", "argument_type": "Output processed file" }, "name": "output_pairs_index", "target": [ { "name": "output_pairs_index" }, { "name": "pairs_index", "step": "cooler" } ] }, { "meta": { "argument_format": "pairs", "argument_type": "Output processed file" }, "name": "output_pairs", "target": [ { "name": "output_pairs" }, { "name": "input_pairs", "step": "pairs2hic" }, { "name": "pairs", "step": "cooler" } ] } ] }, { "inputs": [ { "meta": { "argument_type": "parameter" }, "name": "ncores", "source": [ { "name": "ncores" } ] }, { "meta": { "argument_type": "parameter" }, "name": "binsize", "source": [ { "name": "binsize" } ] }, { "meta": {}, "name": "pairs_index", "source": [ { "name": "output_pairs_index", "step": "merge_pairs" } ] }, { "meta": {}, "name": "pairs", "source": [ { "name": "output_pairs", "step": "merge_pairs" } ] } ], "meta": { "analysis_step_types": [ "aggregation" ], "software_used": [ "/software/02d636b9-d8dd-4da9-950c-2ca994b23555/" ] }, "name": "cooler", "outputs": [ { "meta": { "argument_format": "cool", "argument_type": "Output processed file" }, "name": "out_cool", "target": [ { "name": "out_cool" } ] } ] }, { "inputs": [ { "meta": { "argument_format": "chromsizes", "argument_type": "Input file" }, "name": "chrsizes", "source": [ { "name": "chrsizes" } ] }, { "meta": { "argument_type": "parameter" }, "name": "min_res", "source": [ { "name": "min_res" } ] }, { "meta": {}, "name": "input_pairs", "source": [ { "name": "output_pairs", "step": "merge_pairs" } ] } ], "meta": { "analysis_step_types": [ "aggregation", "normalization" ], "software_used": [ "/software/02d636b9-d8dd-4da9-950c-2ca994b23576/" ] }, "name": "pairs2hic", "outputs": [ { "meta": { "argument_format": "hic", "argument_type": "Output processed file" }, "name": "output_hic", "target": [ { "name": "output_hic" }, { "name": "input_hic", "step": "hic2mcool" } ] } ] }, { "inputs": [ { "meta": { "argument_type": "parameter" }, "name": "normalization_type", "source": [ { "name": "normalization_type" } ] }, { "meta": {}, "name": "input_hic", "source": [ { "name": "output_hic", "step": "pairs2hic" } ] } ], "meta": { "analysis_step_types": [ "file format conversion" ], "software_used": [ "/software/02d636b9-d8dd-4da9-950c-2ca994b23555/" ] }, "name": "hic2mcool", "outputs": [ { "meta": { "argument_format": "mcool", "argument_type": "Output processed file" }, "name": "out_mcool", "target": [ { "name": "out_mcool" } ] } ] } ], "title": "Hi-C processing part B revision 15", "workflow_type": "Hi-C data analysis" } def test_workflow_upgrade_3_4( app, workflow_3, software): migrator = app.registry['upgrader'] value = migrator.upgrade('workflow', workflow_3, current_version='3', target_version='4') assert value['schema_version'] == '4' assert value['steps'][0]['inputs'][0]['source'][0].get('type') is None assert value['steps'][0]['outputs'][0]['target'][0].get('type') is None assert value['steps'][0]['inputs'][0]['meta'].get('file_format') == 'pairs' assert value['steps'][0]['inputs'][1]['meta'].get('file_format') == 'pairs' assert value['steps'][0]['inputs'][0]['meta'].get('cardinality') == 'array' # 'input_pairs' arg of 'merge_pairs' should get this auto-assigned assert value['steps'][0]['inputs'][0]['meta'].get('type') == 'data file' assert value['steps'][0]['inputs'][1]['meta'].get('type') == 'reference file' # 'input_pairs_index' has 'index' in name ==> 'reference file' upgrade. assert value['steps'][0]['inputs'][0]['meta'].get('global') is True assert value['steps'][0]['inputs'][1]['meta'].get('global') is True assert value['steps'][0]['outputs'][0]['meta'].get('file_format') == 'pairs_px2' assert value['steps'][0]['outputs'][1]['meta'].get('file_format') == 'pairs' assert value['steps'][0]['outputs'][0]['meta'].get('global') is True assert value['steps'][0]['outputs'][1]['meta'].get('global') is True assert value['steps'][0]['outputs'][0]['meta'].get('type') == 'data file' # We don't transform outputs to reference files assert value['steps'][0]['outputs'][1]['meta'].get('type') == 'data file' @pytest.fixture def workflow_4(): return { 'lab': '/labs/encode-lab/', 'steps': [ { 'meta': { 'analysis_step_types': ['file merging'], 'software_used': ['/software/02d636b9-d82d-4da9-950c-2ca994a23547/'] }, 'name': 'merge_pairs', 'outputs': [ { 'meta': { 'cardinality': 'single', 'type': 'data file', 'global': True, 'file_format': 'pairs_px2' }, 'target': [{'name': 'output_pairs_index'}, {'name': 'pairs_index', 'step': 'cooler'}], 'name': 'output_pairs_index' }, { 'meta': {'cardinality': 'single', 'type': 'data file', 'global': True, 'file_format': 'pairs'}, 'target': [{'name': 'output_pairs'}, {'name': 'input_pairs', 'step': 'pairs2hic'}, {'name': 'pairs', 'step': 'cooler'}], 'name': 'output_pairs' } ], 'inputs': [ { 'meta': {'cardinality': 'array', 'type': 'data file', 'global': True, 'file_format': 'pairs'}, 'name': 'input_pairs', 'source': [{'name': 'input_pairs'}] }, { 'meta': { 'type': 'reference file', 'global': True, 'file_format': 'pairs', 'cardinality': 'array' }, 'name': 'input_pairs_index', 'source': [{'name': 'input_pairs_index'}] } ] }, { 'meta': { 'analysis_step_types': ['aggregation'], 'software_used': ['/software/02d636b9-d8dd-4da9-950c-2ca994b23555/'] }, 'name': 'cooler', 'outputs': [ { 'meta': {'cardinality': 'single', 'type': 'data file', 'global': True, 'file_format': 'cool'}, 'target': [{'name': 'out_cool'}], 'name': 'out_cool' } ], 'inputs': [ { 'meta': {'type': 'parameter', 'global': True, 'cardinality': 'single'}, 'name': 'ncores', 'source': [{'name': 'ncores'}] }, { 'meta': {'type': 'parameter', 'global': True, 'cardinality': 'single'}, 'name': 'binsize', 'source': [{'name': 'binsize'}] }, { 'meta': { 'type': 'reference file', 'global': False, 'file_format': 'pairs', 'cardinality': 'single' }, 'name': 'pairs_index', 'source': [{'name': 'output_pairs_index', 'step': 'merge_pairs'}] }, { 'meta': {'type': 'data file', 'global': False, 'file_format': 'pairs', 'cardinality': 'single'}, 'name': 'pairs', 'source': [{'name': 'output_pairs', 'step': 'merge_pairs'}] } ] }, { 'meta': { 'analysis_step_types': ['aggregation', 'normalization'], 'software_used': ['/software/02d636b9-d8dd-4da9-950c-2ca994b23576/'] }, 'name': 'pairs2hic', 'outputs': [ { 'meta': {'cardinality': 'single', 'type': 'data file', 'global': True, 'file_format': 'hic'}, 'target': [{'name': 'output_hic'}, {'name': 'input_hic', 'step': 'hic2mcool'}], 'name': 'output_hic' } ], 'inputs': [ { 'meta': {'cardinality': 'single', 'type': 'reference file', 'global': True, 'file_format': 'chromsizes'}, 'name': 'chrsizes', 'source': [{'name': 'chrsizes'}] }, { 'meta': {'type': 'parameter', 'global': True, 'cardinality': 'single'}, 'name': 'min_res', 'source': [{'name': 'min_res'}] }, { 'meta': {'type': 'data file', 'global': False, 'file_format': 'pairs', 'cardinality': 'single'}, 'name': 'input_pairs', 'source': [{'name': 'output_pairs', 'step': 'merge_pairs'}] } ] }, { 'meta': { 'analysis_step_types': ['file format conversion'], 'software_used': ['/software/02d636b9-d8dd-4da9-950c-2ca994b23555/'] }, 'name': 'hic2mcool', 'outputs': [ { 'meta': {'cardinality': 'single', 'type': 'data file', 'global': True, 'file_format': 'mcool'}, 'target': [{'name': 'out_mcool'}], 'name': 'out_mcool' } ], 'inputs': [ { 'meta': {'type': 'parameter', 'global': True, 'cardinality': 'single'}, 'name': 'normalization_type', 'source': [{'name': 'normalization_type'}] }, { 'meta': {'type': 'data file', 'global': False, 'cardinality': 'single'}, 'name': 'input_hic', 'source': [{'name': 'output_hic', 'step': 'pairs2hic'}] } ] } ], 'name': 'hi-c-processing-partb/15', 'data_types': ['Hi-C'], 'description': 'Hi-C processing part B revision 15', 'category': 'merging + matrix generation', 'schema_version': '4', 'arguments': [ {'workflow_argument_name': 'chrsizes', 'argument_format': 'chromsizes', 'argument_type': 'Input file'}, {'workflow_argument_name': 'input_pairs', 'argument_format': 'pairs', 'argument_type': 'Input file'}, {'workflow_argument_name': 'input_pairs_index', 'argument_format': 'pairs', 'argument_type': 'Input file'}, {'workflow_argument_name': 'ncores', 'argument_type': 'parameter'}, {'workflow_argument_name': 'binsize', 'argument_type': 'parameter'}, {'workflow_argument_name': 'min_res', 'argument_type': 'parameter'}, {'workflow_argument_name': 'normalization_type', 'argument_type': 'parameter'}, {'workflow_argument_name': 'output_pairs_index', 'argument_format': 'pairs_px2', 'argument_type': 'Output processed file'}, {'workflow_argument_name': 'output_pairs', 'argument_format': 'pairs', 'argument_type': 'Output processed file'}, {'workflow_argument_name': 'out_cool', 'argument_format': 'cool', 'argument_type': 'Output processed file'}, {'workflow_argument_name': 'output_hic', 'argument_format': 'hic', 'argument_type': 'Output processed file'}, {'workflow_argument_name': 'out_mcool', 'argument_format': 'mcool', 'argument_type': 'Output processed file'} ], 'award': '/awards/encode3-award/', 'workflow_type': 'Hi-C data analysis', 'title': 'Hi-C processing part B revision 15' } def test_workflow_upgrade_4_5( workflow_4, registry, file_formats): upgrader = registry[UPGRADER] value = upgrader.upgrade('workflow', workflow_4, registry=registry, current_version='4', target_version='5') format_uuids = [f.get('uuid') for f in file_formats.values()] assert value['schema_version'] == '5' arguments = value.get('arguments', []) for arg in arguments: secondary_formats = arg.get('secondary_file_formats', []) for sformat in secondary_formats: assert sformat in format_uuids argument_format = arg.get('argument_format') if argument_format: assert argument_format in format_uuids steps = value.get('steps', []) for step in steps: inputs = step.get('inputs', []) for inp in inputs: meta = inp.get('meta', {}) fformat = meta.get('file_format') if fformat: assert fformat in format_uuids @pytest.fixture def workflow_5(software, award, lab): return{ "schema_version": '5', "award": award['@id'], "lab": lab['@id'], "title": "some workflow", "name": "<NAME>", "workflow_type": "Other", "data_types": ["Hi-C"], "category": "alignment", "steps": [{ "meta": { "software_used" : software['@id'] } }] } def test_workflow_upgrade_5_6( workflow_5, registry): upgrader = registry[UPGRADER] value = upgrader.upgrade('workflow', workflow_5, registry=registry, current_version='5', target_version='6') assert value['schema_version'] == '6' assert 'workflow_type' not in value assert 'category' in value assert isinstance(value['category'], list) assert 'experiment_types' in value assert 'data_types' not in value @pytest.fixture def workflow_6(software, award, lab, workflow_bam): return{ "schema_version": '6', "award": award['@id'], "lab": lab['@id'], "title": "some workflow", "name": "<NAME>", "previous_version": workflow_bam['@id'] } def test_workflow_upgrade_6_7( workflow_6, registry): upgrader = registry[UPGRADER] value = upgrader.upgrade('workflow', workflow_6, registry=registry, current_version='6', target_version='7') assert value['schema_version'] == '7' assert 'previous_version' in value assert isinstance(value['previous_version'], list) # @pytest.fixture # def workflow_7(software, award, lab, workflow_bam): # return{ # "schema_version": '6', # "award": award['@id'], # "lab": lab['@id'], # "title": "some workflow", # "name": "<NAME>", # "previous_version": [workflow_bam['@id']] # } # # # def test_workflow_upgrade_7_8(workflow_7, registry, exp_types): # types2upg = {'Repli-seq': None, 'in situ Hi-C': 'hic', 'Capture Hi-C': 'capc', 'DNA FISH': 'fish', 'dilution Hi-C': 'dilution'} # upgrader = registry[UPGRADER] # for etype, lookup in types2upg.items(): # workflow_7['experiment_types'] = [etype] # value = upgrader.upgrade('workflow', workflow_7, registry=registry, # current_version='7', target_version='8') # assert value['schema_version'] == '8' # newetypes = value['experiment_types'] # if etype == 'Repli-seq': # assert len(newetypes) == 2 # assert exp_types['repliseq'].get('uuid') in newetypes # assert exp_types['multi'].get('uuid') in newetypes # else: # assert exp_types[lookup].get('uuid') == newetypes[0]
EddieVilla/navi
packages/visualizations/app/components/cell-renderers/date-time.js
export { default } from 'navi-visualizations/components/cell-renderers/date-time';
vmariano/Platform
lib/models/user.js
/** * Module dependencies. */ var mongoose = require('mongoose'); var Schema = mongoose.Schema; var ObjectId = Schema.ObjectId; var passportLocalMongoose = require('passport-local-mongoose'); var gravatar = require('mongoose-gravatar'); var t = require('t-component'); /** * Define `User` Schema */ var UserSchema = new Schema({ firstName: { type: String } , lastName: { type: String } , username: { type: String } , avatar: { type: String } , email: { type: String, lowercase: true, trim: true } // main email , emailValidated: { type: Boolean, default: false } , profiles: { facebook: { type: Object } , twitter: { type: Object } } , createdAt: { type: Date, default: Date.now } , updatedAt: { type: Date } , profilePictureUrl: { type: String, match: /^https:\/\// } , disabledAt: { type: Date } , notifications: { replies: { type: Boolean, default: true }, 'new-topic': { type: Boolean, default: false } } }); /** * Define Schema Indexes for MongoDB */ UserSchema.index({ firstName:1, lastName:1 }); /** * Define Schema toObject options */ UserSchema.set('toObject', { getters: true }); UserSchema.set('toJSON', { getters: true }); UserSchema.options.toJSON.transform = function(doc, ret, options) { // remove the hasn and salt of every document before returning the result delete ret.hash; delete ret.salt; ret.deployments = doc.deployments; } /** * -- Model's Plugin Extensions */ UserSchema.plugin(gravatar, { default: 'mm', secure: true }); UserSchema.plugin(passportLocalMongoose, { usernameField: 'email', userExistsError: t('signup.email.used') }); /** * -- Model's API Extension */ /** * Get `fullName` from `firstName` and `lastName` * * @return {String} fullName * @api public */ UserSchema.virtual('fullName').get(function() { return this.firstName + ' ' + this.lastName; }); /** * Set `fullName` from `String` param splitting * and calling firstName as first value and lastName * as the concatenation of the rest values * * @param {String} name * @return {User} * @api public */ UserSchema.virtual('fullName').set(function(name) { var split = name.split(' '); if(split.length) { this.firstName = split.shift(); this.lastName = split.join(' '); } return this; }); /** * Find `User` by its email * * @param {String} email * @return {Error} err * @return {User} user * @api public */ UserSchema.statics.findByEmail = function(email, cb) { return this.findOne({ email: email }) .exec(function(err, user) { if (err) return cb(err); cb(null, user); }); } /** * Find `User` by social provider id * * @param {String|Number} id * @param {String} social * @return {Error} err * @return {User} user * @api public */ UserSchema.statics.findByProvider = function(profile, cb) { var path = 'profiles.'.concat(profile.provider).concat('.id'); var query = {}; query[path] = profile.id; return this.findOne(query) .exec(cb); } /** * Expose `User` Model */ module.exports = function initialize(conn) { return conn.model('User', UserSchema); };
Athos1972/PoLZy
polzy-frontend/src/datafields/attachmentTable.js
import React from 'react' import PropTypes from 'prop-types' import { connect } from 'react-redux' import { Table, TableHead, TableBody, TableRow, TableCell, TableSortLabel, TablePagination, Toolbar, Typography, Paper, Tooltip, IconButton, Drawer, List, ListItem, Divider, Slider, TextField, Grid, Button, Checkbox, Link, Box, } from '@material-ui/core' import Autocomplete from '@material-ui/lab/Autocomplete' import { useTranslation } from 'react-i18next' import { makeStyles } from '@material-ui/core/styles' import EmailIcon from '@material-ui/icons/Email' import PrintIcon from '@material-ui/icons/Print' import CheckCircleIcon from '@material-ui/icons/CheckCircle' import CancelIcon from '@material-ui/icons/Cancel' import DataFieldSelect from './selectField' import { apiHost } from '../utils' import { getFile, editFile, deleteFile, getDocuments, generateEml } from '../api/general' import AttachmentRow from './attachmentRow' import {comparator, sortedData} from './tableUtils' const useStyles = makeStyles((theme) => ({ title: { flex: '1 1 100%', }, emptyMessage: { paddingLeft: theme.spacing(2), }, })) /** * Renders data field of type _Attachments_. * * @component * @category Data Fields */ function AttachmentTable(props) { const classes = useStyles() const {t} = useTranslation('attachment') /** * Defines the headers of the columns to be rendered within the component and its order. * * @type {array} */ const tableHeaders = [ 'name', 'type', 'created', ] /** * @typedef {object} state * @ignore */ /** * State<br/> * Header of a table column according to which the attachments should be ordered. * * @name orderBy * @default null * @prop {string|null} orderBy - state * @prop {function} setOrderBy - setter * @type {state} * @memberOf AttachmentTable * @inner */ const [orderBy, setOrderBy] = React.useState(null) /** * State<br/> * Sets order direction. The ordering is applied to the column defined by * state [orderBy]{@link AttachmentTable~orderBy}.<br/> * Possible values: * * 'asc' - ascending * * 'desc' - descending * * @name order * @default 'asc' * @prop {string} order - state * @prop {function} setOrder - setter * @type {state} * @memberOf AttachmentTable * @inner */ const [order, setOrder] = React.useState('asc') /** * Event Handler<br/> * **_Event:_** click the sort label within a column header.<br/> * **_Implementation:_** sets the given _header_ to state [orderBy]{@link DocumentTable~orderBy} * and corresponded order direction (see [comparator]{@link module:tableUtils~comparator}) * to state [order]{@link DocumentTable~order}. * * @arg {string} header * the header of the column that the documents should be sorted by */ const handleSort = (header) => (event) => { setOrder(comparator(order, header === orderBy)) setOrderBy(header) } return ( <Paper> {/* Table Title & Toolbar */} <Toolbar> <Typography className={classes.title} variant="h6" component="div" > {props.title} </Typography> {/* Actions */} </Toolbar> {/* Table Data */} <Table size="medium" aria-label="data-table" > <TableHead> <TableRow> {tableHeaders.map((header, index) => ( <TableCell key={index} sortDirection={orderBy === header ? order : false} > <TableSortLabel active={orderBy === header} direction={orderBy === header ? order : 'asc'} onClick={handleSort(header)} > {t(header)} </TableSortLabel> </TableCell> ))} <TableCell> {t("actions")} </TableCell> </TableRow> </TableHead> <TableBody> {sortedData(props.data, orderBy, order === 'asc').map((row) => ( <AttachmentRow {...row} key={row.id} headers={tableHeaders} updateParent={props.updateParent} /> ))} </TableBody> </Table> {/* Empty Table Message */} {(!props.data || props.data.length === 0) && <Typography className={classes.emptyMessage} variant="overline" component="div" > {t("empty")} </Typography> } </Paper> ) } AttachmentTable.propTypes = { /** * Title of the table */ title: PropTypes.string, /** * Data of the table */ data: PropTypes.object.isRequired, /** * Callback fired to update the parent instance on the back-end */ updateParent: PropTypes.func, } export default AttachmentTable
draperlaboratory/hope-FreeRTOS-RISC-V_Galois_demo
bsp/gpio.h
#ifndef __GPIO_H__ #define __GPIO_H__ #include <stdint.h> #include "bsp.h" #if BSP_USE_GPIO /** * Initialize GPIO driver */ void gpio_init(void); /** * Set GPIO_1 index `i` as output * @assert 0 <= i <= 7 */ void gpio_set_as_output(uint8_t i); /** * Set GPIO_1 index `i` as input * @assert 0 <= i <= 7 */ void gpio_set_as_input(uint8_t i); /** * Set GPIO_1 index `i` * @assert 0 <= i <= 7 */ void gpio_write(uint8_t i); /** * Clear GPIO_1 index `i` * @assert 0 <= i <= 7 */ void gpio_clear(uint8_t i); /** * Read GPIO_1 index `i` * @assert 0 <= i <= 7 */ uint8_t gpio_read(uint8_t i); /** * Turn on LED 0-7 * Onboard LEDs are on GPIO_1 bank 2 */ void led_write(uint8_t i); /** * Turn off LED 0-7 * Onboard LEDs are on GPIO_1 bank 2 */ void led_clear(uint8_t i); #endif #endif /* __GPIO_H__ */
enfoTek/tomato.linksys.e2000.nvram-mod
release/src/linux/linux/drivers/acpi/debugger/dbexec.c
/******************************************************************************* * * Module Name: dbexec - debugger control method execution * $Revision: 1.1.1.2 $ * ******************************************************************************/ /* * Copyright (C) 2000, 2001 <NAME> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "acpi.h" #include "acparser.h" #include "acdispat.h" #include "amlcode.h" #include "acnamesp.h" #include "acparser.h" #include "acevents.h" #include "acinterp.h" #include "acdebug.h" #include "actables.h" #ifdef ENABLE_DEBUGGER #define _COMPONENT ACPI_DEBUGGER MODULE_NAME ("dbexec") db_method_info acpi_gbl_db_method_info; /******************************************************************************* * * FUNCTION: Acpi_db_execute_method * * PARAMETERS: Info - Valid info segment * Return_obj - Where to put return object * * RETURN: Status * * DESCRIPTION: Execute a control method. * ******************************************************************************/ acpi_status acpi_db_execute_method ( db_method_info *info, acpi_buffer *return_obj) { acpi_status status; acpi_object_list param_objects; acpi_object params[MTH_NUM_ARGS]; u32 i; if (acpi_gbl_db_output_to_file && !acpi_dbg_level) { acpi_os_printf ("Warning: debug output is not enabled!\n"); } /* Are there arguments to the method? */ if (info->args && info->args[0]) { for (i = 0; info->args[i] && i < MTH_NUM_ARGS; i++) { params[i].type = ACPI_TYPE_INTEGER; params[i].integer.value = STRTOUL (info->args[i], NULL, 16); } param_objects.pointer = params; param_objects.count = i; } else { /* Setup default parameters */ params[0].type = ACPI_TYPE_INTEGER; params[0].integer.value = 0x01020304; params[1].type = ACPI_TYPE_STRING; params[1].string.length = 12; params[1].string.pointer = "AML Debugger"; param_objects.pointer = params; param_objects.count = 2; } /* Prepare for a return object of arbitrary size */ return_obj->pointer = acpi_gbl_db_buffer; return_obj->length = ACPI_DEBUG_BUFFER_SIZE; /* Do the actual method execution */ status = acpi_evaluate_object (NULL, info->pathname, &param_objects, return_obj); acpi_gbl_cm_single_step = FALSE; acpi_gbl_method_executing = FALSE; return (status); } /******************************************************************************* * * FUNCTION: Acpi_db_execute_setup * * PARAMETERS: Info - Valid method info * * RETURN: Status * * DESCRIPTION: Setup info segment prior to method execution * ******************************************************************************/ void acpi_db_execute_setup ( db_method_info *info) { /* Catenate the current scope to the supplied name */ info->pathname[0] = 0; if ((info->name[0] != '\\') && (info->name[0] != '/')) { STRCAT (info->pathname, acpi_gbl_db_scope_buf); } STRCAT (info->pathname, info->name); acpi_db_prep_namestring (info->pathname); acpi_db_set_output_destination (DB_DUPLICATE_OUTPUT); acpi_os_printf ("Executing %s\n", info->pathname); if (info->flags & EX_SINGLE_STEP) { acpi_gbl_cm_single_step = TRUE; acpi_db_set_output_destination (DB_CONSOLE_OUTPUT); } else { /* No single step, allow redirection to a file */ acpi_db_set_output_destination (DB_REDIRECTABLE_OUTPUT); } } /******************************************************************************* * * FUNCTION: Acpi_db_get_outstanding_allocations * * PARAMETERS: None * * RETURN: Current global allocation count minus cache entries * * DESCRIPTION: Determine the current number of "outstanding" allocations -- * those allocations that have not been freed and also are not * in one of the various object caches. * ******************************************************************************/ u32 acpi_db_get_outstanding_allocations (void) { u32 i; u32 outstanding = 0; #ifdef ACPI_DBG_TRACK_ALLOCATIONS for (i = ACPI_MEM_LIST_FIRST_CACHE_LIST; i < ACPI_NUM_MEM_LISTS; i++) { outstanding += (acpi_gbl_memory_lists[i].total_allocated - acpi_gbl_memory_lists[i].total_freed - acpi_gbl_memory_lists[i].cache_depth); } #endif return (outstanding); } /******************************************************************************* * * FUNCTION: Acpi_db_execute * * PARAMETERS: Name - Name of method to execute * Args - Parameters to the method * Flags - single step/no single step * * RETURN: Status * * DESCRIPTION: Execute a control method. Name is relative to the current * scope. * ******************************************************************************/ void acpi_db_execute ( NATIVE_CHAR *name, NATIVE_CHAR **args, u32 flags) { acpi_status status; acpi_buffer return_obj; #ifdef ACPI_DEBUG u32 previous_allocations; u32 allocations; /* Memory allocation tracking */ previous_allocations = acpi_db_get_outstanding_allocations (); #endif acpi_gbl_db_method_info.name = name; acpi_gbl_db_method_info.args = args; acpi_gbl_db_method_info.flags = flags; acpi_db_execute_setup (&acpi_gbl_db_method_info); status = acpi_db_execute_method (&acpi_gbl_db_method_info, &return_obj); /* * Allow any handlers in separate threads to complete. * (Such as Notify handlers invoked from AML executed above). */ acpi_os_sleep (0, 10); #ifdef ACPI_DEBUG /* Memory allocation tracking */ allocations = acpi_db_get_outstanding_allocations () - previous_allocations; acpi_db_set_output_destination (DB_DUPLICATE_OUTPUT); if (allocations > 0) { acpi_os_printf ("Outstanding: %ld allocations after execution\n", allocations); } #endif if (ACPI_FAILURE (status)) { acpi_os_printf ("Execution of %s failed with status %s\n", acpi_gbl_db_method_info.pathname, acpi_format_exception (status)); } else { /* Display a return object, if any */ if (return_obj.length) { acpi_os_printf ("Execution of %s returned object %p Buflen %X\n", acpi_gbl_db_method_info.pathname, return_obj.pointer, return_obj.length); acpi_db_dump_object (return_obj.pointer, 1); } } acpi_db_set_output_destination (DB_CONSOLE_OUTPUT); } /******************************************************************************* * * FUNCTION: Acpi_db_method_thread * * PARAMETERS: Context - Execution info segment * * RETURN: None * * DESCRIPTION: Debugger execute thread. Waits for a command line, then * simply dispatches it. * ******************************************************************************/ void acpi_db_method_thread ( void *context) { acpi_status status; db_method_info *info = context; u32 i; acpi_buffer return_obj; for (i = 0; i < info->num_loops; i++) { status = acpi_db_execute_method (info, &return_obj); if (ACPI_SUCCESS (status)) { if (return_obj.length) { acpi_os_printf ("Execution of %s returned object %p Buflen %X\n", info->pathname, return_obj.pointer, return_obj.length); acpi_db_dump_object (return_obj.pointer, 1); } } } /* Signal our completion */ acpi_os_signal_semaphore (info->thread_gate, 1); } /******************************************************************************* * * FUNCTION: Acpi_db_create_execution_threads * * PARAMETERS: Num_threads_arg - Number of threads to create * Num_loops_arg - Loop count for the thread(s) * Method_name_arg - Control method to execute * * RETURN: None * * DESCRIPTION: Create threads to execute method(s) * ******************************************************************************/ void acpi_db_create_execution_threads ( NATIVE_CHAR *num_threads_arg, NATIVE_CHAR *num_loops_arg, NATIVE_CHAR *method_name_arg) { acpi_status status; u32 num_threads; u32 num_loops; u32 i; acpi_handle thread_gate; /* Get the arguments */ num_threads = STRTOUL (num_threads_arg, NULL, 0); num_loops = STRTOUL (num_loops_arg, NULL, 0); if (!num_threads || !num_loops) { acpi_os_printf ("Bad argument: Threads %X, Loops %X\n", num_threads, num_loops); return; } /* Create the synchronization semaphore */ status = acpi_os_create_semaphore (1, 0, &thread_gate); if (ACPI_FAILURE (status)) { acpi_os_printf ("Could not create semaphore, %s\n", acpi_format_exception (status)); return; } /* Setup the context to be passed to each thread */ acpi_gbl_db_method_info.name = method_name_arg; acpi_gbl_db_method_info.args = NULL; acpi_gbl_db_method_info.flags = 0; acpi_gbl_db_method_info.num_loops = num_loops; acpi_gbl_db_method_info.thread_gate = thread_gate; acpi_db_execute_setup (&acpi_gbl_db_method_info); /* Create the threads */ acpi_os_printf ("Creating %X threads to execute %X times each\n", num_threads, num_loops); for (i = 0; i < (num_threads); i++) { acpi_os_queue_for_execution (OSD_PRIORITY_MED, acpi_db_method_thread, &acpi_gbl_db_method_info); } /* Wait for all threads to complete */ i = num_threads; while (i) /* Brain damage for OSD implementations that only support wait of 1 unit */ { status = acpi_os_wait_semaphore (thread_gate, 1, WAIT_FOREVER); i--; } /* Cleanup and exit */ acpi_os_delete_semaphore (thread_gate); acpi_db_set_output_destination (DB_DUPLICATE_OUTPUT); acpi_os_printf ("All threads (%X) have completed\n", num_threads); acpi_db_set_output_destination (DB_CONSOLE_OUTPUT); } #endif /* ENABLE_DEBUGGER */
youngdaLee/Baekjoon
src/7/7581.py
<filename>src/7/7581.py """ 7581. Cuboids 작성자: xCrypt0r 언어: Python 3 사용 메모리: 29,380 KB 소요 시간: 92 ms 해결 날짜: 2020년 9월 14일 """ def main(): while True: l, w, h, v = map(int, input().split()) if all(x == 0 for x in [l, w, h, v]): break elif l == 0: l = v // w // h elif w == 0: w = v // l // h elif h == 0: h = v // l // w elif v == 0: v = l * w * h print(l, w, h, v, sep=' ') if __name__ == '__main__': main()
matiasal55/ejercicio-front-back
front/src/features/userSlice.js
<reponame>matiasal55/ejercicio-front-back import { createSlice } from '@reduxjs/toolkit'; import { getRequest, postRequest } from '../utils/requestHandler'; export const userSlice = createSlice({ name: 'user', initialState: { token: null, userData: {}, serverState: true, registerState: null, loading: false, }, reducers: { setUserData: (state, action) => { state.userData = action.payload.userData; state.token = action.payload.token; state.serverState = true; state.registerState = false; }, setToken: (state, action) => { state.token = action.payload; }, endSession: (state) => { state.token = null; }, setServerState: (state, action) => { state.serverState = action.payload; }, setRegister: (state, action) => { state.registerState = action.payload; }, setLoading: (state) => { state.loading = !state.loading; }, }, }); export const { setUserData, setServerState, setToken, endSession, setRegister, setLoading } = userSlice.actions; export const login = (data) => async (dispatch) => { try { dispatch(setLoading()); const request = await postRequest('/login', data, true); dispatch(setLoading()); dispatch(setUserData({ userData: request.user, token: request.token })); } catch (e) { if (e.response && e.response.status === 400) dispatch(setToken(false)); else dispatch(setServerState(false)); dispatch(setLoading()); } }; export const registerUser = (data) => async (dispatch) => { try { dispatch(setLoading()); const request = await postRequest('/register', data, true); dispatch(setLoading()); dispatch(setRegister(true)); } catch (e) { if (e.response && e.response.status === 400) dispatch(setRegister(false)); else dispatch(setServerState(false)); dispatch(setLoading()); } }; export const recoveryData = (token) => async (dispatch) => { try { const request = await getRequest('/recoveryData', token, true); dispatch(setUserData({ userData: request.user, token: request.token })); } catch (e) { dispatch(setServerState(false)); } }; export const logout = () => (dispatch) => { dispatch(endSession()); }; export const token = (state) => state.user.token; export const userSelector = (state) => state.user; export default userSlice.reducer;
mmtechslv/PhyloMAF
pmaf/sequence/_shared.py
<reponame>mmtechslv/PhyloMAF import warnings warnings.simplefilter('ignore', category=FutureWarning) from skbio.sequence import DNA,RNA,Protein,Sequence def sniff_mode(sequence_str): """ Parameters ---------- sequence_str : Returns ------- """ if isinstance(sequence_str,str): if len(sequence_str)>0: try: skbio_seq = DNA(sequence_str) except ValueError: skbio_seq = None except: raise if skbio_seq is None: try: skbio_seq = RNA(sequence_str) except ValueError: skbio_seq = None except: raise return None if skbio_seq is None else type(skbio_seq) else: raise ValueError('`sequence_str` must have length greater than one.') else: raise TypeError('`sequence_str` must be string.') def mode_as_skbio(mode): """ Parameters ---------- mode : Returns ------- """ ret = False if isinstance(mode,str): mode_str = mode.lower() else: mode_str = mode if mode_str == 'dna': ret = DNA elif mode_str == 'rna': ret = RNA elif mode_str == 'protein': ret = Protein elif mode_str == None: ret = Sequence else: ret = False return ret def mode_as_str(mode_skbio): """ Parameters ---------- mode_skbio : Returns ------- """ ret = False if mode_skbio == DNA: ret = 'dna' elif mode_skbio == RNA: ret = 'rna' elif mode_skbio == Protein: ret = 'protein' elif mode_skbio == Sequence: ret = None else: ret = False return ret def mode_is_nucleotide(mode): """ Parameters ---------- mode : Returns ------- """ ret = False if isinstance(mode,str): mode_str = mode.lower() if mode_str == 'dna' or mode_str == 'rna': ret = True elif mode == DNA or mode == RNA: ret = True return ret def validate_seq_mode(mode_str): """ Parameters ---------- mode_str : Returns ------- """ ret = False mode_str = mode_str.lower() if mode_str == 'dna': ret = True elif mode_str == 'rna': ret = True elif mode_str == 'protein': ret = True return ret def validate_seq_grammar(seq_str,mode_str): """ Parameters ---------- seq_str : mode_str : Returns ------- """ return True
nokia/osgi-microfeatures
com.nokia.as.autoconfig/src/com/nokia/as/autoconfig/parser/JsonParser.java
// Copyright 2000-2021 Nokia // // Licensed under the Apache License 2.0 // SPDX-License-Identifier: Apache-2.0 // package com.nokia.as.autoconfig.parser; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.json.JSONArray; import org.json.JSONObject; import org.json.JSONTokener; import com.alcatel.as.service.log.LogService; import com.nokia.as.autoconfig.AutoConfigurator; import com.nokia.as.autoconfig.Configuration; import com.nokia.as.autoconfig.bnd.VersionedConfiguration; import com.nokia.as.autoconfig.bnd.VersionedFactoryConfiguration; import com.nokia.as.autoconfig.bnd.VersionedSingletonConfiguration; import alcatel.tess.hometop.gateways.utils.Log; public class JsonParser implements Parser { private LogService logger = Log.getLogger(AutoConfigurator.LOGGER); public List<VersionedConfiguration> parse(URL url, String version) { List<VersionedConfiguration> vConfs = new ArrayList<>(); try(InputStream is = url.openStream()) { JSONTokener tokener = new JSONTokener(is); JSONObject root = new JSONObject(tokener); String[] pids = JSONObject.getNames(root); for(String pid : pids) { if(root.get(pid) instanceof JSONArray) { VersionedFactoryConfiguration config = new VersionedFactoryConfiguration(version, pid); JSONArray factoryProps = (JSONArray) root.get(pid); for(int i = 0; i < factoryProps.length(); i++) { JSONObject jsonProps = factoryProps.getJSONObject(i); Map<String, Object> props = new HashMap<>(); String[] keys = JSONObject.getNames(jsonProps); for(String key : keys) { props.put(key, jsonProps.getString(key)); } props.put(Configuration.AUTOCONF_ID, "true"); config.props.add(props); } vConfs.add(config); } else { VersionedSingletonConfiguration config = new VersionedSingletonConfiguration(version, pid); JSONObject props = (JSONObject) root.get(pid); String[] keys = JSONObject.getNames(props); for(String key : keys) { config.props.put(key, props.getString(key)); } props.put(Configuration.AUTOCONF_ID, "true"); vConfs.add(config); } } } catch (Exception e) { logger.warn("Error while parsing configuration from json %s", url); logger.debug("Error is ", e); } return vConfs; } public Map<String, Object> parseFile(URL url) { try(InputStream is = url.openStream()) { JSONTokener tokener = new JSONTokener(is); JSONObject root = new JSONObject(tokener); Map<String, Object> props = new HashMap<>(); String[] keys = JSONObject.getNames(root); for(String key : keys) { props.put(key, root.getString(key)); } props.put(Configuration.AUTOCONF_ID, "true"); return props; } catch (Exception e) { logger.warn("Error while parsing configuration from json %s", url); logger.debug("Error is ", e); } return Collections.emptyMap(); } }
Micablo/Mboehao
app/src/main/java/io/github/jokoframework/auth/AuthInterceptor.java
<reponame>Micablo/Mboehao package io.github.jokoframework.auth; import android.content.Context; import java.io.IOException; import io.github.jokoframework.R; import io.github.jokoframework.activity.BaseActivity; import io.github.jokoframework.mboehaolib.constants.Constants; import io.github.jokoframework.model.UserData; import io.github.jokoframework.singleton.MboehaoApp; import io.github.jokoframework.utilities.AppUtils; import okhttp3.Interceptor; import okhttp3.Request; import okhttp3.Response; public class AuthInterceptor implements Interceptor { private MboehaoApp application; public AuthInterceptor(MboehaoApp application) { this.application = application; } @Override public Response intercept(Chain chain) throws IOException { //final String server = application.getString(R.string.server_hostname); if (!AppUtils.isDnsWorking(Constants.SERVER_NAME)) { //Workaround - afeltes //Sin conexion, explotaba el APP por un UnknownHostException final Context applicationContext = application.getApplicationContext(); AppUtils.showNoConnectionError(applicationContext); Request dummyRequest = new Request.Builder() .url(applicationContext.getString(R.string.dummyHostname)) .build(); return chain.proceed(dummyRequest); } else { BaseActivity activity = application.getBaseActivity(); if (activity != null) { activity.setWithInternetConnection(true); } Request request = chain.request(); //Build new request Request.Builder builder = request.newBuilder(); String userAccessToken = null; UserData userData = application.getUserData(); if (userData != null) { userAccessToken = userData.getUserAccessToken(); } setAuthHeader(builder, userAccessToken); //write current token to request request = builder.build(); //overwrite old request return chain.proceed(request); } } private void setAuthHeader(Request.Builder builder, String token) { if (token != null) { //Add Auth token to each request if authorized builder.header(Constants.HEADER_AUTH, token); } } }
GoodyIT/MERN-stack-donate---Bitcoin-Payment
client/modules/App/AuthUser/Account.js
import React from 'react'; import { connect } from 'react-redux'; import TextField from '@material-ui/core/TextField'; import { browserHistory } from 'react-router'; import AuthHeader from '../components/AuthHeader/AuthHeader'; import Footer from '../components/Footer/Footer'; import { fetchUser } from '../AppActions'; import callApi from '../../../util/apiCaller'; import { toast } from 'react-toastify'; class Account extends React.Component { constructor(props) { super(props); this.state = { loading: true, newPassword: '', confirmPassword: '', }; this.handleChange = this.handleChange.bind(this); } componentWillMount() { if (typeof(window) !== "undefined") { const token = window.localStorage.getItem('smartproject'); this.setState({ isUnAuth: !token, token }); } } componentDidMount() { this.props.dispatch(fetchUser()); } componentWillReceiveProps(nextProps) { if (this.props.res != nextProps.res) { this.setState({ loading: false, user: nextProps.res.user }); } } handleChange = name => event => { this.setState({ ...this.state, [name]: event.target.value, }); }; save = () => { const { user, newPassword, confirmPassword } = this.state; this.setState({ ...this.state, passwordErr: !newPassword || !confirmPassword || newPassword != confirmPassword, }); if (this.state.passwordErr) { toast.warn('Password does not match'); this.setState({ ...this.state }); return; } callApi('updateUser', 'PUT', { user: this.state.user, password: this.state.newPassword }).then((res) => { let message = res.errors && res.errors || 'Successfully Saved'; toast.warn(message); }); } render() { const { loading, user, passwordErr, newPassword, confirmPassword } = this.state; const { res } = this.props; return( <div> <AuthHeader /> <div className="container container-option"> {loading && <div>...loading</div>} {!loading && <div> <h1 className="mb-4">Account Page</h1> <div className="card profile"> <div className="row card-body"> <div className="col-7"> <p><strong>Email: </strong> {user.email} </p> <p><strong>Full Name: </strong> {user.fullName} </p> <p><strong>Birthday: </strong> {user.birthday} </p> <p><strong>Nationality: </strong> {user.nationality} </p> <p><strong>Address: </strong> {user.address} </p> <p><strong>Phone: </strong> {user.phone} </p> <p><strong>ID: </strong> {user.ID} </p> </div> <div className="col-5"> <h4>Change Password</h4> <TextField fullWidth required error={passwordErr} id="newPassword-input" label="New Password" type="password" name="newPassword" value={newPassword} onChange={this.handleChange('newPassword')} margin="normal" /> <TextField fullWidth required error={passwordErr} id="confirmPassword-input" label="Confirm Password" type="password" name="confirmPassword" value={confirmPassword} onChange={this.handleChange('confirmPassword')} margin="normal" /> <button onClick={() => this.save()} className="btn btn-lg bg-warning text-white mt-2 mb-2 float-right">Update</button> </div> </div> </div> <button onClick={() => browserHistory.push('user/referral')} className="btn btn-lg bg-success text-white mt-4 mb-2">Referral</button> </div>} </div> <Footer /> </div> ); } } function mapStateToProps(state) { return { res: state.app.res, }; } export default connect(mapStateToProps)(Account);
NgLoader/Discord-Bot-Wuffy-v1
wuffy-bot/src/main/java/net/wuffy/bot/module/ModuleListenerAdapter.java
package net.wuffy.bot.module; import java.util.HashMap; import java.util.Map; import net.dv8tion.jda.core.entities.Guild; import net.dv8tion.jda.core.events.ReadyEvent; import net.dv8tion.jda.core.events.guild.GuildAvailableEvent; import net.dv8tion.jda.core.events.guild.GuildLeaveEvent; import net.dv8tion.jda.core.events.guild.GuildReadyEvent; import net.dv8tion.jda.core.events.guild.GuildUnavailableEvent; import net.dv8tion.jda.core.hooks.SubscribeEvent; import net.wuffy.bot.Wuffy; import net.wuffy.bot.database.DBExtension; import net.wuffy.common.logger.Logger; public class ModuleListenerAdapter { private static final Map<Long, GuildModule> GUILD_MODULES = new HashMap<Long, GuildModule>(); private Wuffy core; public ModuleListenerAdapter(Wuffy core) { this.core = core; } @SubscribeEvent public void onReadyEvent(ReadyEvent event) { Logger.info("ShardInitializer", String.format("Shard \"%s\" is ready", Integer.toString(event.getJDA().getShardInfo().getShardId()))); } @SubscribeEvent public void onGuildReadyEvent(GuildReadyEvent event) { this.handleGuildReady(event.getGuild()); } @SubscribeEvent public void onGuildAvailableEvent(GuildAvailableEvent event) { this.handleGuildReady(event.getGuild()); } @SubscribeEvent public void onGuildUnavailableEvent(GuildUnavailableEvent event) { this.handleGuildDestoryed(event.getGuild()); } @SubscribeEvent public void onGuildLeaveEvent(GuildLeaveEvent event) { this.handleGuildDestoryed(event.getGuild()); // this.core.getStorageService().getStorage().getProvider(DBExtension.class).getGuild(event.getGuild()).deleteFromDatabase(); NOT USED (Database auto delete) } public void handleGuildReady(Guild guild) { if(guild == null) return; Long guildId = guild.getIdLong(); if(!ModuleListenerAdapter.GUILD_MODULES.containsKey(guildId)) { GuildModule guildModule = new GuildModule(this.core.getStorageService().getStorage().getProvider(DBExtension.class).getGuild(guild)); ModuleListenerAdapter.GUILD_MODULES.put(guildId, guildModule); Logger.debug("ModuleListenerAdapter", String.format("Initializing guild \"%s\"", Long.valueOf(guildId))); if(guildModule.initialize()) Logger.debug("ModuleListenerAdapter", String.format("Initialized guild \"%s\"", Long.valueOf(guildId))); else Logger.info("GuildModule", String.format("Guild was already initialized \"%s\"", Long.toString(guildId))); } } public void handleGuildDestoryed(Guild guild) { if(guild == null) return; Long guildId = guild.getIdLong(); if(ModuleListenerAdapter.GUILD_MODULES.containsKey(guildId)) { GuildModule guildModule = ModuleListenerAdapter.GUILD_MODULES.remove(guildId); if(guildModule != null) { guildModule.destroy(); Logger.debug("GuildModule", String.format("Destroyed guild \"%s\"", Long.valueOf(guildId))); } } } }
xiefan46/samza
samza-core/src/main/java/org/apache/samza/operators/spec/FilterOperatorSpec.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.samza.operators.spec; import java.util.ArrayList; import java.util.Collection; import org.apache.samza.context.Context; import org.apache.samza.operators.functions.FilterFunction; import org.apache.samza.operators.functions.FlatMapFunction; import org.apache.samza.operators.functions.ScheduledFunction; import org.apache.samza.operators.functions.WatermarkFunction; /** * The spec for an operator that filters input messages based on some conditions. * * @param <M> type of input message */ class FilterOperatorSpec<M> extends StreamOperatorSpec<M, M> { private final FilterFunction<M> filterFn; FilterOperatorSpec(FilterFunction<M> filterFn, String opId) { super(new FlatMapFunction<M, M>() { @Override public Collection<M> apply(M message) { return new ArrayList<M>() { { if (filterFn.apply(message)) { this.add(message); } } }; } @Override public void init(Context context) { filterFn.init(context); } @Override public void close() { filterFn.close(); } }, OpCode.FILTER, opId); this.filterFn = filterFn; } @Override public WatermarkFunction getWatermarkFn() { return this.filterFn instanceof WatermarkFunction ? (WatermarkFunction) this.filterFn : null; } @Override public ScheduledFunction getScheduledFn() { return this.filterFn instanceof ScheduledFunction ? (ScheduledFunction) this.filterFn : null; } }
jellybean4/yosaipy2
yosaipy2/registry/pyramid/tweens.py
<reponame>jellybean4/yosaipy2 #!/usr/bin/env python # -*- coding: utf-8 -*- from pyramid.exceptions import ConfigurationError from yosaipy2.web import WebYosai from .webregistry import PyramidWebRegistry def pyramid_yosai_tween_factory(handler, registry): """ This tween obtains the currently executing subject instance from Yosai and makes it available from the request object. """ yosai = registry.get('yosai') if yosai is None: msg = ('You cannot register the Yosai subject tween without first ' 'registering a yosai instance with Pyramid."') raise ConfigurationError(msg) def tween(request): web_registry = PyramidWebRegistry(request) with WebYosai.context(yosai, web_registry): response = handler(request) return response return tween
datacite/sashimi
spec/requests/report_types_spec.rb
require 'rails_helper' describe 'ReportTypes', type: :request do let(:bearer) { User.generate_token(uid: "datacite.datacite", role_id: "staff_admin") } let(:headers) { {'ACCEPT'=>'application/json', 'CONTENT_TYPE'=>'application/json', 'Authorization' => 'Bearer ' + bearer}} # describe 'GET /reports' do # let!(:report_type) { {report_type: "Master_report"} } # context 'index' do # before { get '/report-types' } # it 'returns reports' do # expect(json).not_to be_empty # expect(json['report-types'].size).to eq(1) # expect(response).to have_http_status(200) # end # end # end # describe 'GET /report-types/:id' do # let(:report) { create(:report) } # before { get "/report-types/#{report.uid}", headers: headers } # context 'when the record exists' do # it 'returns the report' do # puts json # expect(json.dig("report","report-header", "report-id")).to eq(report.report_id) # expect(response).to have_http_status(200) # end # end # context 'when the record does not exist' do # before { get "/report-types/0f8372ff-9bbb-44d0-80ff-a03f308f5889", headers: headers } # it 'returns status code 404' do # expect(response).to have_http_status(404) # expect(json["errors"].first).to eq("status"=>"404", "title"=>"The resource you are looking for doesn't exist.") # end # end # end # describe 'POST /report-types' do # let!(:params) { {"report-id": "Master_report"}} # context 'when the request is valid' do # before { post '/report-types', params: params.to_json, headers: headers } # it 'creates a report' do # puts json # expect(response).to have_http_status(201) # expect(json.dig("report_id")).to eq("Master_report") # end # end # end end
Tekh-ops/ezEngine
Code/Tools/Libs/ToolsFoundation/Selection/Implementation/SelectionManager.cpp
<filename>Code/Tools/Libs/ToolsFoundation/Selection/Implementation/SelectionManager.cpp<gh_stars>100-1000 #include <ToolsFoundation/ToolsFoundationPCH.h> #include <ToolsFoundation/Document/Document.h> #include <ToolsFoundation/Object/DocumentObjectManager.h> #include <ToolsFoundation/Selection/SelectionManager.h> ezSelectionManager::ezSelectionManager(const ezDocumentObjectManager* pObjectManager) { auto pStorage = EZ_DEFAULT_NEW(Storage); pStorage->m_pObjectManager = pObjectManager; SwapStorage(pStorage); } ezSelectionManager::~ezSelectionManager() { m_ObjectStructureUnsubscriber.Unsubscribe(); m_EventsUnsubscriber.Unsubscribe(); } void ezSelectionManager::TreeEventHandler(const ezDocumentObjectStructureEvent& e) { switch (e.m_EventType) { case ezDocumentObjectStructureEvent::Type::BeforeObjectRemoved: RemoveObject(e.m_pObject, true); break; default: return; } } bool ezSelectionManager::RecursiveRemoveFromSelection(const ezDocumentObject* pObject) { auto it = m_pSelectionStorage->m_SelectionSet.Find(pObject->GetGuid()); bool bRemoved = false; if (it.IsValid()) { m_pSelectionStorage->m_SelectionSet.Remove(it); m_pSelectionStorage->m_SelectionList.RemoveAndCopy(pObject); bRemoved = true; } for (const ezDocumentObject* pChild : pObject->GetChildren()) { bRemoved = bRemoved || RecursiveRemoveFromSelection(pChild); } return bRemoved; } void ezSelectionManager::Clear() { if (!m_pSelectionStorage->m_SelectionList.IsEmpty() || !m_pSelectionStorage->m_SelectionSet.IsEmpty()) { m_pSelectionStorage->m_SelectionList.Clear(); m_pSelectionStorage->m_SelectionSet.Clear(); ezSelectionManagerEvent e; e.m_pDocument = GetDocument(); e.m_pObject = nullptr; e.m_Type = ezSelectionManagerEvent::Type::SelectionCleared; m_pSelectionStorage->m_Events.Broadcast(e); } } void ezSelectionManager::AddObject(const ezDocumentObject* pObject) { EZ_ASSERT_DEBUG(pObject, "Object must be valid"); if (IsSelected(pObject)) return; EZ_ASSERT_DEV(pObject->GetDocumentObjectManager() == m_pSelectionStorage->m_pObjectManager, "Passed in object does not belong to same object manager."); ezStatus res = m_pSelectionStorage->m_pObjectManager->CanSelect(pObject); if (res.m_Result.Failed()) { ezLog::Error("{0}", res.m_sMessage); return; } m_pSelectionStorage->m_SelectionList.PushBack(pObject); m_pSelectionStorage->m_SelectionSet.Insert(pObject->GetGuid()); ezSelectionManagerEvent e; e.m_pDocument = GetDocument(); e.m_pObject = pObject; e.m_Type = ezSelectionManagerEvent::Type::ObjectAdded; m_pSelectionStorage->m_Events.Broadcast(e); } void ezSelectionManager::RemoveObject(const ezDocumentObject* pObject, bool bRecurseChildren) { if (bRecurseChildren) { // We only want one message for the change in selection so we first everything and then fire // SelectionSet instead of multiple ObjectRemoved messages. if (RecursiveRemoveFromSelection(pObject)) { ezSelectionManagerEvent e; e.m_pDocument = GetDocument(); e.m_pObject = nullptr; e.m_Type = ezSelectionManagerEvent::Type::SelectionSet; m_pSelectionStorage->m_Events.Broadcast(e); } } else { auto it = m_pSelectionStorage->m_SelectionSet.Find(pObject->GetGuid()); if (!it.IsValid()) return; m_pSelectionStorage->m_SelectionSet.Remove(it); m_pSelectionStorage->m_SelectionList.RemoveAndCopy(pObject); ezSelectionManagerEvent e; e.m_pDocument = GetDocument(); e.m_pObject = pObject; e.m_Type = ezSelectionManagerEvent::Type::ObjectRemoved; m_pSelectionStorage->m_Events.Broadcast(e); } } void ezSelectionManager::SetSelection(const ezDocumentObject* pSingleObject) { ezDeque<const ezDocumentObject*> objs; objs.PushBack(pSingleObject); SetSelection(objs); } void ezSelectionManager::SetSelection(const ezDeque<const ezDocumentObject*>& Selection) { if (Selection.IsEmpty()) { Clear(); return; } if (m_pSelectionStorage->m_SelectionList == Selection) return; m_pSelectionStorage->m_SelectionList.Clear(); m_pSelectionStorage->m_SelectionSet.Clear(); m_pSelectionStorage->m_SelectionList.Reserve(Selection.GetCount()); for (ezUInt32 i = 0; i < Selection.GetCount(); ++i) { if (Selection[i] != nullptr) { EZ_ASSERT_DEV(Selection[i]->GetDocumentObjectManager() == m_pSelectionStorage->m_pObjectManager, "Passed in object does not belong to same object manager."); ezStatus res = m_pSelectionStorage->m_pObjectManager->CanSelect(Selection[i]); if (res.m_Result.Failed()) { ezLog::Error("{0}", res.m_sMessage); continue; } // actually == nullptr should never happen, unless we have an error somewhere else m_pSelectionStorage->m_SelectionList.PushBack(Selection[i]); m_pSelectionStorage->m_SelectionSet.Insert(Selection[i]->GetGuid()); } } { // Sync selection model. ezSelectionManagerEvent e; e.m_pDocument = GetDocument(); e.m_pObject = nullptr; e.m_Type = ezSelectionManagerEvent::Type::SelectionSet; m_pSelectionStorage->m_Events.Broadcast(e); } } void ezSelectionManager::ToggleObject(const ezDocumentObject* pObject) { if (IsSelected(pObject)) RemoveObject(pObject); else AddObject(pObject); } const ezDocumentObject* ezSelectionManager::GetCurrentObject() const { return m_pSelectionStorage->m_SelectionList.IsEmpty() ? nullptr : m_pSelectionStorage->m_SelectionList[m_pSelectionStorage->m_SelectionList.GetCount() - 1]; } bool ezSelectionManager::IsSelected(const ezDocumentObject* pObject) const { return m_pSelectionStorage->m_SelectionSet.Find(pObject->GetGuid()).IsValid(); } bool ezSelectionManager::IsParentSelected(const ezDocumentObject* pObject) const { const ezDocumentObject* pParent = pObject->GetParent(); while (pParent != nullptr) { if (m_pSelectionStorage->m_SelectionSet.Find(pParent->GetGuid()).IsValid()) return true; pParent = pParent->GetParent(); } return false; } const ezDocument* ezSelectionManager::GetDocument() const { return m_pSelectionStorage->m_pObjectManager->GetDocument(); } ezSharedPtr<ezSelectionManager::Storage> ezSelectionManager::SwapStorage(ezSharedPtr<ezSelectionManager::Storage> pNewStorage) { EZ_ASSERT_ALWAYS(pNewStorage != nullptr, "Need a valid history storage object"); auto retVal = m_pSelectionStorage; m_ObjectStructureUnsubscriber.Unsubscribe(); m_EventsUnsubscriber.Unsubscribe(); m_pSelectionStorage = pNewStorage; m_pSelectionStorage->m_pObjectManager->m_StructureEvents.AddEventHandler(ezMakeDelegate(&ezSelectionManager::TreeEventHandler, this), m_ObjectStructureUnsubscriber); m_pSelectionStorage->m_Events.AddEventHandler([this](const ezSelectionManagerEvent& e) { m_Events.Broadcast(e); }, m_EventsUnsubscriber); return retVal; } struct ezObjectHierarchyComparor { using Tree = ezHybridArray<const ezDocumentObject*, 4>; ezObjectHierarchyComparor(ezDeque<const ezDocumentObject*>& items) { for (const ezDocumentObject* pObject : items) { Tree& tree = lookup[pObject]; while (pObject) { tree.PushBack(pObject); pObject = pObject->GetParent(); } std::reverse(begin(tree), end(tree)); } } EZ_ALWAYS_INLINE bool Less(const ezDocumentObject* lhs, const ezDocumentObject* rhs) const { const Tree& A = *lookup.GetValue(lhs); const Tree& B = *lookup.GetValue(rhs); const ezUInt32 minSize = ezMath::Min(A.GetCount(), B.GetCount()); for (ezUInt32 i = 0; i < minSize; i++) { // The first element in the loop should always be the root so there is not risk that there is no common parent. if (A[i] != B[i]) { // These elements are the first different ones so they share the same parent. // We just assume that the hierarchy is integer-based for now. return A[i]->GetPropertyIndex().ConvertTo<ezUInt32>() < B[i]->GetPropertyIndex().ConvertTo<ezUInt32>(); } } return A.GetCount() < B.GetCount(); } EZ_ALWAYS_INLINE bool Equal(const ezDocumentObject* lhs, const ezDocumentObject* rhs) const { return lhs == rhs; } ezMap<const ezDocumentObject*, Tree> lookup; }; const ezDeque<const ezDocumentObject*> ezSelectionManager::GetTopLevelSelection() const { ezDeque<const ezDocumentObject*> items; for (const auto* pObj : m_pSelectionStorage->m_SelectionList) { if (!IsParentSelected(pObj)) { items.PushBack(pObj); } } ezObjectHierarchyComparor c(items); items.Sort(c); return items; } const ezDeque<const ezDocumentObject*> ezSelectionManager::GetTopLevelSelection(const ezRTTI* pBase) const { ezDeque<const ezDocumentObject*> items; for (const auto* pObj : m_pSelectionStorage->m_SelectionList) { if (!pObj->GetTypeAccessor().GetType()->IsDerivedFrom(pBase)) continue; if (!IsParentSelected(pObj)) { items.PushBack(pObj); } } ezObjectHierarchyComparor c(items); items.Sort(c); return items; }
zhyinty/HeliumRain
Source/HeliumRain/UI/Components/FlareColorPanel.cpp
<gh_stars>100-1000 #include "HeliumRain/UI/Components/FlareColorPanel.h" #include "../../Flare.h" #include "../../Game/FlareGame.h" #include "../../Player/FlareMenuPawn.h" #include "../../Player/FlareMenuManager.h" #include "../../Player/FlarePlayerController.h" #include "../../Data/FlareCustomizationCatalog.h" #define LOCTEXT_NAMESPACE "FlareColorPanel" /*---------------------------------------------------- Construct ----------------------------------------------------*/ void SFlareColorPanel::Construct(const FArguments& InArgs) { // Data MenuManager = InArgs._MenuManager; AFlareGame* Game = Cast<AFlareGame>(MenuManager->GetWorld()->GetAuthGameMode()); UFlareCustomizationCatalog* CustomizationCatalog = Game->GetCustomizationCatalog(); UFlareSpacecraftComponentsCatalog* ShipPartsCatalog = Game->GetShipPartsCatalog(); // Layout ChildSlot .HAlign(HAlign_Fill) .VAlign(VAlign_Fill) [ SAssignNew(PickerList, SHorizontalBox) // Pattern picker + SHorizontalBox::Slot().AutoWidth() .VAlign(VAlign_Top) [ SAssignNew(PatternPicker, SFlareDropList<int32>) .OnItemPicked(this, &SFlareColorPanel::OnPatternPicked) ] // Base paint picker + SHorizontalBox::Slot().AutoWidth() .VAlign(VAlign_Top) [ SAssignNew(BasePaintColorPicker, SFlareDropList<FLinearColor>) .OnItemPicked(this, &SFlareColorPanel::OnBasePaintColorPickedByIndex) .OnColorPicked(this, &SFlareColorPanel::OnBasePaintColorPicked) .LineSize(3) .ItemWidth(1) .ItemHeight(1) .ShowColorWheel(true) ] // Paint picker + SHorizontalBox::Slot().AutoWidth() .VAlign(VAlign_Top) [ SAssignNew(PaintColorPicker, SFlareDropList<FLinearColor>) .OnItemPicked(this, &SFlareColorPanel::OnPaintColorPickedByIndex) .OnColorPicked(this, &SFlareColorPanel::OnPaintColorPicked) .LineSize(3) .ItemWidth(1) .ItemHeight(1) .ShowColorWheel(true) ] // Overlay picker + SHorizontalBox::Slot().AutoWidth() .VAlign(VAlign_Top) [ SAssignNew(OverlayColorPicker, SFlareDropList<FLinearColor>) .OnItemPicked(this, &SFlareColorPanel::OnOverlayColorPickedByIndex) .OnColorPicked(this, &SFlareColorPanel::OnOverlayColorPicked) .LineSize(3) .ItemWidth(1) .ItemHeight(1) .ShowColorWheel(true) ] // Light picker + SHorizontalBox::Slot().AutoWidth() .VAlign(VAlign_Top) [ SAssignNew(LightColorPicker, SFlareDropList<FLinearColor>) .OnItemPicked(this, &SFlareColorPanel::OnLightColorPickedByIndex) .OnColorPicked(this, &SFlareColorPanel::OnLightColorPicked) .LineSize(3) .ItemWidth(1) .ItemHeight(1) .ShowColorWheel(true) ] ]; // Fill patterns for (int i = 0; i < CustomizationCatalog->GetPatternCount(); i++) { PatternPicker->AddItem(SNew(SImage).Image(CustomizationCatalog->GetPatternBrush(i))); } // Fill colors for (int i = 0; i < CustomizationCatalog->GetColorCount(); i++) { BasePaintColorPicker->AddItem(SNew(SColorBlock).Color(CustomizationCatalog->GetColorByIndex(i))); PaintColorPicker->AddItem(SNew(SColorBlock).Color(CustomizationCatalog->GetColorByIndex(i))); OverlayColorPicker->AddItem(SNew(SColorBlock).Color(CustomizationCatalog->GetColorByIndex(i))); LightColorPicker->AddItem(SNew(SColorBlock).Color(CustomizationCatalog->GetColorByIndex(i))); } // Setup initial data BasePaintColorPicker->SetSelectedIndex(0); PaintColorPicker->SetSelectedIndex(0); OverlayColorPicker->SetSelectedIndex(0); LightColorPicker->SetSelectedIndex(0); PatternPicker->SetSelectedIndex(0); BasePaintColorPicker->SetColor(FLinearColor(0,0,0)); PaintColorPicker->SetColor(FLinearColor(0,0,0)); OverlayColorPicker->SetColor(FLinearColor(0,0,0)); LightColorPicker->SetColor(FLinearColor(0,0,0)); } /*---------------------------------------------------- Interaction ----------------------------------------------------*/ void SFlareColorPanel::Setup(FFlarePlayerSave& PlayerData) { AFlareGame* Game = Cast<AFlareGame>(MenuManager->GetWorld()->GetAuthGameMode()); UFlareCompany* Company = Game->GetGameWorld()->FindCompany(PlayerData.CompanyIdentifier); if (Company) { UFlareCustomizationCatalog* CustomizationCatalog = Game->GetCustomizationCatalog(); BasePaintColorPicker->SetSelectedIndex(CustomizationCatalog->FindColor(Company->GetBasePaintColor())); PaintColorPicker->SetSelectedIndex(CustomizationCatalog->FindColor(Company->GetPaintColor())); OverlayColorPicker->SetSelectedIndex(CustomizationCatalog->FindColor(Company->GetOverlayColor())); LightColorPicker->SetSelectedIndex(CustomizationCatalog->FindColor(Company->GetLightColor())); PatternPicker->SetSelectedIndex(Company->GetPatternIndex()); BasePaintColorPicker->SetColor(Company->GetBasePaintColor()); PaintColorPicker->SetColor(Company->GetPaintColor()); OverlayColorPicker->SetColor(Company->GetOverlayColor()); LightColorPicker->SetColor(Company->GetLightColor()); } } void SFlareColorPanel::SetupDefault() { const FFlareCompanyDescription* CurrentCompanyData = MenuManager->GetPC()->GetCompanyDescription(); AFlareGame* Game = Cast<AFlareGame>(MenuManager->GetWorld()->GetAuthGameMode()); UFlareCustomizationCatalog* CustomizationCatalog = Game->GetCustomizationCatalog(); BasePaintColorPicker->SetSelectedIndex(CustomizationCatalog->FindColor(CurrentCompanyData->CustomizationBasePaintColor)); PaintColorPicker->SetSelectedIndex(CustomizationCatalog->FindColor(CurrentCompanyData->CustomizationPaintColor)); OverlayColorPicker->SetSelectedIndex(CustomizationCatalog->FindColor(CurrentCompanyData->CustomizationOverlayColor)); LightColorPicker->SetSelectedIndex(CustomizationCatalog->FindColor(CurrentCompanyData->CustomizationLightColor)); PatternPicker->SetSelectedIndex(CurrentCompanyData->CustomizationPatternIndex); BasePaintColorPicker->SetColor(CurrentCompanyData->CustomizationBasePaintColor); PaintColorPicker->SetColor(CurrentCompanyData->CustomizationPaintColor); OverlayColorPicker->SetColor(CurrentCompanyData->CustomizationOverlayColor); LightColorPicker->SetColor(CurrentCompanyData->CustomizationLightColor); } void SFlareColorPanel::OnBasePaintColorPickedByIndex(int32 Index) { AFlarePlayerController* PC = MenuManager->GetPC(); if (PC) { AFlareGame* Game = Cast<AFlareGame>(MenuManager->GetWorld()->GetAuthGameMode()); UFlareCustomizationCatalog* CustomizationCatalog = Game->GetCustomizationCatalog(); const FFlareCompanyDescription* CurrentCompanyData = MenuManager->GetPC()->GetCompanyDescription(); FLOGV("SFlareColorPanel::OnBasePaintColorPicked %d", Index); PC->SetBasePaintColor(CustomizationCatalog->GetColorByIndex(Index)); PC->GetMenuPawn()->UpdateCustomization(); BasePaintColorPicker->SetColor(CurrentCompanyData->CustomizationBasePaintColor); } } void SFlareColorPanel::OnPaintColorPickedByIndex(int32 Index) { AFlarePlayerController* PC = MenuManager->GetPC(); if (PC) { AFlareGame* Game = Cast<AFlareGame>(MenuManager->GetWorld()->GetAuthGameMode()); UFlareCustomizationCatalog* CustomizationCatalog = Game->GetCustomizationCatalog(); const FFlareCompanyDescription* CurrentCompanyData = MenuManager->GetPC()->GetCompanyDescription(); FLOGV("SFlareColorPanel::OnPaintColorPicked %d", Index); PC->SetPaintColor(CustomizationCatalog->GetColorByIndex(Index)); PC->GetMenuPawn()->UpdateCustomization(); PaintColorPicker->SetColor(CurrentCompanyData->CustomizationPaintColor); } } void SFlareColorPanel::OnOverlayColorPickedByIndex(int32 Index) { AFlarePlayerController* PC = MenuManager->GetPC(); if (PC) { AFlareGame* Game = Cast<AFlareGame>(MenuManager->GetWorld()->GetAuthGameMode()); UFlareCustomizationCatalog* CustomizationCatalog = Game->GetCustomizationCatalog(); const FFlareCompanyDescription* CurrentCompanyData = MenuManager->GetPC()->GetCompanyDescription(); FLOGV("SFlareColorPanel::OnOverlayColorPicked %d", Index); PC->SetOverlayColor(CustomizationCatalog->GetColorByIndex(Index)); PC->GetMenuPawn()->UpdateCustomization(); OverlayColorPicker->SetColor(CurrentCompanyData->CustomizationOverlayColor); } } void SFlareColorPanel::OnLightColorPickedByIndex(int32 Index) { AFlarePlayerController* PC = MenuManager->GetPC(); if (PC) { AFlareGame* Game = Cast<AFlareGame>(MenuManager->GetWorld()->GetAuthGameMode()); UFlareCustomizationCatalog* CustomizationCatalog = Game->GetCustomizationCatalog(); const FFlareCompanyDescription* CurrentCompanyData = MenuManager->GetPC()->GetCompanyDescription(); FLOGV("SFlareColorPanel::OnLightColorPicked %d", Index); PC->SetLightColor(CustomizationCatalog->GetColorByIndex(Index)); PC->GetMenuPawn()->UpdateCustomization(); LightColorPicker->SetColor(CurrentCompanyData->CustomizationLightColor); } } void SFlareColorPanel::OnBasePaintColorPicked(FLinearColor Color) { AFlarePlayerController* PC = MenuManager->GetPC(); if (PC) { PC->SetBasePaintColor(Color); PC->GetMenuPawn()->UpdateCustomization(); } } void SFlareColorPanel::OnPaintColorPicked(FLinearColor Color) { AFlarePlayerController* PC = MenuManager->GetPC(); if (PC) { PC->SetPaintColor(Color); PC->GetMenuPawn()->UpdateCustomization(); } } void SFlareColorPanel::OnOverlayColorPicked(FLinearColor Color) { AFlarePlayerController* PC = MenuManager->GetPC(); if (PC) { PC->SetOverlayColor(Color); PC->GetMenuPawn()->UpdateCustomization(); } } void SFlareColorPanel::OnLightColorPicked(FLinearColor Color) { AFlarePlayerController* PC = MenuManager->GetPC(); if (PC) { PC->SetLightColor(Color); PC->GetMenuPawn()->UpdateCustomization(); } } void SFlareColorPanel::OnPatternPicked(int32 Index) { AFlarePlayerController* PC = MenuManager->GetPC(); if (PC) { FLOGV("SFlareColorPanel::OnPatternPicked %d", Index); PC->SetPatternIndex(Index); PC->GetMenuPawn()->UpdateCustomization(); } } #undef LOCTEXT_NAMESPACE
jizi19911101/gin-vue-admin
server/global/viper.go
<gh_stars>1-10 package global import ( "fmt" "os" "path/filepath" "time" "github.com/songzhibin97/gkit/cache/local_cache" _ "github.com/jizi19911101/gin-vue-admin/server/packfile" "github.com/fsnotify/fsnotify" "github.com/spf13/viper" ) const ( ConfigEnv = "GVA_CONFIG" ConfigFile = "config.yaml" ) func Viper(path ...string) *viper.Viper { var config string if len(path) == 0 { if config == "" { if configEnv := os.Getenv(ConfigEnv); configEnv == "" { config = RedirectConfigFile(ConfigFile) //config = ConfigFile fmt.Printf("您正在使用config的默认值,config的路径为%v\n", config) } else { config = configEnv fmt.Printf("您正在使用GVA_CONFIG环境变量,config的路径为%v\n", config) } } else { fmt.Printf("您正在使用命令行的-c参数传递的值,config的路径为%v\n", config) } } else { config = path[0] fmt.Printf("您正在使用func Viper()传递的值,config的路径为%v\n", config) } v := viper.New() v.SetConfigFile(config) v.SetConfigType("yaml") err := v.ReadInConfig() if err != nil { panic(fmt.Errorf("Fatal error config file: %s \n", err)) } v.WatchConfig() v.OnConfigChange(func(e fsnotify.Event) { fmt.Println("config file changed:", e.Name) if err := v.Unmarshal(&GVA_CONFIG); err != nil { fmt.Println(err) } }) if err := v.Unmarshal(&GVA_CONFIG); err != nil { fmt.Println(err) } // root 适配性 // 根据root位置去找到对应迁移位置,保证root路径有效 GVA_CONFIG.AutoCode.Root, _ = filepath.Abs("..") BlackCache = local_cache.NewCache( local_cache.SetDefaultExpire(time.Second * time.Duration(GVA_CONFIG.JWT.ExpiresTime)), ) return v } // todo 提取为公共方法 const MaxRedirectCount = 5 var redirectCount = 0 // 一直往上级目录寻到文件 func RedirectConfigFile(path string) string { // 防止无线递归,找不到配置文件 if redirectCount > MaxRedirectCount { return path } redirectCount++ if _, err := os.Stat(path); err == nil { return path } return RedirectConfigFile("../" + path) }
KuoWeiEli/DP_By_Pokemon
src/proxy/ProxyDemo.java
<filename>src/proxy/ProxyDemo.java package proxy; /** 代理模式-示範 **/ public class ProxyDemo { public static void main(String[] args) { /** 到健康中心電腦前操作電腦 **/ Computer computer = new Computer(); /** 將綠毛蟲送去保管 **/ Pokemon caterpie = new Pokemon("綠毛蟲"); computer.put(caterpie); /** 操作不正確,沒有選擇寶可夢 **/ computer.put(null); /** 將手上寶可夢都送去保管 **/ Pokemon pikachu = new Pokemon("皮卡丘"); computer.put(pikachu); computer.put(new Pokemon("傑尼龜")); computer.put(new Pokemon("小火龍")); computer.put(new Pokemon("妙蛙種子")); /** 綠毛蟲決定放生 **/ computer.remove(caterpie); /** 將皮卡丘領出 **/ computer.get(pikachu); } }
DamieFC/chromium
content/browser/background_fetch/background_fetch_job_controller.h
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_BROWSER_BACKGROUND_FETCH_BACKGROUND_FETCH_JOB_CONTROLLER_H_ #define CONTENT_BROWSER_BACKGROUND_FETCH_BACKGROUND_FETCH_JOB_CONTROLLER_H_ #include <stdint.h> #include <memory> #include <string> #include <vector> #include "base/callback.h" #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "content/browser/background_fetch/background_fetch_delegate_proxy.h" #include "content/browser/background_fetch/background_fetch_registration_id.h" #include "content/browser/background_fetch/background_fetch_request_info.h" #include "content/browser/background_fetch/background_fetch_scheduler.h" #include "content/common/background_fetch/background_fetch_types.h" #include "content/common/content_export.h" #include "content/public/browser/browser_thread.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/skia/include/core/SkBitmap.h" namespace content { class BackgroundFetchDataManager; // The JobController will be responsible for coordinating communication with the // DownloadManager. It will get requests from the RequestManager and dispatch // them to the DownloadService. It lives entirely on the service worker core // thread. // // Lifetime: It is created lazily only once a Background Fetch registration // starts downloading, and it is destroyed once no more communication with the // DownloadService or Offline Items Collection is necessary (i.e. once the // registration has been aborted, or once it has completed/failed and the // waitUntil promise has been resolved so UpdateUI can no longer be called). class CONTENT_EXPORT BackgroundFetchJobController : public BackgroundFetchDelegateProxy::Controller { public: using ErrorCallback = base::OnceCallback<void(blink::mojom::BackgroundFetchError)>; using FinishedCallback = base::OnceCallback<void(const BackgroundFetchRegistrationId&, blink::mojom::BackgroundFetchFailureReason, ErrorCallback)>; using ProgressCallback = base::RepeatingCallback<void( const std::string& unique_id, const blink::mojom::BackgroundFetchRegistrationData&)>; using RequestStartedCallback = base::OnceCallback<void(const BackgroundFetchRegistrationId&, const BackgroundFetchRequestInfo*)>; using RequestFinishedCallback = base::OnceCallback<void(const BackgroundFetchRegistrationId&, scoped_refptr<BackgroundFetchRequestInfo>)>; BackgroundFetchJobController( BackgroundFetchDataManager* data_manager, BackgroundFetchDelegateProxy* delegate_proxy, const BackgroundFetchRegistrationId& registration_id, blink::mojom::BackgroundFetchOptionsPtr options, const SkBitmap& icon, uint64_t bytes_downloaded, uint64_t bytes_uploaded, uint64_t upload_total, ProgressCallback progress_callback, FinishedCallback finished_callback); ~BackgroundFetchJobController() override; // Initializes the job controller with the status of the active and completed // downloads, as well as the title to use. // Only called when this has been loaded from the database. void InitializeRequestStatus( int completed_downloads, int total_downloads, std::vector<scoped_refptr<BackgroundFetchRequestInfo>> active_fetch_requests, bool start_paused); // Gets the number of bytes downloaded/uploaded for jobs that are currently // running. uint64_t GetInProgressDownloadedBytes(); uint64_t GetInProgressUploadedBytes(); // Returns a blink::mojom::BackgroundFetchRegistrationDataPtr object // created with member fields. blink::mojom::BackgroundFetchRegistrationDataPtr NewRegistrationData() const; const BackgroundFetchRegistrationId& registration_id() const { return registration_id_; } // BackgroundFetchDelegateProxy::Controller implementation: void DidStartRequest( const std::string& guid, std::unique_ptr<BackgroundFetchResponse> response) override; void DidUpdateRequest(const std::string& guid, uint64_t bytes_uploaded, uint64_t bytes_downloaded) override; void DidCompleteRequest( const std::string& guid, std::unique_ptr<BackgroundFetchResult> result) override; void AbortFromDelegate( blink::mojom::BackgroundFetchFailureReason failure_reason) override; void GetUploadData( const std::string& guid, BackgroundFetchDelegate::GetUploadDataCallback callback) override; // Aborts the fetch. |callback| will run with the result of marking the // registration for deletion. void Abort(blink::mojom::BackgroundFetchFailureReason failure_reason, ErrorCallback callback); // Request processing. void PopNextRequest(RequestStartedCallback request_started_callback, RequestFinishedCallback request_finished_callback); void DidPopNextRequest( RequestStartedCallback request_started_callback, RequestFinishedCallback request_finished_callback, blink::mojom::BackgroundFetchError error, scoped_refptr<BackgroundFetchRequestInfo> request_info); void StartRequest(scoped_refptr<BackgroundFetchRequestInfo> request, RequestFinishedCallback request_finished_callback); void MarkRequestAsComplete(scoped_refptr<BackgroundFetchRequestInfo> request); // Whether there are more requests to process as part of this job. bool HasMoreRequests(); int pending_downloads() const { return pending_downloads_; } private: struct InProgressRequestBytes { uint64_t uploaded = 0u; uint64_t downloaded = 0u; }; // Called after the request is completely processed, and the next one can be // started. void DidMarkRequestAsComplete(blink::mojom::BackgroundFetchError error); // Notifies the scheduler that the download is complete, and hands the result // over. void NotifyDownloadComplete( scoped_refptr<BackgroundFetchRequestInfo> request); // Called when the job completes or has been aborted. |callback| will run // with the result of marking the registration for deletion. void Finish(blink::mojom::BackgroundFetchFailureReason reason_to_abort, ErrorCallback callback); void DidGetUploadData(BackgroundFetchDelegate::GetUploadDataCallback callback, blink::mojom::BackgroundFetchError error, blink::mojom::SerializedBlobPtr blob); // Manager for interacting with the DB. It is owned by the // BackgroundFetchContext. BackgroundFetchDataManager* data_manager_; // Proxy for interacting with the BackgroundFetchDelegate across thread // boundaries. It is owned by the BackgroundFetchContext. BackgroundFetchDelegateProxy* delegate_proxy_; // A map from the download GUID to the active request. std::map<std::string, scoped_refptr<BackgroundFetchRequestInfo>> active_request_map_; // A map from the download GUID to the in-progress bytes. std::map<std::string, InProgressRequestBytes> active_bytes_map_; // The registration ID of the fetch this controller represents. BackgroundFetchRegistrationId registration_id_; // Options for the represented background fetch registration. blink::mojom::BackgroundFetchOptionsPtr options_; // Icon for the represented background fetch registration. SkBitmap icon_; // Finished callback to invoke when the active request has finished mapped by // its download GUID. std::map<std::string, RequestFinishedCallback> active_request_finished_callbacks_; // Cache of downloaded byte count stored by the DataManager, to enable // delivering progress events without having to read from the database. uint64_t complete_requests_downloaded_bytes_cache_; // Overall number of bytes that have been uploaded. uint64_t complete_requests_uploaded_bytes_cache_; // Total number of bytes to upload. uint64_t upload_total_; // Callback run each time download progress updates. ProgressCallback progress_callback_; // Number of requests that comprise the whole job. int total_downloads_ = 0; // Number of the requests that have been completed so far. int completed_downloads_ = 0; // The number of requests that are currently being processed. int pending_downloads_ = 0; // The reason background fetch was aborted. blink::mojom::BackgroundFetchFailureReason failure_reason_ = blink::mojom::BackgroundFetchFailureReason::NONE; // Custom callback that runs after the controller is finished. FinishedCallback finished_callback_; base::WeakPtrFactory<BackgroundFetchJobController> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(BackgroundFetchJobController); }; } // namespace content #endif // CONTENT_BROWSER_BACKGROUND_FETCH_BACKGROUND_FETCH_JOB_CONTROLLER_H_
BartKnucle/dext-starter
lib/modules/incoming.js
<reponame>BartKnucle/dext-starter import Module from './module' export default class Incoming extends Module { constructor(node) { super(node) } //Init the incoming messages async init() { //Create the incoming databases this.db = await this.node.orbitdb.create(this.name, { type: 'eventlog', create: true, accessController: { write: [this.node.orbitdb.getPubKey(), '*'] } }) //On incoming database update this.db.events.subscribe(async () => { await this.node.messages.onReceived() }) super.init() } //Get all incoming messages getAllIncoming() { this.node.logger.silly(`Get all incoming messages`) const all = this.db.database .iterator({ limit: -1 }) .collect() .map(e => { var message = { data: e.payload.value.data, date: e.payload.value.date, from: e.payload.value.from, to: e.payload.value.to } return { id: e.hash, message: message } }) return all } }
stxent/lpclib
include/halm/platform/lpc/lpc43xx/flash_defs.h
<reponame>stxent/lpclib /* * halm/platform/lpc/lpc43xx/flash_defs.h * Copyright (C) 2015 xent * Project is distributed under the terms of the MIT License */ #ifndef HALM_PLATFORM_LPC_FLASH_DEFS_H_ #error This header should not be included directly #endif #ifndef HALM_PLATFORM_LPC_LPC43XX_FLASH_DEFS_H_ #define HALM_PLATFORM_LPC_LPC43XX_FLASH_DEFS_H_ /*----------------------------------------------------------------------------*/ #include <xcore/bits.h> #include <stdint.h> /*----------------------------------------------------------------------------*/ #define CODE_LPC4350 0xA0000830UL #define CODE_LPC4330 0xA0000A30UL #define CODE_LPC4320 0xA000CB3CUL #define CODE_LPC4310 0xA00ACB3FUL #define CODE_LPC4370FET256 0x00000030UL #define CODE_LPC4370FET100 0x00000230UL #define CODE_LPC435X 0xA001C830UL #define CODE_LPC433X 0xA001CA30UL #define CODE_LPC4325_17 0xA001CB3CUL #define CODE_LPC4322_13 0xA00BCB3CUL #define CODE_LPC4315_17 0xA001CB3FUL #define CODE_LPC4312_13 0xA00BCB3FUL #define FLASH_AVAILABLE 0x00010000UL #define FLASH_SIZE_MASK 0x000000FFUL #define FLASH_SIZE_256_256 0x00000044UL #define FLASH_SIZE_384_384 0x00000022UL #define FLASH_SIZE_512_0 0x00000080UL #define FLASH_SIZE_512_512 0x00000000UL /*----------------------------------------------------------------------------*/ #define FLASH_BANK_A 0x1A000000UL #define FLASH_BANK_B 0x1B000000UL #define FLASH_BANK_MASK 0x0007FFFFUL #define FLASH_BANKS_BORDER 0x80000 #define FLASH_PAGE_SIZE 512 #define FLASH_SECTOR_SIZE_0 8192 #define FLASH_SECTOR_SIZE_1 65536 #define FLASH_SECTORS_BORDER 0x10000 #define FLASH_SECTORS_OFFSET (FLASH_SECTORS_BORDER / FLASH_SECTOR_SIZE_0) /*----------------------------------------------------------------------------*/ #define IAP_BASE (*(volatile uint32_t *)0x10400100UL) /*----------------------------------------------------------------------------*/ #define FLASH_SIZE_ENCODE(a, b) \ (BIT_FIELD((a) >> 10, 0) | BIT_FIELD((b) >> 10, 16)) #define FLASH_SIZE_DECODE_A(value) \ (FIELD_VALUE(value, BIT_FIELD(MASK(16), 0), 0) << 10) #define FLASH_SIZE_DECODE_B(value) \ (FIELD_VALUE(value, BIT_FIELD(MASK(16), 16), 16) << 10) /*----------------------------------------------------------------------------*/ static inline uint8_t addressToBank(uint32_t address) { return address < FLASH_BANK_B ? 0 : 1; } /*----------------------------------------------------------------------------*/ static inline uint32_t addressToPage(uint32_t address) { return address; } /*----------------------------------------------------------------------------*/ static inline uint32_t addressToSector(uint32_t address) { const uint32_t localAddress = address & FLASH_BANK_MASK; if (localAddress < FLASH_SECTORS_BORDER) { /* Sectors from 0 to 7 have size of 8 kB */ return localAddress / FLASH_SECTOR_SIZE_0; } else { /* Sectors from 8 to 14 have size of 64 kB */ return (localAddress - FLASH_SECTORS_BORDER) / FLASH_SECTOR_SIZE_1 + FLASH_SECTORS_OFFSET; } } /*----------------------------------------------------------------------------*/ #endif /* HALM_PLATFORM_LPC_LPC43XX_FLASH_DEFS_H_ */
14ms/Minecraft-Disclosed-Source-Modifications
Flux 39/today/flux/module/implement/Player/AutoBypass.java
package today.flux.module.implement.Player; import com.darkmagician6.eventapi.EventTarget; import com.soterdev.SoterObfuscator; import today.flux.event.TickEvent; import today.flux.module.Category; import today.flux.module.Module; import today.flux.module.ModuleManager; import today.flux.module.implement.Combat.*; import today.flux.module.implement.Movement.*; import today.flux.module.implement.World.*; import today.flux.utility.PlayerUtils; import today.flux.utility.ServerUtils; public class AutoBypass extends Module { public AutoBypass() { super("我觉得你真的好像一个傻逼", Category.Player, false); } @EventTarget @SoterObfuscator.Obfuscation(flags = "+native") public void onTick(TickEvent e) { if (ServerUtils.getServer() == ServerUtils.Server.Hypixel) { for (Module module : ModuleManager.getModList()) { Class moduleClass = module.getClass(); if (moduleClass == AntiBots.class && !module.isEnabled()) { module.setEnabled(true); } if (moduleClass == Criticals.class || moduleClass == Speed.class || moduleClass == Fly.class || moduleClass == NoFall.class || moduleClass == LongJump.class || moduleClass == NoSlow.class || moduleClass == Scaffold.class || moduleClass == AntiBots.class) { if (module.isEnabled() && !module.getMode().isCurrentMode("Hypixel")) { module.getMode().setValue("Hypixel"); PlayerUtils.tellPlayer("[Auto Bypass] Set " + module.getName() + " mode to Hypixel."); } break; } if ( // Combat moduleClass == AutoPot.class || moduleClass == BetterSword.class || moduleClass == BowAimbot.class || moduleClass == HitBox.class || moduleClass == KillAura.class || moduleClass == Reach.class || moduleClass == TargetStrafe.class || moduleClass == Velocity.class || // Movement moduleClass == AntiVoid.class || moduleClass == InvMove.class || moduleClass == SafeWalk.class || moduleClass == Sprint.class || moduleClass == Strafe.class || moduleClass == Step.class || // Player moduleClass == NoRotate.class || moduleClass == Wings.class || moduleClass == ItemPhysics.class || moduleClass == InvCleaner.class || moduleClass == ChatBypass.class || moduleClass == AutoTools.class || // World moduleClass == AutoGG.class || moduleClass == AutoL.class || moduleClass == ChestStealer.class || moduleClass == FastBreak.class || // Misc & Ghost module.getCategory() == Category.Misc || module.getCategory() == Category.Ghost ) { continue; } module.setEnabled(false); PlayerUtils.tellPlayer("[Auto Bypass] Disabled " + module.getName() + " for Hypixel."); } } } }
softwarekid/crayon
exercise/src/example/TextureSampling/TextureSamplingFsParam.h
<reponame>softwarekid/crayon<filename>exercise/src/example/TextureSampling/TextureSamplingFsParam.h #ifndef texture_sampling_fs_param__ #define texture_sampling_fs_param__ #include <CgShaderParametersBase.h> #include <CgShader.h> class TextureSamplingFsParam : public CgShaderParametersBase { private: CGparameter decal; public: void EnableTexture(); void DisableTexture(); void SetTexture(GLuint name); void ExtractParams() override; explicit TextureSamplingFsParam(const CgShader& shader); }; #endif
jmikeowen/Spheral
src/NodeList/SolidNodeList.cc
//---------------------------------Spheral++----------------------------------// // SolidNodeList -- A form of the SPH NodeList appropriate for use with // solid materials. // // Created by JMO, Tue Sep 7 22:44:37 2004 //----------------------------------------------------------------------------// #include "FileIO/FileIO.hh" #include "Field/Field.hh" #include "Field/FieldList.hh" #include "Material/EquationOfState.hh" #include "Kernel/TableKernel.hh" #include "Hydro/HydroFieldNames.hh" #include "Strength/SolidFieldNames.hh" #include "DataBase/IncrementState.hh" #include "SolidMaterial/StrengthModel.hh" #include "Utilities/DBC.hh" #include "SolidNodeList.hh" using std::vector; using std::list; using std::string; using std::cerr; using std::endl; namespace Spheral { //------------------------------------------------------------------------------ // Construct with the given EOS object, along with optional numInternal nodes, // numGhost nodes, and name. //------------------------------------------------------------------------------ template<typename Dimension> SolidNodeList<Dimension>:: SolidNodeList(string name, EquationOfState<Dimension>& eos, StrengthModel<Dimension>& strength, const int numInternal, const int numGhost, const Scalar hmin, const Scalar hmax, const Scalar hminratio, const Scalar nPerh, const int maxNumNeighbors, const Scalar rhoMin, const Scalar rhoMax): FluidNodeList<Dimension>(name, eos, numInternal, numGhost, hmin, hmax, hminratio, nPerh, maxNumNeighbors, rhoMin, rhoMax), mDeviatoricStress(SolidFieldNames::deviatoricStress, *this), mPlasticStrain(SolidFieldNames::plasticStrain, *this), mPlasticStrainRate(SolidFieldNames::plasticStrainRate, *this), mDamage(SolidFieldNames::tensorDamage, *this), mFragmentIDs(SolidFieldNames::fragmentIDs, *this), mParticleTypes(SolidFieldNames::particleTypes, *this), mStrength(strength) { } //------------------------------------------------------------------------------ // Destructor. //------------------------------------------------------------------------------ template<typename Dimension> SolidNodeList<Dimension>:: ~SolidNodeList() { } //------------------------------------------------------------------------------ // Calculate and return the sound speed field. //------------------------------------------------------------------------------ template<typename Dimension> void SolidNodeList<Dimension>:: soundSpeed(Field<Dimension, typename Dimension::Scalar>& field) const { // Get the straight EOS look up from the base class. FluidNodeList<Dimension>::soundSpeed(field); // Augment the sound speed with the strength model. const auto& rho = this->massDensity(); const auto& u = this->specificThermalEnergy(); const auto& D = this->damage(); Field<Dimension, Scalar> P(HydroFieldNames::pressure, *this); this->pressure(P); mStrength.soundSpeed(field, rho, u, P, field, D); } //------------------------------------------------------------------------------ // Calculate and return the bulk modulus. //------------------------------------------------------------------------------ template<typename Dimension> void SolidNodeList<Dimension>:: bulkModulus(Field<Dimension, typename Dimension::Scalar>& field) const { const auto& rho = this->massDensity(); const auto& u = this->specificThermalEnergy(); this->equationOfState().setBulkModulus(field, rho, u); } //------------------------------------------------------------------------------ // Calculate and return the shear modulus. //------------------------------------------------------------------------------ template<typename Dimension> void SolidNodeList<Dimension>:: shearModulus(Field<Dimension, typename Dimension::Scalar>& field) const { const auto& rho = this->massDensity(); const auto& u = this->specificThermalEnergy(); const auto& D = this->damage(); Field<Dimension, Scalar> P(HydroFieldNames::pressure, *this); this->pressure(P); mStrength.shearModulus(field, rho, u, P, D); } //------------------------------------------------------------------------------ // Calculate and return the yield strength. //------------------------------------------------------------------------------ template<typename Dimension> void SolidNodeList<Dimension>:: yieldStrength(Field<Dimension, typename Dimension::Scalar>& field) const { const auto& rho = this->massDensity(); const auto& u = this->specificThermalEnergy(); const auto& D = this->damage(); Field<Dimension, Scalar> P(HydroFieldNames::pressure, *this); this->pressure(P); mStrength.yieldStrength(field, rho, u, P, mPlasticStrain, mPlasticStrainRate, D); } //------------------------------------------------------------------------------ // Dump the current state of the NodeList to the given file. //------------------------------------------------------------------------------ template<typename Dimension> void SolidNodeList<Dimension>:: dumpState(FileIO& file, const string& pathName) const { // Dump the ancestor class. FluidNodeList<Dimension>::dumpState(file, pathName); file.write(mDeviatoricStress, pathName + "/" + mDeviatoricStress.name()); file.write(mPlasticStrain, pathName + "/" + mPlasticStrain.name()); file.write(mPlasticStrainRate, pathName + "/" + mPlasticStrainRate.name()); file.write(mDamage, pathName + "/" + mDamage.name()); file.write(mFragmentIDs, pathName + "/" + mFragmentIDs.name()); file.write(mParticleTypes, pathName + "/" + mParticleTypes.name()); } //------------------------------------------------------------------------------ // Restore the state of the NodeList from the given file. //------------------------------------------------------------------------------ template<typename Dimension> void SolidNodeList<Dimension>:: restoreState(const FileIO& file, const string& pathName) { // Restore the ancestor class. FluidNodeList<Dimension>::restoreState(file, pathName); file.read(mDeviatoricStress, pathName + "/" + mDeviatoricStress.name()); file.read(mPlasticStrain, pathName + "/" + mPlasticStrain.name()); file.read(mPlasticStrainRate, pathName + "/" + mPlasticStrainRate.name()); file.read(mDamage, pathName + "/" + mDamage.name()); file.read(mFragmentIDs, pathName + "/" + mFragmentIDs.name()); file.read(mParticleTypes, pathName + "/" + mParticleTypes.name()); } }
yehzu/vespa
eval/src/vespa/eval/tensor/sparse/sparse_tensor_address_combiner.cpp
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "sparse_tensor_address_combiner.h" #include "sparse_tensor_address_decoder.h" #include <vespa/eval/eval/value_type.h> namespace vespalib::tensor::sparse { TensorAddressCombiner::TensorAddressCombiner(const eval::ValueType &lhs, const eval::ValueType &rhs) { auto rhsItr = rhs.dimensions().cbegin(); auto rhsItrEnd = rhs.dimensions().cend(); for (auto &lhsDim : lhs.dimensions()) { while (rhsItr != rhsItrEnd && rhsItr->name < lhsDim.name) { _ops.push_back(AddressOp::RHS); ++rhsItr; } if (rhsItr != rhsItrEnd && rhsItr->name == lhsDim.name) { _ops.push_back(AddressOp::BOTH); ++rhsItr; } else { _ops.push_back(AddressOp::LHS); } } while (rhsItr != rhsItrEnd) { _ops.push_back(AddressOp::RHS); ++rhsItr; } } TensorAddressCombiner::~TensorAddressCombiner() = default; size_t TensorAddressCombiner::numOverlappingDimensions() const { size_t count = 0; for (AddressOp op : _ops) { if (op == AddressOp::BOTH) { count++; } } return count; } bool TensorAddressCombiner::combine(SparseTensorAddressRef lhsRef, SparseTensorAddressRef rhsRef) { clear(); ensure_room(lhsRef.size() + rhsRef.size()); SparseTensorAddressDecoder lhs(lhsRef); SparseTensorAddressDecoder rhs(rhsRef); for (auto op : _ops) { switch (op) { case AddressOp::LHS: append(lhs.decodeLabel()); break; case AddressOp::RHS: append(rhs.decodeLabel()); break; case AddressOp::BOTH: auto lhsLabel(lhs.decodeLabel()); auto rhsLabel(rhs.decodeLabel()); if (lhsLabel != rhsLabel) { return false; } append(lhsLabel); } } return true; } }
kakuilan/es6-example
t022.js
// es6 class类 // 定义类 class Point { constructor (x, y) { this.x = x this.y = y } toString () { return '(' + this.x + ', ' + this.y + ')' } } // 继承类,使用extends class ColorPoint extends Point { constructor (x, y, color) { super(x, y) // 等同于super.constructor(x,y) this.color = color } toString () { return this.color + ' ' + super.toString() } } // 基类 var point = new Point(2, 3) console.log(point.toString()) // 子类 var child = new ColorPoint(4, 5, 'red') console.log(child.toString())
t3zeng/mynewt-nimble
nimble/host/util/include/host/util/util.h
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #ifndef H_HOST_UTIL_ #define H_HOST_UTIL_ #ifdef __cplusplus extern "C" { #endif /** * Tries to configure the device with at least one Bluetooth address. * Addresses are restored in a hardware-specific fashion. * * @param prefer_random Whether to attempt to restore a random address * before checking if a public address has * already been configured. * * @return 0 on success; * BLE_HS_ENOADDR if the device does not have any * available addresses. * Other BLE host core code on error. */ int ble_hs_util_ensure_addr(int prefer_random); #ifdef __cplusplus } #endif #endif
SpiNNakerManchester/nengo_spinnaker
regression-tests/test_node_input.py
import logging logging.basicConfig(level=logging.DEBUG) import nengo import nengo_spinnaker import numpy as np def test_node_input_received_from_board(): """Test that Nodes do receive data from a running simulation. """ # Node just maintains a list of received values class NodeCallable(object): def __init__(self): self.received_values = [] def __call__(self, t, x): self.received_values.append(x) nc = NodeCallable() with nengo.Network("Test Network") as network: # Ensemble representing a constant 0.5 a = nengo.Node(0.5) b = nengo.Ensemble(100, 1) nengo.Connection(a, b) # Feeds into the target Node with some transforms. The transforms # could be combined in a single connection but we use two here to check # that this works! node = nengo.Node(nc, size_in=2, size_out=0) nengo.Connection(b, node[0], transform=0.5, synapse=0.05) nengo.Connection(b, node[1], transform=-1.0, synapse=0.05) # Create the simulate and simulate sim = nengo_spinnaker.Simulator(network) # Run the simulation for long enough to ensure that the decoded value is # with +/-20% of the input value. with sim: sim.run(2.0) # All we can really check is that the received values aren't all zero, that # the last few are within the expected range. vals = np.array(nc.received_values) offset = int(0.05 * 3 / sim.dt) print(vals[offset:]) assert np.any(vals != np.zeros(vals.shape)) assert (np.all(+0.20 <= vals[offset:, 0]) and np.all(+0.30 >= vals[offset:, 0]) and np.all(-0.40 >= vals[offset:, 1]) and np.all(-0.60 <= vals[offset:, 1])) if __name__ == "__main__": test_node_input_received_from_board()
AlexeyKashintsev/PlatypusJS
designer/PlatypusQueries/src/com/eas/designer/application/query/editing/DeleteParameterRiddleTask.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.eas.designer.application.query.editing; import com.eas.client.metadata.Parameter; import com.eas.designer.application.query.editing.riddle.RiddleTask; import java.util.HashSet; import java.util.Set; import net.sf.jsqlparser.expression.NamedParameter; /** * * @author mg */ public class DeleteParameterRiddleTask implements RiddleTask { protected Parameter param; protected Set<Object> deleted = new HashSet<>(); public DeleteParameterRiddleTask(Parameter aParam) { super(); param = aParam; } @Override public boolean needToDelete(Object aExpression) { if (aExpression instanceof NamedParameter) { NamedParameter nParam = (NamedParameter) aExpression; return nParam.getName().equalsIgnoreCase(param.getName()); } return false; } @Override public void markAsDeleted(Object aExpression) { deleted.add(aExpression); } @Override public boolean markedAsDeleted(Object aExpression) { return deleted.contains(aExpression); } @Override public void observe(Object aExpression) { } }
LaudateCorpus1/oracle-timesten-samples
quickstart/classic/sample_code/j2ee_orm/src/com/timesten/tptbmas/JPAClient.java
/* * Copyright (c) 1999, 2017, Oracle and/or its affiliates. All rights reserved. * * Licensed under the Universal Permissive License v 1.0 as shown * at http://oss.oracle.com/licenses/upl */ package com.timesten.tptbmas; import java.util.Iterator; import java.io.PrintWriter; import javax.persistence.*; /* Implements an EJB 3.0 client using the EntityManager persistence API. This is * a J2SE application configuration that does not involve a separate application * server process. */ public class JPAClient extends CommonClient { // interfaces for EJB 3.0 J2SE persistence private static EntityManagerFactory m_emf = null; private EntityManager m_emgr = null; // the name of the EntityManager configuration specified // in the persistence.xml file private static String m_emName = "TptbmHibernate"; // keep global track of the number of JPAClient threads that // are using the EntityManagerFactory private static int m_factoryUseCount = 0; public JPAClient (PrintWriter writer, int keyCount, int numXacts, int numThreads, int threadId, int percentReads, int percentInserts, boolean verbose) { super (writer, keyCount, numXacts, numThreads, threadId, percentReads, percentInserts, verbose); return; } public CommonClient createNewInstance (PrintWriter writer, int keyCount, int numXacts, int numThreads, int threadId, int percentReads, int percentInserts, boolean verbose) { return new JPAClient (writer, keyCount, numXacts, numThreads, threadId, percentReads, percentInserts, verbose); } // Runs the benchmark from the command line. public static void main (String[] args) { JPAClient client = null; // read and validate command line args if (!processArgs (args)) { System.exit (1); } System.out.println ("Beginning JPAClient..."); // instantiate a new client with threadId = 0 client = new JPAClient (new PrintWriter (System.out, true), m_keyCount, m_numXacts, m_numThreads, 0, m_percentReads, m_percentInserts, m_verbose); try { client.runMain (); } catch (Exception ex) { ex.printStackTrace (); } System.out.println ("End JPAClient."); } // validate and assign command line arguments public static boolean processArgs (String[] args) { // locals boolean status = true; int argCount = args.length; int index; // check for the entity manager name command line arg. for (index = 0; index < argCount; index ++) { if (args[index].equals ("-emName")) { // set the m_emName attribute if (index + 1 < argCount) { m_emName = args[index + 1]; index ++; status = true; } else { status = false; } } } // read the common client command line args if (status) { status = CommonClient.processArgs (args); } if (!status) { System.out.println ("Usage: com.timesten.tptbmas.JPAClient " + "[-emName entity_manager_name] " + "[-keyCount num_keys**2] " + "[-numXacts num_xacts_per_thread] " + "[-numThreads num_threads] " + "[-percentReads percent_reads] " + "[-percentInserts percent_inserts] " + "[-seed random_seed] " + "[-debug] " + "[-quiet] "); } return status; } public synchronized void open () throws Exception { // open a single EntityManagerFactory to be shared among all threads if (m_emf == null) { m_emf = Persistence.createEntityManagerFactory (m_emName); } m_factoryUseCount ++; // open an exclusive EntityManager for this thread m_emgr = m_emf.createEntityManager (); return; } public synchronized void close () throws Exception { // close this thread's EntityManager m_emgr.close (); m_emgr = null; // if there are no other threads using this EntityManagerFactory then // close it m_factoryUseCount --; if (m_factoryUseCount == 0) { m_emf.close (); m_emf = null; } } public void txnBegin () throws Exception { m_emgr.getTransaction ().begin (); } public void txnCommit () throws Exception { m_emgr.getTransaction ().commit (); m_emgr.clear (); } public void txnRollback () throws Exception { m_emgr.getTransaction ().rollback (); m_emgr.clear (); } public void read () throws Exception { TptbmPKey pkey = getRandomKey (); Tptbm tptbm; log ("Reading Tptbm " + pkey.toString () + "..."); tptbm = m_emgr.find (Tptbm.class, pkey); if (m_debug) { logVerbose (tptbm.toString ()); } } public void insert () throws Exception { // create and persist a new Tptbm instance Tptbm newTptbm = new Tptbm (); TptbmPKey pkey = new TptbmPKey (m_keyCount + m_threadId, m_insertOpCount); String last_calling_party = "" + pkey.getVpn_id () + "x" + pkey.getVpn_nb (); String directory_nb = "55" + pkey.getVpn_id () + "" + pkey.getVpn_nb (); String descr = "<place holder for description of VPN " + pkey.getVpn_id () + " extension " + pkey.getVpn_nb () + ">"; newTptbm.setKey (pkey); newTptbm.setDirectory_nb (directory_nb); newTptbm.setLast_calling_party (last_calling_party); newTptbm.setDescr (descr); log ("Inserting Tptbm " + pkey.toString () + "..."); m_emgr.persist (newTptbm); if (m_debug) { logVerbose (newTptbm.toString ()); } } public void update () throws Exception { Tptbm tptbm = null; TptbmPKey pkey = getRandomKey (); log ("Updating Tptbm " + pkey.toString () + "..."); // lookup the record tptbm = m_emgr.find (Tptbm.class, pkey); // update the record tptbm.setLast_calling_party (pkey.getVpn_id () + "x" + pkey.getVpn_nb ()); if (m_debug) { logVerbose (tptbm.toString ()); } } public void populate () throws Exception { TptbmPKey pkey; String directory_nb; String last_calling_party = "0000000000"; String descr; int cacheCount = 0; long startTime, endTime; logVerbose ("Populating TPTBM table ..."); startTime = System.currentTimeMillis (); // VPN_ID & VPN_NB are 1-based indexes for (int id = 1; id <= m_keyCount; id ++) { for (int nb = 1; nb <= m_keyCount; nb ++) { pkey = new TptbmPKey (id, nb); directory_nb = "55" + id + "" + nb; descr = "<place holder for description of VPN " + id + " extension " + nb + ">"; // create and persist the instance Tptbm newTptbm = new Tptbm (); newTptbm.setKey (pkey); newTptbm.setDirectory_nb (directory_nb); newTptbm.setLast_calling_party (last_calling_party); newTptbm.setDescr (descr); m_emgr.persist (newTptbm); cacheCount ++; if (m_debug) { logVerbose (newTptbm.toString ()); } if (cacheCount % m_maxEntitiesInCache == 0) { m_emgr.flush (); } } } endTime = System.currentTimeMillis (); logVerbose ("TPTBM table populated with " + (m_keyCount * m_keyCount) + " rows in " + ((double)(endTime - startTime) / (double)1000) + " seconds."); return; } public void deleteAll () throws Exception { int cacheCount = 0; long startTime, endTime; Iterator tptbms; Tptbm tptbm; logVerbose ("Deleting all rows from TPTBM table..."); startTime = System.currentTimeMillis (); tptbms = m_emgr.createNamedQuery ("findAllTptbms"). getResultList ().iterator (); while (tptbms.hasNext ()) { tptbm = (Tptbm) tptbms.next (); if (m_debug) { logVerbose (tptbm.toString ()); } if (!m_emgr.contains (tptbm)) { tptbm = m_emgr.merge (tptbm); } m_emgr.remove (tptbm); cacheCount ++; if (cacheCount % m_maxEntitiesInCache == 0) { m_emgr.flush(); } } endTime = System.currentTimeMillis (); logVerbose (cacheCount + " rows in TPTBM table deleted in " + ((double)(endTime - startTime) / (double)1000) + " seconds."); return; } }
MOIPA/RetailManager
Backend/src/main/java/com/dql/retailmanager/dao/mapper/AccountDao.java
<gh_stars>1-10 package com.dql.retailmanager.dao.mapper; import com.dql.retailmanager.entity.Account; import com.dql.retailmanager.entity.form.SearchForm; import org.apache.ibatis.annotations.Select; import java.util.List; /** * @Entity com.dql.retailmanager.entity.Account */ public interface AccountDao { /** * @mbg.generated 2021-04-27 15:11:36 */ int deleteByPrimaryKey(Integer id); /** * @mbg.generated 2021-04-27 15:11:36 */ int insert(Account record); /** * @mbg.generated 2021-04-27 15:11:36 */ int insertSelective(Account record); /** * @mbg.generated 2021-04-27 15:11:36 */ Account selectByPrimaryKey(Integer id); /** * @mbg.generated 2021-04-27 15:11:36 */ int updateByPrimaryKeySelective(Account record); /** * @mbg.generated 2021-04-27 15:11:36 */ int updateByPrimaryKey(Account record); @Select("select id,bank_name bankName,code ,initial_money initialMoney,current_money currentMoney,remark,active from account where bank_name like concat('%',#{bankname},'%') ") List<Account> selectPage(SearchForm pageRequest); @Select("update account set active=1 where id = #{id}") int activeAccount(int id); @Select("select * from account where active=1") List<Account> getActivedAccount(); }
geoff5802/liftie
lib/client/resort/lifts.js
<filename>lib/client/resort/lifts.js<gh_stars>10-100 var dom = require('./dom'); module.exports = render; module.exports.section = 0; var states = ['open', 'hold', 'scheduled', 'closed']; function renderStatus(node, status) { dom.removeAllChildren(node); if (status) { node.innerHTML = Object.keys(status).map(function(name) { var klass = "status ls-" + status[name]; return '<li class="lift">' + '<span class="name">' + name + '</span>' + '<span class="' + klass + '">' + '</span></li>'; }).join(''); } } function renderStats(node, stats) { states.forEach(function(s) { node.querySelector('.ls-' + s).innerHTML = stats ? stats[s] : 0; }); } function renderColorBar(node, percentage) { states.forEach(function(state) { var width = 'width:' + (percentage ? percentage[state] : 25) + '%;'; node.querySelector('.' + state).setAttribute('style', width); }); } function render(node, lifts) { renderStatus(node.querySelector('.lifts'), lifts.status); renderStats(node.querySelector('.summary'), lifts.stats); renderColorBar(node.querySelector('.summary-color-bar'), lifts.stats.percentage); }
scaug10/NETESP
src/main/java/com/g10/ssm/po/UserPerssionVo.java
package com.g10.ssm.po; import java.util.List; public class UserPerssionVo { private List<UserPerssionKey> list; public List<UserPerssionKey> getList() { return list; } public void setList(List<UserPerssionKey> list) { this.list = list; } }
mheidt/graphql-maven-plugin-project
graphql-java-runtime/src/test/java/com/graphql_java_generator/client/domain/starwars/CustomJacksonDeserializers.java
/** Generated by the default template from graphql-java-generator */ package com.graphql_java_generator.client.domain.starwars; import java.io.IOException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.graphql_java_generator.customscalars.CustomScalarRegistryImpl; import com.graphql_java_generator.client.response.AbstractCustomJacksonDeserializer; import com.graphql_java_generator.customscalars.GraphQLScalarTypeDate; import com.graphql_java_generator.exception.GraphQLRequestExecutionException; import graphql.schema.GraphQLScalarType; import java.util.List; /** * This class is a standard Deserializer for Jackson. It uses the {@link GraphQLScalarType} that is implemented by the project for this scalar */ public class CustomJacksonDeserializers { public static class List__Field extends AbstractCustomJacksonDeserializer<List<com.graphql_java_generator.client.domain.starwars.__Field>> { private static final long serialVersionUID = 1L; public List__Field() { super( null, true, com.graphql_java_generator.client.domain.starwars.__Field.class, null ); } } public static class List__Directive extends AbstractCustomJacksonDeserializer<List<com.graphql_java_generator.client.domain.starwars.__Directive>> { private static final long serialVersionUID = 1L; public List__Directive() { super( null, true, com.graphql_java_generator.client.domain.starwars.__Directive.class, null ); } } public static class List__DirectiveLocation extends AbstractCustomJacksonDeserializer<List<com.graphql_java_generator.client.domain.starwars.__DirectiveLocation>> { private static final long serialVersionUID = 1L; public List__DirectiveLocation() { super( null, true, com.graphql_java_generator.client.domain.starwars.__DirectiveLocation.class, null ); } } public static class List__InputValue extends AbstractCustomJacksonDeserializer<List<com.graphql_java_generator.client.domain.starwars.__InputValue>> { private static final long serialVersionUID = 1L; public List__InputValue() { super( null, true, com.graphql_java_generator.client.domain.starwars.__InputValue.class, null ); } } public static class ListEpisode extends AbstractCustomJacksonDeserializer<List<com.graphql_java_generator.client.domain.starwars.Episode>> { private static final long serialVersionUID = 1L; public ListEpisode() { super( null, true, com.graphql_java_generator.client.domain.starwars.Episode.class, null ); } } public static class ListCharacter extends AbstractCustomJacksonDeserializer<List<com.graphql_java_generator.client.domain.starwars.Character>> { private static final long serialVersionUID = 1L; public ListCharacter() { super( null, true, com.graphql_java_generator.client.domain.starwars.Character.class, null ); } } public static class List__Type extends AbstractCustomJacksonDeserializer<List<com.graphql_java_generator.client.domain.starwars.__Type>> { private static final long serialVersionUID = 1L; public List__Type() { super( null, true, com.graphql_java_generator.client.domain.starwars.__Type.class, null ); } } public static class List__EnumValue extends AbstractCustomJacksonDeserializer<List<com.graphql_java_generator.client.domain.starwars.__EnumValue>> { private static final long serialVersionUID = 1L; public List__EnumValue() { super( null, true, com.graphql_java_generator.client.domain.starwars.__EnumValue.class, null ); } } }
DHBin/minion
minion-auth/minion-auth-biz/src/main/java/cn/dhbin/minion/auth/service/impl/TokenServiceImpl.java
package cn.dhbin.minion.auth.service.impl; import cn.dhbin.minion.auth.api.TokenService; import cn.dhbin.minion.upms.Version; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.dubbo.config.annotation.Service; import org.springframework.security.oauth2.common.OAuth2AccessToken; import org.springframework.security.oauth2.provider.token.TokenStore; import java.util.Collection; /** * @author donghaibin * @date 2020/3/12 */ @Service(version = Version.V_1_0_0) @Slf4j @RequiredArgsConstructor public class TokenServiceImpl implements TokenService { private final TokenStore tokenStore; @Override public Boolean removeToken(String clientId, String username) { try { Collection<OAuth2AccessToken> accessTokens = tokenStore.findTokensByClientIdAndUserName(clientId, username); for (OAuth2AccessToken accessToken : accessTokens) { tokenStore.removeAccessToken(accessToken); tokenStore.removeRefreshToken(accessToken.getRefreshToken()); } } catch (Exception e) { log.error("removeToken error", e); return false; } return true; } }
zxnso/min_project_vue
node_modules/vant/lib/utils/vnodes.js
<filename>node_modules/vant/lib/utils/vnodes.js "use strict"; exports.__esModule = true; exports.sortChildren = sortChildren; function flattenVNodes(vnodes) { var result = []; function traverse(vnodes) { vnodes.forEach(function (vnode) { result.push(vnode); if (vnode.componentInstance) { traverse(vnode.componentInstance.$children.map(function (item) { return item.$vnode; })); } if (vnode.children) { traverse(vnode.children); } }); } traverse(vnodes); return result; } // sort children instances by vnodes order function sortChildren(children, parent) { var componentOptions = parent.$vnode.componentOptions; if (!componentOptions || !componentOptions.children) { return; } var vnodes = flattenVNodes(componentOptions.children); children.sort(function (a, b) { return vnodes.indexOf(a.$vnode) - vnodes.indexOf(b.$vnode); }); }
lca1/medco-connector
connector/client/querytools/cohorts_patient_list.go
package querytoolsclient import ( "crypto/tls" "errors" "fmt" "net/http" "net/url" "time" medcomodels "github.com/ldsec/medco/connector/models" "github.com/ldsec/medco/connector/wrappers/unlynx" httptransport "github.com/go-openapi/runtime/client" medcoclient "github.com/ldsec/medco/connector/client" "github.com/ldsec/medco/connector/restapi/client" "github.com/ldsec/medco/connector/restapi/client/medco_node" utilclient "github.com/ldsec/medco/connector/util/client" "github.com/sirupsen/logrus" ) // CohortsPatientList is a MedCo client query to get saved cohorts type CohortsPatientList struct { // httpMedCoClients are the HTTP clients for the MedCo connectors httpMedCoClients []*client.MedcoCli // authToken is the OIDC authentication JWT authToken string id string cohortName string userPublicKey string userPrivateKey string } // NewCohortsPatientList returns a new cohorts patient list func NewCohortsPatientList(token, cohortName string, disableTLSCheck bool) (cohortsPatientList *CohortsPatientList, err error) { cohortsPatientList = &CohortsPatientList{ authToken: token, cohortName: cohortName, id: "MedCo_Cohrts_Patient_List" + time.Now().Format(time.RFC3339), } getMetadataResp, err := medcoclient.MetaData(token, disableTLSCheck) if err != nil { logrus.Error(err) return } cohortsPatientList.httpMedCoClients = make([]*client.MedcoCli, len(getMetadataResp.Payload.Nodes)) for _, node := range getMetadataResp.Payload.Nodes { if cohortsPatientList.httpMedCoClients[*node.Index] != nil { err = errors.New("duplicated node index in network metadata") logrus.Error(err) return } nodeURL, err := url.Parse(node.URL) if err != nil { logrus.Error("cannot parse MedCo connector URL: ", err) return nil, err } nodeTransport := httptransport.New(nodeURL.Host, nodeURL.Path, []string{nodeURL.Scheme}) nodeTransport.Transport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: disableTLSCheck} cohortsPatientList.httpMedCoClients[*node.Index] = client.New(nodeTransport, nil) } cohortsPatientList.userPublicKey, cohortsPatientList.userPrivateKey, err = unlynx.GenerateKeyPair() if err != nil { logrus.Errorf("while generating key pair: %s", err.Error()) return } return } type patientListNodeResult = struct { patientList *medco_node.PostCohortsPatientListOKBody nodeIndex int } // Execute executes the patient list retrieval and decryption func (pl *CohortsPatientList) Execute() (patientLists [][]int64, nodeTimers []medcomodels.Timers, localTimers medcomodels.Timers, err error) { nOfNodes := len(pl.httpMedCoClients) errChan := make(chan error) nodeTimers = make([]medcomodels.Timers, nOfNodes) resultChan := make(chan patientListNodeResult, nOfNodes) cipherPatientLists := make([][]string, nOfNodes) patientLists = make([][]int64, nOfNodes) logrus.Infof("There are %d nodes", nOfNodes) for i := 0; i < nOfNodes; i++ { go func(idx int) { resultBody, err := pl.submitToNode(idx) if err != nil { errChan <- err return } resultChan <- patientListNodeResult{resultBody, idx} return }(i) } timeout := time.After(time.Duration(utilclient.QueryToolsTimeoutSeconds) * time.Second) for i := 0; i < nOfNodes; i++ { select { case err = <-errChan: return case <-timeout: err = fmt.Errorf("Timeout %d seconds elapsed", utilclient.QueryToolsTimeoutSeconds) logrus.Error(err) return case nodeRes := <-resultChan: logrus.Infof("Operation successfully returns in node %d.", nodeRes.nodeIndex) cipherPatientLists[nodeRes.nodeIndex] = nodeRes.patientList.Results nodeTimers[nodeRes.nodeIndex] = medcomodels.NewTimersFromAPIModel(nodeRes.patientList.Timers) } } //Decryption logrus.Info("All lists receiveds. Decrypting") localTimers = medcomodels.NewTimers() timer := time.Now() for i, list := range cipherPatientLists { patientLists[i] = make([]int64, len(list)) for j, encNum := range list { patientLists[i][j], err = unlynx.Decrypt(encNum, pl.userPrivateKey) if err != nil { err = fmt.Errorf("during local decryption: %s", err.Error()) logrus.Error(err) return } } } localTimers.AddTimers("local-decryption-of-patient-lists", timer, nil) return } func (pl *CohortsPatientList) submitToNode(nodeIdx int) (*medco_node.PostCohortsPatientListOKBody, error) { params := medco_node.NewPostCohortsPatientListParamsWithTimeout(time.Duration(utilclient.QueryTimeoutSeconds) * time.Second) body := medco_node.PostCohortsPatientListBody{ CohortName: &pl.cohortName, ID: pl.id, UserPublicKey: &pl.userPublicKey, } params.SetCohortsPatientListRequest(body) response, err := pl.httpMedCoClients[nodeIdx].MedcoNode.PostCohortsPatientList(params, httptransport.BearerToken(pl.authToken)) if err != nil { return nil, err } return response.GetPayload(), nil }
jpkulasingham/Eelbrain
eelbrain/_utils/parse.py
# Author: <NAME> <<EMAIL>> import ast FLOAT_PATTERN = "^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$" POS_FLOAT_PATTERN = "^[+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$" INT_PATTERN = "^-?\d+$" # matches float as well as NaN: FLOAT_NAN_PATTERN = "^([Nn][Aa][Nn]$)|([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)$" def find_variables(expr): """Find the variables participating in an expressions Returns ------- variables : tuple of str Variables occurring in expr. """ try: st = ast.parse(expr) except SyntaxError as error: raise ValueError("Invalid expression: %r (%s)" % (expr, error)) return {n.id for n in ast.walk(st) if isinstance(n, ast.Name)}
huotuinc/Android_Fanmore_Treasure
raiders/src/main/java/com/huotu/fanmore/pinkcatraiders/adapter/SysMsgAdapter.java
<filename>raiders/src/main/java/com/huotu/fanmore/pinkcatraiders/adapter/SysMsgAdapter.java package com.huotu.fanmore.pinkcatraiders.adapter; import android.content.Context; import android.content.res.Resources; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.widget.BaseAdapter; import android.widget.TextView; import com.huotu.fanmore.pinkcatraiders.R; import com.huotu.fanmore.pinkcatraiders.model.MsgData; import com.huotu.fanmore.pinkcatraiders.uitls.DateUtils; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; /** * 系统消息适配 */ public class SysMsgAdapter extends BaseAdapter { List< MsgData > msgs; Context mContext; public SysMsgAdapter ( Context mContext, List< MsgData > msgs ) { this.mContext = mContext; this.msgs = msgs; } @Override public int getCount ( ) { return msgs.size ( ); } @Override public Object getItem ( int position ) { return msgs.get ( position ); } @Override public long getItemId ( int position ) { return position; } @Override public View getView ( int position, View convertView, ViewGroup parent ) { ViewHolder holder = null; Resources res = mContext.getResources(); if (convertView == null) { convertView = View.inflate(mContext, R.layout.sysmsg_item, null); holder = new ViewHolder(convertView); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } if(null!=msgs && msgs.size() > 0) { holder.msgTime.setText(DateUtils.transformDataformat6(msgs.get(position).getDate())); holder.msgCon.setText(msgs.get(position).getContext()); } return convertView; } class ViewHolder { public ViewHolder(View view) { ButterKnife.bind(this, view); } @Bind(R.id.msgTime) TextView msgTime; @Bind(R.id.msgCon) TextView msgCon; } }
PhilShishov/Software-University
JS Essentials/Homeworks/03.Arrays-and-Matrices_Exercise/Interview.js
function solve() { // console.log(1 + "2" + "2"); 122 // console.log(1 + +"2" + "2"); 32 // console.log(1 + -"1" + "2"); 02 // console.log(+"1" + "1" + "2"); 112 // console.log( "A" - "B" + "2"); NaN2 // console.log( "A" - "B" + 2); NaN //clone an object - array is reference type object, not value // let firstObj = { // name: "first", // age: 2222 // }; // let secondObj = {}; // // let secondObj = Object.assign(firstObj); // for (let kvp in firstObj){ // if (!secondObj.hasOwnProperty(kvp)) { // secondObj[kvp] = firstObj[kvp]; // } // } // console.log(firstObj); // console.log(secondObj); // console.log(1 < 2 < 3); // console.log(3 > 2 > 1); // a = 5; // console.log(a++ + ++a); } solve();
LightBit/libkripto
include/kripto/block/rijndael128.h
<reponame>LightBit/libkripto<gh_stars>1-10 #ifndef KRIPTO_BLOCK_RIJNDAEL128_H #define KRIPTO_BLOCK_RIJNDAEL128_H extern const kripto_block_desc *const kripto_block_rijndael128; #endif
BadBaman/ods
ods-main/src/main/java/cn/stylefeng/guns/onlineaccess/modular/mapper/ProjectMapper.java
package cn.stylefeng.guns.onlineaccess.modular.mapper; import cn.stylefeng.guns.onlineaccess.modular.entity.Project; import cn.stylefeng.guns.onlineaccess.modular.result.ProjectResult; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import java.util.List; @Mapper public interface ProjectMapper extends BaseMapper<Project> { /** * 获取项目分页列表 * * @param page 分页参数 * @param id 查询参数 * @return 查询分页结果 * @author xuyuxiang * @date 2020/4/7 21:14 */ List<Project> getProjectByProjectIdResult(Page page, long id); /** * 获取项目分页列表 * * @param page 分页参数 * @param name 查询参数 * @return 查询分页结果 * @author xuyuxiang * @date 2020/4/7 21:14 */ List<Project> getProjectByUserIdResult(Page page, Long id); List<Project> getProjectByUserIdAndStatusResult(Page page, Long id, int status); }
pyrello/assist
resources/assets/js/store/modules/clientOutcomes.js
<filename>resources/assets/js/store/modules/clientOutcomes.js import CrudModule from '../crud/CrudModule' export default { ...new CrudModule('client-outcomes') }
BuildJet/sat4envi
s4e-backend/src/main/java/pl/cyfronet/s4e/service/UserRoleService.java
/* * Copyright 2020 ACC Cyfronet AGH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package pl.cyfronet.s4e.service; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import lombok.val; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import pl.cyfronet.s4e.bean.AppRole; import pl.cyfronet.s4e.bean.AppUser; import pl.cyfronet.s4e.bean.Institution; import pl.cyfronet.s4e.bean.UserRole; import pl.cyfronet.s4e.controller.request.CreateUserRoleRequest; import pl.cyfronet.s4e.controller.request.DeleteUserRoleRequest; import pl.cyfronet.s4e.data.repository.AppUserRepository; import pl.cyfronet.s4e.data.repository.InstitutionRepository; import pl.cyfronet.s4e.data.repository.UserRoleRepository; import pl.cyfronet.s4e.ex.NotFoundException; @Service @RequiredArgsConstructor @Slf4j public class UserRoleService { private final UserRoleRepository userRoleRepository; private final AppUserRepository appUserRepository; private final InstitutionRepository institutionRepository; @Transactional(rollbackFor = NotFoundException.class) public void addRole(CreateUserRoleRequest request) throws NotFoundException { Institution institution = institutionRepository.findBySlug(request.getInstitutionSlug(), Institution.class) .orElseThrow(() -> new NotFoundException( "Institution not found for id " + request.getInstitutionSlug() + "'" )); AppUser appUser = appUserRepository.findByEmail(request.getEmail()) .orElseThrow(() -> new NotFoundException("User not found for mail: '" + request.getEmail() + "'")); addRole(institution, appUser, request.getRole()); } @Transactional(rollbackFor = NotFoundException.class) public void addRole(String institutionSlug, Long appUserId, AppRole role) throws NotFoundException { val appUser = appUserRepository.findById(appUserId) .orElseThrow(() -> new NotFoundException("User not found for id: '" + appUserId + "'")); val institution = institutionRepository.findBySlug(institutionSlug, Institution.class) .orElseThrow(() -> new NotFoundException("Institution not found for slug " + institutionSlug + "'")); addRole(institution, appUser, role); } private void addRole(Institution institution, AppUser appUser, AppRole role) { { val optionalUserRole = userRoleRepository.findByUser_IdAndInstitution_IdAndRole(appUser.getId(), institution.getId(), role); if (optionalUserRole.isPresent()) { return; } UserRole userRole = UserRole.builder() .institution(institution) .user(appUser) .role(role) .build(); institution.addMemberRole(userRole); appUser.addRole(userRole); } // If role is admin, then try to add an ordinary membership and propagate the admin down the hierarchy. if (role == AppRole.INST_ADMIN) { addRole(institution, appUser, AppRole.INST_MEMBER); for (val childInstitution : institutionRepository.findAllByParentId(institution.getId())) { addRole(childInstitution, appUser, AppRole.INST_ADMIN); } } } @Transactional(rollbackFor = NotFoundException.class) public void removeRole(DeleteUserRoleRequest request) throws NotFoundException { Institution institution = institutionRepository.findBySlug(request.getInstitutionSlug()) .orElseThrow(() -> new NotFoundException( "Institution not found for id " + request.getInstitutionSlug() + "'" )); AppUser appUser = appUserRepository.findByEmail(request.getEmail()) .orElseThrow(() -> new NotFoundException("User not found for mail: '" + request.getEmail() + "'")); removeRole(institution.getId(), appUser.getId(), request.getRole()); } @Transactional(rollbackFor = NotFoundException.class) public void removeRole( String institutionSlug, Long appUserId, AppRole role ) throws NotFoundException { val appUser = appUserRepository.findById(appUserId) .orElseThrow(() -> new NotFoundException("User not found for id: '" + appUserId + "'")); val institution = institutionRepository.findBySlug(institutionSlug, Institution.class) .orElseThrow(() -> new NotFoundException("Institution not found for slug " + institutionSlug + "'")); removeRole(institution.getId(), appUser.getId(), role); } private void removeRole(Long institutionId, Long appUserId, AppRole role) { { val optionalUserRole = userRoleRepository.findByUser_IdAndInstitution_IdAndRole(appUserId, institutionId, role); if (optionalUserRole.isEmpty()) { return; } UserRole userRole = optionalUserRole.get(); userRole.getInstitution().removeMemberRole(userRole); userRole.getUser().removeRole(userRole); } // Try removing admin role as well, if exists. if (role == AppRole.INST_MEMBER) { removeRole(institutionId, appUserId, AppRole.INST_ADMIN); // If removing an admin role then propagate this deletion down the institution hierarchy. } else if (role == AppRole.INST_ADMIN) { for (val childInstitution : institutionRepository.findAllByParentId(institutionId)) { removeRole(childInstitution.getId(), appUserId, AppRole.INST_ADMIN); } } } }
cojennin/facet
project/editorial/migrations/0074_auto_20171216_2326.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('editorial', '0073_accountsubscription_organization'), ] operations = [ migrations.CreateModel( name='ContractorSubscription', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('standard', models.BooleanField(default=True, help_text=b'If an organization is using the account for base features of editorial workflow, project management and collaboration.')), ('user', models.ForeignKey(help_text=b'User associated with this subscription.', to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='OrganizationSubscription', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('collaborations', models.BooleanField(default=True, help_text=b'If an organization is using the account for base features of editorial workflow, project management and collaboration.')), ('contractors', models.BooleanField(default=False, help_text=b'If an organization is using the account to manage contractors.')), ('organization', models.ForeignKey(help_text=b'Organization associated with this subscription if Org subscription type.', to='editorial.Organization')), ], ), migrations.RemoveField( model_name='accountsubscription', name='organization', ), migrations.RemoveField( model_name='accountsubscription', name='user', ), migrations.DeleteModel( name='AccountSubscription', ), ]
mfaithfull/QOR
Include/ArchQOR/Zarch/HLAssembler/ZHLAssembler.h
<reponame>mfaithfull/QOR<filename>Include/ArchQOR/Zarch/HLAssembler/ZHLAssembler.h<gh_stars>1-10 //CZHLAssembler.h // Copyright Querysoft Limited 2015 // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. //Z specific High Level Assembler #ifndef ARCHQOR_Z_HLASSEMBLER_H_1 #define ARCHQOR_Z_HLASSEMBLER_H_1 #include "CompilerQOR.h" #include "ArchQOR/Common/HLAssembler/HighLevelAssemblerBase.h" #include "ArchQOR/Zarch/HLAssembler/Emittables/Z_ETarget.h" #include "ArchQOR/Zarch/HLAssembler/Emittables/Z_EJmp.h" #include "ArchQOR/Zarch/HLAssembler/Emittables/Z_EFunction.h" #include "ArchQOR/Zarch/HLAssembler/Emittables/Z_ECall.h" #include "CodeQOR/DataStructures/PODVector.h" //------------------------------------------------------------------------------ namespace nsArch { //------------------------------------------------------------------------------ namespace nsZ { class __QOR_INTERFACE( __ARCHQOR ) StateData; //------------------------------------------------------------------------------ class __QOR_INTERFACE( __ARCHQOR ) CZHLAssembler : public nsArch::CHighLevelAssemblerBase { public: __QOR_DECLARE_OCLASS_ID(CZHLAssembler); CZHLAssembler( nsArch::CCodeGeneratorBase* codeGenerator ) __QCMP_THROW; // Create new (empty) instance of HLA virtual ~CZHLAssembler() __QCMP_THROW; // Destroy HLA instance. virtual void setLogger( CLogger* logger ) __QCMP_THROW; // Set logger to logger. //------------------------------------------------------------------------------ inline Cmp_unsigned__int32 getError() const __QCMP_THROW { return m_uiError; } virtual void setError( Cmp_unsigned__int32 error ) __QCMP_THROW; // Set error code. This method is virtual, because higher classes can use it to catch all errors. Cmp_unsigned__int32 getProperty( Cmp_unsigned__int32 propertyId ); // Get HLA property. void setProperty( Cmp_unsigned__int32 propertyId, Cmp_unsigned__int32 value ); // Set HLA property. void clear() __QCMP_THROW; // Clear everything, but not deallocate buffers. Note This method will destroy your code. void free() __QCMP_THROW; // Free internal buffer, all emitters and 0 all pointers. Note This method will destroy your code. // Emit a single comment line that will be logged. // Emitting comments are useful to log something. Because assembler can be // generated from AST or other data structures, you may sometimes need to // log data characteristics or statistics. // Note Emitting comment is not directly sent to logger, but instead it's // stored in HLA and emitted when serialize() method is // called. Each comment keeps correct order. void comment( const char* fmt, ... ) __QCMP_THROW; // -------------------------------------------------------------------------- // Create a new function. // // method. Recommended is to save the pointer. // inline CEFunction* newFunction( Cmp_unsigned__int32 cconv, const CFunctionDefinition& def ) __QCMP_THROW { return newFunction_( cconv, def.getArguments(), def.getArgumentsCount(), def.getReturnValue() ); } //-------------------------------------------------------------------------- // Create a new function (low level version). // // cconv Function calling convention (see CALL_CONV). // args Function arguments (see VARIABLE_TYPE). // count Arguments count. // // This method is internally called from newFunction() method and // contains arguments thats used internally by HLA // // Note To get current function use currentFunction() method. CEFunction* newFunction_( Cmp_unsigned__int32 cconv, const Cmp_unsigned__int32* arguments, Cmp_unsigned__int32 argumentsCount, Cmp_unsigned__int32 returnValue ) __QCMP_THROW; //-------------------------------------------------------------------------- // Get current function. // This method can be called within newFunction() and endFunction() // block to get current function you are working with. It's recommended // to store Function pointer returned by newFunction<> method, // because this allows you in future implement function sections outside of // function itself (yeah, this is possible!). inline CEFunction* getFunction() const __QCMP_THROW { return m_pFunction; } // End of current function scope and all variables. CEFunction* endFunction() __QCMP_THROW; inline CEInstruction* newInstruction( Cmp_unsigned__int32 code, COperand** operandsData, Cmp_unsigned__int32 operandsCount ) __QCMP_THROW; void _emitInstruction( Cmp_unsigned__int32 code ) __QCMP_THROW; // Emit instruction with no operand. void _emitInstruction( Cmp_unsigned__int32 code, const COperand* o0 ) __QCMP_THROW; // Emit instruction with one operand. void _emitInstruction( Cmp_unsigned__int32 code, const COperand* o0, const COperand* o1 ) __QCMP_THROW; // Emit instruction with two operands. void _emitInstruction( Cmp_unsigned__int32 code, const COperand* o0, const COperand* o1, const COperand* o2 ) __QCMP_THROW; // Emit instruction with three operands. void _emitInstruction( Cmp_unsigned__int32 code, const COperand* o0, const COperand* o1, const COperand* o2, const COperand* o3 ) __QCMP_THROW; // Emit instruction with four operands (Special instructions). void _emitInstruction( Cmp_unsigned__int32 code, const COperand* o0, const COperand* o1, const COperand* o2, const COperand* o3, const COperand* o4 ) __QCMP_THROW; // Emit instruction with five operands (Special instructions). void _emitJcc( Cmp_unsigned__int32 code, const CLabel* label, Cmp_unsigned__int32 hint ) __QCMP_THROW; // method for emitting jcc. CECall* _emitCall( const COperand* o0 ) __QCMP_THROW; // method for emitting function call. void _emitReturn( const COperand* first, const COperand* second ) __QCMP_THROW; // method for returning a value from the function. void embed( const void* data, Cmp_uint_ptr len ) __QCMP_THROW; // Embed data into instruction stream. // Align target buffer to m bytes. // Typical usage of this is to align labels at start of the inner loops. // Inserts nop() instructions or CPU optimized NOPs. //void align( Cmp_unsigned__int32 m ) __QCMP_THROW; CLabel newLabel() __QCMP_THROW; // Create and return new label. void bind( const CLabel& label ) __QCMP_THROW; // Bind label to the current offset. Note Label can be bound only once! VarData* _newVarData( const char* name, Cmp_unsigned__int32 type, Cmp_unsigned__int32 size ) __QCMP_THROW; // Create a new variable data. //-------------------------------------------------------------------------- // Get variable data. inline VarData* _getVarData( Cmp_unsigned__int32 id ) const __QCMP_THROW { //assert(id != INVALID_VALUE); return m_VarData[ id & OPERAND_ID_VALUE_MASK ]; } //CGPVar newGP( Cmp_unsigned__int32 variableType = VARIABLE_TYPE_GPN, const char* name = 0 ) __QCMP_THROW; // Create a new general-purpose variable. //CGPVar argGP( Cmp_unsigned__int32 index ) __QCMP_THROW; // Get argument as general-purpose variable. //CMMVar newMM( Cmp_unsigned__int32 variableType = VARIABLE_TYPE_MM, const char* name = 0 ) __QCMP_THROW; // Create a new MM variable. //CMMVar argMM( Cmp_unsigned__int32 index ) __QCMP_THROW; // Get argument as MM variable. //CXMMVar newXMM( Cmp_unsigned__int32 variableType = VARIABLE_TYPE_XMM, const char* name = 0 ) __QCMP_THROW; // Create a new XMM variable. //CXMMVar argXMM( Cmp_unsigned__int32 index ) __QCMP_THROW; // Get argument as XMM variable. //void _vhint( CBaseVar& var, Cmp_unsigned__int32 hintId, Cmp_unsigned__int32 hintValue) __QCMP_THROW; // Serialize variable hint. //void alloc( CBaseVar& var ) __QCMP_THROW; // Alloc variable var. //void alloc( CBaseVar& var, Cmp_unsigned__int32 regIndex ) __QCMP_THROW; // Alloc variable var using regIndex as a register index. //void alloc( CBaseVar& var, const CBaseReg& reg ) __QCMP_THROW; // Alloc variable var using reg as a demanded register. //void spill( CBaseVar& var ) __QCMP_THROW; // Spill variable var. //void save( CBaseVar& var ) __QCMP_THROW; // Save variable var if modified. //void unuse( CBaseVar& var ) __QCMP_THROW; // Unuse variable var. //void getMemoryHome( CBaseVar& var, CGPVar* home, int* displacement = 0 ); // Get memory home of variable var. // Set memory home of variable var. // Default memory home location is on stack (ESP/RSP), but when needed the // bebahior can be changed by this method. // It is an error to chaining memory home locations. For example the given // code is invalid: // // Compiler c; // // ... // GPVar v0 = c.newGP(); // GPVar v1 = c.newGP(); // GPVar v2 = c.newGP(); // GPVar v3 = c.newGP(); // // c.setMemoryHome(v1, v0, 0); // Allowed, [v0] is memory home for v1. // c.setMemoryHome(v2, v0, 4); // Allowed, [v0+4] is memory home for v2. // c.setMemoryHome(v3, v2); // CHAINING, NOT ALLOWED! //void setMemoryHome( CBaseVar& var, const CGPVar& home, int displacement = 0 ); //Cmp_unsigned__int32 getPriority( CBaseVar& var ) const __QCMP_THROW; // Get priority of variable var. //void setPriority( CBaseVar& var, Cmp_unsigned__int32 priority ) __QCMP_THROW; // Set priority of variable var to priority. //bool getSaveOnUnuse( CBaseVar& var ) const __QCMP_THROW; // Get save-on-unuse var property. //void setSaveOnUnuse( CBaseVar& var, bool value ) __QCMP_THROW; // Set save-on-unuse var property to value. //void rename( CBaseVar& var, const char* name ) __QCMP_THROW; // Rename variable var to name. Note Only new name will appear in the logger. StateData* _newStateData( Cmp_unsigned__int32 memVarsCount ) __QCMP_THROW; // Create a new StateData instance. // Make is convenience method to make currently serialized code and // return pointer to generated function. // // What you need is only to cast this pointer to your function type and call // it. Note that if there was an error and calling getError() method doesn't // return ERROR_NONE (zero) then this function always return 0 and // error value remains the same. virtual void* make() __QCMP_THROW; // Method that will emit everything to Assembler instance a. virtual void serialize() __QCMP_THROW; //-------------------------------------------------------------------------- // Get target (emittable) from operand id (label id). inline CETarget* _getTarget( Cmp_unsigned__int32 id ) { //assert((id & OPERAND_ID_TYPE_MASK) == OPERAND_ID_TYPE_LABEL); return m_TargetData[ id & OPERAND_ID_VALUE_MASK ]; } //-------------------------------------------------------------------------- inline nsCodeQOR::PodVector< VarData* >& getVarData( void ) { return m_VarData; } //-------------------------------------------------------------------------- inline Cmp_unsigned__int32 getEmitOptions( void ) { return m_uiEmitOptions; } //-------------------------------------------------------------------------- inline void setEmitOptions( Cmp_unsigned__int32 uiOptions ) { m_uiEmitOptions = uiOptions; } //-------------------------------------------------------------------------- inline Cx86HLAContext* getContext( void ) const __QCMP_THROW { return m_pContext; } //-------------------------------------------------------------------------- virtual nsArch::CCPUBase* getAssembler( void ) __QCMP_THROW { return &m_CPU; } //-------------------------------------------------------------------------- void WriteLaunchPad( byte* pFunc, byte* pLaunchPad ) { #if ( QOR_ARCH_WORDSIZE == 32 ) pLaunchPad[ 0 ] = 0xE9; //jmp ( (Cmp_unsigned__int32*)( pLaunchPad + 1 ) )[ 0 ] = (Cmp_uint_ptr)( pFunc - ( pLaunchPad + 5 ) ); //relative address of target pLaunchPad[ 5 ] = 0xC3; //ret | /* pLaunchPad[ 0 ] = 0xFF; //call pLaunchPad[ 1 ] = 0x15; ( (Cmp_unsigned__int32*)( pLaunchPad + 2 ) )[ 0 ] = (Cmp_uint_ptr)( pLaunchPad + 8 ); //address of target pLaunchPad[ 6 ] = 0xC3; //ret | ( (Cmp_uint_ptr*)( pLaunchPad + 8 ) )[ 0 ] = (Cmp_uint_ptr)pFunc; // Absolute address. <' */ #elif ( QOR_ARCH_WORDSIZE == 64 ) pLaunchPad[ 0 ] = 0xFF; // Jmp. pLaunchPad[ 1 ] = 0x25; // ModM (RIP addressing). ( (Cmp_unsigned__int32*)( pLaunchPad + 2 ) )[ 0 ] = 0; // Offset (zero). ( (Cmp_uint_ptr*)( pLaunchPad + 6 ) )[ 0 ] = (Cmp_uint_ptr)pFunc; // Absolute address. #endif } protected: Cmp_unsigned__int32 m_uiError; // Last error code. Cmp_unsigned__int32 m_uiProperties; // Properties. Cmp_unsigned__int32 m_uiEmitOptions; // Contains options for next emitted instruction, clear after each emit. Cmp_unsigned__int32 m_uiFinished; // Whether compiler was finished the job (register allocator, etc...). CEFunction* m_pFunction; // Current function. nsCodeQOR::PodVector< CETarget* > m_TargetData; // Label data. nsCodeQOR::PodVector< VarData* > m_VarData; // Variable data. int m_iVarNameId; // Variable name id (used to generate unique names per function). Cx86HLAContext* m_pContext; // Compiler context instance, only available after prepare(). CCPU m_CPU; // Assembler instance. __QCS_DECLARE_NONCOPYABLE( CZHLAssembler ); }; }//nsZ }//nsArch #endif//ARCHQOR_Z_HLASSEMBLER_H_1
ahabra/tecuj2
src/main/java/com/tek271/util2/reflection/FieldReflector.java
<reponame>ahabra/tecuj2 package com.tek271.util2.reflection; import org.apache.commons.lang3.tuple.Pair; import java.lang.reflect.Field; import java.util.*; import java.util.stream.Collectors; import static com.google.common.collect.Sets.newHashSet; public class FieldReflector<T> { private final T obj; private final Set<String> excludedFieldNames = new HashSet<>(); private final Set<ScopeEnum> excludedScopes = new HashSet<>(); public FieldReflector(T obj) { this.obj = obj; } @SuppressWarnings("unchecked") public <V> V getFieldValue(Field field) { boolean accessChanged = false; if (! field.isAccessible()) { field.setAccessible(true); accessChanged = true; } try { return (V) field.get(obj); } catch (IllegalAccessException e) { throw new RuntimeException(fieldAccessError(field.getName()), e); } finally { if (accessChanged) { field.setAccessible(false); } } } public <V> V getFieldValue(String fieldName) { Field field = findField(fieldName); return getFieldValue(field); } public Field findField(String fieldName) { try { return obj.getClass().getDeclaredField(fieldName); } catch (NoSuchFieldException e) { throw new RuntimeException(fieldAccessError(fieldName), e); } } private String fieldAccessError(String fieldName) { return "Cannot access field " + fieldName + " in " + obj.getClass().getName(); } public FieldReflector<T> excludeScope(Set<ScopeEnum> scopes) { excludedScopes.addAll(scopes); return this; } public FieldReflector<T> excludeScope(ScopeEnum... scopes) { return excludeScope(newHashSet(scopes)); } public FieldReflector<T> excludeField(Set<String> fieldNames) { excludedFieldNames.addAll(fieldNames); return this; } public FieldReflector<T> excludeField(String... fieldNames) { excludeField(newHashSet(fieldNames)); return this; } private boolean isExcluded(Field field) { if (excludedFieldNames.contains(field.getName())) return true; ScopeEnum scope = ScopeEnum.scopeOf(field); return excludedScopes.contains(scope); } public Map<String, Object> toMap() { Field[] fields = obj.getClass().getDeclaredFields(); Map<String, Object> map = new LinkedHashMap<>(); for (Field f: fields) { if (! isExcluded(f)) { map.put(f.getName(), getFieldValue(f)); } } return map; } public List<Pair<String, Object>> toPairs() { Map<String, Object> map = toMap(); return map.entrySet().stream() .map(e -> Pair.of(e.getKey(), e.getValue())) .collect(Collectors.toList()); } @SuppressWarnings("unchecked") public Pair<String, Object>[] toPairsArray() { List<Pair<String, Object>> list = toPairs(); return list.toArray( new Pair[list.size()] ); } public List<String> getFields() { Field[] fields = obj.getClass().getDeclaredFields(); List<String> names= new ArrayList<>(); for (Field f: fields) { names.add(f.getName()); } return names; } }
matthew-brett/pymc
pymc/sandbox/__init__.py
__modules__ = ['bayes','EM','parallel','NormalSubmodel','NormalModel','DLM','DP'] for mod in __modules__: try: exec('import %s' %mod) except: pass
Amourspirit/ooo_uno_tmpl
ooobuild/cssdyn/ui/__init__.py
# coding: utf-8 # # Copyright 2022 :Barry-Thomas-Paul: Moss # # 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. # from ...dyn.ui.action_trigger import ActionTrigger as ActionTrigger from ...dyn.ui.action_trigger_container import ActionTriggerContainer as ActionTriggerContainer from ...dyn.ui.action_trigger_separator import ActionTriggerSeparator as ActionTriggerSeparator from ...dyn.ui.action_trigger_separator_type import ActionTriggerSeparatorType as ActionTriggerSeparatorType from ...dyn.ui.action_trigger_separator_type import ActionTriggerSeparatorTypeEnum as ActionTriggerSeparatorTypeEnum from ...dyn.ui.address_book_source_dialog import AddressBookSourceDialog as AddressBookSourceDialog from ...dyn.ui.configurable_ui_element import ConfigurableUIElement as ConfigurableUIElement from ...dyn.ui.configuration_event import ConfigurationEvent as ConfigurationEvent from ...dyn.ui.context_change_event_multiplexer import ContextChangeEventMultiplexer as ContextChangeEventMultiplexer from ...dyn.ui.context_change_event_object import ContextChangeEventObject as ContextChangeEventObject from ...dyn.ui.context_menu_execute_event import ContextMenuExecuteEvent as ContextMenuExecuteEvent from ...dyn.ui.context_menu_interceptor_action import ContextMenuInterceptorAction as ContextMenuInterceptorAction from ...dyn.ui.docking_area import DockingArea as DockingArea from ...dyn.ui.document_accelerator_configuration import DocumentAcceleratorConfiguration as DocumentAcceleratorConfiguration from ...dyn.ui.global_accelerator_configuration import GlobalAcceleratorConfiguration as GlobalAcceleratorConfiguration from ...dyn.ui.image_manager import ImageManager as ImageManager from ...dyn.ui.image_type import ImageType as ImageType from ...dyn.ui.image_type import ImageTypeEnum as ImageTypeEnum from ...dyn.ui.item_descriptor import ItemDescriptor as ItemDescriptor from ...dyn.ui.item_style import ItemStyle as ItemStyle from ...dyn.ui.item_style import ItemStyleEnum as ItemStyleEnum from ...dyn.ui.item_type import ItemType as ItemType from ...dyn.ui.item_type import ItemTypeEnum as ItemTypeEnum from ...dyn.ui.layout_size import LayoutSize as LayoutSize from ...dyn.ui.module_accelerator_configuration import ModuleAcceleratorConfiguration as ModuleAcceleratorConfiguration from ...dyn.ui.module_ui_category_description import ModuleUICategoryDescription as ModuleUICategoryDescription from ...dyn.ui.module_ui_command_description import ModuleUICommandDescription as ModuleUICommandDescription from ...dyn.ui.module_ui_configuration_manager import ModuleUIConfigurationManager as ModuleUIConfigurationManager from ...dyn.ui.module_ui_configuration_manager_supplier import ModuleUIConfigurationManagerSupplier as ModuleUIConfigurationManagerSupplier from ...dyn.ui.module_window_state_configuration import ModuleWindowStateConfiguration as ModuleWindowStateConfiguration from ...dyn.ui.ui_category_description import UICategoryDescription as UICategoryDescription from ...dyn.ui.ui_configuration_manager import UIConfigurationManager as UIConfigurationManager from ...dyn.ui.ui_element import UIElement as UIElement from ...dyn.ui.ui_element_factory import UIElementFactory as UIElementFactory from ...dyn.ui.ui_element_factory_manager import UIElementFactoryManager as UIElementFactoryManager from ...dyn.ui.ui_element_settings import UIElementSettings as UIElementSettings from ...dyn.ui.ui_element_type import UIElementType as UIElementType from ...dyn.ui.ui_element_type import UIElementTypeEnum as UIElementTypeEnum from ...dyn.ui.window_content_factory import WindowContentFactory as WindowContentFactory from ...dyn.ui.window_content_factory_manager import WindowContentFactoryManager as WindowContentFactoryManager from ...dyn.ui.window_state_configuration import WindowStateConfiguration as WindowStateConfiguration from ...dyn.ui.x_accelerator_configuration import XAcceleratorConfiguration as XAcceleratorConfiguration from ...dyn.ui.x_context_change_event_listener import XContextChangeEventListener as XContextChangeEventListener from ...dyn.ui.x_context_change_event_multiplexer import XContextChangeEventMultiplexer as XContextChangeEventMultiplexer from ...dyn.ui.x_context_menu_interception import XContextMenuInterception as XContextMenuInterception from ...dyn.ui.x_context_menu_interceptor import XContextMenuInterceptor as XContextMenuInterceptor from ...dyn.ui.x_deck import XDeck as XDeck from ...dyn.ui.x_decks import XDecks as XDecks from ...dyn.ui.x_docking_area_acceptor import XDockingAreaAcceptor as XDockingAreaAcceptor from ...dyn.ui.x_image_manager import XImageManager as XImageManager from ...dyn.ui.x_module_ui_configuration_manager import XModuleUIConfigurationManager as XModuleUIConfigurationManager from ...dyn.ui.x_module_ui_configuration_manager2 import XModuleUIConfigurationManager2 as XModuleUIConfigurationManager2 from ...dyn.ui.x_module_ui_configuration_manager_supplier import XModuleUIConfigurationManagerSupplier as XModuleUIConfigurationManagerSupplier from ...dyn.ui.x_panel import XPanel as XPanel from ...dyn.ui.x_panels import XPanels as XPanels from ...dyn.ui.x_sidebar import XSidebar as XSidebar from ...dyn.ui.x_sidebar_panel import XSidebarPanel as XSidebarPanel from ...dyn.ui.x_sidebar_provider import XSidebarProvider as XSidebarProvider from ...dyn.ui.x_statusbar_item import XStatusbarItem as XStatusbarItem from ...dyn.ui.x_tool_panel import XToolPanel as XToolPanel from ...dyn.ui.xui_configuration import XUIConfiguration as XUIConfiguration from ...dyn.ui.xui_configuration_listener import XUIConfigurationListener as XUIConfigurationListener from ...dyn.ui.xui_configuration_manager import XUIConfigurationManager as XUIConfigurationManager from ...dyn.ui.xui_configuration_manager2 import XUIConfigurationManager2 as XUIConfigurationManager2 from ...dyn.ui.xui_configuration_manager_supplier import XUIConfigurationManagerSupplier as XUIConfigurationManagerSupplier from ...dyn.ui.xui_configuration_persistence import XUIConfigurationPersistence as XUIConfigurationPersistence from ...dyn.ui.xui_configuration_storage import XUIConfigurationStorage as XUIConfigurationStorage from ...dyn.ui.xui_element import XUIElement as XUIElement from ...dyn.ui.xui_element_factory import XUIElementFactory as XUIElementFactory from ...dyn.ui.xui_element_factory_manager import XUIElementFactoryManager as XUIElementFactoryManager from ...dyn.ui.xui_element_factory_registration import XUIElementFactoryRegistration as XUIElementFactoryRegistration from ...dyn.ui.xui_element_settings import XUIElementSettings as XUIElementSettings from ...dyn.ui.xui_function_listener import XUIFunctionListener as XUIFunctionListener from ...dyn.ui.x_update_model import XUpdateModel as XUpdateModel from ...dyn.ui.the_module_ui_configuration_manager_supplier import theModuleUIConfigurationManagerSupplier as theModuleUIConfigurationManagerSupplier from ...dyn.ui.the_ui_category_description import theUICategoryDescription as theUICategoryDescription from ...dyn.ui.the_ui_element_factory_manager import theUIElementFactoryManager as theUIElementFactoryManager from ...dyn.ui.the_window_content_factory_manager import theWindowContentFactoryManager as theWindowContentFactoryManager from ...dyn.ui.the_window_state_configuration import theWindowStateConfiguration as theWindowStateConfiguration
qussarah/declare
idea/testData/kotlinAndJavaChecker/javaAgainstKotlin/FunctionInNestedClassInDataFlowInspection.java
package test; import org.jetbrains.annotations.NotNull; import test.kotlin.A.B.C.C; public class FunctionInNestedClassInDataFlowInspection { void other(@NotNull Object some) { Object foo = new C().foo(some); } }
omolinab/jbpm
jbpm-case-mgmt/jbpm-case-mgmt-cmmn/src/main/java/org/jbpm/casemgmt/cmmn/xml/DecisionTaskHandler.java
/* * Copyright 2018 Red Hat, Inc. and/or its affiliates. * * 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 org.jbpm.casemgmt.cmmn.xml; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.drools.core.xml.ExtensibleXmlParser; import org.jbpm.process.core.Work; import org.jbpm.process.core.impl.WorkImpl; import org.jbpm.workflow.core.Node; import org.jbpm.workflow.core.node.DataAssociation; import org.jbpm.workflow.core.node.RuleSetNode; import org.jbpm.workflow.core.node.WorkItemNode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Element; import org.xml.sax.Attributes; import org.xml.sax.SAXException; public class DecisionTaskHandler extends AbstractCaseNodeHandler { private static final String NAMESPACE_PROP = "namespace"; private static final String MODEL_PROP = "model"; private static final String DECISION_PROP = "decision"; private static final Logger logger = LoggerFactory.getLogger(DecisionTaskHandler.class); protected Node createNode(Attributes attrs) { return new RuleSetNode(); } @SuppressWarnings("unchecked") public Class generateNodeFor() { return RuleSetNode.class; } protected void handleNode(final Node node, final Element element, final String uri, final String localName, final ExtensibleXmlParser parser) throws SAXException { super.handleNode(node, element, uri, localName, parser); String decisionRef = element.getAttribute("decisionRef"); if (decisionRef == null) { throw new IllegalArgumentException("Decision information is mandatory"); } RuleSetNode ruleSetNode = (RuleSetNode) node; ruleSetNode.setRuleFlowGroup(decisionRef); ruleSetNode.setLanguage(RuleSetNode.DRL_LANG); ruleSetNode.setNamespace((String) ruleSetNode.removeParameter(NAMESPACE_PROP)); ruleSetNode.setModel((String) ruleSetNode.removeParameter(MODEL_PROP)); ruleSetNode.setDecision((String) ruleSetNode.removeParameter(DECISION_PROP)); Map<String, String> inputs = new HashMap<>(); Map<String, String> outputs = new HashMap<>(); Map<String, String> inputTypes = new HashMap<>(); Map<String, String> outputTypes = new HashMap<>(); loadDataInputsAndOutputs(element, inputs, outputs, inputTypes, outputTypes, parser); ruleSetNode.setMetaData("DataInputs", inputTypes); ruleSetNode.setMetaData("DataOutputs", outputTypes); for (Entry<String, String> entry : inputs.entrySet()) { ruleSetNode.addInAssociation(new DataAssociation(entry.getValue(), entry.getKey(), Collections.emptyList(), null)); } for (Entry<String, String> entry : outputs.entrySet()) { ruleSetNode.addOutAssociation(new DataAssociation(entry.getKey(), entry.getValue(), Collections.emptyList(), null)); } } }
gvramana/topcarbondata
hadoop/src/main/java/org/carbondata/hadoop/util/CarbonInputFormatUtil.java
<gh_stars>1-10 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.carbondata.hadoop.util; import java.util.List; import org.carbondata.core.carbon.AbsoluteTableIdentifier; import org.carbondata.core.carbon.metadata.schema.table.CarbonTable; import org.carbondata.core.carbon.metadata.schema.table.column.CarbonDimension; import org.carbondata.core.carbon.metadata.schema.table.column.CarbonMeasure; import org.carbondata.scan.expression.Expression; import org.carbondata.scan.filter.FilterExpressionProcessor; import org.carbondata.scan.filter.resolver.FilterResolverIntf; import org.carbondata.scan.model.CarbonQueryPlan; import org.carbondata.scan.model.QueryDimension; import org.carbondata.scan.model.QueryMeasure; import org.carbondata.scan.model.QueryModel; /** * Utility class */ public class CarbonInputFormatUtil { public static CarbonQueryPlan createQueryPlan(CarbonTable carbonTable, String columnString) { String[] columns = null; if (columnString != null) { columns = columnString.split(","); } String factTableName = carbonTable.getFactTableName(); CarbonQueryPlan plan = new CarbonQueryPlan(carbonTable.getDatabaseName(), factTableName); // fill dimensions // If columns are null, set all dimensions and measures int i = 0; List<CarbonMeasure> tableMsrs = carbonTable.getMeasureByTableName(factTableName); List<CarbonDimension> tableDims = carbonTable.getDimensionByTableName(factTableName); if (columns == null) { for (CarbonDimension dimension : tableDims) { addQueryDimension(plan, i, dimension); i++; } for (CarbonMeasure measure : tableMsrs) { addQueryMeasure(plan, i, measure); i++; } } else { for (String column : columns) { CarbonDimension dimensionByName = carbonTable.getDimensionByName(factTableName, column); if (dimensionByName != null) { addQueryDimension(plan, i, dimensionByName); i++; } else { CarbonMeasure measure = carbonTable.getMeasureByName(factTableName, column); if (measure == null) { throw new RuntimeException(column + " column not found in the table " + factTableName); } addQueryMeasure(plan, i, measure); i++; } } } plan.setLimit(-1); plan.setRawDetailQuery(true); plan.setQueryId(System.nanoTime() + ""); return plan; } private static void addQueryMeasure(CarbonQueryPlan plan, int order, CarbonMeasure measure) { QueryMeasure queryMeasure = new QueryMeasure(measure.getColName()); queryMeasure.setQueryOrder(order); queryMeasure.setMeasure(measure); plan.addMeasure(queryMeasure); } private static void addQueryDimension(CarbonQueryPlan plan, int order, CarbonDimension dimension) { QueryDimension queryDimension = new QueryDimension(dimension.getColName()); queryDimension.setQueryOrder(order); queryDimension.setDimension(dimension); plan.addDimension(queryDimension); } public static void processFilterExpression(Expression filterExpression, CarbonTable carbonTable) { List<CarbonDimension> dimensions = carbonTable.getDimensionByTableName(carbonTable.getFactTableName()); List<CarbonMeasure> measures = carbonTable.getMeasureByTableName(carbonTable.getFactTableName()); QueryModel.processFilterExpression(filterExpression, dimensions, measures); } /** * Resolve the filter expression. * * @param filterExpression * @param absoluteTableIdentifier * @return */ public static FilterResolverIntf resolveFilter(Expression filterExpression, AbsoluteTableIdentifier absoluteTableIdentifier) { try { FilterExpressionProcessor filterExpressionProcessor = new FilterExpressionProcessor(); //get resolved filter return filterExpressionProcessor.getFilterResolver(filterExpression, absoluteTableIdentifier); } catch (Exception e) { throw new RuntimeException("Error while resolving filter expression", e); } } public static String processPath(String path) { if (path != null && path.startsWith("file:")) { return path.substring(5, path.length()); } return path; } }
intercity/intercity-classic
test/test_helper.rb
<filename>test/test_helper.rb ENV["RAILS_ENV"] ||= "test" require File.expand_path('../../config/environment', __FILE__) require 'rails/test_help' require 'sidekiq/testing' require 'minitest/mock' require "mocha/mini_test" require "minitest/rails" require "minitest/rails/capybara" require "minitest/reporters" require "support/ssl_helper" require "rack_session_access/capybara" require "capybara/poltergeist" require 'database_cleaner' Sidekiq::Testing.fake! Minitest::Reporters.use!( Minitest::Reporters::DefaultReporter.new(color: true), ENV, Minitest.backtrace_filter ) DatabaseCleaner.strategy = :transaction class ActiveSupport::TestCase include SslHelper ActiveRecord::Migration.check_pending! # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. # # Note: You'll currently still have to declare fixtures explicitly in integration tests # -- they do not yet inherit this setting fixtures :all self.use_transactional_fixtures = false # Add more helper methods to be used by all tests here... def setup Sidekiq::Worker.clear_all end end class ActionController::TestCase include Devise::TestHelpers end class Capybara::Rails::TestCase include Warden::Test::Helpers Warden.test_mode! Capybara.javascript_driver = :poltergeist DatabaseCleaner.clean_with :truncation Capybara.register_driver :poltergeist do |app| Capybara::Poltergeist::Driver.new(app, js_errors: true, timeout: 90) end def use_javascript_driver Capybara.current_driver = Capybara.javascript_driver end def teardown Capybara.current_driver = nil end end EncryptedValue.encryption_key = 'f3fd12e9f3cef8ec5d508b26afbdafa2'
DavideCorradiDev/houzi-game-engine
source/hougfx/include/hou/gfx/vertex_array.hpp
<filename>source/hougfx/include/hou/gfx/vertex_array.hpp // Houzi Game Engine // Copyright (c) 2018 <NAME> // Licensed under the MIT license. #ifndef HOU_GFX_VERTEX_ARRAY_HPP #define HOU_GFX_VERTEX_ARRAY_HPP #include "hou/cor/non_copyable.hpp" #include "hou/gfx/gfx_config.hpp" #include "hou/gl/gl_vertex_array_handle.hpp" namespace hou { class vertex_buffer; class vertex_format; /** Represents a vertex_array object. */ class HOU_GFX_API vertex_array final : public non_copyable { public: /** Binds the vertex_array to the current graphic_context. * * \param va the vertex_array to be bound. */ static void bind(const vertex_array& va); /** Unbinds the currently bound vertex_array, if present. */ static void unbind(); /** Retrieves the maximum number of vertex_buffer objects that can be bound to * a single vertex_array object. * * \return the maximum number of vertex_buffer objects that can be bound. */ static uint get_max_binding_index(); public: /** default constructor. */ vertex_array(); /** Retrieves the reference to the OpenGL vertex array object. * * \return the reference to the OpenGL vertex array object. */ const gl::vertex_array_handle& get_handle() const noexcept; /** Checks if the vertex_array is currently bound. * * \return the result of the check. */ bool is_bound() const; /** Binds a vertex_buffer as a vertex buffer. * * The data in the vertex_buffer represents vertex data. * Throws if binding index is greater than the maximum binding index. * * \param vb the vertex_buffer to be bound. * * \param binding_index the binding index to be used. * * \param vf the format of the vertices contained in vb. */ void set_vertex_data( const vertex_buffer& vb, uint binding_index, const vertex_format& vf); /** Binds a vertex_buffer as an element buffer. * * The data in the vertex_buffer represents indices referring to element of * the bound vertex buffer. * * \param eb the vertex_buffer to be bound. */ void set_element_data(const vertex_buffer& eb); private: gl::vertex_array_handle m_handle; }; } // namespace hou #endif
acabra85/googleTechDevAlgs
src/main/java/com/acabra/gtechdevalgs/litcode/arrays/PermutationSequence.java
package com.acabra.gtechdevalgs.litcode.arrays; import java.util.LinkedList; import java.util.List; import java.util.PriorityQueue; public class PermutationSequence { /** * Use brute force: generate all permutations store them in a min_queue retrieve the k first elements from the queue * @param n the length of the array 1 .... n * @param k the position where the ordered kth permutation is * @return the kth permutation. */ public String findKPermutation_bf(int n, int k) { int a[] = new int[n]; for(int i = 0; i<n; i++) a[i] = i+1; PriorityQueue<Integer> pq = new PriorityQueue<>(); permutations(a, n, pq); Integer elm; for(int i = 0; i < k && !pq.isEmpty(); i++){ elm = pq.remove(); if(i==k-1) { return elm + ""; } } return ""; } /** * Brute force method for creating all permutations of an array * @param a the array containing the data to create the permutation * @param size the array size * @param pq the priority queue that holds all results in ascending order */ private void permutations(int a[], int size, PriorityQueue<Integer> pq) { if (size == 1) { StringBuilder val = new StringBuilder(); for(int i=0;i<a.length;i++) { val.append(a[i]); } pq.offer(Integer.parseInt(val.toString())); } for (int i=0; i<size; i++) { permutations(a, size-1, pq); if (size % 2 != 0) { int temp = a[0]; a[0] = a[size-1]; a[size-1] = temp; } else { int temp = a[i]; a[i] = a[size-1]; a[size-1] = temp; } } } /** * Uses the factorial number system to retrieve calculate the kth permutation * 0! = 1, 1! = 1, 2! = 2, 3! = 6, 4! = 24, 5! = 120 * Representing decimal numbers in factorial system * 0 -> 0 = 0*0! * 1 -> 10 = 1*1! + 0*0! * 2 -> 100 = 2*1! + 0*1! + 0*0! * 3 -> 110 = 2*1 + 1*1! + 0*0! * 4 -> 200 = 2*2! + 0*1! + 0*0! * @param n the length of the array, n [ 1 ... 9 ] * @param k the position where the ordered kth permutation is, k [1 ... n!] * @return the kth permutation. */ public String findKPermutation(int n, int k) { if (n < 1 || n > 9) throw new IllegalArgumentException("n must be between [1,9] given:" + n); if (k < 0) throw new IllegalArgumentException("k must be between [1,9] given:" + k); List<Integer> kInFactorialBase = convertToFactorialBase(k - 1, n); LinkedList<Character> stringToPermute = buildPermutationString(n); StringBuilder res = new StringBuilder(); for(int i = 0; !stringToPermute.isEmpty(); i++) { int index1 = kInFactorialBase.get(i); res.append(stringToPermute.remove(index1)); } return res.toString(); } private LinkedList<Character> buildPermutationString(int n) { LinkedList<Character> linked = new LinkedList<>(); for (int i = 49; i < n+49; i++) { linked.addLast((char)i); } return linked; } /** * Converts a k decimal into its factorial-base representation * @param k the number to convert * @param n the size (required to complete padding) * @return a list containing the factorial digits */ private List<Integer> convertToFactorialBase(int k, int n) { LinkedList<Integer> sb = new LinkedList<>(); int i = 1; int q = k; while(q/i > 0) { sb.addFirst(q%i); q = q/i++; } sb.addFirst(q%i); while(sb.size() < n) { //pad zeroes to the beginning of the number to complete n characters sb.addFirst(0); } return sb; } }
vbogatyrov/tdi-studio-se
main/plugins/org.talend.designer.components.libs/libs_src/Netsuite_Client/src/main/java/com/netsuite/webservices/platform/common/TaskSearchBasic.java
<gh_stars>100-1000 package com.netsuite.webservices.platform.common; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import com.netsuite.webservices.platform.core.SearchBooleanField; import com.netsuite.webservices.platform.core.SearchCustomFieldList; import com.netsuite.webservices.platform.core.SearchDateField; import com.netsuite.webservices.platform.core.SearchDoubleField; import com.netsuite.webservices.platform.core.SearchEnumMultiSelectField; import com.netsuite.webservices.platform.core.SearchLongField; import com.netsuite.webservices.platform.core.SearchMultiSelectField; import com.netsuite.webservices.platform.core.SearchRecordBasic; import com.netsuite.webservices.platform.core.SearchStringField; /** * <p>Java class for TaskSearchBasic complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="TaskSearchBasic"&gt; * &lt;complexContent&gt; * &lt;extension base="{urn:core_2014_2.platform.webservices.netsuite.com}SearchRecordBasic"&gt; * &lt;sequence&gt; * &lt;element name="actualTime" type="{urn:core_2014_2.platform.webservices.netsuite.com}SearchDoubleField" minOccurs="0"/&gt; * &lt;element name="assigned" type="{urn:core_2014_2.platform.webservices.netsuite.com}SearchMultiSelectField" minOccurs="0"/&gt; * &lt;element name="company" type="{urn:core_2014_2.platform.webservices.netsuite.com}SearchMultiSelectField" minOccurs="0"/&gt; * &lt;element name="completedDate" type="{urn:core_2014_2.platform.webservices.netsuite.com}SearchDateField" minOccurs="0"/&gt; * &lt;element name="contact" type="{urn:core_2014_2.platform.webservices.netsuite.com}SearchMultiSelectField" minOccurs="0"/&gt; * &lt;element name="createdDate" type="{urn:core_2014_2.platform.webservices.netsuite.com}SearchDateField" minOccurs="0"/&gt; * &lt;element name="endDate" type="{urn:core_2014_2.platform.webservices.netsuite.com}SearchDateField" minOccurs="0"/&gt; * &lt;element name="estimatedTime" type="{urn:core_2014_2.platform.webservices.netsuite.com}SearchDoubleField" minOccurs="0"/&gt; * &lt;element name="estimatedTimeOverride" type="{urn:core_2014_2.platform.webservices.netsuite.com}SearchDoubleField" minOccurs="0"/&gt; * &lt;element name="externalId" type="{urn:core_2014_2.platform.webservices.netsuite.com}SearchMultiSelectField" minOccurs="0"/&gt; * &lt;element name="externalIdString" type="{urn:core_2014_2.platform.webservices.netsuite.com}SearchStringField" minOccurs="0"/&gt; * &lt;element name="internalId" type="{urn:core_2014_2.platform.webservices.netsuite.com}SearchMultiSelectField" minOccurs="0"/&gt; * &lt;element name="internalIdNumber" type="{urn:core_2014_2.platform.webservices.netsuite.com}SearchLongField" minOccurs="0"/&gt; * &lt;element name="isJobSummaryTask" type="{urn:core_2014_2.platform.webservices.netsuite.com}SearchBooleanField" minOccurs="0"/&gt; * &lt;element name="isJobTask" type="{urn:core_2014_2.platform.webservices.netsuite.com}SearchBooleanField" minOccurs="0"/&gt; * &lt;element name="isPrivate" type="{urn:core_2014_2.platform.webservices.netsuite.com}SearchBooleanField" minOccurs="0"/&gt; * &lt;element name="lastModifiedDate" type="{urn:core_2014_2.platform.webservices.netsuite.com}SearchDateField" minOccurs="0"/&gt; * &lt;element name="milestone" type="{urn:core_2014_2.platform.webservices.netsuite.com}SearchLongField" minOccurs="0"/&gt; * &lt;element name="owner" type="{urn:core_2014_2.platform.webservices.netsuite.com}SearchMultiSelectField" minOccurs="0"/&gt; * &lt;element name="percentComplete" type="{urn:core_2014_2.platform.webservices.netsuite.com}SearchLongField" minOccurs="0"/&gt; * &lt;element name="percentTimeComplete" type="{urn:core_2014_2.platform.webservices.netsuite.com}SearchLongField" minOccurs="0"/&gt; * &lt;element name="priority" type="{urn:core_2014_2.platform.webservices.netsuite.com}SearchEnumMultiSelectField" minOccurs="0"/&gt; * &lt;element name="startDate" type="{urn:core_2014_2.platform.webservices.netsuite.com}SearchDateField" minOccurs="0"/&gt; * &lt;element name="status" type="{urn:core_2014_2.platform.webservices.netsuite.com}SearchEnumMultiSelectField" minOccurs="0"/&gt; * &lt;element name="timeRemaining" type="{urn:core_2014_2.platform.webservices.netsuite.com}SearchDoubleField" minOccurs="0"/&gt; * &lt;element name="title" type="{urn:core_2014_2.platform.webservices.netsuite.com}SearchStringField" minOccurs="0"/&gt; * &lt;element name="customFieldList" type="{urn:core_2014_2.platform.webservices.netsuite.com}SearchCustomFieldList" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;/extension&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "TaskSearchBasic", propOrder = { "actualTime", "assigned", "company", "completedDate", "contact", "createdDate", "endDate", "estimatedTime", "estimatedTimeOverride", "externalId", "externalIdString", "internalId", "internalIdNumber", "isJobSummaryTask", "isJobTask", "isPrivate", "lastModifiedDate", "milestone", "owner", "percentComplete", "percentTimeComplete", "priority", "startDate", "status", "timeRemaining", "title", "customFieldList" }) public class TaskSearchBasic extends SearchRecordBasic { protected SearchDoubleField actualTime; protected SearchMultiSelectField assigned; protected SearchMultiSelectField company; protected SearchDateField completedDate; protected SearchMultiSelectField contact; protected SearchDateField createdDate; protected SearchDateField endDate; protected SearchDoubleField estimatedTime; protected SearchDoubleField estimatedTimeOverride; protected SearchMultiSelectField externalId; protected SearchStringField externalIdString; protected SearchMultiSelectField internalId; protected SearchLongField internalIdNumber; protected SearchBooleanField isJobSummaryTask; protected SearchBooleanField isJobTask; protected SearchBooleanField isPrivate; protected SearchDateField lastModifiedDate; protected SearchLongField milestone; protected SearchMultiSelectField owner; protected SearchLongField percentComplete; protected SearchLongField percentTimeComplete; protected SearchEnumMultiSelectField priority; protected SearchDateField startDate; protected SearchEnumMultiSelectField status; protected SearchDoubleField timeRemaining; protected SearchStringField title; protected SearchCustomFieldList customFieldList; /** * Gets the value of the actualTime property. * * @return * possible object is * {@link SearchDoubleField } * */ public SearchDoubleField getActualTime() { return actualTime; } /** * Sets the value of the actualTime property. * * @param value * allowed object is * {@link SearchDoubleField } * */ public void setActualTime(SearchDoubleField value) { this.actualTime = value; } /** * Gets the value of the assigned property. * * @return * possible object is * {@link SearchMultiSelectField } * */ public SearchMultiSelectField getAssigned() { return assigned; } /** * Sets the value of the assigned property. * * @param value * allowed object is * {@link SearchMultiSelectField } * */ public void setAssigned(SearchMultiSelectField value) { this.assigned = value; } /** * Gets the value of the company property. * * @return * possible object is * {@link SearchMultiSelectField } * */ public SearchMultiSelectField getCompany() { return company; } /** * Sets the value of the company property. * * @param value * allowed object is * {@link SearchMultiSelectField } * */ public void setCompany(SearchMultiSelectField value) { this.company = value; } /** * Gets the value of the completedDate property. * * @return * possible object is * {@link SearchDateField } * */ public SearchDateField getCompletedDate() { return completedDate; } /** * Sets the value of the completedDate property. * * @param value * allowed object is * {@link SearchDateField } * */ public void setCompletedDate(SearchDateField value) { this.completedDate = value; } /** * Gets the value of the contact property. * * @return * possible object is * {@link SearchMultiSelectField } * */ public SearchMultiSelectField getContact() { return contact; } /** * Sets the value of the contact property. * * @param value * allowed object is * {@link SearchMultiSelectField } * */ public void setContact(SearchMultiSelectField value) { this.contact = value; } /** * Gets the value of the createdDate property. * * @return * possible object is * {@link SearchDateField } * */ public SearchDateField getCreatedDate() { return createdDate; } /** * Sets the value of the createdDate property. * * @param value * allowed object is * {@link SearchDateField } * */ public void setCreatedDate(SearchDateField value) { this.createdDate = value; } /** * Gets the value of the endDate property. * * @return * possible object is * {@link SearchDateField } * */ public SearchDateField getEndDate() { return endDate; } /** * Sets the value of the endDate property. * * @param value * allowed object is * {@link SearchDateField } * */ public void setEndDate(SearchDateField value) { this.endDate = value; } /** * Gets the value of the estimatedTime property. * * @return * possible object is * {@link SearchDoubleField } * */ public SearchDoubleField getEstimatedTime() { return estimatedTime; } /** * Sets the value of the estimatedTime property. * * @param value * allowed object is * {@link SearchDoubleField } * */ public void setEstimatedTime(SearchDoubleField value) { this.estimatedTime = value; } /** * Gets the value of the estimatedTimeOverride property. * * @return * possible object is * {@link SearchDoubleField } * */ public SearchDoubleField getEstimatedTimeOverride() { return estimatedTimeOverride; } /** * Sets the value of the estimatedTimeOverride property. * * @param value * allowed object is * {@link SearchDoubleField } * */ public void setEstimatedTimeOverride(SearchDoubleField value) { this.estimatedTimeOverride = value; } /** * Gets the value of the externalId property. * * @return * possible object is * {@link SearchMultiSelectField } * */ public SearchMultiSelectField getExternalId() { return externalId; } /** * Sets the value of the externalId property. * * @param value * allowed object is * {@link SearchMultiSelectField } * */ public void setExternalId(SearchMultiSelectField value) { this.externalId = value; } /** * Gets the value of the externalIdString property. * * @return * possible object is * {@link SearchStringField } * */ public SearchStringField getExternalIdString() { return externalIdString; } /** * Sets the value of the externalIdString property. * * @param value * allowed object is * {@link SearchStringField } * */ public void setExternalIdString(SearchStringField value) { this.externalIdString = value; } /** * Gets the value of the internalId property. * * @return * possible object is * {@link SearchMultiSelectField } * */ public SearchMultiSelectField getInternalId() { return internalId; } /** * Sets the value of the internalId property. * * @param value * allowed object is * {@link SearchMultiSelectField } * */ public void setInternalId(SearchMultiSelectField value) { this.internalId = value; } /** * Gets the value of the internalIdNumber property. * * @return * possible object is * {@link SearchLongField } * */ public SearchLongField getInternalIdNumber() { return internalIdNumber; } /** * Sets the value of the internalIdNumber property. * * @param value * allowed object is * {@link SearchLongField } * */ public void setInternalIdNumber(SearchLongField value) { this.internalIdNumber = value; } /** * Gets the value of the isJobSummaryTask property. * * @return * possible object is * {@link SearchBooleanField } * */ public SearchBooleanField getIsJobSummaryTask() { return isJobSummaryTask; } /** * Sets the value of the isJobSummaryTask property. * * @param value * allowed object is * {@link SearchBooleanField } * */ public void setIsJobSummaryTask(SearchBooleanField value) { this.isJobSummaryTask = value; } /** * Gets the value of the isJobTask property. * * @return * possible object is * {@link SearchBooleanField } * */ public SearchBooleanField getIsJobTask() { return isJobTask; } /** * Sets the value of the isJobTask property. * * @param value * allowed object is * {@link SearchBooleanField } * */ public void setIsJobTask(SearchBooleanField value) { this.isJobTask = value; } /** * Gets the value of the isPrivate property. * * @return * possible object is * {@link SearchBooleanField } * */ public SearchBooleanField getIsPrivate() { return isPrivate; } /** * Sets the value of the isPrivate property. * * @param value * allowed object is * {@link SearchBooleanField } * */ public void setIsPrivate(SearchBooleanField value) { this.isPrivate = value; } /** * Gets the value of the lastModifiedDate property. * * @return * possible object is * {@link SearchDateField } * */ public SearchDateField getLastModifiedDate() { return lastModifiedDate; } /** * Sets the value of the lastModifiedDate property. * * @param value * allowed object is * {@link SearchDateField } * */ public void setLastModifiedDate(SearchDateField value) { this.lastModifiedDate = value; } /** * Gets the value of the milestone property. * * @return * possible object is * {@link SearchLongField } * */ public SearchLongField getMilestone() { return milestone; } /** * Sets the value of the milestone property. * * @param value * allowed object is * {@link SearchLongField } * */ public void setMilestone(SearchLongField value) { this.milestone = value; } /** * Gets the value of the owner property. * * @return * possible object is * {@link SearchMultiSelectField } * */ public SearchMultiSelectField getOwner() { return owner; } /** * Sets the value of the owner property. * * @param value * allowed object is * {@link SearchMultiSelectField } * */ public void setOwner(SearchMultiSelectField value) { this.owner = value; } /** * Gets the value of the percentComplete property. * * @return * possible object is * {@link SearchLongField } * */ public SearchLongField getPercentComplete() { return percentComplete; } /** * Sets the value of the percentComplete property. * * @param value * allowed object is * {@link SearchLongField } * */ public void setPercentComplete(SearchLongField value) { this.percentComplete = value; } /** * Gets the value of the percentTimeComplete property. * * @return * possible object is * {@link SearchLongField } * */ public SearchLongField getPercentTimeComplete() { return percentTimeComplete; } /** * Sets the value of the percentTimeComplete property. * * @param value * allowed object is * {@link SearchLongField } * */ public void setPercentTimeComplete(SearchLongField value) { this.percentTimeComplete = value; } /** * Gets the value of the priority property. * * @return * possible object is * {@link SearchEnumMultiSelectField } * */ public SearchEnumMultiSelectField getPriority() { return priority; } /** * Sets the value of the priority property. * * @param value * allowed object is * {@link SearchEnumMultiSelectField } * */ public void setPriority(SearchEnumMultiSelectField value) { this.priority = value; } /** * Gets the value of the startDate property. * * @return * possible object is * {@link SearchDateField } * */ public SearchDateField getStartDate() { return startDate; } /** * Sets the value of the startDate property. * * @param value * allowed object is * {@link SearchDateField } * */ public void setStartDate(SearchDateField value) { this.startDate = value; } /** * Gets the value of the status property. * * @return * possible object is * {@link SearchEnumMultiSelectField } * */ public SearchEnumMultiSelectField getStatus() { return status; } /** * Sets the value of the status property. * * @param value * allowed object is * {@link SearchEnumMultiSelectField } * */ public void setStatus(SearchEnumMultiSelectField value) { this.status = value; } /** * Gets the value of the timeRemaining property. * * @return * possible object is * {@link SearchDoubleField } * */ public SearchDoubleField getTimeRemaining() { return timeRemaining; } /** * Sets the value of the timeRemaining property. * * @param value * allowed object is * {@link SearchDoubleField } * */ public void setTimeRemaining(SearchDoubleField value) { this.timeRemaining = value; } /** * Gets the value of the title property. * * @return * possible object is * {@link SearchStringField } * */ public SearchStringField getTitle() { return title; } /** * Sets the value of the title property. * * @param value * allowed object is * {@link SearchStringField } * */ public void setTitle(SearchStringField value) { this.title = value; } /** * Gets the value of the customFieldList property. * * @return * possible object is * {@link SearchCustomFieldList } * */ public SearchCustomFieldList getCustomFieldList() { return customFieldList; } /** * Sets the value of the customFieldList property. * * @param value * allowed object is * {@link SearchCustomFieldList } * */ public void setCustomFieldList(SearchCustomFieldList value) { this.customFieldList = value; } }
halmusaibeli/RoboDK-API
Python/Examples/Macros/Synchronize_3_Robots.py
<gh_stars>0 # Type help("robolink") or help("robodk") for more information # Press F5 to run the script # Documentation: https://robodk.com/doc/en/RoboDK-API.html # Reference: https://robodk.com/doc/en/PythonAPI/index.html # # This example shows to synchronize multiple robots at the same time from robodk.robolink import * # API to communicate with RoboDK for offline/online programming from robodk.robomath import * # Robot toolbox import threading import queue #---------------------------------------------- # Function definitions and global variable declarations # Global variables used to synchronize the robot movements # These variables are managed by SyncSet() and SynchWait() SYNC_COUNT = 0 SYNC_TOTAL = 0 SYNC_ID = 0 lock = threading.Lock() def SyncSet(total_sync): """SyncSet will set the number of total robot programs (threads) that must be synchronized togeter. Every time SyncSet is called SYNC_ID is increased by one.""" global SYNC_COUNT global SYNC_TOTAL global SYNC_ID with lock: SYNC_COUNT = 0 SYNC_TOTAL = total_sync SYNC_ID = SYNC_ID + 1 #print('SyncSet') def SyncWait(): """SyncWait will block the robot movements for a robot when necessary, synchronizing the movements sequentially. Use SyncSet(nrobots) to define how many robots must be synchronized together.""" global SYNC_COUNT # Save a local variable with the sync event id sync_id = SYNC_ID with lock: # Increase the number of threads that are synchronized SYNC_COUNT += 1 # Move to the next sync event if all threads reached the SyncWait (SYNC_COUNT = SYNC_TOTAL) if SYNC_COUNT >= SYNC_TOTAL: SyncSet(SYNC_TOTAL) return # Wait for a SynchSet to move forward while sync_id >= SYNC_ID: time.sleep(0.0001) # Main procedure to move each robot def DoWeld(q, robotname): # Any interaction with RoboDK must be done through Robolink() # Each robot movement requires a new Robolink() object (new link of communication). # Two robots can't be moved by the same communication link. rdk = Robolink() # get the robot item: robot = rdk.Item(robotname) # get the home joints target home = robot.JointsHome() # get the reference welding target: target = rdk.Item('Target') # get the reference frame and set it to the robot reference = target.Parent() robot.setPoseFrame(reference) # get the pose of the target (4x4 matrix): poseref = target.Pose() pose_approach = poseref * transl(0, 0, -100) # move the robot to home, then to the center: robot.MoveJ(home) robot.MoveJ(pose_approach) SyncWait() robot.MoveL(target) # make an hexagon around the center: for i in range(7): ang = i * 2 * pi / 6 #angle: 0, 60, 120, ... posei = poseref * rotz(ang) * transl(200, 0, 0) * rotz(-ang) SyncWait() robot.MoveL(posei) # move back to the center, then home: SyncWait() robot.MoveL(target) robot.MoveL(pose_approach) robot.MoveJ(home) q.put('Robot %s finished' % robotname) #---------------------------------------- # Python program start # retrieve all available robots in the RoboDK station (as a list of names) RDK = Robolink() robots = RDK.ItemList(ITEM_TYPE_ROBOT) print(robots) # retrieve the number of robots to synchronize together nrobots = len(robots) SyncSet(nrobots) # the queue allows sharing messages between threads q = queue.Queue() # Start the DoWeld program for all robots. Each robot will run on a separate thread. threads = [] for i in range(nrobots): robotname = robots[i] t = threading.Thread(target=DoWeld, args=(q, robotname)) t.daemon = True t.start() threads.append(t) # wait for every thead to finish for x in threads: x.join() print(q.get()) print('Main program finished')
mehrdad-shokri/neopg
legacy/libksba/tests/t-dnparser.cpp
<gh_stars>100-1000 /* t-dnparser.c - basic test for the DN parser * Copyright (C) 2002, 2006 g10 Code GmbH * * This file is part of KSBA. * * KSBA is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * KSBA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses/>. */ #include <assert.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "../src/ksba.h" #include "t-common.h" static void test_0(void) { static const char *good_strings[] = { "C=de,O=g10 Code,OU=qa,CN=Pépé le Moko", "C= de, O=g10 Code , OU=qa ,CN=Pépé le Moko", "CN=www.gnupg.org", " CN=www.gnupg.org ", "C=fr,L=Paris,CN=<NAME>,EMAIL=<EMAIL>", NULL}; gpg_error_t err; int i; unsigned char *buf; size_t off, len; for (i = 0; good_strings[i]; i++) { err = ksba_dn_str2der(good_strings[i], &buf, &len); if (err) { fprintf(stderr, "%s:%d: ksba_dn_str2der failed for `%s': %s\n", __FILE__, __LINE__, good_strings[i], gpg_strerror(err)); exit(1); } err = ksba_dn_teststr(good_strings[i], 0, &off, &len); if (err) { fprintf(stderr, "%s:%d: ksba_dn_teststr failed for `%s': %s\n", __FILE__, __LINE__, good_strings[i], gpg_strerror(err)); exit(1); } xfree(buf); } } static void test_1(void) { static const char *empty_elements[] = {"C=de,O=foo,OU=,CN=joe", "C=de,O=foo,OU= ,CN=joe", "C=de,O=foo,OU=\"\" ,CN=joe", "C=de,O=foo,OU=", "C=de,O=foo,OU= ", "C=,O=foo,OU=bar ", "C = ,O=foo,OU=bar ", "C=", NULL}; gpg_error_t err; int i; unsigned char *buf; size_t off, len; for (i = 0; empty_elements[i]; i++) { err = ksba_dn_str2der(empty_elements[i], &buf, &len); if (err != GPG_ERR_SYNTAX) fail("empty element not detected"); err = ksba_dn_teststr(empty_elements[i], 0, &off, &len); if (!err) fail("ksba_dn_teststr returned no error"); printf("string ->%s<- error at %lu.%lu (%.*s)\n", empty_elements[i], (unsigned long)off, (unsigned long)len, (int)len, empty_elements[i] + off); xfree(buf); } } static void test_2(void) { static const char *invalid_labels[] = {"C=de,FOO=something,O=bar", "Y=foo, C=baz", NULL}; gpg_error_t err; int i; unsigned char *buf; size_t off, len; for (i = 0; invalid_labels[i]; i++) { err = ksba_dn_str2der(invalid_labels[i], &buf, &len); if (err != GPG_ERR_UNKNOWN_NAME) fail("invalid label not detected"); err = ksba_dn_teststr(invalid_labels[i], 0, &off, &len); if (!err) fail("ksba_dn_test_str returned no error"); printf("string ->%s<- error at %lu.%lu (%.*s)\n", invalid_labels[i], (unsigned long)off, (unsigned long)len, (int)len, invalid_labels[i] + off); xfree(buf); } } int dnparser_main(int argc, char **argv) { char inputbuf[4096]; unsigned char *buf; size_t len; gpg_error_t err; size_t amt; if (argc == 2 && !strcmp(argv[1], "--to-str")) { /* Read the DER encoded DN from stdin write the string to stdout */ amt = fread(inputbuf, 1, sizeof inputbuf, stdin); assert(amt == sizeof(inputbuf)); if (!feof(stdin)) fail("read error or input too large"); fail("not yet implemented"); } else if (argc == 2 && !strcmp(argv[1], "--to-der")) { /* Read the String from stdin write the DER encoding to stdout */ amt = fread(inputbuf, 1, sizeof inputbuf, stdin); assert(amt == sizeof(inputbuf)); if (!feof(stdin)) fail("read error or input too large"); err = ksba_dn_str2der(inputbuf, &buf, &len); fail_if_err(err); fwrite(buf, len, 1, stdout); } else if (argc <= 1) { test_0(); test_1(); test_2(); } else { fprintf(stderr, "usage: t-dnparser [--to-str|--to-der]\n"); return 1; } return 0; }
j0gurt/ggrc-core
src/ggrc-client/js/application.js
/* Copyright (C) 2018 Google Inc. Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> */ (function (root, GGRC, $, can) { let doc = root.document; let body = doc.body; let $win = $(root); let $doc = $(doc); let $body = $(body); $.migrateMute = true; // turn off console warnings for jQuery-migrate root.cms_singularize = function (type) { let _type = type.trim().toLowerCase(); switch (_type) { case 'facilities': type = type[0] + 'acility'; break; case 'people': type = type[0] + 'erson'; break; case 'processes': type = type[0] + 'rocess'; break; case 'policies': type = type[0] + 'olicy'; break; case 'systems_processes': type = type[0] + 'ystem_' + type[8] + 'rocess'; break; default: type = type.replace(/s$/, ''); } return type; }; root.calculate_spinner_z_index = function () { let zindex = 0; $(this).parents().each(function () { let z = parseInt($(this).css('z-index'), 10); if (z) { zindex = z; return false; } }); return zindex + 10; }; $doc.ready(function () { // monitor target, where flash messages are added let AUTOHIDE_TIMEOUT = 10000; let timeoutId; let target = $('section.content div.flash')[0]; let observer = new MutationObserver(function (mutations) { mutations.forEach(function (mutation) { // check for new nodes if (mutation.addedNodes && mutation.addedNodes.length > 0) { // remove the success message from non-expandable // flash success messages after timeout clearTimeout(timeoutId); timeoutId = setTimeout(function () { $('.flash .alert-autohide').remove(); }, AUTOHIDE_TIMEOUT); } }); }); let config = { attributes: true, childList: true, characterData: true, }; if (target) { observer.observe(target, config); } }); $win.load(function () { $body.on('click', 'ul.tree-structure .item-main .openclose', function (ev) { ev.stopPropagation(); $(this).openclose(); }); // top nav dropdown position function dropdownPosition() { let $this = $(this); let $dropdown = $this.closest('.hidden-widgets-list') .find('.dropdown-menu'); let $menuItem = $dropdown.find('.inner-nav-item').find('a'); let offset = $this.offset(); let win = $(window); let winWidth = win.width(); if (winWidth - offset.left < 322) { $dropdown.addClass('right-pos'); } else { $dropdown.removeClass('right-pos'); } if ($menuItem.length === 1) { $dropdown.addClass('one-item'); } else { $dropdown.removeClass('one-item'); } } $('.dropdown-toggle').on('click', dropdownPosition); }); // Make sure GGRC.config is defined (needed to run Karma tests) GGRC.config = GGRC.config || {}; })(window, GGRC, jQuery, can);
toffaletti/libten
examples/echo-server.cc
#include "ten/net.hh" #include "ten/buffer.hh" #include <iostream> using namespace ten; class echo_server : public netsock_server { public: echo_server() : netsock_server{"echo"} {} private: void on_connection(netsock &s) override { buffer buf{4*1024}; for (;;) { buf.reserve(4*1024); ssize_t nr = s.recv(buf.back(), buf.available()); if (nr <= 0) break; buf.commit(nr); ssize_t nw = s.send(buf.front(), buf.size()); if (nw != nr) break; buf.remove(nw); } } }; int main() { return task::main([] { address addr{"127.0.0.1", 0}; std::shared_ptr<echo_server> server = std::make_shared<echo_server>(); server->serve(addr); }); }
mhuryanov/gitlab
ee/spec/lib/ee/api/entities/billable_membership_spec.rb
<reponame>mhuryanov/gitlab # frozen_string_literal: true require 'spec_helper' RSpec.describe ::EE::API::Entities::BillableMembership do describe '#as_json' do it 'returns source_members_url for a group' do membership = create(:group_member) group_members_url = Gitlab::Routing.url_helpers.group_group_members_url(membership.source) expect(described_class.new(membership).as_json[:source_members_url]).to eq(group_members_url) end it 'returns source_members_url for a project' do membership = create(:project_member) project_members_url = Gitlab::Routing.url_helpers.project_project_members_url(membership.source) expect(described_class.new(membership).as_json[:source_members_url]).to eq(project_members_url) end end end
anoshenko/rui
properties.go
<reponame>anoshenko/rui package rui import ( "sort" "strings" ) // Properties interface of properties map type Properties interface { // Get returns a value of the property with name defined by the argument. // The type of return value depends on the property. If the property is not set then nil is returned. Get(tag string) interface{} getRaw(tag string) interface{} // Set sets the value (second argument) of the property with name defined by the first argument. // Return "true" if the value has been set, in the opposite case "false" are returned and // a description of the error is written to the log Set(tag string, value interface{}) bool setRaw(tag string, value interface{}) // Remove removes the property with name defined by the argument Remove(tag string) // Clear removes all properties Clear() // AllTags returns an array of the set properties AllTags() []string } type propertyList struct { properties map[string]interface{} } func (properties *propertyList) init() { properties.properties = map[string]interface{}{} } func (properties *propertyList) Get(tag string) interface{} { return properties.getRaw(strings.ToLower(tag)) } func (properties *propertyList) getRaw(tag string) interface{} { if value, ok := properties.properties[tag]; ok { return value } return nil } func (properties *propertyList) setRaw(tag string, value interface{}) { properties.properties[tag] = value } func (properties *propertyList) Remove(tag string) { delete(properties.properties, strings.ToLower(tag)) } func (properties *propertyList) remove(tag string) { delete(properties.properties, tag) } func (properties *propertyList) Clear() { properties.properties = map[string]interface{}{} } func (properties *propertyList) AllTags() []string { tags := make([]string, 0, len(properties.properties)) for t := range properties.properties { tags = append(tags, t) } sort.Strings(tags) return tags } func parseProperties(properties Properties, object DataObject) { count := object.PropertyCount() for i := 0; i < count; i++ { if node := object.Property(i); node != nil { switch node.Type() { case TextNode: properties.Set(node.Tag(), node.Text()) case ObjectNode: properties.Set(node.Tag(), node.Object()) case ArrayNode: properties.Set(node.Tag(), node.ArrayElements()) } } } }
sukim96/Sapphire
Includes/Sapphire/compute/sparse/naive/SparseGemm.hpp
<gh_stars>1-10 // Copyright (c) 2021, <NAME> // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #ifndef SAPPHIRE_COMPUTE_SPARSE_NAIVE_SPARSEGEMM_HPP #define SAPPHIRE_COMPUTE_SPARSE_NAIVE SPARSEGEMM_HPP #include <Sapphire/compute/sparse/SparseMatrix.hpp> #include <cstdlib> namespace Sapphire::Compute::Sparse::Naive { void Gemm(SparseMatrix** output, SparseMatrix* a, SparseMatrix* b, uint32_t m, uint32_t n, size_t numMatrices); } #endif // SAPPHIRE_SPARSEGEMM_HPP
syret45/runelite
runescape-client/src/main/java/class115.java
import net.runelite.mapping.Export; import net.runelite.mapping.ObfuscatedGetter; import net.runelite.mapping.ObfuscatedName; import net.runelite.mapping.ObfuscatedSignature; import net.runelite.rs.ScriptOpcodes; @ObfuscatedName("dt") public class class115 { @ObfuscatedName("ps") @ObfuscatedSignature( descriptor = "Lop;" ) @Export("HitSplatDefinition_cachedSprites") static class409 HitSplatDefinition_cachedSprites; @ObfuscatedName("c") boolean field1434; @ObfuscatedName("l") boolean field1418; @ObfuscatedName("s") @ObfuscatedSignature( descriptor = "Ldi;" ) class114 field1422; @ObfuscatedName("e") @ObfuscatedSignature( descriptor = "Ldi;" ) class114 field1420; @ObfuscatedName("r") @ObfuscatedSignature( descriptor = "[Ldz;" ) class111[] field1430; @ObfuscatedName("o") boolean field1421; @ObfuscatedName("i") float field1423; @ObfuscatedName("w") float field1424; @ObfuscatedName("v") float[] field1425; @ObfuscatedName("a") float[] field1426; @ObfuscatedName("y") boolean field1419; @ObfuscatedName("u") @ObfuscatedGetter( intValue = 653716445 ) int field1428; @ObfuscatedName("h") float[] field1429; @ObfuscatedName("q") @ObfuscatedGetter( intValue = -1292100391 ) int field1417; @ObfuscatedName("x") @ObfuscatedGetter( intValue = -1964265085 ) int field1427; @ObfuscatedName("p") float field1431; @ObfuscatedName("n") float field1433; class115() { this.field1425 = new float[4]; // L: 16 this.field1426 = new float[4]; // L: 17 this.field1419 = true; // L: 18 this.field1428 = 0; // L: 19 } // L: 26 @ObfuscatedName("c") @ObfuscatedSignature( descriptor = "(Lpi;II)I", garbageValue = "-1427192972" ) int method2619(Buffer var1, int var2) { int var3 = var1.readUnsignedShort(); // L: 29 class334.method6128(var1.readUnsignedByte()); // L: 30 int var5 = var1.readUnsignedByte(); // L: 32 class114 var6 = (class114)class140.findEnumerated(UrlRequester.method2418(), var5); // L: 34 if (var6 == null) { // L: 35 var6 = class114.field1408; } this.field1422 = var6; // L: 38 int var7 = var1.readUnsignedByte(); // L: 40 class114 var8 = (class114)class140.findEnumerated(UrlRequester.method2418(), var7); // L: 42 if (var8 == null) { // L: 43 var8 = class114.field1408; } this.field1420 = var8; // L: 46 this.field1434 = var1.readUnsignedByte() != 0; // L: 47 this.field1430 = new class111[var3]; // L: 48 class111 var11 = null; // L: 49 int var9; for (var9 = 0; var9 < var3; ++var9) { // L: 50 class111 var10 = new class111(); // L: 51 var10.method2526(var1, var2); // L: 52 this.field1430[var9] = var10; // L: 53 if (var11 != null) { // L: 54 var11.field1383 = var10; // L: 55 } var11 = var10; // L: 57 } this.field1417 = this.field1430[0].field1377; // L: 59 this.field1427 = this.field1430[this.method2617() - 1].field1377; // L: 60 this.field1429 = new float[this.method2622() + 1]; // L: 62 for (var9 = this.method2612(); var9 <= this.method2613(); ++var9) { // L: 63 this.field1429[var9 - this.method2612()] = class127.method2767(this, (float)var9); // L: 64 } this.field1430 = null; // L: 66 this.field1431 = class127.method2767(this, (float)(this.method2612() - 1)); // L: 68 this.field1433 = class127.method2767(this, (float)(this.method2613() + 1)); // L: 69 return var3; // L: 70 } @ObfuscatedName("l") @ObfuscatedSignature( descriptor = "(II)F", garbageValue = "789038903" ) public float method2611(int var1) { if (var1 < this.method2612()) { // L: 75 return this.field1431; // L: 76 } else { return var1 > this.method2613() ? this.field1433 : this.field1429[var1 - this.method2612()]; // L: 78 79 81 } } @ObfuscatedName("s") @ObfuscatedSignature( descriptor = "(I)I", garbageValue = "1770559129" ) int method2612() { return this.field1417; // L: 86 } @ObfuscatedName("e") @ObfuscatedSignature( descriptor = "(I)I", garbageValue = "1803710712" ) int method2613() { return this.field1427; // L: 90 } @ObfuscatedName("r") @ObfuscatedSignature( descriptor = "(I)I", garbageValue = "2138979238" ) int method2622() { return this.method2613() - this.method2612(); // L: 94 } @ObfuscatedName("o") @ObfuscatedSignature( descriptor = "(FB)I", garbageValue = "69" ) int method2615(float var1) { if (this.field1428 < 0 || (float)this.field1430[this.field1428].field1377 > var1 || this.field1430[this.field1428].field1383 != null && (float)this.field1430[this.field1428].field1383.field1377 <= var1) { // L: 98 if (var1 >= (float)this.method2612() && var1 <= (float)this.method2613()) { // L: 101 int var2 = this.method2617(); // L: 104 int var3 = this.field1428; // L: 105 if (var2 > 0) { // L: 106 int var4 = 0; int var5 = var2 - 1; // L: 108 do { int var6 = var4 + var5 >> 1; // L: 110 if (var1 < (float)this.field1430[var6].field1377) { // L: 111 if (var1 > (float)this.field1430[var6 - 1].field1377) { // L: 112 var3 = var6 - 1; // L: 113 break; } var5 = var6 - 1; // L: 117 } else { if (var1 <= (float)this.field1430[var6].field1377) { // L: 120 var3 = var6; // L: 130 break; // L: 131 } if (var1 < (float)this.field1430[var6 + 1].field1377) { // L: 121 var3 = var6; // L: 122 break; // L: 123 } var4 = var6 + 1; // L: 126 } } while(var4 <= var5); // L: 133 } if (var3 != this.field1428) { // L: 135 this.field1428 = var3; // L: 136 this.field1419 = true; // L: 137 } return this.field1428; // L: 139 } else { return -1; // L: 102 } } else { return this.field1428; // L: 99 } } @ObfuscatedName("i") @ObfuscatedSignature( descriptor = "(FI)Ldz;", garbageValue = "-1285668133" ) class111 method2616(float var1) { int var2 = this.method2615(var1); // L: 143 return var2 >= 0 && var2 < this.field1430.length ? this.field1430[var2] : null; // L: 144 145 148 } @ObfuscatedName("w") @ObfuscatedSignature( descriptor = "(B)I", garbageValue = "0" ) int method2617() { return this.field1430 == null ? 0 : this.field1430.length; // L: 153 154 } @ObfuscatedName("e") @ObfuscatedSignature( descriptor = "(B)[Ldp;", garbageValue = "38" ) static class121[] method2620() { return new class121[]{class121.field1483, class121.field1485, class121.field1481, class121.field1487, class121.field1480, class121.field1484, class121.field1479, class121.field1486, class121.field1482}; // L: 107 } @ObfuscatedName("j") @ObfuscatedSignature( descriptor = "(ZI)V", garbageValue = "-596145677" ) public static void method2638(boolean var0) { if (var0 != MilliClock.ItemDefinition_inMembersWorld) { // L: 552 ItemComposition.ItemDefinition_cached.clear(); // L: 554 ItemComposition.ItemDefinition_cachedModels.clear(); // L: 555 ItemComposition.ItemDefinition_cachedSprites.clear(); // L: 556 MilliClock.ItemDefinition_inMembersWorld = var0; // L: 558 } } // L: 560 @ObfuscatedName("g") @ObfuscatedSignature( descriptor = "(ILbl;ZI)I", garbageValue = "-1910308552" ) static int method2637(int var0, Script var1, boolean var2) { String var7; if (var0 == ScriptOpcodes.MES) { // L: 1409 var7 = Interpreter.Interpreter_stringStack[--BufferedNetSocket.Interpreter_stringStackSize]; // L: 1410 LoginScreenAnimation.addGameMessage(0, "", var7); // L: 1411 return 1; // L: 1412 } else if (var0 == ScriptOpcodes.ANIM) { Interpreter.Interpreter_intStackSize -= 2; // L: 1415 ItemContainer.performPlayerAnimation(WorldMapSprite.localPlayer, Interpreter.Interpreter_intStack[Interpreter.Interpreter_intStackSize], Interpreter.Interpreter_intStack[Interpreter.Interpreter_intStackSize + 1]); // L: 1416 return 1; // L: 1417 } else if (var0 == ScriptOpcodes.IF_CLOSE) { if (!Interpreter.field848) { // L: 1420 Interpreter.field846 = true; // L: 1421 } return 1; // L: 1423 } else { int var16; if (var0 == ScriptOpcodes.RESUME_COUNTDIALOG) { var7 = Interpreter.Interpreter_stringStack[--BufferedNetSocket.Interpreter_stringStackSize]; // L: 1426 var16 = 0; // L: 1427 if (class117.isNumber(var7)) { // L: 1428 var16 = UserComparator7.method2464(var7); } PacketBufferNode var14 = class135.getPacketBufferNode(ClientPacket.field2893, Client.packetWriter.isaacCipher); // L: 1430 var14.packetBuffer.writeInt(var16); // L: 1431 Client.packetWriter.addNode(var14); // L: 1432 return 1; // L: 1433 } else { PacketBufferNode var12; if (var0 == ScriptOpcodes.RESUME_NAMEDIALOG) { var7 = Interpreter.Interpreter_stringStack[--BufferedNetSocket.Interpreter_stringStackSize]; // L: 1436 var12 = class135.getPacketBufferNode(ClientPacket.field2894, Client.packetWriter.isaacCipher); // L: 1438 var12.packetBuffer.writeByte(var7.length() + 1); // L: 1439 var12.packetBuffer.writeStringCp1252NullTerminated(var7); // L: 1440 Client.packetWriter.addNode(var12); // L: 1441 return 1; // L: 1442 } else if (var0 == ScriptOpcodes.RESUME_STRINGDIALOG) { var7 = Interpreter.Interpreter_stringStack[--BufferedNetSocket.Interpreter_stringStackSize]; // L: 1445 var12 = class135.getPacketBufferNode(ClientPacket.field2853, Client.packetWriter.isaacCipher); // L: 1447 var12.packetBuffer.writeByte(var7.length() + 1); // L: 1448 var12.packetBuffer.writeStringCp1252NullTerminated(var7); // L: 1449 Client.packetWriter.addNode(var12); // L: 1450 return 1; // L: 1451 } else { String var4; int var10; if (var0 == ScriptOpcodes.OPPLAYER) { var10 = Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize]; // L: 1454 var4 = Interpreter.Interpreter_stringStack[--BufferedNetSocket.Interpreter_stringStackSize]; // L: 1455 ModelData0.method4274(var10, var4); // L: 1456 return 1; // L: 1457 } else if (var0 == ScriptOpcodes.IF_DRAGPICKUP) { Interpreter.Interpreter_intStackSize -= 3; // L: 1460 var10 = Interpreter.Interpreter_intStack[Interpreter.Interpreter_intStackSize]; // L: 1461 var16 = Interpreter.Interpreter_intStack[Interpreter.Interpreter_intStackSize + 1]; // L: 1462 int var9 = Interpreter.Interpreter_intStack[Interpreter.Interpreter_intStackSize + 2]; // L: 1463 Widget var15 = class130.getWidget(var9); // L: 1464 class11.clickWidget(var15, var10, var16); // L: 1465 return 1; // L: 1466 } else if (var0 == ScriptOpcodes.CC_DRAGPICKUP) { Interpreter.Interpreter_intStackSize -= 2; // L: 1469 var10 = Interpreter.Interpreter_intStack[Interpreter.Interpreter_intStackSize]; // L: 1470 var16 = Interpreter.Interpreter_intStack[Interpreter.Interpreter_intStackSize + 1]; // L: 1471 Widget var13 = var2 ? class16.scriptDotWidget : Interpreter.scriptActiveWidget; // L: 1472 class11.clickWidget(var13, var10, var16); // L: 1473 return 1; // L: 1474 } else if (var0 == ScriptOpcodes.MOUSECAM) { class370.mouseCam = Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize] == 1; // L: 1477 return 1; // L: 1478 } else if (var0 == ScriptOpcodes.GETREMOVEROOFS) { Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = class424.clientPreferences.roofsHidden ? 1 : 0; // L: 1481 return 1; // L: 1482 } else if (var0 == ScriptOpcodes.SETREMOVEROOFS) { class424.clientPreferences.roofsHidden = Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize] == 1; // L: 1485 GameEngine.savePreferences(); // L: 1486 return 1; // L: 1487 } else if (var0 == ScriptOpcodes.OPENURL) { var7 = Interpreter.Interpreter_stringStack[--BufferedNetSocket.Interpreter_stringStackSize]; // L: 1490 boolean var8 = Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize] == 1; // L: 1491 MilliClock.openURL(var7, var8, false); // L: 1492 return 1; // L: 1493 } else if (var0 == ScriptOpcodes.RESUME_OBJDIALOG) { var10 = Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize]; // L: 1496 var12 = class135.getPacketBufferNode(ClientPacket.field2906, Client.packetWriter.isaacCipher); // L: 1498 var12.packetBuffer.writeShort(var10); // L: 1499 Client.packetWriter.addNode(var12); // L: 1500 return 1; // L: 1501 } else if (var0 == ScriptOpcodes.BUG_REPORT) { var10 = Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize]; // L: 1504 BufferedNetSocket.Interpreter_stringStackSize -= 2; // L: 1505 var4 = Interpreter.Interpreter_stringStack[BufferedNetSocket.Interpreter_stringStackSize]; // L: 1506 String var5 = Interpreter.Interpreter_stringStack[BufferedNetSocket.Interpreter_stringStackSize + 1]; // L: 1507 if (var4.length() > 500) { // L: 1508 return 1; } else if (var5.length() > 500) { // L: 1509 return 1; } else { PacketBufferNode var6 = class135.getPacketBufferNode(ClientPacket.field2879, Client.packetWriter.isaacCipher); // L: 1510 var6.packetBuffer.writeShort(1 + GrandExchangeEvents.stringCp1252NullTerminatedByteSize(var4) + GrandExchangeEvents.stringCp1252NullTerminatedByteSize(var5)); // L: 1511 var6.packetBuffer.writeStringCp1252NullTerminated(var5); // L: 1512 var6.packetBuffer.writeStringCp1252NullTerminated(var4); // L: 1513 var6.packetBuffer.method7458(var10); // L: 1514 Client.packetWriter.addNode(var6); // L: 1515 return 1; // L: 1516 } } else if (var0 == ScriptOpcodes.SETSHIFTCLICKDROP) { Client.shiftClickDrop = Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize] == 1; // L: 1519 return 1; // L: 1520 } else if (var0 == ScriptOpcodes.SETSHOWMOUSEOVERTEXT) { Client.showMouseOverText = Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize] == 1; // L: 1523 return 1; // L: 1524 } else if (var0 == ScriptOpcodes.RENDERSELF) { Client.renderSelf = Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize] == 1; // L: 1527 return 1; // L: 1528 } else if (var0 == 3120) { if (Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize] == 1) { // L: 1531 Client.drawPlayerNames |= 1; } else { Client.drawPlayerNames &= -2; // L: 1532 } return 1; // L: 1533 } else if (var0 == 3121) { if (Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize] == 1) { // L: 1536 Client.drawPlayerNames |= 2; } else { Client.drawPlayerNames &= -3; // L: 1537 } return 1; // L: 1538 } else if (var0 == 3122) { if (Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize] == 1) { // L: 1541 Client.drawPlayerNames |= 4; } else { Client.drawPlayerNames &= -5; // L: 1542 } return 1; // L: 1543 } else if (var0 == 3123) { if (Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize] == 1) { // L: 1546 Client.drawPlayerNames |= 8; } else { Client.drawPlayerNames &= -9; // L: 1547 } return 1; // L: 1548 } else if (var0 == 3124) { Client.drawPlayerNames = 0; // L: 1551 return 1; // L: 1552 } else if (var0 == ScriptOpcodes.SETSHOWMOUSECROSS) { Client.showMouseCross = Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize] == 1; // L: 1555 return 1; // L: 1556 } else if (var0 == ScriptOpcodes.SETSHOWLOADINGMESSAGES) { Client.showLoadingMessages = Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize] == 1; // L: 1559 return 1; // L: 1560 } else if (var0 == ScriptOpcodes.SETTAPTODROP) { Archive.setTapToDrop(Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize] == 1); // L: 1563 return 1; // L: 1564 } else if (var0 == ScriptOpcodes.GETTAPTODROP) { Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = class126.getTapToDrop() ? 1 : 0; // L: 1567 return 1; // L: 1568 } else if (var0 == 3129) { Interpreter.Interpreter_intStackSize -= 2; // L: 1571 Client.oculusOrbNormalSpeed = Interpreter.Interpreter_intStack[Interpreter.Interpreter_intStackSize]; // L: 1572 Client.oculusOrbSlowedSpeed = Interpreter.Interpreter_intStack[Interpreter.Interpreter_intStackSize + 1]; // L: 1573 return 1; // L: 1574 } else if (var0 == 3130) { Interpreter.Interpreter_intStackSize -= 2; // L: 1577 return 1; // L: 1578 } else if (var0 == 3131) { --Interpreter.Interpreter_intStackSize; // L: 1581 return 1; // L: 1582 } else if (var0 == ScriptOpcodes.GETCANVASSIZE) { Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = DirectByteArrayCopier.canvasWidth; // L: 1585 Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = NPC.canvasHeight; // L: 1586 return 1; // L: 1587 } else if (var0 == ScriptOpcodes.MOBILE_SETFPS) { --Interpreter.Interpreter_intStackSize; // L: 1590 return 1; // L: 1591 } else if (var0 == ScriptOpcodes.MOBILE_OPENSTORE) { return 1; // L: 1594 } else if (var0 == ScriptOpcodes.MOBILE_OPENSTORECATEGORY) { Interpreter.Interpreter_intStackSize -= 2; // L: 1597 return 1; // L: 1598 } else if (var0 == 3136) { Client.field666 = 3; // L: 1601 Client.field667 = Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize]; // L: 1602 return 1; // L: 1603 } else if (var0 == 3137) { Client.field666 = 2; // L: 1606 Client.field667 = Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize]; // L: 1607 return 1; // L: 1608 } else if (var0 == 3138) { Client.field666 = 0; // L: 1611 return 1; // L: 1612 } else if (var0 == 3139) { Client.field666 = 1; // L: 1615 return 1; // L: 1616 } else if (var0 == 3140) { Client.field666 = 3; // L: 1619 Client.field667 = var2 ? class16.scriptDotWidget.id * 98457465 * -180788535 : Interpreter.scriptActiveWidget.id * 98457465 * -180788535; // L: 1620 return 1; // L: 1621 } else { boolean var11; if (var0 == ScriptOpcodes.SETHIDEUSERNAME) { var11 = Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize] == 1; // L: 1624 class424.clientPreferences.hideUsername = var11; // L: 1625 GameEngine.savePreferences(); // L: 1626 return 1; // L: 1627 } else if (var0 == ScriptOpcodes.GETHIDEUSERNAME) { Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = class424.clientPreferences.hideUsername ? 1 : 0; // L: 1630 return 1; // L: 1631 } else if (var0 == ScriptOpcodes.SETREMEMBERUSERNAME) { var11 = Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize] == 1; // L: 1634 Client.Login_isUsernameRemembered = var11; // L: 1635 if (!var11) { // L: 1636 class424.clientPreferences.rememberedUsername = ""; // L: 1637 GameEngine.savePreferences(); // L: 1638 } return 1; // L: 1640 } else if (var0 == ScriptOpcodes.GETREMEMBERUSERNAME) { Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = Client.Login_isUsernameRemembered ? 1 : 0; // L: 1643 return 1; // L: 1644 } else if (var0 == ScriptOpcodes.SHOW_IOS_REVIEW) { return 1; // L: 1647 } else if (var0 == 3146) { var11 = Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize] == 1; // L: 1650 if (var11 == class424.clientPreferences.titleMusicDisabled) { // L: 1651 class424.clientPreferences.titleMusicDisabled = !var11; // L: 1652 GameEngine.savePreferences(); // L: 1653 } return 1; // L: 1655 } else if (var0 == 3147) { Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = class424.clientPreferences.titleMusicDisabled ? 0 : 1; // L: 1658 return 1; // L: 1659 } else if (var0 == 3148) { return 1; // L: 1662 } else if (var0 == 3149) { Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = 0; // L: 1665 return 1; // L: 1666 } else if (var0 == 3150) { Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = 0; // L: 1669 return 1; // L: 1670 } else if (var0 == 3151) { Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = 0; // L: 1673 return 1; // L: 1674 } else if (var0 == 3152) { Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = 0; // L: 1677 return 1; // L: 1678 } else if (var0 == 3153) { Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = Login.Login_loadingPercent; // L: 1681 return 1; // L: 1682 } else if (var0 == 3154) { Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = Actor.method2178(); // L: 1685 return 1; // L: 1686 } else if (var0 == 3155) { --BufferedNetSocket.Interpreter_stringStackSize; // L: 1689 return 1; // L: 1690 } else if (var0 == 3156) { return 1; // L: 1693 } else if (var0 == 3157) { Interpreter.Interpreter_intStackSize -= 2; // L: 1696 return 1; // L: 1697 } else if (var0 == 3158) { Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = 0; // L: 1700 return 1; // L: 1701 } else if (var0 == 3159) { Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = 0; // L: 1704 return 1; // L: 1705 } else if (var0 == 3160) { Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = 0; // L: 1708 return 1; // L: 1709 } else if (var0 == 3161) { --Interpreter.Interpreter_intStackSize; // L: 1712 Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = 0; // L: 1713 return 1; // L: 1714 } else if (var0 == 3162) { --Interpreter.Interpreter_intStackSize; // L: 1717 Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = 0; // L: 1718 return 1; // L: 1719 } else if (var0 == 3163) { --BufferedNetSocket.Interpreter_stringStackSize; // L: 1722 Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = 0; // L: 1723 return 1; // L: 1724 } else if (var0 == 3164) { --Interpreter.Interpreter_intStackSize; // L: 1727 Interpreter.Interpreter_stringStack[++BufferedNetSocket.Interpreter_stringStackSize - 1] = ""; // L: 1728 return 1; // L: 1729 } else if (var0 == 3165) { --Interpreter.Interpreter_intStackSize; // L: 1732 Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = 0; // L: 1733 return 1; // L: 1734 } else if (var0 == 3166) { Interpreter.Interpreter_intStackSize -= 2; // L: 1737 Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = 0; // L: 1738 return 1; // L: 1739 } else if (var0 == 3167) { Interpreter.Interpreter_intStackSize -= 2; // L: 1742 Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = 0; // L: 1743 return 1; // L: 1744 } else if (var0 == 3168) { Interpreter.Interpreter_intStackSize -= 2; // L: 1747 Interpreter.Interpreter_stringStack[++BufferedNetSocket.Interpreter_stringStackSize - 1] = ""; // L: 1748 Interpreter.Interpreter_stringStack[++BufferedNetSocket.Interpreter_stringStackSize - 1] = ""; // L: 1749 Interpreter.Interpreter_stringStack[++BufferedNetSocket.Interpreter_stringStackSize - 1] = ""; // L: 1750 Interpreter.Interpreter_stringStack[++BufferedNetSocket.Interpreter_stringStackSize - 1] = ""; // L: 1751 Interpreter.Interpreter_stringStack[++BufferedNetSocket.Interpreter_stringStackSize - 1] = ""; // L: 1752 Interpreter.Interpreter_stringStack[++BufferedNetSocket.Interpreter_stringStackSize - 1] = ""; // L: 1753 Interpreter.Interpreter_stringStack[++BufferedNetSocket.Interpreter_stringStackSize - 1] = ""; // L: 1754 Interpreter.Interpreter_stringStack[++BufferedNetSocket.Interpreter_stringStackSize - 1] = ""; // L: 1755 Interpreter.Interpreter_stringStack[++BufferedNetSocket.Interpreter_stringStackSize - 1] = ""; // L: 1756 return 1; // L: 1757 } else if (var0 == 3169) { return 1; // L: 1760 } else if (var0 == 3170) { Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = 0; // L: 1763 return 1; // L: 1764 } else if (var0 == 3171) { Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = 0; // L: 1767 return 1; // L: 1768 } else if (var0 == 3172) { --Interpreter.Interpreter_intStackSize; // L: 1771 return 1; // L: 1772 } else if (var0 == 3173) { --Interpreter.Interpreter_intStackSize; // L: 1775 Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = 0; // L: 1776 return 1; // L: 1777 } else if (var0 == 3174) { --Interpreter.Interpreter_intStackSize; // L: 1780 return 1; // L: 1781 } else if (var0 == 3175) { Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = 0; // L: 1784 return 1; // L: 1785 } else if (var0 == 3176) { return 1; // L: 1788 } else if (var0 == 3177) { return 1; // L: 1791 } else if (var0 == 3178) { --BufferedNetSocket.Interpreter_stringStackSize; // L: 1794 return 1; // L: 1795 } else if (var0 == 3179) { return 1; // L: 1798 } else if (var0 == 3180) { --BufferedNetSocket.Interpreter_stringStackSize; // L: 1801 return 1; // L: 1802 } else if (var0 == 3181) { var10 = 100 - Math.min(Math.max(Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize], 0), 100); // L: 1805 LoginType.method7149((double)((float)var10 / 200.0F + 0.5F)); // L: 1806 return 1; // L: 1807 } else if (var0 == 3182) { float var3 = ((float)class424.clientPreferences.brightness - 0.5F) * 200.0F; // L: 1810 Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = 100 - Math.round(var3); // L: 1811 return 1; // L: 1812 } else if (var0 != 3183 && var0 != 3184) { if (var0 == 3187) { BufferedNetSocket.Interpreter_stringStackSize -= 2; // L: 1819 return 1; // L: 1820 } else { return var0 == 3188 ? 1 : 2; // L: 1823 1825 } } else { --Interpreter.Interpreter_intStackSize; // L: 1815 return 1; // L: 1816 } } } } } } }
Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo
REDSI_1160929_1161573/boost_1_67_0/libs/hana/example/ext/std/ratio/arithmetic.cpp
// Copyright <NAME> 2013-2017 // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) #include <boost/hana/assert.hpp> #include <boost/hana/div.hpp> #include <boost/hana/equal.hpp> #include <boost/hana/ext/std/ratio.hpp> #include <boost/hana/minus.hpp> #include <boost/hana/mod.hpp> #include <boost/hana/mult.hpp> #include <boost/hana/one.hpp> #include <boost/hana/plus.hpp> #include <boost/hana/zero.hpp> #include <ratio> namespace hana = boost::hana; BOOST_HANA_CONSTANT_CHECK(hana::equal( hana::plus(std::ratio<5, 3>{}, std::ratio<3, 12>{}), std::ratio<23, 12>{} )); BOOST_HANA_CONSTANT_CHECK(hana::equal( hana::minus(std::ratio<5, 3>{}, std::ratio<3, 13>{}), std::ratio<56, 39>{} )); BOOST_HANA_CONSTANT_CHECK(hana::equal( hana::mult(std::ratio<5, 3>{}, std::ratio<3, 13>{}), std::ratio<15, 39>{} )); BOOST_HANA_CONSTANT_CHECK(hana::equal( hana::div(std::ratio<5, 3>{}, std::ratio<3, 13>{}), std::ratio<65, 9>{} )); // The mod of two ratios is always 0, because they can always be // divided without remainder. BOOST_HANA_CONSTANT_CHECK(hana::equal( hana::mod(std::ratio<5, 3>{}, std::ratio<3, 13>{}), std::ratio<0>{} )); BOOST_HANA_CONSTANT_CHECK(hana::equal( hana::zero<hana::ext::std::ratio_tag>(), std::ratio<0>{} )); BOOST_HANA_CONSTANT_CHECK(hana::equal( hana::one<hana::ext::std::ratio_tag>(), std::ratio<1>{} )); int main() { }
upallnightcoding/Xgl
XglTestProgram/src/XglNodeProgram.h
#pragma once #include "XglNode.h" #include "XglValue.h" #include "XglContext.h" class XglNodeProgram : public XglNode { public: XglNodeProgram(XglNode *codeBlock); virtual ~XglNodeProgram(); public: virtual XglValue *execute(XglContext *context); private: XglNode *codeBlock; };
memtrip/SQLKing
preprocessor/src/main/resources/Q.java
<filename>preprocessor/src/main/resources/Q.java package com.memtrip.sqlking.gen; import android.database.Cursor; import android.content.ContentValues; import com.memtrip.sqlking.common.SQLQuery; import com.memtrip.sqlking.common.Resolver; import java.util.List; import java.util.ArrayList; public class Q { public static class DefaultResolver implements Resolver { @Override public SQLQuery getSQLQuery(Class<?> classDef) { <#assign isAssignableFrom> <#list tables as table> } else if (classDef.isAssignableFrom(${table.getPackage()}.${table.getName()}.class)) { return new ${table.getName()}(); </#list> } </#assign> ${isAssignableFrom?trim?remove_beginning("} else ")} else { throw new IllegalStateException("Please ensure all SQL tables are annotated with @Table"); } } } <#list tables as table> <#assign getColumnNames> <#list table.getMutableColumns(tables) as column> "${table.getName()}.${column.getName()}", </#list> </#assign> <#assign unionInsertColumnNames><#list table.getMutableColumns(tables) as column>${column.getName()},</#list></#assign> <#assign packagedTableName> ${table.getPackage()}.${table.getName()} </#assign> public static class ${table.getName()} implements SQLQuery { <#list table.getColumns() as column> public static final String ${formatConstant(column.getName())} = "${column.getName()}"; </#list> @Override public String getTableName() { return "${table.getName()}"; } @Override public String getTableInsertQuery() { return ${assembleCreateTable(table, tables)} } @Override public String[] getIndexNames() { return new String[]{ <#list table.getMutableColumns(tables) as column> <#if column.isIndex()> "${table.getName()}_${column.getName()}_index", </#if> </#list> }; } @Override public String getCreateIndexQuery() { StringBuilder sb = new StringBuilder(); <#list table.getMutableColumns(tables) as column> <#if column.isIndex()> sb.append("CREATE INDEX ${table.getName()}_${column.getName()}_index ON ${table.getName()} (${column.getName()});"); </#if> </#list> return (sb.length() > 0) ? sb.toString() : null; } @Override public String[] buildUnionInsertQuery(Object[] modelsToInsert) { List<List<Object>> chunks = new ArrayList<>(); List<Object> models = new ArrayList<>(); for (int i = 0; i < modelsToInsert.length; i++) { models.add(modelsToInsert[i]); if ((i+1) % 500 == 0) { chunks.add(new ArrayList<>(models)); models.clear(); } } if (models.size() > 0) { chunks.add(models); } String[] unionInsertQueries = new String[chunks.size()]; for (int i = 0; i < chunks.size(); i++) { unionInsertQueries[i] = buildInsertQuery(chunks.get(i)); } return unionInsertQueries; } private String buildInsertQuery(List<Object> models) { StringBuilder sb = new StringBuilder(); sb.append("INSERT INTO ${table.getName()} "); for (int i = 0; i < models.size(); i++) { ${packagedTableName} ${table.getName()?lower_case} = (${packagedTableName})models.get(i); if (i == 0){ sb.append("(${unionInsertColumnNames?remove_ending(",")}) "); sb.append("SELECT "); <#list table.getMutableColumns(tables) as column> <#assign getter> ${table.getName()?lower_case}.get${column.getName()?cap_first}() </#assign> sb.append("${getInsertValue(column,getter)} AS ${column.getName()}, "); </#list> sb.delete(sb.length()-2,sb.length()); } else { sb.append(" UNION ALL SELECT "); <#list table.getMutableColumns(tables) as column> <#assign getter> ${table.getName()?lower_case}.get${column.getName()?cap_first}() </#assign> sb.append("${getInsertValue(column,getter)}, "); </#list> sb.delete(sb.length()-2,sb.length()); } } return sb.toString(); } private String assembleBlob(byte[] val) { if (val != null) { StringBuilder sb = new StringBuilder(); for (byte b : val) sb.append(String.format("%02X ", b)); return sb.toString(); } else { return "NULL"; } } @Override public List<${packagedTableName}> retrieveSQLSelectResults(Cursor cursor) { List<${packagedTableName}> result = new ArrayList<>(); cursor.moveToFirst(); for (int i = 0; !cursor.isAfterLast(); i++) { ${packagedTableName} ${table.getName()?lower_case} = new ${packagedTableName}(); ${joinReferences(table.getName(),tables)} for (int x = 0; x < cursor.getColumnCount(); x++) { <#assign retrieveSQLSelectResults> <#list table.getColumns() as column> <#if column.isJoinable(tables)> ${join(column.getClassName(),tables)} <#else> } else if (cursor.getColumnName(x).equals(${formatConstant(column.getName())})) { ${table.getName()?lower_case}.set${column.getName()?cap_first}(${getCursorGetter(column.getType())}); </#if> </#list> } </#assign> ${retrieveSQLSelectResults?trim?remove_beginning("} else ")} } result.add(${table.getName()?lower_case}); cursor.moveToNext(); } cursor.close(); return result; } @Override public String[] getColumnNames() { return new String[]{${getColumnNames?remove_ending(",")}}; } @Override public ContentValues getContentValues(Object model) { ${packagedTableName} ${table.getName()?lower_case} = (${packagedTableName})model; ContentValues contentValues = new ContentValues(); <#list table.getMutableColumns(tables) as column> contentValues.put(${formatConstant(column.getName())}, ${table.getName()?lower_case}.get${column.getName()?cap_first}()); </#list> return contentValues; } } </#list> }
mattantonelli/ffxiv-collect
app/models/character_record.rb
<reponame>mattantonelli/ffxiv-collect # == Schema Information # # Table name: character_records # # id :bigint(8) not null, primary key # character_id :integer # record_id :integer # created_at :datetime not null # updated_at :datetime not null # class CharacterRecord < ApplicationRecord belongs_to :character, counter_cache: :records_count, touch: true belongs_to :record end
louisdem/IMKit
trunk/preflet/main.cpp
<reponame>louisdem/IMKit /* * Copyright 2003-2008, IM Kit Team. * Distributed under the terms of the MIT License. * * Authors: * <NAME> <<EMAIL>> */ #include "PApplication.h" int main(int argc, char* argv[]) { PApplication app; app.Run(); return 0; }
trekmedics/beacon
app/controllers/administrators_controller.rb
class AdministratorsController < AdministrativeInterfaceController before_action :set_administrator, only: [:show, :edit, :update, :destroy] # GET /administrators def index @administrators = Administrator.find_by_data_center(current_user.data_center).all end # GET /administrators/new def new @administrator = Administrator.new(data_center: current_user.data_center) end # GET /administrators/1/edit def edit end # POST /administrators def create @administrator = Administrator.new(administrator_params.merge(data_center: current_user.data_center)) if @administrator.save redirect_to administrators_path, notice: I18n.t('activerecord.notices.models.administrator.success.create') else render :new end end # PATCH/PUT /administrators/1 def update if @administrator.update(administrator_params) redirect_to administrators_path, notice: I18n.t('activerecord.notices.models.administrator.success.update') else render :edit end end # DELETE /administrators/1 def destroy @administrator.destroy redirect_to administrators_url, notice: I18n.t('activerecord.notices.models.administrator.success.destroy') end private # Use callbacks to share common setup or constraints between actions. def set_administrator @administrator = Administrator.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def administrator_params return self.params.require(:administrator).permit(:name, :phone_number, :email) end end
felixbinder/tdw
Python/tdw/FBOutput/ImageSensors.py
# automatically generated by the FlatBuffers compiler, do not modify # namespace: FBOutput import tdw.flatbuffers class ImageSensors(object): __slots__ = ['_tab'] @classmethod def GetRootAsImageSensors(cls, buf, offset): n = tdw.flatbuffers.encode.Get(tdw.flatbuffers.packer.uoffset, buf, offset) x = ImageSensors() x.Init(buf, n + offset) return x # ImageSensors def Init(self, buf, pos): self._tab = tdw.flatbuffers.table.Table(buf, pos) # ImageSensors def AvatarId(self): o = tdw.flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) if o != 0: return self._tab.String(o + self._tab.Pos) return None # ImageSensors def Sensors(self, j): o = tdw.flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) if o != 0: x = self._tab.Vector(o) x += tdw.flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 x = self._tab.Indirect(x) from .ImageSensor import ImageSensor obj = ImageSensor() obj.Init(self._tab.Bytes, x) return obj return None # ImageSensors def SensorsLength(self): o = tdw.flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) if o != 0: return self._tab.VectorLen(o) return 0 def ImageSensorsStart(builder): builder.StartObject(2) def ImageSensorsAddAvatarId(builder, avatarId): builder.PrependUOffsetTRelativeSlot(0, tdw.flatbuffers.number_types.UOffsetTFlags.py_type(avatarId), 0) def ImageSensorsAddSensors(builder, sensors): builder.PrependUOffsetTRelativeSlot(1, tdw.flatbuffers.number_types.UOffsetTFlags.py_type(sensors), 0) def ImageSensorsStartSensorsVector(builder, numElems): return builder.StartVector(4, numElems, 4) def ImageSensorsEnd(builder): return builder.EndObject()
rohinigaonkar/deltacloud
clients/cimi/lib/entities/network.rb
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. The # ASF licenses this file to you 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. class CIMI::Frontend::Network < CIMI::Frontend::Entity get '/cimi/networks/:id' do network_xml = get_entity('networks', params[:id], credentials) @network = CIMI::Model::Network.from_xml(network_xml) haml :'networks/show' end get '/cimi/networks' do forwarding_groups_xml = get_entity_collection('forwarding_groups', credentials) @forwarding_groups = CIMI::Model::ForwardingGroupCollection.from_xml(forwarding_groups_xml) network_config_xml = get_entity_collection('network_configurations', credentials) @network_configurations = CIMI::Model::NetworkConfigurationCollection.from_xml(network_config_xml) networks_xml = get_entity_collection('networks', credentials) @networks = CIMI::Model::NetworkCollection.from_xml(networks_xml) haml :'networks/index' end post '/cimi/networks' do network_xml = Nokogiri::XML::Builder.new do |xml| xml.Network(:xmlns => CIMI::Frontend::CMWG_NAMESPACE) { xml.name params[:network][:name] xml.description params[:network][:description] xml.networkTemplate { xml.networkConfig( :href => params[:network][:network_configuration] ) xml.forwardingGroup( :href => params[:network][:forwarding_group] ) } } end.to_xml begin result = create_entity('networks', network_xml, credentials) network = CIMI::Model::NetworkCollection.from_xml(result) flash[:success] = "Network was successfully created." redirect "/cimi/networks/#{network.name}", 302 rescue => e flash[:error] = "Network cannot be created: #{e.message}" end end end
StefanRomanov/Ask-Me-Anything
back-end/util/pagination.js
<reponame>StefanRomanov/Ask-Me-Anything module.exports = (page, pageSize ) => { const offset = page * pageSize; const limit = pageSize; return { offset, limit, } };
Sajaki/intellij-community
python/python-psi-api/src/com/jetbrains/python/PyTokenTypes.java
/* * Copyright 2000-2014 JetBrains s.r.o. * * 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.jetbrains.python; import com.intellij.psi.TokenType; import com.intellij.psi.tree.IElementType; import com.intellij.psi.tree.TokenSet; import com.jetbrains.python.psi.PyElementType; public class PyTokenTypes { private PyTokenTypes() { } public static final PyElementType IDENTIFIER = new PyElementType("IDENTIFIER"); public static final PyElementType LINE_BREAK = new PyElementType("LINE_BREAK"); public static final PyElementType STATEMENT_BREAK = new PyElementType("STATEMENT_BREAK"); public static final PyElementType SPACE = new PyElementType("SPACE"); public static final PyElementType TAB = new PyElementType("TAB"); public static final PyElementType FORMFEED = new PyElementType("FORMFEED"); public static final IElementType BAD_CHARACTER = TokenType.BAD_CHARACTER; public static final PyElementType INCONSISTENT_DEDENT = new PyElementType("INCONSISTENT_DEDENT"); public static final PyElementType END_OF_LINE_COMMENT = new PyElementType("END_OF_LINE_COMMENT"); public static final PyElementType AND_KEYWORD = new PyElementType("AND_KEYWORD"); public static final PyElementType AS_KEYWORD = new PyElementType("AS_KEYWORD"); public static final PyElementType ASSERT_KEYWORD = new PyElementType("ASSERT_KEYWORD"); public static final PyElementType BREAK_KEYWORD = new PyElementType("BREAK_KEYWORD"); public static final PyElementType CLASS_KEYWORD = new PyElementType("CLASS_KEYWORD"); public static final PyElementType CONTINUE_KEYWORD = new PyElementType("CONTINUE_KEYWORD"); public static final PyElementType DEF_KEYWORD = new PyElementType("DEF_KEYWORD"); public static final PyElementType DEL_KEYWORD = new PyElementType("DEL_KEYWORD"); public static final PyElementType ELIF_KEYWORD = new PyElementType("ELIF_KEYWORD"); public static final PyElementType ELSE_KEYWORD = new PyElementType("ELSE_KEYWORD"); public static final PyElementType EXCEPT_KEYWORD = new PyElementType("EXCEPT_KEYWORD"); public static final PyElementType EXEC_KEYWORD = new PyElementType("EXEC_KEYWORD"); public static final PyElementType FINALLY_KEYWORD = new PyElementType("FINALLY_KEYWORD"); public static final PyElementType FOR_KEYWORD = new PyElementType("FOR_KEYWORD"); public static final PyElementType FROM_KEYWORD = new PyElementType("FROM_KEYWORD"); public static final PyElementType GLOBAL_KEYWORD = new PyElementType("GLOBAL_KEYWORD"); public static final PyElementType IF_KEYWORD = new PyElementType("IF_KEYWORD"); public static final PyElementType IMPORT_KEYWORD = new PyElementType("IMPORT_KEYWORD"); public static final PyElementType IN_KEYWORD = new PyElementType("IN_KEYWORD", "__contains__"); public static final PyElementType IS_KEYWORD = new PyElementType("IS_KEYWORD"); public static final PyElementType LAMBDA_KEYWORD = new PyElementType("LAMBDA_KEYWORD"); public static final PyElementType NOT_KEYWORD = new PyElementType("NOT_KEYWORD"); public static final PyElementType OR_KEYWORD = new PyElementType("OR_KEYWORD"); public static final PyElementType PASS_KEYWORD = new PyElementType("PASS_KEYWORD"); public static final PyElementType PRINT_KEYWORD = new PyElementType("PRINT_KEYWORD"); public static final PyElementType RAISE_KEYWORD = new PyElementType("RAISE_KEYWORD"); public static final PyElementType RETURN_KEYWORD = new PyElementType("RETURN_KEYWORD"); public static final PyElementType TRY_KEYWORD = new PyElementType("TRY_KEYWORD"); public static final PyElementType WITH_KEYWORD = new PyElementType("WITH_KEYWORD"); public static final PyElementType WHILE_KEYWORD = new PyElementType("WHILE_KEYWORD"); public static final PyElementType YIELD_KEYWORD = new PyElementType("YIELD_KEYWORD"); // new keywords in Python 3 public static final PyElementType NONE_KEYWORD = new PyElementType("NONE_KEYWORD"); public static final PyElementType TRUE_KEYWORD = new PyElementType("TRUE_KEYWORD"); public static final PyElementType FALSE_KEYWORD = new PyElementType("FALSE_KEYWORD"); public static final PyElementType NONLOCAL_KEYWORD = new PyElementType("NONLOCAL_KEYWORD"); public static final PyElementType DEBUG_KEYWORD = new PyElementType("DEBUG_KEYWORD"); public static final PyElementType ASYNC_KEYWORD = new PyElementType("ASYNC_KEYWORD"); public static final PyElementType AWAIT_KEYWORD = new PyElementType("AWAIT_KEYWORD", "__await__"); public static final PyElementType INTEGER_LITERAL = new PyElementType("INTEGER_LITERAL"); public static final PyElementType FLOAT_LITERAL = new PyElementType("FLOAT_LITERAL"); public static final PyElementType IMAGINARY_LITERAL = new PyElementType("IMAGINARY_LITERAL"); public static final PyElementType SINGLE_QUOTED_STRING = new PyElementType("SINGLE_QUOTED_STRING"); public static final PyElementType TRIPLE_QUOTED_STRING = new PyElementType("TRIPLE_QUOTED_STRING"); public static final PyElementType SINGLE_QUOTED_UNICODE = new PyElementType("SINGLE_QUOTED_UNICODE"); public static final PyElementType TRIPLE_QUOTED_UNICODE = new PyElementType("TRIPLE_QUOTED_UNICODE"); public static final PyElementType DOCSTRING = new PyElementType("DOCSTRING"); public static final TokenSet UNICODE_NODES = TokenSet.create(TRIPLE_QUOTED_UNICODE, SINGLE_QUOTED_UNICODE); public static final TokenSet TRIPLE_NODES = TokenSet.create(TRIPLE_QUOTED_UNICODE, TRIPLE_QUOTED_STRING); public static final TokenSet STRING_NODES = TokenSet.orSet(UNICODE_NODES, TokenSet.create(SINGLE_QUOTED_STRING, TRIPLE_QUOTED_STRING, DOCSTRING)); // Operators public static final PyElementType PLUS = new PyElementType("PLUS", "__add__");// + public static final PyElementType MINUS = new PyElementType("MINUS", "__sub__");// - public static final PyElementType MULT = new PyElementType("MULT", "__mul__");// * public static final PyElementType EXP = new PyElementType("EXP", "__pow__");// ** public static final PyElementType DIV = new PyElementType("DIV", "__div__"); // / public static final PyElementType FLOORDIV = new PyElementType("FLOORDIV", "__floordiv__"); // // public static final PyElementType PERC = new PyElementType("PERC", "__mod__");// % public static final PyElementType LTLT = new PyElementType("LTLT", "__lshift__");// << public static final PyElementType GTGT = new PyElementType("GTGT", "__rshift__");// >> public static final PyElementType AND = new PyElementType("AND", "__and__");// & public static final PyElementType OR = new PyElementType("OR", "__or__");// | public static final PyElementType XOR = new PyElementType("XOR", "__xor__");// ^ public static final PyElementType TILDE = new PyElementType("TILDE", "__invert__");// ~ public static final PyElementType LT = new PyElementType("LT", "__lt__");// < public static final PyElementType GT = new PyElementType("GT", "__gt__");// > public static final PyElementType LE = new PyElementType("LE", "__le__");// <= public static final PyElementType GE = new PyElementType("GE", "__ge__");// >= public static final PyElementType EQEQ = new PyElementType("EQEQ", "__eq__");// == public static final PyElementType NE = new PyElementType("NE", "__ne__");// != public static final PyElementType NE_OLD = new PyElementType("NE_OLD", "__ne__");// <> // Delimiters public static final PyElementType LPAR = new PyElementType("LPAR");// ( public static final PyElementType RPAR = new PyElementType("RPAR");// ) public static final PyElementType LBRACKET = new PyElementType("LBRACKET");// [ public static final PyElementType RBRACKET = new PyElementType("RBRACKET");// ] public static final PyElementType LBRACE = new PyElementType("LBRACE");// { public static final PyElementType RBRACE = new PyElementType("RBRACE");// } public static final PyElementType AT = new PyElementType("AT", "__matmul__");// @ public static final PyElementType COMMA = new PyElementType("COMMA");// , public static final PyElementType COLON = new PyElementType("COLON");// : public static final PyElementType DOT = new PyElementType("DOT");// . public static final PyElementType TICK = new PyElementType("TICK");// ` public static final PyElementType EQ = new PyElementType("EQ");// = public static final PyElementType SEMICOLON = new PyElementType("SEMICOLON");// ; public static final PyElementType PLUSEQ = new PyElementType("PLUSEQ");// += public static final PyElementType MINUSEQ = new PyElementType("MINUSEQ");// -= public static final PyElementType MULTEQ = new PyElementType("MULTEQ");// *= public static final PyElementType ATEQ = new PyElementType("ATEQ"); // @= public static final PyElementType DIVEQ = new PyElementType("DIVEQ"); // /= public static final PyElementType FLOORDIVEQ = new PyElementType("FLOORDIVEQ"); // //= public static final PyElementType PERCEQ = new PyElementType("PERCEQ");// %= public static final PyElementType ANDEQ = new PyElementType("ANDEQ");// &= public static final PyElementType OREQ = new PyElementType("OREQ");// |= public static final PyElementType XOREQ = new PyElementType("XOREQ");// ^= public static final PyElementType LTLTEQ = new PyElementType("LTLTEQ");// <<= public static final PyElementType GTGTEQ = new PyElementType("GTGTEQ");// >>= public static final PyElementType EXPEQ = new PyElementType("EXPEQ");// **= public static final PyElementType RARROW = new PyElementType("RARROW");// -> public static final PyElementType COLONEQ = new PyElementType("COLONEQ");// := public static final TokenSet OPERATIONS = TokenSet.create( PLUS, MINUS, MULT, AT, EXP, DIV, FLOORDIV, PERC, LTLT, GTGT, AND, OR, XOR, TILDE, LT, GT, LE, GE, EQEQ, NE, NE_OLD, AT, COLON, TICK, EQ, PLUSEQ, MINUSEQ, MULTEQ, ATEQ, DIVEQ, FLOORDIVEQ, PERCEQ, ANDEQ, OREQ, XOREQ, LTLTEQ, GTGTEQ, EXPEQ, COLONEQ); public static final TokenSet COMPARISON_OPERATIONS = TokenSet.create( LT, GT, EQEQ, GE, LE, NE, NE_OLD, IN_KEYWORD, IS_KEYWORD, NOT_KEYWORD); public static final TokenSet SHIFT_OPERATIONS = TokenSet.create(LTLT, GTGT); public static final TokenSet ADDITIVE_OPERATIONS = TokenSet.create(PLUS, MINUS); public static final TokenSet MULTIPLICATIVE_OPERATIONS = TokenSet.create(MULT, AT, FLOORDIV, DIV, PERC); public static final TokenSet STAR_OPERATORS = TokenSet.create(MULT, EXP); public static final TokenSet UNARY_OPERATIONS = TokenSet.create(PLUS, MINUS, TILDE); public static final TokenSet BITWISE_OPERATIONS = TokenSet.create(AND, OR, XOR); public static final TokenSet EQUALITY_OPERATIONS = TokenSet.create(EQEQ, NE, NE_OLD); public static final TokenSet RELATIONAL_OPERATIONS = TokenSet.create(LT, GT, LE, GE); public static final TokenSet END_OF_STATEMENT = TokenSet.create(STATEMENT_BREAK, SEMICOLON); public static final TokenSet WHITESPACE = TokenSet.create(SPACE, TAB, FORMFEED); public static final TokenSet WHITESPACE_OR_LINEBREAK = TokenSet.create(SPACE, TAB, FORMFEED, LINE_BREAK); public static final TokenSet OPEN_BRACES = TokenSet.create(LBRACKET, LBRACE, LPAR); public static final TokenSet CLOSE_BRACES = TokenSet.create(RBRACKET, RBRACE, RPAR); public static final TokenSet NUMERIC_LITERALS = TokenSet.create(FLOAT_LITERAL, INTEGER_LITERAL, IMAGINARY_LITERAL); public static final TokenSet BOOL_LITERALS = TokenSet.create(TRUE_KEYWORD, FALSE_KEYWORD); public static final TokenSet SCALAR_LITERALS = TokenSet.orSet(BOOL_LITERALS, NUMERIC_LITERALS, TokenSet.create(NONE_KEYWORD)); public static final TokenSet EXPRESSION_KEYWORDS = TokenSet.create(TRUE_KEYWORD, FALSE_KEYWORD, NONE_KEYWORD); public static final TokenSet AUG_ASSIGN_OPERATIONS = TokenSet.create(PLUSEQ, MINUSEQ, MULTEQ, ATEQ, DIVEQ, PERCEQ, EXPEQ, GTGTEQ, LTLTEQ, ANDEQ, OREQ, XOREQ, FLOORDIVEQ); public static final PyElementType BACKSLASH = new PyElementType("BACKSLASH"); public static final PyElementType INDENT = new PyElementType("INDENT"); public static final PyElementType DEDENT = new PyElementType("DEDENT"); public static final PyElementType FSTRING_TEXT = new PyElementType("FSTRING_TEXT"); public static final PyElementType FSTRING_RAW_TEXT = new PyElementType("FSTRING_RAW_TEXT"); public static final PyElementType FSTRING_START = new PyElementType("FSTRING_START"); public static final PyElementType FSTRING_END = new PyElementType("FSTRING_END"); public static final PyElementType FSTRING_FRAGMENT_START = new PyElementType("FSTRING_FRAGMENT_START"); public static final PyElementType FSTRING_FRAGMENT_END = new PyElementType("FSTRING_FRAGMENT_END"); public static final PyElementType FSTRING_FRAGMENT_FORMAT_START = new PyElementType("FSTRING_FRAGMENT_FORMAT_START"); public static final PyElementType FSTRING_FRAGMENT_TYPE_CONVERSION = new PyElementType("FSTRING_FRAGMENT_TYPE_CONVERSION"); public static final TokenSet FSTRING_TOKENS = TokenSet.create(FSTRING_TEXT, FSTRING_START, FSTRING_END, FSTRING_FRAGMENT_START, FSTRING_FRAGMENT_END, FSTRING_FRAGMENT_FORMAT_START, FSTRING_FRAGMENT_TYPE_CONVERSION); public static final TokenSet FSTRING_TEXT_TOKENS = TokenSet.create(FSTRING_TEXT, FSTRING_RAW_TEXT); }
tudorv91/SparkJNI
sparkjni-examples/src/main/java/sparkJNIPi/SparkJNIPi.java
<filename>sparkjni-examples/src/main/java/sparkJNIPi/SparkJNIPi.java<gh_stars>10-100 package sparkJNIPi; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.api.java.function.Function; import org.apache.spark.api.java.function.Function2; import sparkjni.utils.DeployMode; import sparkjni.utils.SparkJni; import sparkjni.utils.SparkJniBuilder; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.List; import static sparkjni.utils.DeployMode.DeployModes.JUST_BUILD; public class SparkJNIPi { public static String appName = "SparkJNIPi"; private static int slices = 8; private static int sliceSize = 10000000; private static int noExecs = 1; private static String logFilePath = "/home/tudor/dev/SparkJNI/cppSrc/examples/SparkJNIPi/SparkJNIPi.log"; private static String nativeDirPath = "/home/tudor/dev/SparkJNI/cppSrc/examples/SparkJNIPi"; private static JavaSparkContext jscSingleton; public static void main(String[] args) { String nativeLibPath = initSparkJni(args); long start = System.currentTimeMillis(); List<Integer> input = getInputMocks(slices); JavaRDD<RandNumArray> piBeanJavaRDD = getSparkContext().parallelize(input).map(callSparkJNIPiNativeFunction); JavaRDD<SumArray> intermediateResult = piBeanJavaRDD.map(new RandOpenclPiMap(nativeLibPath, "randToSum")); SumArray result = intermediateResult.reduce(reduceCountPi); computePiAndLog(result, start); } private static String initSparkJni(String[] args) { slices = args.length > 0 ? Integer.parseInt(args[0]) : 4; sliceSize = args.length > 1 ? Integer.parseInt(args[1]) : 4194304; noExecs = args.length > 2 ? Integer.parseInt(args[2]) : 1; SparkJni sparkJni = new SparkJniBuilder() .appName(appName) .nativePath(nativeDirPath) .build(); sparkJni.registerContainer(RandNumArray.class); sparkJni.registerContainer(SumArray.class); sparkJni.registerJniFunction(RandOpenclPiMap.class); sparkJni.setUserIncludeDirs("OpenCL"); sparkJni.setDeployMode(new DeployMode(JUST_BUILD)) .setSparkContext(getSparkContext()) .deploy(); return String.format("%s/%s.so", nativeDirPath, appName); } private static void computePiAndLog(SumArray result, long start){ int sum = 0; for (int i = 0; i < sliceSize; i++) { sum += result.sum[i]; } float PI = ((float) sum * 4.0f) / (sliceSize * slices); long end = System.currentTimeMillis(); log((end - start) / 1000.0f, slices, sliceSize, String.format("local[%d]", noExecs)); System.out.println("Result: " + PI + " in " + (end - start) / 1000.0f + " seconds"); } private static List<Integer> getInputMocks(int slices) { List<Integer> input = new ArrayList<>(); for (int i = 0; i < slices; i++) input.add(i); return input; } private static void log(Float duration, int noSlices, int sliceSize, String local) { String logLine = String.format("SparkJNIPi, %s, %d, %d, %s\n", local, noSlices, sliceSize, duration.toString()); try { Files.write(Paths.get(logFilePath), logLine.getBytes(), StandardOpenOption.APPEND); } catch (IOException e) { e.printStackTrace(); } } private static Function<Integer, RandNumArray> callSparkJNIPiNativeFunction = new Function<Integer, RandNumArray>() { @Override public RandNumArray call(Integer integer) throws Exception { float[] aux = new float[sliceSize * 2]; for (int bIdx = 0; bIdx < sliceSize * 2; bIdx++) { aux[bIdx] = (float) Math.random(); } return new RandNumArray(aux); } }; private static Function2<SumArray, SumArray, SumArray> reduceCountPi = new Function2<SumArray, SumArray, SumArray>() { @Override public SumArray call(SumArray sum1, SumArray sum2) throws Exception { for (int idx = 0; idx < sum1.sum.length; idx++) sum1.sum[idx] += sum2.sum[idx]; return sum1; } }; public static JavaSparkContext getSparkContext() { if (jscSingleton == null) { SparkConf sparkConf = new SparkConf().setAppName(appName); sparkConf.setMaster(String.format("local[%d]", noExecs)) .setExecutorEnv("spark.executor.memory", "4g").setExecutorEnv("spark.driver.memory", "4g").validateSettings(); jscSingleton = new JavaSparkContext(sparkConf); } return jscSingleton; } }
coder-qi/leetcode-algs
src/main/CountingBits.java
<reponame>coder-qi/leetcode-algs import java.util.Arrays; /** * 338. 比特位计数:https://leetcode-cn.com/problems/counting-bits/ */ public class CountingBits { public static int[] countBits(int n) { int[] result = new int[n + 1]; for (int i = 0; i <= n; i++) { result[i] = i % 2 == 0 ? result[i / 2] : result[i / 2] + 1; } return result; } public static void main(String[] args) { System.out.println(Arrays.toString(countBits(2))); // [0,1,1] System.out.println(Arrays.toString(countBits(5))); // [0,1,1] } }
achilex/MgDev
Oem/dbxml/dbxml/src/utils/shell/QueryCommand.cpp
// // See the file LICENSE for redistribution information. // // Copyright (c) 2002,2009 Oracle. All rights reserved. // // #include "QueryCommand.hpp" #include <sstream> using namespace DbXml; using namespace std; string QueryCommand::getCommandName() const { return "query"; } string QueryCommand::getBriefHelp() const { return "Execute the given query expression, or the default pre-parsed query"; } string QueryCommand::getMoreHelp() const { return string("Usage: query [queryExpression]\n") + string("This command uses the XmlManager::query() method."); } static string showErrorContext(const XmlException &e, const char *query) { ostringstream msg; msg << e.what(); if(e.getQueryLine() != 0 && e.getQueryFile() == 0) { msg << endl; int line = 1; while(line != e.getQueryLine() && *query != 0) { if(*query == '\n' || (*query == '\r' && *(query + 1) != '\n')) ++line; ++query; } if(line == e.getQueryLine()) { while(*query != 0) { msg << (*query); if(*query == '\n' || (*query == '\r' && *(query + 1) != '\n')) break; ++query; } if(e.getQueryColumn() != 0) { if(*query == 0) msg << endl; msg << string(e.getQueryColumn() - 1, ' ') << "^"; } } } return msg.str(); } void QueryCommand::execute(Args &args, Environment &env) { if(args.size() > 2) { throw CommandException("Wrong number of arguments"); } string query; if(args.size() == 1) { env.testQuery(); query = env.query()->getQuery(); } else { query = args[1]; } u_int32_t flags = DBXML_LAZY_DOCS; if(env.documentProjection()) flags |= DBXML_DOCUMENT_PROJECTION; XmlResults *newResults = 0; try { if(env.txn()) { if(args.size() == 1) { newResults = new XmlResults(env.query()->execute(*env.txn(), env.context(), flags)); } else { newResults = new XmlResults(env.db().query(*env.txn(), args[1], env.context(), flags)); } } else { if(args.size() == 1) { newResults = new XmlResults(env.query()->execute(env.context(), flags)); } else { newResults = new XmlResults(env.db().query(args[1], env.context(), flags)); } } } catch(XmlException &e) { if(e.getExceptionCode() == XmlException::OPERATION_INTERRUPTED) env.sigBlock().reset(); throw CommandException(showErrorContext(e, query.c_str())); } env.deleteResults(); env.results() = newResults; if(env.context().getEvaluationType() == XmlQueryContext::Eager) { if(env.verbose()) cout << (unsigned int) env.results()->size() << " objects returned for eager expression '" << query << "'" << endl << endl; } else { if(env.verbose()) cout << "Lazy expression '" << query << "' completed" << endl << endl; } }
jainsakshi2395/linux
arch/ia64/include/asm/xtp.h
<gh_stars>10-100 /* SPDX-License-Identifier: GPL-2.0 */ #ifndef _ASM_IA64_XTP_H #define _ASM_IA64_XTP_H #include <asm/io.h> #ifdef CONFIG_SMP #define XTP_OFFSET 0x1e0008 #define SMP_IRQ_REDIRECTION (1 << 0) #define SMP_IPI_REDIRECTION (1 << 1) extern unsigned char smp_int_redirect; /* * XTP control functions: * min_xtp : route all interrupts to this CPU * normal_xtp: nominal XTP value * max_xtp : never deliver interrupts to this CPU. */ static inline void min_xtp (void) { if (smp_int_redirect & SMP_IRQ_REDIRECTION) writeb(0x00, ipi_base_addr + XTP_OFFSET); /* XTP to min */ } static inline void normal_xtp (void) { if (smp_int_redirect & SMP_IRQ_REDIRECTION) writeb(0x08, ipi_base_addr + XTP_OFFSET); /* XTP normal */ } static inline void max_xtp (void) { if (smp_int_redirect & SMP_IRQ_REDIRECTION) writeb(0x0f, ipi_base_addr + XTP_OFFSET); /* Set XTP to max */ } #endif /* CONFIG_SMP */ #endif /* _ASM_IA64_XTP_Hy */
thisismana/frontend
static/src/javascripts/projects/common/modules/crosswords/clues.js
<filename>static/src/javascripts/projects/common/modules/crosswords/clues.js /* jshint newcap: false */ define([ 'common/utils/_', 'react' ], function ( _, React ) { var classSet = React.addons.classSet, Clue = React.createClass({ onClick: function (event) { event.preventDefault(); this.props.focusClue(); }, render: function () { return React.DOM.li({ className: classSet({ 'crossword__clue': true, 'crossword__clue--answered': this.props.hasAnswered, 'crossword__clue--selected': this.props.isSelected }), onClick: this.onClick, value: this.props.number, dangerouslySetInnerHTML: { '__html': this.props.clue } }); } }); return React.createClass({ render: function () { var that = this, headerClass = 'crossword__clues-header'; function cluesByDirection(direction) { return _.chain(that.props.clues) .filter(function (clue) { return clue.entry.direction === direction; }) .map(function (clue) { return Clue({ number: clue.entry.number + '.', clue: clue.entry.clue, hasAnswered: clue.hasAnswered, isSelected: clue.isSelected, focusClue: function () { that.props.focusClue(clue.entry.position.x, clue.entry.position.y, direction); } }); }); } return React.DOM.div({ className: 'crossword__clues' }, React.DOM.div({ className: 'crossword__clues--across' }, React.DOM.h3({ className: headerClass }, 'Across'), React.DOM.ol({ className: 'crossword__clues-list' }, cluesByDirection('across'))), React.DOM.div({ className: 'crossword__clues--down' }, React.DOM.h3({ className: headerClass }, 'Down'), React.DOM.ol({ className: 'crossword__clues-list' }, cluesByDirection('down')))); } }); });
jimyuan/wallscreen
src/charts/lineData.js
<gh_stars>0 import common from 'CHARTS/commonData' // const textStyle = common.textStyle const xAxis = [{ type: 'category', axisLine: { lineStyle: { color: common.lineColor } }, axisTick: { show: false }, data: [] }, { type: 'category', position: 'top', axisLine: { onZero: false, lineStyle: { color: common.lineColor } } }] const yAxis = [{ type: 'value', nameTextStyle: { color: '#fff' }, axisLine: { lineStyle: { color: common.lineColor } }, axisTick: { show: false }, axisLabel: { textStyle: { fontSize: 10 } }, splitLine: { show: true, lineStyle: { color: '#11202f' } } }, { type: 'category', position: 'top', axisLine: { onZero: false, lineStyle: { color: common.lineColor } } }] const series = [{ type: 'line', symbol: 'circle', symbolSize: common.symbol8, itemStyle: { normal: { color: common.lineColor } }, lineStyle: { normal: { color: '#3b8378', width: 1, type: 'dashed' } }, data: [] }] export default { xAxis, yAxis, series }
automaton82/pspace
CommonGame/MathUtil.cpp
#include "MathUtil.h" #include <math.h> #include <stdlib.h> //for rand namespace MathUtil { double round(double value) { double retval = value; double roundedLow = ::floor(value); double roundedHigh = ::ceil(value); double absDiffHigh = fabs(value - roundedHigh); double absDiffLow = fabs(value - roundedLow); if(absDiffLow < absDiffHigh) retval = roundedLow; else retval = roundedHigh; return retval; } double round(double value, double delta) { double retval = value; double roundedLow = value - fmod(value, delta); double roundedHigh = roundedLow + delta; double absDiffHigh = fabs(value - roundedHigh); double absDiffLow = fabs(value - roundedLow); if(absDiffLow < absDiffHigh) retval = roundedLow; else retval = roundedHigh; return retval; } double floor(double value, double delta) { if(value >= 0) return value - fmod(value, delta); else return value - delta - fmod(value, delta); //double retval = value - fmod(value, delta); //return retval; } double ceil(double value, double delta) { if(value >= 0) return value + delta - fmod(value, delta); else return value - fmod(value, delta); //double retval = value - fmod(value), delta); //retval += delta; //return retval; } double clamp(double value, double epsilon) { double retval = value; double roundedHigh = ::ceil(value); double roundedLow = ::floor(value); double absDiffHigh = fabs(value - roundedHigh); double absDiffLow = fabs(value - roundedLow); if(absDiffLow < absDiffHigh && absDiffLow < epsilon) { //use roundedLow retval = roundedLow; } else if(absDiffHigh < epsilon) { retval = roundedHigh; } return retval; } bool pointInBox(double x, double y, const Rect& box) { //TODO: check top and bottom if(x < box.left || x > box.right || y < box.bottom || y > box.top) return false; else return true; } double unitRand() { double retval = rand() / (double)RAND_MAX; return retval; } double unitRandDiscreet(unsigned int intervals) { double retval = ::floor(unitRand()*intervals) / (double)intervals; return retval; } Vector rayPlaneIntersection(const Vector& rayOrigin, const Vector& rayDirection, const Vector& planeNormal, double planeDistance) { //ray equation: R = R0 + tD Vector pointOnPlane = planeNormal * planeDistance; //TODO: this may not be a valid point double t = - ((rayOrigin-pointOnPlane).dot(planeNormal)+planeDistance) / rayDirection.dot(planeNormal); //TODO: check for special cases Vector point = rayOrigin + t*rayDirection; //intersection return point; } Vector rotateVectorX(const Vector& v, double angle) { return Vector( v.x_, v.y_*cos(angle) - v.z_*sin(angle), v.y_*sin(angle) - v.z_*cos(angle) ); } Vector rotateVectorY(const Vector& v, double angle) { return Vector( v.x_*cos(angle) - v.z_*sin(angle), v.y_, -v.x_*sin(angle) + v.z_*cos(angle) ); } Vector rotateVectorZ(const Vector& v, double angle) { return Vector( v.x_*cos(angle) - v.y_*sin(angle), v.x_*sin(angle) + v.y_*cos(angle), v.z_ ); } } //namespace MathUtil
norrs/logevents
logevents/src/main/java/org/logevents/observers/file/FileChannelTracker.java
<reponame>norrs/logevents package org.logevents.observers.file; import org.logevents.observers.FileLogEventObserver; import org.logevents.status.LogEventStatus; import org.logevents.util.ExceptionUtil; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.time.Duration; import java.time.Instant; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; /** * Utility class to keep open files for {@link FileLogEventObserver} for efficiency. Will close * files when necessary to avoid resource leak. */ public class FileChannelTracker { private int maxOpenChannels = 100; private boolean lockOnWrite; public FileChannelTracker(boolean lockOnWrite) { this.lockOnWrite = lockOnWrite; } public void setMaxOpenChannels(int maxOpenChannels) { this.maxOpenChannels = maxOpenChannels; } public void reset() { for (Map.Entry<Path, Entry<FileChannel>> entry : channels.entrySet()) { try { entry.getValue().getTarget().close(); } catch (IOException e) { LogEventStatus.getInstance().addError(this, "While closing " + entry.getKey(), e); } } channels.clear(); } static class Entry<T> { private final T target; private Instant accessTime; private Entry(T target) { this.target = target; } public T getTarget() { return target; } public Instant getAccessTime() { return accessTime; } public void setAccessTime(Instant accessTime) { this.accessTime = accessTime; } } private Map<Path, Entry<FileChannel>> channels = Collections.synchronizedMap(new LinkedHashMap<>()); private Duration timeout = Duration.ofMinutes(10); public void writeToFile(Path path, String message) throws IOException { FileChannel channel = getChannel(path, Instant.now()); try { ByteBuffer src = ByteBuffer.wrap(message.getBytes()); if (lockOnWrite) { try(FileLock ignored = channel.tryLock()) { channel.write(src); } } else { channel.write(src); } } catch (IOException e) { try { channel.close(); } catch (IOException ignored) { } channels.remove(path); throw e; } } /** * Returns a channel for the specified path, considering it as opened with the now parameter. If the * requested channel is already opened, this is returned, otherwise a new channel is returned. If a * new channel is opened, the {@link FileChannelTracker} reviews existing opened channels and make sure * that no channel has been idle for longer than {@link #timeout} and that now more than {@link #maxOpenChannels} * are opened. If channels need to be closed, the least recently accessed channels are closed first. * * @throws IOException if openChannel throws */ FileChannel getChannel(Path path, Instant now) throws IOException { Entry<FileChannel> result = channels.get(path); if (result == null) { result = openChannel(path, now); channels.put(path, result); } result.setAccessTime(now); return result.getTarget(); } Entry<FileChannel> openChannel(Path p, Instant now) throws IOException { for (Iterator<Map.Entry<Path, Entry<FileChannel>>> iterator = channels.entrySet().iterator(); iterator.hasNext(); ) { Map.Entry<Path, Entry<FileChannel>> e = iterator.next(); if (e.getValue().getAccessTime().isBefore(now.minus(getTimeout()))) { e.getValue().getTarget().close(); iterator.remove(); } } int mustBeRemoved = channels.size() - maxOpenChannels + 1; if (mustBeRemoved > 0) { channels.entrySet().stream() .sorted(Comparator.comparing(a -> a.getValue().getAccessTime())) .limit(mustBeRemoved) .map(Map.Entry::getKey) .forEach(ExceptionUtil.softenExceptions(k -> channels.remove(k).getTarget().close())); } createDirectory(p.getParent()); return new Entry<>(FileChannel.open(p, StandardOpenOption.APPEND, StandardOpenOption.CREATE)); } private void createDirectory(Path directory) { if (directory != null) { try { Files.createDirectories(directory); } catch (IOException e) { LogEventStatus.getInstance().addFatal(this, "Can't create directory " + directory, e); } } } public Duration getTimeout() { return timeout; } }
sreekanth1990/djangoproject.com
docs/migrations/0003_auto_20171107_1513.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2017-11-07 15:13 from __future__ import unicode_literals import django.contrib.postgres.fields.jsonb import django.contrib.postgres.indexes import django.contrib.postgres.search from django.contrib.postgres.operations import TrigramExtension from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('docs', '0002_extend_lang_field'), ] operations = [ migrations.AddField( model_name='document', name='metadata', field=django.contrib.postgres.fields.jsonb.JSONField(default=dict), ), migrations.AddField( model_name='document', name='search', field=django.contrib.postgres.search.SearchVectorField(editable=False, null=True), ), migrations.AddIndex( model_name='document', index=django.contrib.postgres.indexes.GinIndex(fields=['search'], name='docs_docume_search_5dc895_gin'), ), TrigramExtension(), ]
highiq/angular.next
client/app/components/my/organize/my-code-repositories/my-code-repositories.component.js
import template from './my-code-repositories.html'; import controller from './my-code-repositories.controller'; import './my-code-repositories.styl'; let myCodeRepositoriesComponent = function () { return { restrict: 'E', scope: {}, template, controller, controllerAs: 'vm', bindToController: true }; }; export default myCodeRepositoriesComponent;