text
stringlengths
2
1.04M
meta
dict
/* ---------------------------------------------------------------------- * Project: CMSIS DSP Library * Title: arm_fir_interpolate_f32.c * Description: Floating-point FIR interpolation sequences * * $Date: 18. March 2019 * $Revision: V1.6.0 * * Target Processor: Cortex-M cores * -------------------------------------------------------------------- */ /* * Copyright (C) 2010-2019 ARM Limited or its affiliates. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * 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 * * www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an AS IS BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "arm_math.h" /** @defgroup FIR_Interpolate Finite Impulse Response (FIR) Interpolator These functions combine an upsampler (zero stuffer) and an FIR filter. They are used in multirate systems for increasing the sample rate of a signal without introducing high frequency images. Conceptually, the functions are equivalent to the block diagram below: \image html FIRInterpolator.gif "Components included in the FIR Interpolator functions" After upsampling by a factor of <code>L</code>, the signal should be filtered by a lowpass filter with a normalized cutoff frequency of <code>1/L</code> in order to eliminate high frequency copies of the spectrum. The user of the function is responsible for providing the filter coefficients. The FIR interpolator functions provided in the CMSIS DSP Library combine the upsampler and FIR filter in an efficient manner. The upsampler inserts <code>L-1</code> zeros between each sample. Instead of multiplying by these zero values, the FIR filter is designed to skip them. This leads to an efficient implementation without any wasted effort. The functions operate on blocks of input and output data. <code>pSrc</code> points to an array of <code>blockSize</code> input values and <code>pDst</code> points to an array of <code>blockSize*L</code> output values. The library provides separate functions for Q15, Q31, and floating-point data types. @par Algorithm The functions use a polyphase filter structure: <pre> y[n] = b[0] * x[n] + b[L] * x[n-1] + ... + b[L*(phaseLength-1)] * x[n-phaseLength+1] y[n+1] = b[1] * x[n] + b[L+1] * x[n-1] + ... + b[L*(phaseLength-1)+1] * x[n-phaseLength+1] ... y[n+(L-1)] = b[L-1] * x[n] + b[2*L-1] * x[n-1] + ....+ b[L*(phaseLength-1)+(L-1)] * x[n-phaseLength+1] </pre> This approach is more efficient than straightforward upsample-then-filter algorithms. With this method the computation is reduced by a factor of <code>1/L</code> when compared to using a standard FIR filter. @par <code>pCoeffs</code> points to a coefficient array of size <code>numTaps</code>. <code>numTaps</code> must be a multiple of the interpolation factor <code>L</code> and this is checked by the initialization functions. Internally, the function divides the FIR filter's impulse response into shorter filters of length <code>phaseLength=numTaps/L</code>. Coefficients are stored in time reversed order. <pre> {b[numTaps-1], b[numTaps-2], b[N-2], ..., b[1], b[0]} </pre> @par <code>pState</code> points to a state array of size <code>blockSize + phaseLength - 1</code>. Samples in the state buffer are stored in the order: <pre> {x[n-phaseLength+1], x[n-phaseLength], x[n-phaseLength-1], x[n-phaseLength-2]....x[0], x[1], ..., x[blockSize-1]} </pre> @par The state variables are updated after each block of data is processed, the coefficients are untouched. @par Instance Structure The coefficients and state variables for a filter are stored together in an instance data structure. A separate instance structure must be defined for each filter. Coefficient arrays may be shared among several instances while state variable array should be allocated separately. There are separate instance structure declarations for each of the 3 supported data types. @par Initialization Functions There is also an associated initialization function for each data type. The initialization function performs the following operations: - Sets the values of the internal structure fields. - Zeros out the values in the state buffer. - Checks to make sure that the length of the filter is a multiple of the interpolation factor. To do this manually without calling the init function, assign the follow subfields of the instance structure: L (interpolation factor), pCoeffs, phaseLength (numTaps / L), pState. Also set all of the values in pState to zero. @par Use of the initialization function is optional. However, if the initialization function is used, then the instance structure cannot be placed into a const data section. To place an instance structure into a const data section, the instance structure must be manually initialized. The code below statically initializes each of the 3 different data type filter instance structures <pre> arm_fir_interpolate_instance_f32 S = {L, phaseLength, pCoeffs, pState}; arm_fir_interpolate_instance_q31 S = {L, phaseLength, pCoeffs, pState}; arm_fir_interpolate_instance_q15 S = {L, phaseLength, pCoeffs, pState}; </pre> @par where <code>L</code> is the interpolation factor; <code>phaseLength=numTaps/L</code> is the length of each of the shorter FIR filters used internally, <code>pCoeffs</code> is the address of the coefficient buffer; <code>pState</code> is the address of the state buffer. Be sure to set the values in the state buffer to zeros when doing static initialization. @par Fixed-Point Behavior Care must be taken when using the fixed-point versions of the FIR interpolate filter functions. In particular, the overflow and saturation behavior of the accumulator used in each function must be considered. Refer to the function specific documentation below for usage guidelines. */ /** @addtogroup FIR_Interpolate @{ */ /** @brief Processing function for floating-point FIR interpolator. @param[in] S points to an instance of the floating-point FIR interpolator structure @param[in] pSrc points to the block of input data @param[out] pDst points to the block of output data @param[in] blockSize number of samples to process @return none */ #if defined(ARM_MATH_MVEF) && !defined(ARM_MATH_AUTOVECTORIZE) #include "arm_helium_utils.h" static void arm_fir_interpolate2_f32_mve( const arm_fir_interpolate_instance_f32 *S, const float32_t *pSrc, float32_t *pDst, uint32_t blockSize) { float32_t *pState = S->pState; /* State pointer */ const float32_t *pCoeffs = S->pCoeffs; /* Coefficient pointer */ float32_t *pStateCurnt; /* Points to the current sample of the state */ const float32_t *ptr1, *ptr2; /* Temporary pointers for state and coefficient buffers */ uint32_t tapCnt; uint32_t blkCnt; /* Loop counters */ uint16_t phaseLen = S->phaseLength; /* Length of each polyphase filter component */ uint32_t strides[4] = { 0, 1 * 2, 2 * 2, 3 * 2 }; uint32x4_t vec_strides0 = vld1q_u32(strides); uint32x4_t vec_strides1 = vec_strides0 + 1; f32x4_t acc0, acc1; /* * S->pState buffer contains previous frame (phaseLen - 1) samples * pStateCurnt points to the location where the new input data should be written */ pStateCurnt = S->pState + (phaseLen - 1U); /* * Total number of intput samples */ blkCnt = blockSize; /* * Loop over the blockSize. */ while (blkCnt > 0U) { /* * Copy new input sample into the state buffer */ *pStateCurnt++ = *pSrc++; /* * Initialize state pointer */ ptr1 = pState; acc0 = vdupq_n_f32(0.0f); acc1 = vdupq_n_f32(0.0f); /* * Initialize coefficient pointer */ ptr2 = pCoeffs; tapCnt = phaseLen >> 2; while (tapCnt > 0U) { f32x4_t vecCoef, vecState; vecState = vldrwq_f32(ptr1); vecCoef = vldrwq_gather_shifted_offset_f32(ptr2, vec_strides1); acc1 = vfmaq_f32(acc1, vecState, vecCoef); vecCoef = vldrwq_gather_shifted_offset_f32(ptr2, vec_strides0); acc0 = vfmaq_f32(acc0, vecState, vecCoef); ptr2 += 4 * 2; ptr1 += 4; /* * Decrement the loop counter */ tapCnt--; } tapCnt = phaseLen & 3; if (tapCnt > 0U) { mve_pred16_t p0 = vctp32q(tapCnt); f32x4_t vecCoef, vecState; vecState = vldrwq_z_f32(ptr1, p0); vecCoef = vldrwq_gather_shifted_offset_z_f32(ptr2, vec_strides1, p0); acc1 = vfmaq_f32(acc1, vecState, vecCoef); vecCoef = vldrwq_gather_shifted_offset_z_f32(ptr2, vec_strides0, p0); acc0 = vfmaq_f32(acc0, vecState, vecCoef); } *pDst++ = vecAddAcrossF32Mve(acc1); *pDst++ = vecAddAcrossF32Mve(acc0); /* * Advance the state pointer by 1 * * to process the next group of interpolation factor number samples */ pState = pState + 1; /* * Decrement the loop counter */ blkCnt--; } /* * Processing is complete. * ** Now copy the last phaseLen - 1 samples to the start of the state buffer. * ** This prepares the state buffer for the next function call. */ /* * Points to the start of the state buffer */ pStateCurnt = S->pState; blkCnt = (phaseLen - 1U) >> 2; while (blkCnt > 0U) { vst1q(pStateCurnt, vldrwq_f32(pState)); pState += 4; pStateCurnt += 4; blkCnt--; } blkCnt = (phaseLen - 1U) & 3; if (blkCnt > 0U) { mve_pred16_t p0 = vctp32q(blkCnt); vstrwq_p_f32(pStateCurnt, vldrwq_f32(pState), p0); } } void arm_fir_interpolate_f32( const arm_fir_interpolate_instance_f32 *S, const float32_t *pSrc, float32_t *pDst, uint32_t blockSize) { float32_t *pState = S->pState; /* State pointer */ const float32_t *pCoeffs = S->pCoeffs; /* Coefficient pointer */ float32_t *pStateCurnt; /* Points to the current sample of the state */ const float32_t *ptr1, *ptr2; /* Temporary pointers for state and coefficient buffers */ uint32_t tapCnt; uint32_t i, blkCnt; /* Loop counters */ uint16_t phaseLen = S->phaseLength; /* Length of each polyphase filter component */ uint32_t strides[4] = { 0, 1 * S->L, 2 * S->L, 3 * S->L }; uint32_t stridesM[4] = { 4, 3, 2, 1 }; uint32x4_t vec_stridesM = vld1q_u32(stridesM); uint32x4_t vec_strides = vld1q_u32(strides); f32x4_t acc; if (S->L == 2) { arm_fir_interpolate2_f32_mve(S, pSrc, pDst, blockSize); return; } /* * S->pState buffer contains previous frame (phaseLen - 1) samples */ /* * pStateCurnt points to the location where the new input data should be written */ pStateCurnt = S->pState + (phaseLen - 1U); /* * Total number of intput samples */ blkCnt = blockSize; /* * Loop over the blockSize. */ while (blkCnt > 0U) { /* * Copy new input sample into the state buffer */ *pStateCurnt++ = *pSrc++; /* * Loop over the Interpolation factor. */ i = S->L; while (i > 0U) { /* * Initialize state pointer */ ptr1 = pState; if (i >= 4) { float32_t state0, state1, state2, state3; acc = vdupq_n_f32(0.0f); /* * Initialize coefficient pointer */ ptr2 = pCoeffs + (i - 1U) - 4; tapCnt = phaseLen >> 2; while (tapCnt > 0U) { f32x4_t vecCoef; const float32_t *pCoef = ptr2; state0 = ptr1[0]; state1 = ptr1[1]; state2 = ptr1[2]; state3 = ptr1[3]; ptr1 += 4; vecCoef = vldrwq_gather_shifted_offset_f32(pCoef, vec_stridesM); pCoef += S->L; acc = vfmaq_n_f32(acc, vecCoef, state0); vecCoef = vldrwq_gather_shifted_offset_f32(pCoef, vec_stridesM); pCoef += S->L; acc = vfmaq_n_f32(acc, vecCoef, state1); vecCoef = vldrwq_gather_shifted_offset_f32(pCoef, vec_stridesM); pCoef += S->L; acc = vfmaq_n_f32(acc, vecCoef, state2); vecCoef = vldrwq_gather_shifted_offset_f32(pCoef, vec_stridesM); pCoef += S->L; acc = vfmaq_n_f32(acc, vecCoef, state3); ptr2 = ptr2 + 4 * S->L; /* * Decrement the loop counter */ tapCnt--; } tapCnt = phaseLen & 3; if (tapCnt > 0U) { mve_pred16_t p0 = vctp32q(tapCnt); f32x4_t vecCoef; const float32_t *pCoef = ptr2; state0 = ptr1[0]; state1 = ptr1[1]; state2 = ptr1[2]; state3 = ptr1[3]; vecCoef = vldrwq_gather_shifted_offset_z_f32(pCoef, vec_stridesM, p0); pCoef += S->L; acc = vfmaq_n_f32(acc, vecCoef, state0); vecCoef = vldrwq_gather_shifted_offset_z_f32(pCoef, vec_stridesM, p0); pCoef += S->L; acc = vfmaq_n_f32(acc, vecCoef, state1); vecCoef = vldrwq_gather_shifted_offset_z_f32(pCoef, vec_stridesM, p0); pCoef += S->L; acc = vfmaq_n_f32(acc, vecCoef, state2); vecCoef = vldrwq_gather_shifted_offset_z_f32(pCoef, vec_stridesM, p0); pCoef += S->L; acc = vfmaq_n_f32(acc, vecCoef, state3); } vst1q(pDst, acc); pDst += 4; i -= 4; } else { acc = vdupq_n_f32(0.0f); /* * Initialize coefficient pointer */ ptr2 = pCoeffs + (i - 1U); tapCnt = phaseLen >> 2; while (tapCnt > 0U) { f32x4_t vecCoef, vecState; vecState = vldrwq_f32(ptr1); ptr1 += 4; vecCoef = vldrwq_gather_shifted_offset_f32(ptr2, vec_strides); ptr2 += 4 * S->L; acc = vfmaq_f32(acc, vecState, vecCoef); /* * Decrement the loop counter */ tapCnt--; } tapCnt = phaseLen & 3; if (tapCnt > 0U) { mve_pred16_t p0 = vctp32q(tapCnt); f32x4_t vecCoef, vecState; vecState = vldrwq_z_f32(ptr1, p0); vecCoef = vldrwq_gather_shifted_offset_z_f32(ptr2, vec_strides, p0); acc = vfmaq_f32(acc, vecState, vecCoef); } *pDst++ = vecAddAcrossF32Mve(acc); /* * Decrement the loop counter */ i--; } } /* * Advance the state pointer by 1 * * to process the next group of interpolation factor number samples */ pState = pState + 1; /* * Decrement the loop counter */ blkCnt--; } /* * Processing is complete. * ** Now copy the last phaseLen - 1 samples to the start of the state buffer. * ** This prepares the state buffer for the next function call. */ /* * Points to the start of the state buffer */ pStateCurnt = S->pState; blkCnt = (phaseLen - 1U) >> 2; while (blkCnt > 0U) { vst1q(pStateCurnt, vldrwq_f32(pState)); pState += 4; pStateCurnt += 4; blkCnt--; } blkCnt = (phaseLen - 1U) & 3; if (blkCnt > 0U) { mve_pred16_t p0 = vctp32q(blkCnt); vstrwq_p_f32(pStateCurnt, vldrwq_f32(pState), p0); } } #else #if defined(ARM_MATH_NEON) void arm_fir_interpolate_f32( const arm_fir_interpolate_instance_f32 *S, const float32_t *pSrc, float32_t *pDst, uint32_t blockSize) { float32_t *pState = S->pState; /* State pointer */ const float32_t *pCoeffs = S->pCoeffs; /* Coefficient pointer */ float32_t *pStateCurnt; /* Points to the current sample of the state */ float32_t *ptr1; /* Temporary pointers for state buffer */ const float32_t *ptr2; /* Temporary pointers for coefficient buffer */ float32_t sum0; /* Accumulators */ float32_t c0; /* Temporary variables to hold state and coefficient values */ uint32_t i, blkCnt, j; /* Loop counters */ uint16_t phaseLen = S->phaseLength, tapCnt; /* Length of each polyphase filter component */ uint32_t blkCntN4; float32_t c1, c2, c3; float32x4_t sum0v; float32x4_t accV0, accV1; float32x4_t x0v, x1v, x2v, xa, xb; float32x2_t tempV; /* S->pState buffer contains previous frame (phaseLen - 1) samples */ /* pStateCurnt points to the location where the new input data should be written */ pStateCurnt = S->pState + (phaseLen - 1U); /* Initialise blkCnt */ blkCnt = blockSize >> 3; blkCntN4 = blockSize & 7; /* Loop unrolling */ while (blkCnt > 0U) { /* Copy new input samples into the state buffer */ sum0v = vld1q_f32(pSrc); vst1q_f32(pStateCurnt, sum0v); pSrc += 4; pStateCurnt += 4; sum0v = vld1q_f32(pSrc); vst1q_f32(pStateCurnt, sum0v); pSrc += 4; pStateCurnt += 4; /* Address modifier index of coefficient buffer */ j = 1U; /* Loop over the Interpolation factor. */ i = (S->L); while (i > 0U) { /* Set accumulator to zero */ accV0 = vdupq_n_f32(0.0); accV1 = vdupq_n_f32(0.0); /* Initialize state pointer */ ptr1 = pState; /* Initialize coefficient pointer */ ptr2 = pCoeffs + (S->L - j); /* Loop over the polyPhase length. Unroll by a factor of 4. ** Repeat until we've computed numTaps-(4*S->L) coefficients. */ tapCnt = phaseLen >> 2U; x0v = vld1q_f32(ptr1); x1v = vld1q_f32(ptr1 + 4); while (tapCnt > 0U) { /* Read the input samples */ x2v = vld1q_f32(ptr1 + 8); /* Read the coefficients */ c0 = *(ptr2); /* Perform the multiply-accumulate */ accV0 = vmlaq_n_f32(accV0, x0v, c0); accV1 = vmlaq_n_f32(accV1, x1v, c0); /* Read the coefficients, inputs and perform multiply-accumulate */ c1 = *(ptr2 + S->L); xa = vextq_f32(x0v, x1v, 1); xb = vextq_f32(x1v, x2v, 1); accV0 = vmlaq_n_f32(accV0, xa, c1); accV1 = vmlaq_n_f32(accV1, xb, c1); /* Read the coefficients, inputs and perform multiply-accumulate */ c2 = *(ptr2 + S->L * 2); xa = vextq_f32(x0v, x1v, 2); xb = vextq_f32(x1v, x2v, 2); accV0 = vmlaq_n_f32(accV0, xa, c2); accV1 = vmlaq_n_f32(accV1, xb, c2); /* Read the coefficients, inputs and perform multiply-accumulate */ c3 = *(ptr2 + S->L * 3); xa = vextq_f32(x0v, x1v, 3); xb = vextq_f32(x1v, x2v, 3); accV0 = vmlaq_n_f32(accV0, xa, c3); accV1 = vmlaq_n_f32(accV1, xb, c3); /* Upsampling is done by stuffing L-1 zeros between each sample. * So instead of multiplying zeros with coefficients, * Increment the coefficient pointer by interpolation factor times. */ ptr2 += 4 * S->L; ptr1 += 4; x0v = x1v; x1v = x2v; /* Decrement the loop counter */ tapCnt--; } /* If the polyPhase length is not a multiple of 4, compute the remaining filter taps */ tapCnt = phaseLen % 0x4U; x2v = vld1q_f32(ptr1 + 8); switch (tapCnt) { case 3: c0 = *(ptr2); accV0 = vmlaq_n_f32(accV0, x0v, c0); accV1 = vmlaq_n_f32(accV1, x1v, c0); ptr2 += S->L; c0 = *(ptr2); xa = vextq_f32(x0v, x1v, 1); xb = vextq_f32(x1v, x2v, 1); accV0 = vmlaq_n_f32(accV0, xa, c0); accV1 = vmlaq_n_f32(accV1, xb, c0); ptr2 += S->L; c0 = *(ptr2); xa = vextq_f32(x0v, x1v, 2); xb = vextq_f32(x1v, x2v, 2); accV0 = vmlaq_n_f32(accV0, xa, c0); accV1 = vmlaq_n_f32(accV1, xb, c0); ptr2 += S->L; break; case 2: c0 = *(ptr2); accV0 = vmlaq_n_f32(accV0, x0v, c0); accV1 = vmlaq_n_f32(accV1, x1v, c0); ptr2 += S->L; c0 = *(ptr2); xa = vextq_f32(x0v, x1v, 1); xb = vextq_f32(x1v, x2v, 1); accV0 = vmlaq_n_f32(accV0, xa, c0); accV1 = vmlaq_n_f32(accV1, xb, c0); ptr2 += S->L; break; case 1: c0 = *(ptr2); accV0 = vmlaq_n_f32(accV0, x0v, c0); accV1 = vmlaq_n_f32(accV1, x1v, c0); ptr2 += S->L; break; default: break; } /* The result is in the accumulator, store in the destination buffer. */ *pDst = vgetq_lane_f32(accV0, 0); *(pDst + S->L) = vgetq_lane_f32(accV0, 1); *(pDst + 2 * S->L) = vgetq_lane_f32(accV0, 2); *(pDst + 3 * S->L) = vgetq_lane_f32(accV0, 3); *(pDst + 4 * S->L) = vgetq_lane_f32(accV1, 0); *(pDst + 5 * S->L) = vgetq_lane_f32(accV1, 1); *(pDst + 6 * S->L) = vgetq_lane_f32(accV1, 2); *(pDst + 7 * S->L) = vgetq_lane_f32(accV1, 3); pDst++; /* Increment the address modifier index of coefficient buffer */ j++; /* Decrement the loop counter */ i--; } /* Advance the state pointer by 1 * to process the next group of interpolation factor number samples */ pState = pState + 8; pDst += S->L * 7; /* Decrement the loop counter */ blkCnt--; } /* If the blockSize is not a multiple of 4, compute any remaining output samples here. ** No loop unrolling is used. */ while (blkCntN4 > 0U) { /* Copy new input sample into the state buffer */ *pStateCurnt++ = *pSrc++; /* Address modifier index of coefficient buffer */ j = 1U; /* Loop over the Interpolation factor. */ i = S->L; while (i > 0U) { /* Set accumulator to zero */ sum0v = vdupq_n_f32(0.0); /* Initialize state pointer */ ptr1 = pState; /* Initialize coefficient pointer */ ptr2 = pCoeffs + (S->L - j); /* Loop over the polyPhase length. Unroll by a factor of 4. ** Repeat until we've computed numTaps-(4*S->L) coefficients. */ tapCnt = phaseLen >> 2U; while (tapCnt > 0U) { /* Read the coefficient */ x1v = vsetq_lane_f32(*(ptr2), x1v, 0); /* Upsampling is done by stuffing L-1 zeros between each sample. * So instead of multiplying zeros with coefficients, * Increment the coefficient pointer by interpolation factor times. */ ptr2 += S->L; /* Read the input sample */ x0v = vld1q_f32(ptr1); ptr1 += 4; /* Read the coefficient */ x1v = vsetq_lane_f32(*(ptr2), x1v, 1); /* Increment the coefficient pointer by interpolation factor times. */ ptr2 += S->L; /* Read the coefficient */ x1v = vsetq_lane_f32(*(ptr2), x1v, 2); /* Increment the coefficient pointer by interpolation factor times. */ ptr2 += S->L; /* Read the coefficient */ x1v = vsetq_lane_f32(*(ptr2), x1v, 3); /* Increment the coefficient pointer by interpolation factor times. */ ptr2 += S->L; sum0v = vmlaq_f32(sum0v, x0v, x1v); /* Decrement the loop counter */ tapCnt--; } tempV = vpadd_f32(vget_low_f32(sum0v), vget_high_f32(sum0v)); sum0 = vget_lane_f32(tempV, 0) + vget_lane_f32(tempV, 1); /* If the polyPhase length is not a multiple of 4, compute the remaining filter taps */ tapCnt = phaseLen % 0x4U; while (tapCnt > 0U) { /* Perform the multiply-accumulate */ sum0 += *(ptr1++) * (*ptr2); /* Increment the coefficient pointer by interpolation factor times. */ ptr2 += S->L; /* Decrement the loop counter */ tapCnt--; } /* The result is in the accumulator, store in the destination buffer. */ *pDst++ = sum0; /* Increment the address modifier index of coefficient buffer */ j++; /* Decrement the loop counter */ i--; } /* Advance the state pointer by 1 * to process the next group of interpolation factor number samples */ pState = pState + 1; /* Decrement the loop counter */ blkCntN4--; } /* Processing is complete. ** Now copy the last phaseLen - 1 samples to the satrt of the state buffer. ** This prepares the state buffer for the next function call. */ /* Points to the start of the state buffer */ pStateCurnt = S->pState; tapCnt = (phaseLen - 1U) >> 2U; /* Copy data */ while (tapCnt > 0U) { sum0v = vld1q_f32(pState); vst1q_f32(pStateCurnt, sum0v); pState += 4; pStateCurnt += 4; /* Decrement the loop counter */ tapCnt--; } tapCnt = (phaseLen - 1U) % 0x04U; /* copy data */ while (tapCnt > 0U) { *pStateCurnt++ = *pState++; /* Decrement the loop counter */ tapCnt--; } } #else void arm_fir_interpolate_f32( const arm_fir_interpolate_instance_f32 *S, const float32_t *pSrc, float32_t *pDst, uint32_t blockSize) { #if (1) //#if !defined(ARM_MATH_CM0_FAMILY) float32_t *pState = S->pState; /* State pointer */ const float32_t *pCoeffs = S->pCoeffs; /* Coefficient pointer */ float32_t *pStateCur; /* Points to the current sample of the state */ float32_t *ptr1; /* Temporary pointer for state buffer */ const float32_t *ptr2; /* Temporary pointer for coefficient buffer */ float32_t sum0; /* Accumulators */ uint32_t i, blkCnt, tapCnt; /* Loop counters */ uint32_t phaseLen = S->phaseLength; /* Length of each polyphase filter component */ uint32_t j; #if defined (ARM_MATH_LOOPUNROLL) float32_t acc0, acc1, acc2, acc3; float32_t x0, x1, x2, x3; float32_t c0, c1, c2, c3; #endif /* S->pState buffer contains previous frame (phaseLen - 1) samples */ /* pStateCur points to the location where the new input data should be written */ pStateCur = S->pState + (phaseLen - 1U); #if defined (ARM_MATH_LOOPUNROLL) /* Loop unrolling: Compute 4 outputs at a time */ blkCnt = blockSize >> 2U; while (blkCnt > 0U) { /* Copy new input sample into the state buffer */ *pStateCur++ = *pSrc++; *pStateCur++ = *pSrc++; *pStateCur++ = *pSrc++; *pStateCur++ = *pSrc++; /* Address modifier index of coefficient buffer */ j = 1U; /* Loop over the Interpolation factor. */ i = (S->L); while (i > 0U) { /* Set accumulator to zero */ acc0 = 0.0f; acc1 = 0.0f; acc2 = 0.0f; acc3 = 0.0f; /* Initialize state pointer */ ptr1 = pState; /* Initialize coefficient pointer */ ptr2 = pCoeffs + (S->L - j); /* Loop over the polyPhase length. Unroll by a factor of 4. Repeat until we've computed numTaps-(4*S->L) coefficients. */ tapCnt = phaseLen >> 2U; x0 = *(ptr1++); x1 = *(ptr1++); x2 = *(ptr1++); while (tapCnt > 0U) { /* Read the input sample */ x3 = *(ptr1++); /* Read the coefficient */ c0 = *(ptr2); /* Perform the multiply-accumulate */ acc0 += x0 * c0; acc1 += x1 * c0; acc2 += x2 * c0; acc3 += x3 * c0; /* Read the coefficient */ c1 = *(ptr2 + S->L); /* Read the input sample */ x0 = *(ptr1++); /* Perform the multiply-accumulate */ acc0 += x1 * c1; acc1 += x2 * c1; acc2 += x3 * c1; acc3 += x0 * c1; /* Read the coefficient */ c2 = *(ptr2 + S->L * 2); /* Read the input sample */ x1 = *(ptr1++); /* Perform the multiply-accumulate */ acc0 += x2 * c2; acc1 += x3 * c2; acc2 += x0 * c2; acc3 += x1 * c2; /* Read the coefficient */ c3 = *(ptr2 + S->L * 3); /* Read the input sample */ x2 = *(ptr1++); /* Perform the multiply-accumulate */ acc0 += x3 * c3; acc1 += x0 * c3; acc2 += x1 * c3; acc3 += x2 * c3; /* Upsampling is done by stuffing L-1 zeros between each sample. * So instead of multiplying zeros with coefficients, * Increment the coefficient pointer by interpolation factor times. */ ptr2 += 4 * S->L; /* Decrement loop counter */ tapCnt--; } /* If the polyPhase length is not a multiple of 4, compute the remaining filter taps */ tapCnt = phaseLen % 0x4U; while (tapCnt > 0U) { /* Read the input sample */ x3 = *(ptr1++); /* Read the coefficient */ c0 = *(ptr2); /* Perform the multiply-accumulate */ acc0 += x0 * c0; acc1 += x1 * c0; acc2 += x2 * c0; acc3 += x3 * c0; /* Increment the coefficient pointer by interpolation factor times. */ ptr2 += S->L; /* update states for next sample processing */ x0 = x1; x1 = x2; x2 = x3; /* Decrement loop counter */ tapCnt--; } /* The result is in the accumulator, store in the destination buffer. */ *(pDst) = acc0; *(pDst + S->L) = acc1; *(pDst + 2 * S->L) = acc2; *(pDst + 3 * S->L) = acc3; pDst++; /* Increment the address modifier index of coefficient buffer */ j++; /* Decrement loop counter */ i--; } /* Advance the state pointer by 1 * to process the next group of interpolation factor number samples */ pState = pState + 4; pDst += S->L * 3; /* Decrement loop counter */ blkCnt--; } /* Loop unrolling: Compute remaining outputs */ blkCnt = blockSize % 0x4U; #else /* Initialize blkCnt with number of samples */ blkCnt = blockSize; #endif /* #if defined (ARM_MATH_LOOPUNROLL) */ while (blkCnt > 0U) { /* Copy new input sample into the state buffer */ *pStateCur++ = *pSrc++; /* Address modifier index of coefficient buffer */ j = 1U; /* Loop over the Interpolation factor. */ i = S->L; while (i > 0U) { /* Set accumulator to zero */ sum0 = 0.0f; /* Initialize state pointer */ ptr1 = pState; /* Initialize coefficient pointer */ ptr2 = pCoeffs + (S->L - j); /* Loop over the polyPhase length. Repeat until we've computed numTaps-(4*S->L) coefficients. */ #if defined (ARM_MATH_LOOPUNROLL) /* Loop unrolling: Compute 4 outputs at a time */ tapCnt = phaseLen >> 2U; while (tapCnt > 0U) { /* Perform the multiply-accumulate */ sum0 += *ptr1++ * *ptr2; /* Upsampling is done by stuffing L-1 zeros between each sample. * So instead of multiplying zeros with coefficients, * Increment the coefficient pointer by interpolation factor times. */ ptr2 += S->L; sum0 += *ptr1++ * *ptr2; ptr2 += S->L; sum0 += *ptr1++ * *ptr2; ptr2 += S->L; sum0 += *ptr1++ * *ptr2; ptr2 += S->L; /* Decrement loop counter */ tapCnt--; } /* Loop unrolling: Compute remaining outputs */ tapCnt = phaseLen % 0x4U; #else /* Initialize tapCnt with number of samples */ tapCnt = phaseLen; #endif /* #if defined (ARM_MATH_LOOPUNROLL) */ while (tapCnt > 0U) { /* Perform the multiply-accumulate */ sum0 += *ptr1++ * *ptr2; /* Upsampling is done by stuffing L-1 zeros between each sample. * So instead of multiplying zeros with coefficients, * Increment the coefficient pointer by interpolation factor times. */ ptr2 += S->L; /* Decrement loop counter */ tapCnt--; } /* The result is in the accumulator, store in the destination buffer. */ *pDst++ = sum0; /* Increment the address modifier index of coefficient buffer */ j++; /* Decrement the loop counter */ i--; } /* Advance the state pointer by 1 * to process the next group of interpolation factor number samples */ pState = pState + 1; /* Decrement the loop counter */ blkCnt--; } /* Processing is complete. Now copy the last phaseLen - 1 samples to the satrt of the state buffer. This prepares the state buffer for the next function call. */ /* Points to the start of the state buffer */ pStateCur = S->pState; #if defined (ARM_MATH_LOOPUNROLL) /* Loop unrolling: Compute 4 outputs at a time */ tapCnt = (phaseLen - 1U) >> 2U; /* copy data */ while (tapCnt > 0U) { *pStateCur++ = *pState++; *pStateCur++ = *pState++; *pStateCur++ = *pState++; *pStateCur++ = *pState++; /* Decrement loop counter */ tapCnt--; } /* Loop unrolling: Compute remaining outputs */ tapCnt = (phaseLen - 1U) % 0x04U; #else /* Initialize tapCnt with number of samples */ tapCnt = (phaseLen - 1U); #endif /* #if defined (ARM_MATH_LOOPUNROLL) */ /* Copy data */ while (tapCnt > 0U) { *pStateCur++ = *pState++; /* Decrement loop counter */ tapCnt--; } #else /* alternate version for CM0_FAMILY */ float32_t *pState = S->pState; /* State pointer */ const float32_t *pCoeffs = S->pCoeffs; /* Coefficient pointer */ float32_t *pStateCur; /* Points to the current sample of the state */ float32_t *ptr1; /* Temporary pointer for state buffer */ const float32_t *ptr2; /* Temporary pointer for coefficient buffer */ float32_t sum0; /* Accumulators */ uint32_t i, blkCnt, tapCnt; /* Loop counters */ uint32_t phaseLen = S->phaseLength; /* Length of each polyphase filter component */ /* S->pState buffer contains previous frame (phaseLen - 1) samples */ /* pStateCur points to the location where the new input data should be written */ pStateCur = S->pState + (phaseLen - 1U); /* Total number of intput samples */ blkCnt = blockSize; /* Loop over the blockSize. */ while (blkCnt > 0U) { /* Copy new input sample into the state buffer */ *pStateCur++ = *pSrc++; /* Loop over the Interpolation factor. */ i = S->L; while (i > 0U) { /* Set accumulator to zero */ sum0 = 0.0f; /* Initialize state pointer */ ptr1 = pState; /* Initialize coefficient pointer */ ptr2 = pCoeffs + (i - 1U); /* Loop over the polyPhase length */ tapCnt = phaseLen; while (tapCnt > 0U) { /* Perform the multiply-accumulate */ sum0 += *ptr1++ * *ptr2; /* Increment the coefficient pointer by interpolation factor times. */ ptr2 += S->L; /* Decrement the loop counter */ tapCnt--; } /* The result is in the accumulator, store in the destination buffer. */ *pDst++ = sum0; /* Decrement loop counter */ i--; } /* Advance the state pointer by 1 * to process the next group of interpolation factor number samples */ pState = pState + 1; /* Decrement loop counter */ blkCnt--; } /* Processing is complete. ** Now copy the last phaseLen - 1 samples to the start of the state buffer. ** This prepares the state buffer for the next function call. */ /* Points to the start of the state buffer */ pStateCur = S->pState; tapCnt = phaseLen - 1U; /* Copy data */ while (tapCnt > 0U) { *pStateCur++ = *pState++; /* Decrement loop counter */ tapCnt--; } #endif /* #if !defined(ARM_MATH_CM0_FAMILY) */ } #endif /* #if defined(ARM_MATH_NEON) */ #endif /* defined(ARM_MATH_MVEF) && !defined(ARM_MATH_AUTOVECTORIZE) */ /** @} end of FIR_Interpolate group */
{ "content_hash": "280f2ad755a7487dc5432addac385d66", "timestamp": "", "source": "github", "line_count": 1212, "max_line_length": 140, "avg_line_length": 28.584158415841586, "alnum_prop": 0.6091963976446138, "repo_name": "Samsung/TizenRT", "id": "6107b05fddc2f899be0d4d8eeb0e0862781ed18c", "size": "34644", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "os/board/rtl8720e/src/component/soc/amebalite/cmsis-dsp/Source/FilteringFunctions/arm_fir_interpolate_f32.c", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "2051079" }, { "name": "Batchfile", "bytes": "42646" }, { "name": "C", "bytes": "107478428" }, { "name": "C++", "bytes": "813875" }, { "name": "CMake", "bytes": "21368" }, { "name": "HTML", "bytes": "2990" }, { "name": "Java", "bytes": "104053" }, { "name": "Makefile", "bytes": "857981" }, { "name": "Perl", "bytes": "4361" }, { "name": "PowerShell", "bytes": "8511" }, { "name": "Python", "bytes": "296172" }, { "name": "Roff", "bytes": "4401" }, { "name": "Shell", "bytes": "253676" }, { "name": "Tcl", "bytes": "163693" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.5.0_07) on Fri Apr 11 15:39:24 BST 2008 --> <META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <TITLE> Uses of Class org.apache.commons.collections.iterators.IteratorEnumeration (Commons Collections 3.2.1 API) </TITLE> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { parent.document.title="Uses of Class org.apache.commons.collections.iterators.IteratorEnumeration (Commons Collections 3.2.1 API)"; } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/commons/collections/iterators/IteratorEnumeration.html" title="class in org.apache.commons.collections.iterators"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/apache/commons/collections/iterators/\class-useIteratorEnumeration.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="IteratorEnumeration.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>org.apache.commons.collections.iterators.IteratorEnumeration</B></H2> </CENTER> No usage of org.apache.commons.collections.iterators.IteratorEnumeration <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/commons/collections/iterators/IteratorEnumeration.html" title="class in org.apache.commons.collections.iterators"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/apache/commons/collections/iterators/\class-useIteratorEnumeration.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="IteratorEnumeration.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright © 2001-2008 <a href="http://www.apache.org/">The Apache Software Foundation</a>. All Rights Reserved. </BODY> </HTML>
{ "content_hash": "fe63c323cc3a7c2ce4c4e1b803c7455f", "timestamp": "", "source": "github", "line_count": 141, "max_line_length": 260, "avg_line_length": 44.744680851063826, "alnum_prop": 0.6271992391821207, "repo_name": "seeseekey/jenet", "id": "8c81d786daafb0b7b4eabdbadbbb4f2e3c255e85", "size": "6309", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "libs/commons-collections-3.2.1/apidocs/org/apache/commons/collections/iterators/class-use/IteratorEnumeration.html", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "234374" } ], "symlink_target": "" }
namespace ArgentPonyWarcraftClient; /// <summary> /// The gender-specific names for a playable class, race, or title. /// </summary> public record GenderName { /// <summary> /// Gets the name for male characters. /// </summary> [JsonPropertyName("male")] public string Male { get; init; } /// <summary> /// Gets the name for female characters. /// </summary> [JsonPropertyName("female")] public string Female { get; init; } }
{ "content_hash": "8a728895a88494681fc9b6c837a56132", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 67, "avg_line_length": 24.68421052631579, "alnum_prop": 0.6289978678038379, "repo_name": "danjagnow/ArgentPonyWarcraftClient", "id": "d77150484e77b574d37fe8af130613f86575dc7a", "size": "471", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "src/ArgentPonyWarcraftClient/Models/GameDataApi/PlayableClass/GenderName.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "109" }, { "name": "C#", "bytes": "245956" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "d5e34c0afcad187ca6aeb9df3663fe2d", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "dd484cc47edd9b70b0576114a67263979358defd", "size": "188", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Hedysarum/Hedysarum vvedenskyi/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
module Genome module Importers module TdgClinicalTrial def self.source_info { base_url: 'https://clinicaltrials.gov/ct2/results?Search=Search&term=', site_url: 'http://www.ncbi.nlm.nih.gov/pubmed/24016212', citation: "The druggable genome: Evaluation of drug targets in clinical trials suggests major shifts in molecular class and indication. Rask-Andersen M, Masuram S, Schioth HB. Annu Rev Pharmacol Toxicol. 2014;54:9-26. doi: 10.1146/annurev-pharmtox-011613-135943. PMID: 24016212", source_db_version: 'Jan-2014', source_type_id: DataModel::SourceType.INTERACTION, source_db_name: 'TdgClinicalTrial', full_name: 'The Druggable Genome: Evaluation of Drug Targets in Clinical Trials Suggests Major Shifts in Molecular Class and Indication (Rask-Andersen, Masuram, Schioth 2014)', license: 'Supplementary table from Annual Reviews copyright publication', license_link: 'https://www.annualreviews.org/doi/10.1146/annurev-pharmtox-011613-135943?url_ver=Z39.88-2003&rfr_id=ori%3Arid%3Acrossref.org&rfr_dat=cr_pub++0pubmed', } end def self.run(tsv_path) blank_filter = ->(x) { x.blank? || x == "''" || x == '""' } upcase = ->(x) {x.upcase} downcase = ->(x) {x.downcase} TSVImporter.import tsv_path, TdgClinicalTrialRow, source_info do interaction known_action_type: 'unknown' do gene :uniprot_id, nomenclature: 'Uniprot Accession' do name :gene_symbol, nomenclature: 'Gene Symbol', unless: blank_filter attribute :target_main_class, name: 'Target Class', unless: blank_filter attributes :target_subclass, name: 'Target Subclass', unless: blank_filter end drug :drug_name, nomenclature: 'Drug Name', primary_name: :drug_name, transform: upcase do attributes :indication, name: 'Drug Indications', unless: blank_filter attribute :drug_class, name: 'Drug Class', unless: blank_filter attribute :fda_approval, name: 'FDA Approval', unless: blank_filter end attribute :trial_name, name: 'Trial Name', unless: blank_filter attribute :target_novelty, name: 'Novel drug target', unless: blank_filter end end.save! s = DataModel::Source.where(source_db_name: source_info['source_db_name']) s.interaction_claims.each do |ic| Genome::OnlineUpdater.new.create_interaction_claim_link(ic, s.citation, "https://www.annualreviews.org/doi/10.1146/annurev-pharmtox-011613-135943") end end end end end
{ "content_hash": "5e7307f97fe2c00378058f072cb18d8d", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 298, "avg_line_length": 57, "alnum_prop": 0.6381578947368421, "repo_name": "griffithlab/dgi-db", "id": "c681a2eaf4e742c84d2049305b7b10ae57554ebe", "size": "2736", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/genome/importers/tdg_clinical_trial/tdg_clinical_trial_tsv_importer.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "68829" }, { "name": "CoffeeScript", "bytes": "12395" }, { "name": "HTML", "bytes": "229841" }, { "name": "JavaScript", "bytes": "18894" }, { "name": "PLpgSQL", "bytes": "52841" }, { "name": "Perl", "bytes": "4903" }, { "name": "Python", "bytes": "32322" }, { "name": "Ruby", "bytes": "484644" }, { "name": "Shell", "bytes": "3068" } ], "symlink_target": "" }
package org.hibernate.test.annotations.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import org.hibernate.annotations.Type; import org.hibernate.annotations.TypeDef; @TypeDef( typeClass = PhoneNumberType.class ) /** * @author Sharath Reddy * */ @Entity public class LocalContactDetails { @Id @GeneratedValue private int id; private PhoneNumber localPhoneNumber; @Type(type="phoneNumber") private OverseasPhoneNumber overseasPhoneNumber; public int getId() { return id; } public void setId(int id) { this.id = id; } public PhoneNumber getLocalPhoneNumber() { return localPhoneNumber; } public void setLocalPhoneNumber(PhoneNumber localPhoneNumber) { this.localPhoneNumber = localPhoneNumber; } public OverseasPhoneNumber getOverseasPhoneNumber() { return overseasPhoneNumber; } public void setOverseasPhoneNumber(OverseasPhoneNumber overseasPhoneNumber) { this.overseasPhoneNumber = overseasPhoneNumber; } }
{ "content_hash": "8ccd270c0092c4b222856f0b13a0b34a", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 78, "avg_line_length": 21.208333333333332, "alnum_prop": 0.7829076620825147, "repo_name": "HerrB92/obp", "id": "7a60dd4948f99dcc525143490d00ef03ffff9f21", "size": "2083", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "OpenBeaconPackage/libraries/hibernate-release-4.2.7.SP1/project/hibernate-core/src/test/java/org/hibernate/test/annotations/entity/LocalContactDetails.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "181658" }, { "name": "Groovy", "bytes": "98685" }, { "name": "Java", "bytes": "34621856" }, { "name": "JavaScript", "bytes": "356255" }, { "name": "Shell", "bytes": "194" }, { "name": "XSLT", "bytes": "21372" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_67) on Wed Oct 08 15:57:24 PDT 2014 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>Uses of Class org.apache.hadoop.hbase.zookeeper.ZKAssign (HBase 0.98.7-hadoop2 API)</title> <meta name="date" content="2014-10-08"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.hadoop.hbase.zookeeper.ZKAssign (HBase 0.98.7-hadoop2 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/hadoop/hbase/zookeeper/ZKAssign.html" title="class in org.apache.hadoop.hbase.zookeeper">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/hadoop/hbase/zookeeper/class-use/ZKAssign.html" target="_top">Frames</a></li> <li><a href="ZKAssign.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.apache.hadoop.hbase.zookeeper.ZKAssign" class="title">Uses of Class<br>org.apache.hadoop.hbase.zookeeper.ZKAssign</h2> </div> <div class="classUseContainer">No usage of org.apache.hadoop.hbase.zookeeper.ZKAssign</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/hadoop/hbase/zookeeper/ZKAssign.html" title="class in org.apache.hadoop.hbase.zookeeper">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/hadoop/hbase/zookeeper/class-use/ZKAssign.html" target="_top">Frames</a></li> <li><a href="ZKAssign.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2014 <a href="http://www.apache.org/">The Apache Software Foundation</a>. All rights reserved.</small></p> </body> </html>
{ "content_hash": "f9382379231166d6b0ffdc1eac186ccf", "timestamp": "", "source": "github", "line_count": 117, "max_line_length": 151, "avg_line_length": 38.52136752136752, "alnum_prop": 0.6141557577102286, "repo_name": "gsoundar/mambo-ec2-deploy", "id": "51e1ba0cbf1d5717749950b21854006844162655", "size": "4507", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/hbase-0.98.7-hadoop2/docs/devapidocs/org/apache/hadoop/hbase/zookeeper/class-use/ZKAssign.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "23179" }, { "name": "CSS", "bytes": "39965" }, { "name": "HTML", "bytes": "263271260" }, { "name": "Java", "bytes": "103085" }, { "name": "JavaScript", "bytes": "1347" }, { "name": "Python", "bytes": "4101" }, { "name": "Ruby", "bytes": "262588" }, { "name": "Shell", "bytes": "118548" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Web.Routing; using Moq; using System.Web; namespace Elastic.Routing.Tests { [TestClass] public class UrlGenerationTests : ElasticRouteTestBase { RequestContext requestContext; [TestInitialize] public void Initialize() { InitializeBase(); requestContext = new RequestContext() { HttpContext = context.Object }; request.SetupGet(r => r.RequestContext).Returns(requestContext); } [TestMethod] public void ElasticRoute_GetVirtualPath_MatchConstraints() { var routeCollection = new RouteCollection() { new ElasticRoute("url1", routeHandler: routeHandler, constraints: new { controller = "Controller1", action = "Action1" }, outgoingDefaults: new { controller = "Controller1", action = "Action1" }), new ElasticRoute("url2", routeHandler: routeHandler, constraints: new { controller = "Controller2", action = "Action1" }, outgoingDefaults: new { controller = "Controller2", action = "Action1" }), new ElasticRoute("url3", routeHandler: routeHandler, constraints: new { controller = "Controller2", action = "Action2" }, outgoingDefaults: new { controller = "Controller2", action = "Action2" }) }; var routeValues = new RouteValueDictionary(new { controller = "Controller2", action = "Action2" }); var virtualPath = routeCollection.GetVirtualPath(requestContext, routeValues); Assert.AreEqual("/url3", virtualPath.VirtualPath); } [TestMethod] public void ElasticRoute_GetVirtualPath_DefaultValueIsNotAdded() { var routeCollection = new RouteCollection() { new ElasticRoute("{controller}/({action})", routeHandler: routeHandler, constraints: new { controller = "Controller1", action = "Action1" }, outgoingDefaults: new { controller = "Controller1", action = "Action1" }) }; var routeValues = new RouteValueDictionary(new { controller = "Controller1", action = "Action1" }); var virtualPath = routeCollection.GetVirtualPath(requestContext, routeValues); Assert.AreEqual("/controller1/", virtualPath.VirtualPath); } [TestMethod] public void ElasticRoute_GetVirtualPath_DiacriticsInQueryString() { var routeCollection = new RouteCollection() { new ElasticRoute("search", routeHandler: routeHandler) }; var routeValues = new RouteValueDictionary(new { q = "ball ø" }); var virtualPath = routeCollection.GetVirtualPath(requestContext, routeValues); Assert.AreEqual("/search?q=ball+%c3%b8", virtualPath.VirtualPath); } [TestMethod] [DeploymentItem("Elastic.Routing.Tests\\DataSource_Common.xml")] [DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML", "|DataDirectory|\\DataSource_Common.xml", "Row", DataAccessMethod.Sequential)] public void ElasticRoute_GetVirtualPath_CommonDataSource() { RunTest(); } [TestMethod] [DeploymentItem("Elastic.Routing.Tests\\DataSource_Outgoing.xml")] [DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML", "|DataDirectory|\\DataSource_Outgoing.xml", "Row", DataAccessMethod.Sequential)] public void ElasticRoute_GetVirtualPath_SpecificDataSource() { RunTest(); } private void RunTest() { var @params = GetParams(); var route = new ElasticRoute(@params.Pattern, routeHandler: routeHandler, constraints: @params.Constraints, outgoingDefaults: @params.Defaults); var path = route.GetVirtualPath(requestContext, @params.RouteValues); if (@params.Result) { Assert.IsNotNull(path); Assert.AreEqual(@params.Url, path.VirtualPath); } else { Assert.IsNull(path); } } } }
{ "content_hash": "c425e93f79a0f37e171e837e7756663b", "timestamp": "", "source": "github", "line_count": 115, "max_line_length": 111, "avg_line_length": 40.15652173913043, "alnum_prop": 0.5807708964919879, "repo_name": "lokiworld/Elastic.Routing", "id": "858d63bcfd91f8ba7e4b8d9e28c463b582b0ef5c", "size": "4621", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/Elastic.Routing.Tests/UrlGenerationTests.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "407" }, { "name": "C#", "bytes": "128578" } ], "symlink_target": "" }
<?php namespace app\models\vendor; use app\models\Organization; use Yii; use yii\behaviors\SluggableBehavior; use yii\behaviors\TimestampBehavior; /** * This is the model class for table "vendor". * * @property integer $id * @property string $name * @property string $slug * @property double $tax_rate * @property double $tax_service_rate * @property integer $comm_prices * @property double $comm_rate * @property string $comm_note * @property string $admin_notes * @property string $payment_notes * @property integer $status * @property integer $created_at * @property integer $updated_at * * @property VendorDestination[] $vendorDestinations * @property VendorDoc[] $vendorDocs */ class Vendor extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'vendor'; } /** * @inheritdoc */ public function behaviors() { return [ TimestampBehavior::className(), [ 'class' => SluggableBehavior::className(), 'attribute' => 'name', ], ]; } /** * @inheritdoc */ public function rules() { return [ [['name'], 'required'], [['tax_rate', 'tax_service_rate', 'comm_rate'], 'number'], [['comm_prices', 'status', 'created_at', 'updated_at'], 'integer'], [['name', 'slug', 'comm_note', 'admin_notes', 'payment_notes'], 'string', 'max' => 255], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'name' => 'Vendor Name', 'slug' => 'Slug', 'tax_rate' => 'Tax Rate', 'tax_service_rate' => 'Service Rate', 'comm_prices' => 'Comm Prices', 'comm_rate' => 'Commission Rate', 'comm_note' => 'Note', 'admin_notes' => 'Admin Notes', 'payment_notes' => 'Payment Notes', 'status' => 'Status', 'created_at' => 'Created At', 'updated_at' => 'Updated At', ]; } /** * @return \yii\db\ActiveQuery */ public function getVendorDestinations() { return $this->hasMany(VendorDestination::className(), ['vendor_id' => 'organization_id']); } /** * @return \yii\db\ActiveQuery */ public function getVendorDocs() { return $this->hasMany(VendorDoc::className(), ['vendor_id' => 'organization_id']); } /** * @return \yii\db\ActiveQuery */ public function getOrganization() { return $this->hasOne(Organization::className(), ['id' => 'organization_id']); } /** * @return \yii\db\ActiveQuery */ public function getVendorHasTypes() { return $this->hasMany(VendorHasType::className(), ['vendor_id' => 'organization_id']); } }
{ "content_hash": "1c3fc37d0b2866ff269c8bc55d9202d7", "timestamp": "", "source": "github", "line_count": 119, "max_line_length": 100, "avg_line_length": 24.554621848739497, "alnum_prop": 0.54072553045859, "repo_name": "PattiMetz/idoweddings", "id": "f11eb4c89aee2ee9ce5fc7946d4b692d90d5c7c7", "size": "2922", "binary": false, "copies": "1", "ref": "refs/heads/html", "path": "models/vendor/Vendor.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "637" }, { "name": "Batchfile", "bytes": "1030" }, { "name": "CSS", "bytes": "141596" }, { "name": "HTML", "bytes": "3718" }, { "name": "JavaScript", "bytes": "75855" }, { "name": "PHP", "bytes": "505490" } ], "symlink_target": "" }
package signature.converter.util; import java.io.IOException; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import signature.converter.Visibility; import signature.model.IApi; public abstract class AbstractTestSourceConverter implements ITestSourceConverter { public IApi convert(Set<CompilationUnit> units) throws IOException { return convert(Visibility.PROTECTED, units); } public IApi convert(CompilationUnit... units) throws IOException { return convert(Visibility.PROTECTED, new HashSet<CompilationUnit>(Arrays.asList(units))); } public IApi convert(Visibility visibility, CompilationUnit... units) throws IOException { return convert(visibility, new HashSet<CompilationUnit>(Arrays.asList(units))); } }
{ "content_hash": "ca27b6b9bf6e4afe59dea63dd5346400", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 97, "avg_line_length": 31.64, "alnum_prop": 0.7648546144121365, "repo_name": "indashnet/InDashNet.Open.UN2000", "id": "5ca7422f080082ba4daff886eaccebc6c839647d", "size": "1410", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "android/cts/tools/signature-tools/test/signature/converter/util/AbstractTestSourceConverter.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
'use strict' var Game = { run: function(options){ var now, //the time since startup in milliseconds dt = 0, // time between last frame last = Timestamp(), // time from the previous frame fps = 60, // fps cap update = options.update, render = options.render, step = 1/fps; // time passed in each frame in seconds // Gameloop function function Frame() { // This should always be called at the beginning of Frame now = Timestamp(); dt = dt + Math.min(1, (now - last) / 1000); while(dt > step) { dt = dt - step; update(step); } render(); last = now; requestAnimationFrame(Frame); } // Will return the time since startup function Timestamp() { return window.performance && window.performance.now ? window.performance.now() : new Date().getTime(); } // call frame for the first time requestAnimationFrame(Frame); }, }
{ "content_hash": "26dc35b52a7f6d30bfd00307da2df3c1", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 88, "avg_line_length": 31.52777777777778, "alnum_prop": 0.5022026431718062, "repo_name": "woutdp/Minesweeper", "id": "90dd5a7b6397b5e240d5ef832d11c5defbbcc360", "size": "1135", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "game.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5755" }, { "name": "JavaScript", "bytes": "73876" } ], "symlink_target": "" }
Configuration is declared through the key "proxy" and may contains the following properties: * `system` (boolean|string) Should the proxy environment variable be written inside the system-wide "/etc/profile.d" directory. Default to false. A string value defines the path where to place a shell script to export proxy environmental variables, or it will default to "proxy.sh". Unless absolute, the path will be relative to "/etc/profile.d". * `host` The proxy host, not required. The value will determine wether or not we use proxying * `port` The proxy port, not required * `username` The proxy username, not required * `password` The proxy password, not required * `secure` An object with the same `host`, `port`, `username` and `password` property but used for secure https proxy. it default to the default http settings. module.exports = (service) -> options = service.options options.system ?= "proxy.sh" options.system = path.resolve '/etc/profile.d', options.system if options.system options.host ?= null options.port ?= null options.username ?= null options.password ?= null options.secure ?= null ## Validation if not options.host and (options.port or options.username or options.password) throw Error "Invalid proxy configuration" ## Utility function toUrl = (secure, auth) => opts = if secure then options.secure else options scheme = if secure then 'https' else 'http' url = "#{scheme}://" if auth url = "#{url}#{opts.username}" if opts.username url = "#{url}:#{opts.password}" if opts.password url = "#{url}@" if opts.username url = "#{url}#{opts.host}" url = "#{url}:#{opts.port}" if opts.port url ## URLs If at least the `host` property is defined, the configuration will be enriched with the `http_proxy`, the `https_proxy`, the `http_proxy_no_auth` and the `https_proxy_no_auth` urls properties. options.http_proxy = toUrl false, true options.https_proxy = toUrl true, true if options.secure options.http_proxy_no_auth = toUrl false, false options.https_proxy_no_auth = toUrl true, false if options.secure ## Finish options ## Dependencies path = require 'path'
{ "content_hash": "be2026b5fa1908bf06e10f89c23fb61a", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 86, "avg_line_length": 32.75, "alnum_prop": 0.6569126378286684, "repo_name": "adaltas/node-masson", "id": "e70a58f3c1d1aff495e9651ec9bc9ce61ee9489d", "size": "2382", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/proxy/configure.coffee.md", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "472967" }, { "name": "JavaScript", "bytes": "223" }, { "name": "Jinja", "bytes": "2720" }, { "name": "Shell", "bytes": "2619" } ], "symlink_target": "" }
namespace xctest { namespace result { std::string notyet = "";// std::string notapplicable = "n/a"; // error std::string checkmark = "\u2713 pass"; // ✓ std::string failmark = "\u2717 fail"; // ✗ std::string cancelmark = "-"; // canceled. std::string unknown = "?"; } namespace arg { std::string help = "-help"; std::string version = "-version"; std::string verbose = "-verbose"; std::string devices = "-devices"; std::string os_list = "-os-list"; std::string workspace = "-workspace"; std::string scheme = "-scheme"; std::string sdk = "-sdk"; std::string clean = "-clean"; std::string platform = "-platform"; std::string slack_channel = "-slack-channel"; std::string slack_message = "-slack-message"; std::string slack_url = "-slack-url"; } namespace text { std::ostream& bold(std::ostream& os) { return os << "\e[1m"; } std::ostream& bold_off(std::ostream& os) { return os << "\e[0m"; } std::string highlighted(std::string in){ std::stringstream out; out << "▸ " << bold << in << bold_off << std::endl; return out.str(); } } class model { public: std::vector<std::string> operating_systems; std::vector<std::string> devices; std::map<std::string,std::map<std::string,int>> result_map; std::string workspace; std::string scheme; std::string sdk; std::string platform; std::string slack_channel; std::string slack_message; std::string slack_url; public: model(){ for (std::string device:this->devices){ this->result_map[device] = std::map<std::string,int>(); } } std::string out(){ ascii::table myTable("Test Results"); ascii::table &T = myTable; T = T("Devices x OS"); for (auto os:this->operating_systems){ T = T(os); } T++; for(auto device:this->devices){ T = T(device); for(auto os:this->operating_systems){ int result = this->result_map[device][os]; std::stringstream result_string; switch(result){ case -1: result_string << xctest::result::notyet; break; case 0: result_string << xctest::result::checkmark; break; case 2: result_string << xctest::result::cancelmark; break; case 17920: result_string << xctest::result::notapplicable; break; case 16640: result_string << xctest::result::failmark; break; default: result_string << result; } T = T(result_string.str()); } T++; } std::stringstream out; out << myTable << std::endl; return out.str(); } inline std::size_t test_count(){ return this->devices.size() * this->operating_systems.size(); } }; std::string pretty(std::string command){ std::stringstream pretty_command; pretty_command << "set -o pipefail && " << command << "| xcpretty -c"; return pretty_command.str(); } class app { xctest::model in; public: app(xctest::options arguments){ in.devices = arguments[xctest::arg::devices].values(); in.operating_systems = arguments[xctest::arg::os_list].values(); in.scheme = arguments[xctest::arg::scheme].value(); in.platform = arguments[xctest::arg::platform].value(); in.sdk = arguments[xctest::arg::sdk].value(); in.workspace = arguments[xctest::arg::workspace].value(); in.slack_message = arguments[xctest::arg::slack_message].value(); in.slack_channel = arguments[xctest::arg::slack_channel].value(); in.slack_url = arguments[xctest::arg::slack_url].value(); } int clean(){ std::stringstream command; command << "xcodebuild clean"; auto pretty_command = xctest::pretty(command.str()); std::cout << xctest::text::highlighted(command.str()) << std::endl; return system(command.str().c_str()); } int build(){ ascii::table out("Stage I - Build for testing"); out << "workspace " << "scheme" << "platform"; out ++; out << in.workspace << in.scheme << in.platform; out ++; std::cout << out << std::endl; std::stringstream command; command << "xcodebuild build-for-testing" << " -workspace " << in.workspace << " -scheme " << in.scheme << " -sdk " << in.sdk << " -destination \"platform=iOS Simulator,name=iPhone SE,OS=10.1\"";; auto pretty_command = xctest::pretty(command.str()); std::cout << xctest::text::highlighted(command.str()) << std::endl; auto result = system(pretty_command.c_str()); std::cout << "Build command exited with code " << result << std::endl; return result; } int test(){ int current_test = 0; for(auto ios:in.operating_systems){ for (std::string device:in.devices){ int percent = 100*current_test/static_cast<int>(in.test_count()); std::stringstream progress; progress << current_test++ << " of " << in.test_count(); std::stringstream percentage; percentage << percent << "%"; ascii::table out("Stage II - running tests."); (out << "complete" << "test" << "device" << "iOS") ++; (out << percentage.str() << progress.str() << device << ios ) ++; std::cout << out << std::endl; std::stringstream command; command << "xcodebuild test-without-building" << " -workspace " << in.workspace << " -scheme " << in.scheme << " -sdk " << in.sdk << " -destination " << "\"" << "platform=" << in.platform << "," << "name=" << device << "," << "OS=" << ios << "\""; auto pretty_command = xctest::pretty(command.str()); std::cout << xctest::text::highlighted(command.str()) << std::endl; auto result = system(pretty_command.c_str()); in.result_map[device][ios] = result; std::cout << device << " for OS " << ios << " have exited with code " << result << std::endl; } } return this->test_result(); } int test_result(){ for(auto ios:in.operating_systems){ for (std::string device:in.devices){ int result = in.result_map[device][ios]; // skip n/a simulator x os combo if(result != 0 && result != 17920){ return result; } } } return 0; } int print(){ std::cout << in.out() << std::endl; return 0; } int slack(){ std::string final_result = in.out(); std::cout << final_result << std::endl; std::stringstream payload; payload << "payload={" << "\\\"channel\\\": \\\"" << in.slack_channel << "\\\"," << "\\\"link_names\\\": 1," << "\\\"username\\\": \\\"Daher's Bot - xctest\\\", " << "\\\"text\\\": \\\"iOS Pull Request" << "\\n - Build #$TRAVIS_BUILD_NUMBER" << "\\n - " << in.scheme << "\\n - " << "Test " << (this->test_result() ? "Failed!" : "Succeeded") << "\\n - " << in.slack_message << " \\n\\`\\`\\`\\n" << final_result << "\\n\\`\\`\\`\\\", " << "\\\"icon_emoji\\\": \\\":ghost:\\\"}"; std::stringstream command; command << "curl -X POST --data-urlencode \""; for(auto c:payload.str()) { if( c == '\n'){ command << "\\n"; continue; } command << c; } command << "\" " << in.slack_url; std::cout << xctest::text::highlighted(command.str()) << std::endl; return system(command.str().c_str()); } }; } #include "xctest_process.hpp" int main(int argc, const char * argv[]) { auto arguments = xctest::options(argc,argv); arguments.map_to({ {xctest::arg::help, xctest::option("produces the usage of this tool.")}, {xctest::arg::version, xctest::option("displays the version of the tool.")}, {xctest::arg::verbose, xctest::option("displays more output than usual.")}, {xctest::arg::devices, xctest::option("overrides the list of devices.")}, {xctest::arg::os_list, xctest::option("overrides the list of operating systems.")}, {xctest::arg::workspace, xctest::option("the xcode workspace file.")}, {xctest::arg::scheme, xctest::option("the scheme from your xcode project.")}, {xctest::arg::sdk, xctest::option("the sdk. (default: iphonesimulator).")}, {xctest::arg::clean, xctest::option("clean the project before building.")}, {xctest::arg::platform, xctest::option("the platform. (default: iOS Simulator.")}, {xctest::arg::slack_channel, xctest::option("the name of the channel on slack.")}, {xctest::arg::slack_message, xctest::option("the extra message to add to slack.")}, {xctest::arg::slack_url, xctest::option("the url to access your slack.")}, }); if(arguments[xctest::arg::version]){ std::cout << "xctest v1.0 by Daher Alfawares" << std::endl; return 0; } if(arguments[xctest::arg::help]){ std::cout << arguments.print() << std::endl; return 0; } if(!arguments[xctest::arg::devices]){ arguments[xctest::arg::devices] += "iPhone 5s"; arguments[xctest::arg::devices] += "iPhone 6s"; arguments[xctest::arg::devices] += "iPhone 6s Plus"; } if(!arguments[xctest::arg::os_list]){ arguments[xctest::arg::os_list] += "9.0"; arguments[xctest::arg::os_list] += "9.1"; arguments[xctest::arg::os_list] += "9.2"; arguments[xctest::arg::os_list] += "9.3"; arguments[xctest::arg::os_list] += "10.0"; arguments[xctest::arg::os_list] += "10.1"; arguments[xctest::arg::os_list] += "10.2"; arguments[xctest::arg::os_list] += "10.3.1"; } if(!arguments[xctest::arg::scheme]){ std::cerr << "please specify a scheme." << std::endl; return -1; } if(!arguments[xctest::arg::workspace] && !arguments["-project"] ){ std::cerr << "please specify a project or a workspace." << std::endl; return -1; } if(!arguments[xctest::arg::sdk]){ arguments[xctest::arg::sdk] += "iphonesimulator"; } if(!arguments[xctest::arg::platform]){ arguments[xctest::arg::platform] += "iOS Simulator"; } if(arguments[xctest::arg::verbose] || true){ std::cout << arguments.print_values() << std::endl; } auto app = xctest::app(arguments); if(arguments[xctest::arg::clean]){ app.clean(); } app.build(); app.test(); if(arguments[xctest::arg::slack_channel] && arguments[xctest::arg::slack_url]){ app.slack(); } return app.test_result(); }
{ "content_hash": "2904afca2aef2916f0169d24646006bf", "timestamp": "", "source": "github", "line_count": 360, "max_line_length": 101, "avg_line_length": 36.77777777777778, "alnum_prop": 0.4474320241691843, "repo_name": "daher-alfawares/xctest", "id": "0507a5e5d42ad212f73606e5b83880f1bd7baf33", "size": "13529", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "xctest/main.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "28382" } ], "symlink_target": "" }
string CapitalizeFilter::apply(const string& line) { string formated(line); if(formated.length() > 0) formated[0] = toupper(formated[0]); for(std::string::iterator it = formated.begin() + 1; it != formated.end(); ++it) { if(!isalpha(*(it - 1)) && islower(*it)) { *it = toupper(*it); } } return formated; } void CapitalizeFilter::serialize(ofstream &output) { output.write(reinterpret_cast<const char *>(&type_), sizeof(type_)); }
{ "content_hash": "b529e1e15cc2ce41bb629b39d7c31399", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 86, "avg_line_length": 29, "alnum_prop": 0.59026369168357, "repo_name": "L3K0V/fmi-commandline-utilities", "id": "577dbf4d6f3dc6f7ee7c23f31694b108f389e0a9", "size": "526", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "filter_capitalize.cc", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "13600" }, { "name": "JavaScript", "bytes": "367" } ], "symlink_target": "" }
package com.reason.ide.search.index; import com.intellij.psi.stubs.*; import com.reason.lang.core.psi.*; import org.jetbrains.annotations.*; public class VariantFqnIndex extends IntStubIndexExtension<PsiVariantDeclaration> { private static final int VERSION = 4; private static final VariantFqnIndex INSTANCE = new VariantFqnIndex(); public static @NotNull VariantFqnIndex getInstance() { return INSTANCE; } @Override public int getVersion() { return super.getVersion() + VERSION; } @Override public @NotNull StubIndexKey<Integer, PsiVariantDeclaration> getKey() { return IndexKeys.VARIANTS_FQN; } }
{ "content_hash": "e297f47db5f2406ac1a46e2571b6ff4f", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 83, "avg_line_length": 27.875, "alnum_prop": 0.7174887892376681, "repo_name": "reasonml-editor/reasonml-idea-plugin", "id": "23a5d3fc2a1669a56af0b22674b51c671caaedba", "size": "669", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/reason/ide/search/index/VariantFqnIndex.java", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "133" }, { "name": "Java", "bytes": "1219386" }, { "name": "Lex", "bytes": "18748" }, { "name": "OCaml", "bytes": "17262" }, { "name": "Reason", "bytes": "1296" } ], "symlink_target": "" }
<div> <h2><span>Room Allocation</span> {{vm.roomAllocation.roomName}}</h2> <hr> <jhi-alert-error></jhi-alert-error> <dl class="dl-horizontal jh-entity-details"> <dt><span>Room Name</span></dt> <dd> <span>{{vm.roomAllocation.roomName}}</span> </dd> <dt><span>User Name</span></dt> <dd> <span>{{vm.roomAllocation.userName}}</span> </dd> <dt><span>From Date</span></dt> <dd> <span>{{vm.roomAllocation.fromDate | date:'mediumDate'}}</span> </dd> <dt><span>To Date</span></dt> <dd> <span>{{vm.roomAllocation.toDate | date:'mediumDate'}}</span> </dd> <dt><span>Curr Status</span></dt> <dd> <span>{{vm.roomAllocation.currStatus}}</span> </dd> <dt><span>Updated By</span></dt> <dd> <span>{{vm.roomAllocation.updatedBy}}</span> </dd> <dt><span>Updated Date Time</span></dt> <dd> <span>{{vm.roomAllocation.updatedDateTime | date:'mediumDate'}}</span> </dd> </dl> <button type="submit" ui-sref="{{ vm.previousState }}" class="btn btn-info"> <span class="glyphicon glyphicon-arrow-left"></span>&nbsp;<span> Back</span> </button> <button type="button" ui-sref="room-allocation-detail.edit({id:vm.roomAllocation.id})" class="btn btn-primary"> <span class="glyphicon glyphicon-pencil"></span> <span class="hidden-sm-down"> Edit</span> </button> </div>
{ "content_hash": "2d150aef3d121aeb5c3e96b9543d755d", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 115, "avg_line_length": 34.23913043478261, "alnum_prop": 0.5333333333333333, "repo_name": "benoyprakash/java-hostel", "id": "90edab1fe4d4d82e60189c87342ae321ee46da59", "size": "1576", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "JHipster-hostel/src/main/webapp/app/entities/room-allocation/room-allocation-detail.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "5006" }, { "name": "CSS", "bytes": "160750" }, { "name": "HTML", "bytes": "175884" }, { "name": "Java", "bytes": "412894" }, { "name": "JavaScript", "bytes": "292653" }, { "name": "Shell", "bytes": "7058" } ], "symlink_target": "" }
This project creates a working snap of youtube-dl. To get this done, we need to do the following: - Build from current git ## Current state Working features: - Video downloading Known issues: - The home plug needs to be connected manually after snap install with "sudo snap connect youtube-dl:home ubuntu-core:home" - ffprobe is not found when using `-x --audioformat mp3` option. Fix proposed in pull request
{ "content_hash": "9f0eb41b46d8f407075475de1c64acef", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 73, "avg_line_length": 28.666666666666668, "alnum_prop": 0.7418604651162791, "repo_name": "wandrewkeech/snappy-playpen", "id": "a0443121ef9e657dce550be0afa9651f6f752cc7", "size": "449", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "youtube-dl/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Makefile", "bytes": "921" }, { "name": "Python", "bytes": "10096" }, { "name": "Shell", "bytes": "12288" } ], "symlink_target": "" }
Bridge.merge(new System.Globalization.CultureInfo("zh-Hans-HK", true), { englishName: "Chinese (Simplified Han, Hong Kong SAR)", nativeName: "中文 (香港特别行政区)", numberFormat: Bridge.merge(new System.Globalization.NumberFormatInfo(), { nanSymbol: "NaN", negativeSign: "-", positiveSign: "+", negativeInfinitySymbol: "-∞", positiveInfinitySymbol: "∞", percentSymbol: "%", percentGroupSizes: [3], percentDecimalDigits: 2, percentDecimalSeparator: ".", percentGroupSeparator: ",", percentPositivePattern: 1, percentNegativePattern: 1, currencySymbol: "$", currencyGroupSizes: [3], currencyDecimalDigits: 2, currencyDecimalSeparator: ".", currencyGroupSeparator: ",", currencyNegativePattern: 1, currencyPositivePattern: 0, numberGroupSizes: [3], numberDecimalDigits: 2, numberDecimalSeparator: ".", numberGroupSeparator: ",", numberNegativePattern: 1 }), dateTimeFormat: Bridge.merge(new System.Globalization.DateTimeFormatInfo(), { abbreviatedDayNames: ["周日","周一","周二","周三","周四","周五","周六"], abbreviatedMonthGenitiveNames: ["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月",""], abbreviatedMonthNames: ["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月",""], amDesignator: "上午", dateSeparator: "/", dayNames: ["星期日","星期一","星期二","星期三","星期四","星期五","星期六"], firstDayOfWeek: 0, fullDateTimePattern: "yyyy年M月d日dddd tth:mm:ss", longDatePattern: "yyyy年M月d日dddd", longTimePattern: "tth:mm:ss", monthDayPattern: "M月d日", monthGenitiveNames: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月",""], monthNames: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月",""], pmDesignator: "下午", rfc1123: "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", shortDatePattern: "d/M/yyyy", shortestDayNames: ["周日","周一","周二","周三","周四","周五","周六"], shortTimePattern: "tth:mm", sortableDateTimePattern: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", sortableDateTimePattern1: "yyyy'-'MM'-'dd", timeSeparator: ":", universalSortableDateTimePattern: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", yearMonthPattern: "yyyy年M月", roundtripFormat: "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffzzz" }), TextInfo: Bridge.merge(new System.Globalization.TextInfo(), { ANSICodePage: 936, CultureName: "zh-Hans-HK", EBCDICCodePage: 500, IsRightToLeft: false, LCID: 4096, listSeparator: ";", MacCodePage: 10008, OEMCodePage: 936, IsReadOnly: true }) });
{ "content_hash": "99e18b910f61793b5c093522544e404c", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 107, "avg_line_length": 39.94285714285714, "alnum_prop": 0.572961373390558, "repo_name": "AndreyZM/Bridge", "id": "eaf0e5a593de9ed7c8f0005b47cc7db74dd86bf0", "size": "3096", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Bridge/Resources/Locales/zh-Hans-HK.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "4769" }, { "name": "C#", "bytes": "23533024" }, { "name": "CSS", "bytes": "507" }, { "name": "HTML", "bytes": "190" }, { "name": "JavaScript", "bytes": "3937" }, { "name": "PowerShell", "bytes": "5284" }, { "name": "Shell", "bytes": "7698" } ], "symlink_target": "" }
Pseudositer looks for elements with particular classes to populate with index links and content. If the element does not already exist on the page, Pseudositer will generate it. If the element does already exist on the page, pseudositer will use the existing element. An empty page with a pseudositer `div` will be generated with this arrangement: <div id="pseudositer"> <div class="pseudositer-index-container"> <!-- Index level 0 contains links to files and folders located in #/ --> <div class="pseudositer-index pseudositer-index-0"> <a href="#/Blue/" class="pseudositer-link">Blue</a> <a href="#/Green/" class="pseudositer-link">Green</a> <a href="#/Red/" class="pseudositer-link-selected">Red</a> <!-- This link is selected --> <!-- Further links to files and folders in #/ go here... --> </div> <!-- Index level 1 contains links to files and folders located in #/Red/ --> <div class="pseudositer-index pseudositer-index-1"> <a href="#/Red/First/" class="pseudositer-link">First</a> <a href="#/Red/Second/" class="pseudositer-link-selected">Second</a> <!-- This link is selected --> <a href="#/Red/Third/" class="pseudositer-link">Third</a> <!-- Further links to files and folders in #/Red/ go here... --> </div> <!-- Index level 2 contains links to files and folders located in #/Red/Second/ --> <div class="pseudositer-index pseudositer-index-2"> <a href="#/Red/Second/file.html" class="pseudositer-link-selected">file</a> <!-- This link is selected --> <a href="#/Red/Second/image.jpg" class="pseudositer-link">image</a> <!-- Further links to files and folders in #/Red/Second/ go here... --> </div> <!-- If there were further index levels visible, they would be here. --> </div> <div class="pseudositer-content"> <!-- Content of #/Red/Second/file.html goes here --> </div> <div class="pseudositer-error"> <!-- Error message goes here --> </div> <div class="pseudositer-loading"> <!-- Loading message goes here --> </div> </div> Your stylesheets should utilize these CSS classes. - - - ### .pseudositer-content The element that holds all content. There should be only one on the page. - - - ### .pseudositer-index-container The element that holds all generated index elements. There should be only one on the page. If you specify your own `.pseudositer-index-<N>` elements, they do not need to be in this class. - - - ### .pseudositer-index This class applies to all generated elements that hold links from an index page. - - - ### .pseudositer-index-`<N>` These elements hold the links from a certain level of index page, starting at `0`. There should only be one element for each level on the page. For example, `pseudositer-index-0` is the class of the index of your root directory. - - - ### .pseudositer-error These elements hold any error messages generated by pseudositer. These include, but are not limited to, timeout and 404 messages. - - - ### .pseudositer-loading These elements will appear when pseudositer is loading new content or indices.
{ "content_hash": "c66387095fa73ae56899a72e0222dfe1", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 269, "avg_line_length": 42.27272727272727, "alnum_prop": 0.6556067588325653, "repo_name": "talos/pseudositer", "id": "784718aa64aab6082243f6617bc8eb06cc2b5446", "size": "3255", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/Styling.md", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "36482" }, { "name": "JavaScript", "bytes": "336398" } ], "symlink_target": "" }
// Copyright (c) 2018, Baidu.com, Inc. All Rights Reserved // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // The Designs of Filter and related codes are inspired by hbase which is licensed under // Apache 2.0 License (found in the LICENSE.Apache file in the root directory). Please refer to // https://hbase.apache.org/2.0/apidocs/org/apache/hadoop/hbase/filter/Filter.html // to see more detailed design of hbase filter. #pragma once #include <string> #include <memory> #include "tera/filter.h" #include "tera/filter_comparator.h" namespace tera { namespace filter { class ValueFilter; using ValueFilterPtr = std::shared_ptr<ValueFilter>; /* * User can use this class to make a value filter. * Please use std::make_shared method to New a value filter object, and assign the object to * the ValueFilterPtr. */ class ValueFilter : public FilterBase { // User interface public: /* * New a value filter by using this method, And assign the object to a ValueFilterPtr. * Note that a comparator object should be exist before you new a value filter. You can refer to * the filter_comparator.h for how to new a comparator object. CompareOperator is also defined * in the filter_comparator.h */ ValueFilter(CompareOperator op, const FilterComparatorPtr& comparator); /* * User can set the column family in which the value cell should be execute filter. * If not set, the family will be "". */ void SetColumnFamily(const std::string& column_family); /* * User can set the qualifier in which the value cell should be execute filter. * If not set, the qualifier will be "". */ void SetColumnQualifier(const std::string& column_qualifier); /* * filter_if_missing is true means that if there is no family and qualifier matched in this row, * which the filter specified, the row will be filtered out (not output), or the row will be not * filtered (the row will be output). * * Default is false. */ void SetFilterIfMissing(bool filter_if_missing); /* * User do NOT need to use the interfaces below. The internal of tera will use them. */ public: ValueFilter(); virtual ~ValueFilter(); virtual FilterType Type(); virtual void Reset(); virtual ReturnCode FilterCell(const std::string& column_family, const std::string& column_qualifier, const std::string& value); virtual bool FilterRow(); virtual bool SerializeTo(std::string* serialized_filter); virtual bool ParseFrom(const std::string& serialized_filter); virtual void GetAllColumn(ColumnSet* column_set); private: virtual ReturnCode FilterCellWithEmptyQualifier(const std::string& column_family, const std::string& column_qualifier, const std::string& value); virtual ReturnCode FilterCellWithNotEmptyQualifier(const std::string& column_family, const std::string& column_qualifier, const std::string& value); bool MatchValue(const std::string& value); bool MatchOp(int compare_result); private: enum MatchStatus { kNotMatchAnything, // not match cf and qu yet kMatchColumnButNotValue, // matched cf and qu, but not match the value of the cf and qu kMatchColumnAndValue // matched cf and qu and the value of them }; private: std::string column_family_; std::string column_qualifier_; CompareOperator op_; FilterComparatorPtr comparator_; bool filter_if_missing_; MatchStatus match_status_; }; } // namesapce filter } // namesapce tera
{ "content_hash": "2f7c6c617666b4aedd8440e8a23738a7", "timestamp": "", "source": "github", "line_count": 102, "max_line_length": 98, "avg_line_length": 36.666666666666664, "alnum_prop": 0.6831550802139037, "repo_name": "BaiduPS/tera", "id": "07fa1cc2069e87edbede82312a752e8f4438f682", "size": "3740", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "include/tera/value_filter.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "80545" }, { "name": "C++", "bytes": "3656768" }, { "name": "CMake", "bytes": "1005" }, { "name": "Java", "bytes": "29791" }, { "name": "Makefile", "bytes": "16373" }, { "name": "Protocol Buffer", "bytes": "28979" }, { "name": "Python", "bytes": "121068" }, { "name": "Shell", "bytes": "36158" } ], "symlink_target": "" }
<?xml version="1.0" encoding="ISO-8859-1"?> <project basedir="." default="jar" name="docgen" xmlns:ivy="antlib:org.apache.ivy.ant" xmlns:docgen="http://freemarker.org/docgen" xmlns:u="http://freemarker.org/ant-utils" > <!-- ================================================================== --> <!-- Properties and filtering --> <!-- ================================================================== --> <!-- Ivy project coordinates: --> <property name="moduleOrg" value="org.freemarker" /> <property name="moduleName" value="docgen" /> <property name="moduleBranch" value="2.0" /> <!-- Will be overidden on the server: --> <property name="server.ivy.repo.root" value="${basedir}/build/dummy-server-ivy-repo" /> <!-- Needed for travis-ci build --> <property name="ivy.install.version" value="2.4.0" /> <condition property="ivy.home" value="${env.IVY_HOME}"> <isset property="env.IVY_HOME" /> </condition> <property name="ivy.home" value="${user.home}/.ant" /> <property name="ivy.jar.dir" value="${ivy.home}/lib" /> <property name="ivy.jar.file" value="${ivy.jar.dir}/ivy.jar" /> <property file="build.properties" /> <!-- When boot.classpath is missing, this is the default: --> <property name="boot.classpath" value="${sun.boot.class.path}" /> <!-- Checking the correctness of the boot.classpath --> <available classpath="${boot.classpath}" classname="java.lang.Object" ignoresystemclasses="true" property="boot.classpath.correct" /> <property file="src/main/org/freemarker/docgen/version.properties" /> <tstamp> <format property="timestamp" pattern="yyyy-MM-dd HH:mm:ss z" timezone="GMT" /> </tstamp> <filter token="version" value="${version}" /> <filter token="buildTimestamp" value="${timestamp}" /> <!-- ================================================================== --> <!-- Paths --> <!-- ================================================================== --> <!-- Classpath-es (dependencies) separately for each module --> <!-- Needed for purely technical resons... --> <path id="classpath.empty" /> <!-- ================================================================== --> <!-- Task definitions --> <!-- ================================================================== --> <!-- A customized and extended version of the standrad javac task. It copies non-java files (resources). --> <macrodef name="javacAndCopyResources" uri="http://freemarker.org/ant-utils"> <attribute name="srcDir" /> <attribute name="destDir" /> <attribute name="classpath" default="" /> <attribute name="classpathRef" default="classpath.empty" /> <sequential> <fail unless="boot.classpath.correct"><!-- -->The "boot.classpath" property value (${boot.classpath}) <!-- -->seems to be an incorrect boot classpath. Please fix it in <!-- -->the &lt;projectDir>/build.properties file, or wherever you <!-- -->set it.<!-- --></fail> <echo level="info">Using boot classpath: ${boot.classpath}</echo> <mkdir dir="@{destDir}" /> <javac srcdir="@{srcDir}" destDir="@{destDir}" deprecation="on" debug="on" source="1.8" target="1.8" classpath="@{classpath}" classpathRef="@{classpathRef}" bootclasspath="${boot.classpath}" /> <copy todir="@{destDir}" filtering="true" includeEmptyDirs="false"> <fileset dir="@{srcDir}"> <include name="**/*.properties" /> </fileset> </copy> <copy todir="@{destDir}" filtering="false" includeEmptyDirs="false"> <fileset dir="@{srcDir}"> <exclude name="**/*.java" /> <exclude name="**/package.html" /> <exclude name="**/overview.html" /> <exclude name="**/*.properties" /> </fileset> </copy> </sequential> </macrodef> <!-- A customized version of the standrad javadoc task. --> <macrodef name="javadoc" uri="http://freemarker.org/ant-utils"> <attribute name="title" /> <attribute name="srcDir" /> <!-- "main" usually --> <attribute name="packageNames" default="*" /> <attribute name="excludePackages" default="non.such.package" /> <attribute name="destDir" /> <attribute name="classpath" default="" /> <attribute name="classpathRef" default="classpath.empty" /> <sequential> <echo level="info"><!-- -->Javadoc generation for: @{title}<!-- --></echo> <u:provideEmptyDir dir="@{destDir}" /> <javadoc sourcepath="@{srcDir}" destdir="@{destDir}" doctitle="@{title}" packagenames="@{packageNames}" excludepackagenames="@{excludePackages}" windowtitle="@{title}" overview="@{srcDir}/overview.html" version="false" author="false" charset="UTF-8" docencoding="UTF-8" locale="en_US" use="yes" failonerror="yes" classpath="@{classpath}" classpathRef="@{classpathRef}" /> </sequential> </macrodef> <macrodef name="provideEmptyDir" uri="http://freemarker.org/ant-utils"> <attribute name="dir" /> <sequential> <mkdir dir="@{dir}" /> <delete includeEmptyDirs="true"> <fileset dir="@{dir}" includes="**/*" defaultexcludes="no" /> </delete> </sequential> </macrodef> <!-- ================================================================== --> <!-- Targets --> <!-- ================================================================== --> <target name="init"> <condition property="deps.available"> <and> <available file=".ivy" /> <available file="node_modules" /> </and> </condition> <antcall target="_autoget-deps" /> </target> <target name="classes" depends="init, gulp" description='Compile + resource copy' > <u:provideEmptyDir dir="build/classes" /> <ivy:cachepath pathid="ivy.dep" /> <u:javacAndCopyResources srcDir="src/main" destDir="build/classes" classpathref="ivy.dep" /> </target> <target name="jar" depends="classes" description='Build "build/docgen.jar".' > <mkdir dir="build/artifacts" /> <jar jarfile="build/artifacts/docgen.jar"> <fileset dir="build/classes" /> <manifest> <attribute name="Main-Class" value="org.freemarker.docgen.TransformCommandLine" /> <attribute name="Class-Path" value="freemarker.jar jing.jar" /> <attribute name="Specification-Version" value="${version}" /> <attribute name="Implementation-Version" value="${version}" /> </manifest> </jar> <mkdir dir="build/lib" /> <ivy:retrieve pattern="build/lib/[artifact].[ext]" /> <copy file="build/artifacts/docgen.jar" todir="build/lib" /> </target> <target name="javadoc" depends="init" description="Build the JavaDoc." > <ivy:cachepath pathid="ivy.dep" /> <u:javadoc title="Docgen API" srcdir="src/main" destDir="build/api" classpathref="ivy.dep" /> </target> <target name="all" depends="jar, javadoc" description='Build "docgen.jar" + javadocs' /> <target name="clean" description='Delete output files.'> <u:provideEmptyDir dir="build" /> <delete file="build/docgen.jar" /> </target> <target name="test" depends="jar"> <echo>***************************************</echo> <echo>* Now issue this in the command-line: *</echo> <echo>* ant -f test.xml *</echo> <echo>***************************************</echo> </target> <target name="archive" description='Archives project into the "archive" directory.'> <mkdir dir="archive" /> <tstamp> <format property="tstamp" pattern="yyyyMMdd-HHmm" /> </tstamp> <delete file="archive/docgen-${tstamp}.tar" /> <delete file="archive/docgen-${tstamp}.tar.bz2" /> <tar tarfile="archive/docgen-${tstamp}.tar" basedir="." longfile="gnu" excludes="build/** .build/** **/*.class **/*.jar archive/** lib/**" /> <bzip2 src="archive/docgen-${tstamp}.tar" zipfile="archive/docgen-${tstamp}.tar.bz2" /> <delete file="archive/docgen-${tstamp}.tar" /> </target> <target name="artifacts" depends="jar" description="Creates the artifacts for Ivy." /> <!-- ================================================================== --> <!-- Dependency management (keep it exactly identical for all projects) --> <!-- ================================================================== --> <!-- Needed for travis-ci build --> <target name="download-ivy" unless="offline"> <mkdir dir="${ivy.jar.dir}"/> <!-- download Ivy from web site so that it can be used even without any special installation --> <get src="http://repo2.maven.org/maven2/org/apache/ivy/ivy/${ivy.install.version}/ivy-${ivy.install.version}.jar" dest="${ivy.jar.file}" usetimestamp="true"/> </target> <target name="_autoget-deps" unless="deps.available"> <antcall target="update-deps" /> <antcall target="node-deps" /> </target> <target name="update-deps" description="Gets the latest version of the dependencies from the Web" > <echo>Getting dependencies...</echo> <echo>-------------------------------------------------------</echo> <ivy:settings id="remote" url="http://freemarker.org/repos/ivy/ivysettings-remote.xml" /> <!-- Build an own repository that will serve us even offline: --> <ivy:retrieve settingsRef="remote" sync="true" ivypattern=".ivy.part/repo/[organisation]/[module]/ivy-[revision].xml" pattern=".ivy.part/repo/[organisation]/[module]/[artifact]-[revision].[ext]" /> <echo>-------------------------------------------------------</echo> <echo>*** Successfully acquired dependencies from the Web ***</echo> <echo>Eclipse users: Now right-click on ivy.xml and Resolve! </echo> <echo>-------------------------------------------------------</echo> <!-- Only now that we got all the dependencies will we delete anything. --> <!-- Thus a net or repo outage doesn't left us without the dependencies. --> <!-- Save the resolution cache from the soon coming <delete>: --> <move todir=".ivy.part/update-deps-reso-cache"> <fileset dir=".ivy/update-deps-reso-cache" /> </move> <!-- Drop all the old stuff: --> <delete dir=".ivy" /> <!-- And use the new stuff instead: --> <move todir=".ivy"> <fileset dir=".ivy.part" /> </move> </target> <!-- Do NOT call this from 'clean'; offline guys would stuck after that. --> <target name="clean-deps" description="Deletes all dependencies" > <delete dir=".ivy" /> <delete dir="node_modules" /> </target> <!-- See README.md about installing node.js and Gulp! --> <target name="node-deps"> <exec executable="npm" dir="${basedir}" failonerror="true" osfamily="unix"> <arg line="install" /> </exec> <exec executable="cmd" dir="${basedir}" failonerror="true" osfamily="windows"> <arg line="/c npm install" /> </exec> </target> <target name="gulp"> <exec executable="node" failonerror="true" dir="${basedir}"> <arg line="node_modules/gulp/bin/gulp.js"/> </exec> <!-- <exec executable="${nodeJsCommand}" failonerror="true" dir="${basedir}"> <arg value="node_modules/gulp/bin/gulp.js"/> </exec> --> </target> <target name="publish-override" depends="artifacts" description="Ivy-publishes THIS project locally as an override" > <ivy:resolve /> <ivy:publish pubrevision="${moduleBranch}-branch-head" overwrite="true" forcedeliver="true" resolver="freemarker-devel-local-override" > <artifacts pattern="build/artifacts/[artifact].[ext]" /> </ivy:publish> <echo>-------------------------------------------------------</echo> <echo>*** Don't forget to `ant unpublish-override` later! ***</echo> </target> <target name="unpublish-override" description="Undoes publish-override (made in THIS project)" > <delete dir="${user.home}/.ivy2/freemarker-devel-local-override/${moduleOrg}/${moduleName}" /> <delete dir="${user.home}/.ivy2/freemarker-devel-local-override-cache/${moduleOrg}/${moduleName}" /> </target> <target name="unpublish-override-all" description="Undoes publish-override-s made in ALL projects" > <delete dir="${user.home}/.ivy2/freemarker-devel-local-override" /> <delete dir="${user.home}/.ivy2/freemarker-devel-local-override-cache" /> </target> <target name="uninstall" description="Deletes external files created by FreeMarker developement" > <delete dir="${user.home}/.ivy2/freemarker-devel-cache" /> <delete dir="${user.home}/.ivy2/freemarker-devel-local-override" /> <delete dir="${user.home}/.ivy2/freemarker-devel-local-override-cache " /> </target> <target name="report-deps" description="Creates a HTML document that summarizes the dependencies." > <mkdir dir="build/deps-report" /> <ivy:resolve /> <ivy:report todir="build/deps-report" /> </target> <target name="ide-dependencies" description="If your IDE has no Ivy support, this generates ide-lib/*.jar for it"> <mkdir dir="ide-dependencies" /> <delete includeEmptyDirs="true"> <fileset dir="ide-dependencies"> <include name="*/**" /> </fileset> </delete> <ivy:retrieve pattern="ide-dependencies/[artifact]-[revision].[ext]" /> </target> <!-- This meant to be called on the Continuous Integration server, so the integration builds appear in the freemarker.org public Ivy repository. The artifacts must be already built. --> <target name="server-publish-last-build" description="(For the Continuous Integration server only)" > <delete dir="build/dummy-server-ivy-repo" /> <ivy:resolve /> <ivy:publish pubrevision="${moduleBranch}-branch-head" overwrite="true" forcedeliver="true" resolver="server-publishing-target" > <artifacts pattern="build/artifacts/[artifact].[ext]" /> </ivy:publish> </target> </project>
{ "content_hash": "a628fbca9f2063d4f743e514484f2e6c", "timestamp": "", "source": "github", "line_count": 418, "max_line_length": 117, "avg_line_length": 34.77751196172249, "alnum_prop": 0.5624269106418106, "repo_name": "pradeepmurugesan/incubator-freemarker-docgen", "id": "dd5a5a540f482aa91a0007df70d708328aec7371", "size": "14537", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "build.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "31388" }, { "name": "HTML", "bytes": "131" }, { "name": "Java", "bytes": "334237" }, { "name": "JavaScript", "bytes": "6276" } ], "symlink_target": "" }
package org.smartpony.common.error trait ErrorCode { val identifier: String lazy val code: String = identifier.split(": ")(0) lazy val message: String = identifier.split(": ")(1) }
{ "content_hash": "a292ad32f5cb0667b0cd9755cc123c2f", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 54, "avg_line_length": 21.11111111111111, "alnum_prop": 0.6947368421052632, "repo_name": "Dextaa/smartpony", "id": "5b421a084ee1544f5b08bce9188b58ea28b2f6e2", "size": "190", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "common/src/main/scala/org/smartpony/common/error/ErrorCode.scala", "mode": "33188", "license": "mit", "language": [ { "name": "Scala", "bytes": "76313" }, { "name": "Shell", "bytes": "247" } ], "symlink_target": "" }
--- uid: SolidEdgePart.StudyOwner summary: remarks: example: [*content] --- [!code-vb[Main](..\snippets\SolidEdgePart.StudyOwner.vb] [!code-csharp[Main](..\snippets\SolidEdgePart.StudyOwner.cs]
{ "content_hash": "f7496de91ffeb0b9e84334f6d15a7c2d", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 60, "avg_line_length": 24.625, "alnum_prop": 0.7309644670050761, "repo_name": "SolidEdgeCommunity/docs", "id": "586761f360963f92d03f2bde7dad0e16c236703c", "size": "199", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docfx_project/apidoc/SolidEdgePart.StudyOwner.md", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "38" }, { "name": "C#", "bytes": "5048212" }, { "name": "C++", "bytes": "2265" }, { "name": "CSS", "bytes": "148" }, { "name": "PowerShell", "bytes": "180" }, { "name": "Smalltalk", "bytes": "1996" }, { "name": "Visual Basic", "bytes": "10236277" } ], "symlink_target": "" }
<?php namespace PHPExiftool\Driver\Tag\XML; use JMS\Serializer\Annotation\ExclusionPolicy; use PHPExiftool\Driver\AbstractTag; /** * @ExclusionPolicy("all") */ class Division extends AbstractTag { protected $Id = 'Division'; protected $Name = 'Division'; protected $FullName = 'OOXML::Main'; protected $GroupName = 'XML'; protected $g0 = 'XML'; protected $g1 = 'XML'; protected $g2 = 'Document'; protected $Type = '?'; protected $Writable = false; protected $Description = 'Division'; }
{ "content_hash": "92a19d8eb9a3a3e58c4bfcd8a112c1c1", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 46, "avg_line_length": 15.13888888888889, "alnum_prop": 0.6477064220183486, "repo_name": "bburnichon/PHPExiftool", "id": "d93ff92e52a7f3c736b6fd111d8ec1b53eb81962", "size": "769", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/PHPExiftool/Driver/Tag/XML/Division.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "22076400" } ], "symlink_target": "" }
@inject('roles', 'App\Repositories\Backend\Role\RoleRepositoryContract') @extends ('backend.layouts.master') @section ('title', trans('menus.permission_management')) @section('page-header') <h1> {{ trans('menus.user_management') }} <small>{{ trans('menus.permission_management') }}</small> </h1> @endsection @section('after-styles-end') {!! HTML::style('css/backend/plugin/nestable/jquery.nestable.css') !!} @stop @section ('breadcrumbs') <li><a href="{!!route('backend.dashboard')!!}"><i class="fa fa-dashboard"></i> {{ trans('menus.dashboard') }}</a></li> <li>{!! link_to_route('admin.access.users.index', trans('menus.user_management')) !!}</li> <li class="active">{!! link_to_route('admin.access.roles.permissions.index', trans('menus.permission_management')) !!}</li> @stop @section('content') @include('backend.access.includes.partials.header-buttons') <div> <!-- Nav tabs --> <ul class="nav nav-tabs" role="tablist"> <li role="presentation" class="active"><a href="#groups" aria-controls="groups" role="tab" data-toggle="tab">Groups</a></li> <li role="presentation"><a href="#permissions" aria-controls="permissions" role="tab" data-toggle="tab">Permissions</a></li> </ul> <!-- Tab panes --> <div class="tab-content"> <div role="tabpanel" class="tab-pane active" id="groups" style="padding-top:20px"> <div class="row"> <div class="col-lg-6"> <div class="alert alert-info"> <i class="fa fa-info-circle"></i> This section allows you to organize your permissions into groups to stay organized. Regardless of the group, the permissions are still individually assigned to each role. </div><!--alert info--> <div class="dd permission-hierarchy"> <ol class="dd-list"> @foreach ($groups as $group) <li class="dd-item" data-id="{!! $group->id !!}"> <div class="dd-handle">{!! $group->name !!} <span class="pull-right">{!! $group->permissions->count() !!} permissions</span></div> @if ($group->children->count()) <ol class="dd-list"> @foreach($group->children as $child) <li class="dd-item" data-id="{!! $child->id !!}"> <div class="dd-handle">{!! $child->name !!} <span class="pull-right">{!! $child->permissions->count() !!} permissions</span></div> </li> @endforeach </ol> </li> @else </li> @endif @endforeach </ol> </div><!--master-list--> </div><!--col-lg-4--> <div class="col-lg-6"> <div class="alert alert-info"> <i class="fa fa-info-circle"></i> If you performed operations in the hierarchy section without refreshing this page, you will need to refresh to reflect the changes here. </div><!--alert info--> <table class="table table-striped table-bordered table-hover"> <thead> <tr> <th>{{ trans('crud.permissions.groups.name') }}</th> <th>{{ trans('crud.actions') }}</th> </tr> </thead> <tbody> @foreach ($groups as $group) <tr> <td> {!! $group->name !!} @if ($group->permissions->count()) <div style="padding-left:40px;font-size:.8em"> @foreach ($group->permissions as $permission) {!! $permission->display_name !!}<br/> @endforeach </div> @endif </td> <td>{!! $group->action_buttons !!}</td> </tr> @if ($group->children->count()) @foreach ($group->children as $child) <tr> <td style="padding-left:40px"> <em>{!! $child->name !!}</em> @if ($child->permissions->count()) <div style="padding-left:40px;font-size:.8em"> @foreach ($child->permissions as $permission) {!! $permission->display_name !!}<br/> @endforeach </div> @endif </td> <td>{!! $child->action_buttons !!}</td> </tr> @endforeach @endif @endforeach </tbody> </table> </div><!--col-lg-8--> </div><!--row--> </div><!--groups--> <div role="tabpanel" class="tab-pane" id="permissions" style="padding-top:20px"> <table class="table table-striped table-bordered table-hover"> <thead> <tr> <th>{{ trans('crud.permissions.permission') }}</th> <th>{{ trans('crud.permissions.name') }}</th> <th>{{ trans('crud.permissions.dependencies') }}</th> <th>{{ trans('crud.permissions.users') }}</th> <th>{{ trans('crud.permissions.roles') }}</th> <th>{{ trans('crud.permissions.group') }}</th> <th>{{ trans('crud.permissions.group-sort') }}</th> <th>{{ trans('crud.permissions.system') }}</th> <th>{{ trans('crud.actions') }}</th> </tr> </thead> <tbody> @foreach ($permissions as $permission) <tr> <td>{!! $permission->name !!}</td> <td>{!! $permission->display_name !!}</td> <td> @if (count($permission->dependencies)) @foreach($permission->dependencies as $dependency) {!! $dependency->permission->display_name !!}<br/> @endforeach @else <span class="label label-success">None</span> @endif </td> <td> @if (count($permission->users)) @foreach($permission->users as $user) {!! $user->name !!}<br/> @endforeach @else <span class="label label-danger">None</span> @endif </td> <td> {!! $roles->findOrThrowException(1)->name !!}<br/> @if (count($permission->roles)) @foreach($permission->roles as $role) {!! $role->name !!}<br/> @endforeach @endif </td> <td> @if ($permission->group) {!! $permission->group->name !!} @else <span class="label label-danger">None</span> @endif </td> <td>{!! $permission->sort !!}</td> <td>{!! $permission->system_label !!}</td> <td>{!! $permission->action_buttons !!}</td> </tr> @endforeach </tbody> </table> <div class="pull-left"> {{ $permissions->total() }} {{ trans('crud.permissions.total') }} </div> <div class="pull-right"> {{ $permissions->render() }} </div> <div class="clearfix"></div> </div><!--permissions--> </div> </div><!--permission tabs--> @stop @section('after-scripts-end') {!! HTML::script('js/backend/plugin/nestable/jquery.nestable.js') !!} <script> $(function() { var hierarchy = $('.permission-hierarchy'); hierarchy.nestable({maxDepth:2}); hierarchy.on('change', function() { @permission('sort-permission-groups') $.ajax({ url : "{!! route('admin.access.roles.groups.update-sort') !!}", type: "post", data : {data:hierarchy.nestable('serialize')}, success: function(data) { if (data.status == "OK") toastr.success("Hierarchy successfully saved."); else toastr.error("An unknown error occurred."); }, error: function (jqXHR, textStatus, errorThrown) { toastr.error("An unknown error occurred: " + errorThrown); } }); @else toastr.error("You do not have permission to do that."); @endauth }); }); </script> @stop
{ "content_hash": "91fcac2039a210fec0ca4d922e13db50", "timestamp": "", "source": "github", "line_count": 229, "max_line_length": 232, "avg_line_length": 50.043668122270745, "alnum_prop": 0.3532286212914485, "repo_name": "Lphmedia/youbloom", "id": "adc4bf3151eac49b1f50e6ffc7cdee9c3940fb3b", "size": "11460", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "resources/views/backend/access/roles/permissions/index.blade.php", "mode": "33261", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "39551" }, { "name": "CSS", "bytes": "103277" }, { "name": "JavaScript", "bytes": "100534" }, { "name": "PHP", "bytes": "517901" } ], "symlink_target": "" }
using System; using FluentAssertions; using Nest; using Tests.Framework.Integration; using Tests.Framework.MockData; using static Nest.Infer; namespace Tests.Aggregations.Metric.ValueCount { public class ValueCountAggregationUsageTests : AggregationUsageTestBase { public ValueCountAggregationUsageTests(ReadOnlyCluster i, EndpointUsage usage) : base(i, usage) { } protected override object ExpectJson => new { aggs = new { commit_count = new { value_count = new { field = Field<Project>(p => p.NumberOfCommits) } } } }; protected override Func<SearchDescriptor<Project>, ISearchRequest> Fluent => s => s .Aggregations(a => a .ValueCount("commit_count", c => c .Field(p => p.NumberOfCommits) ) ); protected override SearchRequest<Project> Initializer => new SearchRequest<Project> { Aggregations = new ValueCountAggregation("commit_count", Field<Project>(p => p.NumberOfCommits)) }; protected override void ExpectResponse(ISearchResponse<Project> response) { response.IsValid.Should().BeTrue(); var commitCount = response.Aggs.ValueCount("commit_count"); commitCount.Should().NotBeNull(); commitCount.Value.Should().BeGreaterThan(0); } } }
{ "content_hash": "b4ed2a436886c7c0b151d8d3090c229f", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 101, "avg_line_length": 25.571428571428573, "alnum_prop": 0.7055067837190743, "repo_name": "azubanov/elasticsearch-net", "id": "a646b488260398ac864c3fc0a21820e0e9492d5c", "size": "1255", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/Tests/Aggregations/Metric/ValueCount/ValueCountAggregationUsageTests.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1521" }, { "name": "C#", "bytes": "6640106" }, { "name": "F#", "bytes": "40329" }, { "name": "HTML", "bytes": "348323" }, { "name": "Shell", "bytes": "698" }, { "name": "Smalltalk", "bytes": "3426" } ], "symlink_target": "" }
planning and documents related to the project
{ "content_hash": "fa5dd9634bad7010748e5944bef81d2c", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 45, "avg_line_length": 46, "alnum_prop": 0.8478260869565217, "repo_name": "orbuculum/planning", "id": "5743fbbd98bc6d6ae3d009026fe0e1d63121551a", "size": "57", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
#ifndef MODULES_AUDIO_CODING_INCLUDE_AUDIO_CODING_MODULE_H_ #define MODULES_AUDIO_CODING_INCLUDE_AUDIO_CODING_MODULE_H_ #include <memory> #include <string> #include <vector> #include BOSS_WEBRTC_U_api__audio_codecs__audio_decoder_factory_h //original-code:"api/audio_codecs/audio_decoder_factory.h" #include BOSS_WEBRTC_U_api__audio_codecs__audio_encoder_h //original-code:"api/audio_codecs/audio_encoder.h" #include BOSS_WEBRTC_U_api__optional_h //original-code:"api/optional.h" #include BOSS_WEBRTC_U_common_types_h //original-code:"common_types.h" // NOLINT(build/include) #include "modules/audio_coding/include/audio_coding_module_typedefs.h" #include "modules/audio_coding/neteq/include/neteq.h" #include BOSS_WEBRTC_U_modules__include__module_h //original-code:"modules/include/module.h" #include BOSS_WEBRTC_U_rtc_base__deprecation_h //original-code:"rtc_base/deprecation.h" #include BOSS_WEBRTC_U_rtc_base__function_view_h //original-code:"rtc_base/function_view.h" #include BOSS_WEBRTC_U_system_wrappers__include__clock_h //original-code:"system_wrappers/include/clock.h" #include BOSS_WEBRTC_U_typedefs_h //original-code:"typedefs.h" // NOLINT(build/include) namespace webrtc { // forward declarations struct CodecInst; struct WebRtcRTPHeader; class AudioDecoder; class AudioEncoder; class AudioFrame; class RTPFragmentationHeader; #define WEBRTC_10MS_PCM_AUDIO 960 // 16 bits super wideband 48 kHz // Callback class used for sending data ready to be packetized class AudioPacketizationCallback { public: virtual ~AudioPacketizationCallback() {} virtual int32_t SendData(FrameType frame_type, uint8_t payload_type, uint32_t timestamp, const uint8_t* payload_data, size_t payload_len_bytes, const RTPFragmentationHeader* fragmentation) = 0; }; // Callback class used for reporting VAD decision class ACMVADCallback { public: virtual ~ACMVADCallback() {} virtual int32_t InFrameType(FrameType frame_type) = 0; }; class AudioCodingModule { protected: AudioCodingModule() {} public: struct Config { Config(); Config(const Config&); ~Config(); NetEq::Config neteq_config; Clock* clock; rtc::scoped_refptr<AudioDecoderFactory> decoder_factory; }; /////////////////////////////////////////////////////////////////////////// // Creation and destruction of a ACM. // // The second method is used for testing where a simulated clock can be // injected into ACM. ACM will take the ownership of the object clock and // delete it when destroyed. // // TODO(solenberg): Remove once downstream projects are updated. RTC_DEPRECATED static AudioCodingModule* Create(int id); static AudioCodingModule* Create(); static AudioCodingModule* Create(Clock* clock); static AudioCodingModule* Create(const Config& config); virtual ~AudioCodingModule() = default; /////////////////////////////////////////////////////////////////////////// // Utility functions // /////////////////////////////////////////////////////////////////////////// // uint8_t NumberOfCodecs() // Returns number of supported codecs. // // Return value: // number of supported codecs. /// static int NumberOfCodecs(); /////////////////////////////////////////////////////////////////////////// // int32_t Codec() // Get supported codec with list number. // // Input: // -list_id : list number. // // Output: // -codec : a structure where the parameters of the codec, // given by list number is written to. // // Return value: // -1 if the list number (list_id) is invalid. // 0 if succeeded. // static int Codec(int list_id, CodecInst* codec); /////////////////////////////////////////////////////////////////////////// // int32_t Codec() // Get supported codec with the given codec name, sampling frequency, and // a given number of channels. // // Input: // -payload_name : name of the codec. // -sampling_freq_hz : sampling frequency of the codec. Note! for RED // a sampling frequency of -1 is a valid input. // -channels : number of channels ( 1 - mono, 2 - stereo). // // Output: // -codec : a structure where the function returns the // default parameters of the codec. // // Return value: // -1 if no codec matches the given parameters. // 0 if succeeded. // static int Codec(const char* payload_name, CodecInst* codec, int sampling_freq_hz, size_t channels); /////////////////////////////////////////////////////////////////////////// // int32_t Codec() // // Returns the list number of the given codec name, sampling frequency, and // a given number of channels. // // Input: // -payload_name : name of the codec. // -sampling_freq_hz : sampling frequency of the codec. Note! for RED // a sampling frequency of -1 is a valid input. // -channels : number of channels ( 1 - mono, 2 - stereo). // // Return value: // if the codec is found, the index of the codec in the list, // -1 if the codec is not found. // static int Codec(const char* payload_name, int sampling_freq_hz, size_t channels); /////////////////////////////////////////////////////////////////////////// // bool IsCodecValid() // Checks the validity of the parameters of the given codec. // // Input: // -codec : the structure which keeps the parameters of the // codec. // // Return value: // true if the parameters are valid, // false if any parameter is not valid. // static bool IsCodecValid(const CodecInst& codec); /////////////////////////////////////////////////////////////////////////// // Sender // /////////////////////////////////////////////////////////////////////////// // int32_t RegisterSendCodec() // Registers a codec, specified by |send_codec|, as sending codec. // This API can be called multiple of times to register Codec. The last codec // registered overwrites the previous ones. // The API can also be used to change payload type for CNG and RED, which are // registered by default to default payload types. // Note that registering CNG and RED won't overwrite speech codecs. // This API can be called to set/change the send payload-type, frame-size // or encoding rate (if applicable for the codec). // // Note: If a stereo codec is registered as send codec, VAD/DTX will // automatically be turned off, since it is not supported for stereo sending. // // Note: If a secondary encoder is already registered, and the new send-codec // has a sampling rate that does not match the secondary encoder, the // secondary encoder will be unregistered. // // Input: // -send_codec : Parameters of the codec to be registered, c.f. // common_types.h for the definition of // CodecInst. // // Return value: // -1 if failed to initialize, // 0 if succeeded. // virtual int32_t RegisterSendCodec(const CodecInst& send_codec) = 0; // Registers |external_speech_encoder| as encoder. The new encoder will // replace any previously registered speech encoder (internal or external). virtual void RegisterExternalSendCodec( AudioEncoder* external_speech_encoder) = 0; // |modifier| is called exactly once with one argument: a pointer to the // unique_ptr that holds the current encoder (which is null if there is no // current encoder). For the duration of the call, |modifier| has exclusive // access to the unique_ptr; it may call the encoder, steal the encoder and // replace it with another encoder or with nullptr, etc. virtual void ModifyEncoder( rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)> modifier) = 0; // |modifier| is called exactly once with one argument: a const pointer to the // current encoder (which is null if there is no current encoder). virtual void QueryEncoder( rtc::FunctionView<void(AudioEncoder const*)> query) = 0; // Utility method for simply replacing the existing encoder with a new one. void SetEncoder(std::unique_ptr<AudioEncoder> new_encoder) { ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) { *encoder = std::move(new_encoder); }); } /////////////////////////////////////////////////////////////////////////// // int32_t SendCodec() // Get parameters for the codec currently registered as send codec. // // Return value: // The send codec, or nothing if we don't have one // virtual rtc::Optional<CodecInst> SendCodec() const = 0; /////////////////////////////////////////////////////////////////////////// // int32_t SendFrequency() // Get the sampling frequency of the current encoder in Hertz. // // Return value: // positive; sampling frequency [Hz] of the current encoder. // -1 if an error has happened. // virtual int32_t SendFrequency() const = 0; /////////////////////////////////////////////////////////////////////////// // Sets the bitrate to the specified value in bits/sec. If the value is not // supported by the codec, it will choose another appropriate value. // // This is only used in test code that rely on old ACM APIs. // TODO(minyue): Remove it when possible. virtual void SetBitRate(int bitrate_bps) = 0; // int32_t RegisterTransportCallback() // Register a transport callback which will be called to deliver // the encoded buffers whenever Process() is called and a // bit-stream is ready. // // Input: // -transport : pointer to the callback class // transport->SendData() is called whenever // Process() is called and bit-stream is ready // to deliver. // // Return value: // -1 if the transport callback could not be registered // 0 if registration is successful. // virtual int32_t RegisterTransportCallback( AudioPacketizationCallback* transport) = 0; /////////////////////////////////////////////////////////////////////////// // int32_t Add10MsData() // Add 10MS of raw (PCM) audio data and encode it. If the sampling // frequency of the audio does not match the sampling frequency of the // current encoder ACM will resample the audio. If an encoded packet was // produced, it will be delivered via the callback object registered using // RegisterTransportCallback, and the return value from this function will // be the number of bytes encoded. // // Input: // -audio_frame : the input audio frame, containing raw audio // sampling frequency etc., // c.f. module_common_types.h for definition of // AudioFrame. // // Return value: // >= 0 number of bytes encoded. // -1 some error occurred. // virtual int32_t Add10MsData(const AudioFrame& audio_frame) = 0; /////////////////////////////////////////////////////////////////////////// // (RED) Redundant Coding // /////////////////////////////////////////////////////////////////////////// // int32_t SetREDStatus() // configure RED status i.e. on/off. // // RFC 2198 describes a solution which has a single payload type which // signifies a packet with redundancy. That packet then becomes a container, // encapsulating multiple payloads into a single RTP packet. // Such a scheme is flexible, since any amount of redundancy may be // encapsulated within a single packet. There is, however, a small overhead // since each encapsulated payload must be preceded by a header indicating // the type of data enclosed. // // Input: // -enable_red : if true RED is enabled, otherwise RED is // disabled. // // Return value: // -1 if failed to set RED status, // 0 if succeeded. // virtual int32_t SetREDStatus(bool enable_red) = 0; /////////////////////////////////////////////////////////////////////////// // bool REDStatus() // Get RED status // // Return value: // true if RED is enabled, // false if RED is disabled. // virtual bool REDStatus() const = 0; /////////////////////////////////////////////////////////////////////////// // (FEC) Forward Error Correction (codec internal) // /////////////////////////////////////////////////////////////////////////// // int32_t SetCodecFEC() // Configures codec internal FEC status i.e. on/off. No effects on codecs that // do not provide internal FEC. // // Input: // -enable_fec : if true FEC will be enabled otherwise the FEC is // disabled. // // Return value: // -1 if failed, or the codec does not support FEC // 0 if succeeded. // virtual int SetCodecFEC(bool enable_codec_fec) = 0; /////////////////////////////////////////////////////////////////////////// // bool CodecFEC() // Gets status of codec internal FEC. // // Return value: // true if FEC is enabled, // false if FEC is disabled. // virtual bool CodecFEC() const = 0; /////////////////////////////////////////////////////////////////////////// // int SetPacketLossRate() // Sets expected packet loss rate for encoding. Some encoders provide packet // loss gnostic encoding to make stream less sensitive to packet losses, // through e.g., FEC. No effects on codecs that do not provide such encoding. // // Input: // -packet_loss_rate : expected packet loss rate (0 -- 100 inclusive). // // Return value // -1 if failed to set packet loss rate, // 0 if succeeded. // // This is only used in test code that rely on old ACM APIs. // TODO(minyue): Remove it when possible. virtual int SetPacketLossRate(int packet_loss_rate) = 0; /////////////////////////////////////////////////////////////////////////// // (VAD) Voice Activity Detection // /////////////////////////////////////////////////////////////////////////// // int32_t SetVAD() // If DTX is enabled & the codec does not have internal DTX/VAD // WebRtc VAD will be automatically enabled and |enable_vad| is ignored. // // If DTX is disabled but VAD is enabled no DTX packets are send, // regardless of whether the codec has internal DTX/VAD or not. In this // case, WebRtc VAD is running to label frames as active/in-active. // // NOTE! VAD/DTX is not supported when sending stereo. // // Inputs: // -enable_dtx : if true DTX is enabled, // otherwise DTX is disabled. // -enable_vad : if true VAD is enabled, // otherwise VAD is disabled. // -vad_mode : determines the aggressiveness of VAD. A more // aggressive mode results in more frames labeled // as in-active, c.f. definition of // ACMVADMode in audio_coding_module_typedefs.h // for valid values. // // Return value: // -1 if failed to set up VAD/DTX, // 0 if succeeded. // virtual int32_t SetVAD(const bool enable_dtx = true, const bool enable_vad = false, const ACMVADMode vad_mode = VADNormal) = 0; /////////////////////////////////////////////////////////////////////////// // int32_t VAD() // Get VAD status. // // Outputs: // -dtx_enabled : is set to true if DTX is enabled, otherwise // is set to false. // -vad_enabled : is set to true if VAD is enabled, otherwise // is set to false. // -vad_mode : is set to the current aggressiveness of VAD. // // Return value: // -1 if fails to retrieve the setting of DTX/VAD, // 0 if succeeded. // virtual int32_t VAD(bool* dtx_enabled, bool* vad_enabled, ACMVADMode* vad_mode) const = 0; /////////////////////////////////////////////////////////////////////////// // int32_t RegisterVADCallback() // Call this method to register a callback function which is called // any time that ACM encounters an empty frame. That is a frame which is // recognized inactive. Depending on the codec WebRtc VAD or internal codec // VAD is employed to identify a frame as active/inactive. // // Input: // -vad_callback : pointer to a callback function. // // Return value: // -1 if failed to register the callback function. // 0 if the callback function is registered successfully. // virtual int32_t RegisterVADCallback(ACMVADCallback* vad_callback) = 0; /////////////////////////////////////////////////////////////////////////// // Receiver // /////////////////////////////////////////////////////////////////////////// // int32_t InitializeReceiver() // Any decoder-related state of ACM will be initialized to the // same state when ACM is created. This will not interrupt or // effect encoding functionality of ACM. ACM would lose all the // decoding-related settings by calling this function. // For instance, all registered codecs are deleted and have to be // registered again. // // Return value: // -1 if failed to initialize, // 0 if succeeded. // virtual int32_t InitializeReceiver() = 0; /////////////////////////////////////////////////////////////////////////// // int32_t ReceiveFrequency() // Get sampling frequency of the last received payload. // // Return value: // non-negative the sampling frequency in Hertz. // -1 if an error has occurred. // virtual int32_t ReceiveFrequency() const = 0; /////////////////////////////////////////////////////////////////////////// // int32_t PlayoutFrequency() // Get sampling frequency of audio played out. // // Return value: // the sampling frequency in Hertz. // virtual int32_t PlayoutFrequency() const = 0; // Replace any existing decoders with the given payload type -> decoder map. virtual void SetReceiveCodecs( const std::map<int, SdpAudioFormat>& codecs) = 0; // Registers a decoder for the given payload type. Returns true iff // successful. virtual bool RegisterReceiveCodec(int rtp_payload_type, const SdpAudioFormat& audio_format) = 0; /////////////////////////////////////////////////////////////////////////// // int32_t RegisterReceiveCodec() // Register possible decoders, can be called multiple times for // codecs, CNG-NB, CNG-WB, CNG-SWB, AVT and RED. // // Input: // -receive_codec : parameters of the codec to be registered, c.f. // common_types.h for the definition of // CodecInst. // // Return value: // -1 if failed to register the codec // 0 if the codec registered successfully. // virtual int RegisterReceiveCodec(const CodecInst& receive_codec) = 0; // Register a decoder; call repeatedly to register multiple decoders. |df| is // a decoder factory that returns an iSAC decoder; it will be called once if // the decoder being registered is iSAC. virtual int RegisterReceiveCodec( const CodecInst& receive_codec, rtc::FunctionView<std::unique_ptr<AudioDecoder>()> isac_factory) = 0; // Registers an external decoder. The name is only used to provide information // back to the caller about the decoder. Hence, the name is arbitrary, and may // be empty. virtual int RegisterExternalReceiveCodec(int rtp_payload_type, AudioDecoder* external_decoder, int sample_rate_hz, int num_channels, const std::string& name) = 0; /////////////////////////////////////////////////////////////////////////// // int32_t UnregisterReceiveCodec() // Unregister the codec currently registered with a specific payload type // from the list of possible receive codecs. // // Input: // -payload_type : The number representing the payload type to // unregister. // // Output: // -1 if fails to unregister. // 0 if the given codec is successfully unregistered. // virtual int UnregisterReceiveCodec( uint8_t payload_type) = 0; /////////////////////////////////////////////////////////////////////////// // int32_t ReceiveCodec() // Get the codec associated with last received payload. // // Output: // -curr_receive_codec : parameters of the codec associated with the last // received payload, c.f. common_types.h for // the definition of CodecInst. // // Return value: // -1 if failed to retrieve the codec, // 0 if the codec is successfully retrieved. // virtual int32_t ReceiveCodec(CodecInst* curr_receive_codec) const = 0; /////////////////////////////////////////////////////////////////////////// // rtc::Optional<SdpAudioFormat> ReceiveFormat() // Get the format associated with last received payload. // // Return value: // An SdpAudioFormat describing the format associated with the last // received payload. // An empty Optional if no payload has yet been received. // virtual rtc::Optional<SdpAudioFormat> ReceiveFormat() const = 0; /////////////////////////////////////////////////////////////////////////// // int32_t IncomingPacket() // Call this function to insert a parsed RTP packet into ACM. // // Inputs: // -incoming_payload : received payload. // -payload_len_bytes : the length of payload in bytes. // -rtp_info : the relevant information retrieved from RTP // header. // // Return value: // -1 if failed to push in the payload // 0 if payload is successfully pushed in. // virtual int32_t IncomingPacket(const uint8_t* incoming_payload, const size_t payload_len_bytes, const WebRtcRTPHeader& rtp_info) = 0; /////////////////////////////////////////////////////////////////////////// // int SetMinimumPlayoutDelay() // Set a minimum for the playout delay, used for lip-sync. NetEq maintains // such a delay unless channel condition yields to a higher delay. // // Input: // -time_ms : minimum delay in milliseconds. // // Return value: // -1 if failed to set the delay, // 0 if the minimum delay is set. // virtual int SetMinimumPlayoutDelay(int time_ms) = 0; /////////////////////////////////////////////////////////////////////////// // int SetMaximumPlayoutDelay() // Set a maximum for the playout delay // // Input: // -time_ms : maximum delay in milliseconds. // // Return value: // -1 if failed to set the delay, // 0 if the maximum delay is set. // virtual int SetMaximumPlayoutDelay(int time_ms) = 0; // TODO(kwiberg): Consider if this is needed anymore, now that voe::Channel // doesn't use it. // The shortest latency, in milliseconds, required by jitter buffer. This // is computed based on inter-arrival times and playout mode of NetEq. The // actual delay is the maximum of least-required-delay and the minimum-delay // specified by SetMinumumPlayoutDelay() API. // virtual int LeastRequiredDelayMs() const = 0; // int32_t PlayoutTimestamp() // The send timestamp of an RTP packet is associated with the decoded // audio of the packet in question. This function returns the timestamp of // the latest audio obtained by calling PlayoutData10ms(). // // Input: // -timestamp : a reference to a uint32_t to receive the // timestamp. // Return value: // 0 if the output is a correct timestamp. // -1 if failed to output the correct timestamp. // RTC_DEPRECATED virtual int32_t PlayoutTimestamp(uint32_t* timestamp) = 0; /////////////////////////////////////////////////////////////////////////// // int32_t PlayoutTimestamp() // The send timestamp of an RTP packet is associated with the decoded // audio of the packet in question. This function returns the timestamp of // the latest audio obtained by calling PlayoutData10ms(), or empty if no // valid timestamp is available. // virtual rtc::Optional<uint32_t> PlayoutTimestamp() = 0; /////////////////////////////////////////////////////////////////////////// // int FilteredCurrentDelayMs() // Returns the current total delay from NetEq (packet buffer and sync buffer) // in ms, with smoothing applied to even out short-time fluctuations due to // jitter. The packet buffer part of the delay is not updated during DTX/CNG // periods. // virtual int FilteredCurrentDelayMs() const = 0; /////////////////////////////////////////////////////////////////////////// // int FilteredCurrentDelayMs() // Returns the current target delay for NetEq in ms. // virtual int TargetDelayMs() const = 0; /////////////////////////////////////////////////////////////////////////// // int32_t PlayoutData10Ms( // Get 10 milliseconds of raw audio data for playout, at the given sampling // frequency. ACM will perform a resampling if required. // // Input: // -desired_freq_hz : the desired sampling frequency, in Hertz, of the // output audio. If set to -1, the function returns // the audio at the current sampling frequency. // // Output: // -audio_frame : output audio frame which contains raw audio data // and other relevant parameters, c.f. // module_common_types.h for the definition of // AudioFrame. // -muted : if true, the sample data in audio_frame is not // populated, and must be interpreted as all zero. // // Return value: // -1 if the function fails, // 0 if the function succeeds. // virtual int32_t PlayoutData10Ms(int32_t desired_freq_hz, AudioFrame* audio_frame, bool* muted) = 0; ///////////////////////////////////////////////////////////////////////////// // Same as above, but without the muted parameter. This methods should not be // used if enable_fast_accelerate was set to true in NetEq::Config. // TODO(henrik.lundin) Remove this method when downstream dependencies are // ready. virtual int32_t PlayoutData10Ms(int32_t desired_freq_hz, AudioFrame* audio_frame) = 0; /////////////////////////////////////////////////////////////////////////// // Codec specific // /////////////////////////////////////////////////////////////////////////// // int SetOpusApplication() // Sets the intended application if current send codec is Opus. Opus uses this // to optimize the encoding for applications like VOIP and music. Currently, // two modes are supported: kVoip and kAudio. // // Input: // - application : intended application. // // Return value: // -1 if current send codec is not Opus or error occurred in setting the // Opus application mode. // 0 if the Opus application mode is successfully set. // virtual int SetOpusApplication(OpusApplicationMode application) = 0; /////////////////////////////////////////////////////////////////////////// // int SetOpusMaxPlaybackRate() // If current send codec is Opus, informs it about maximum playback rate the // receiver will render. Opus can use this information to optimize the bit // rate and increase the computation efficiency. // // Input: // -frequency_hz : maximum playback rate in Hz. // // Return value: // -1 if current send codec is not Opus or // error occurred in setting the maximum playback rate, // 0 if maximum bandwidth is set successfully. // virtual int SetOpusMaxPlaybackRate(int frequency_hz) = 0; /////////////////////////////////////////////////////////////////////////// // EnableOpusDtx() // Enable the DTX, if current send codec is Opus. // // Return value: // -1 if current send codec is not Opus or error occurred in enabling the // Opus DTX. // 0 if Opus DTX is enabled successfully. // virtual int EnableOpusDtx() = 0; /////////////////////////////////////////////////////////////////////////// // int DisableOpusDtx() // If current send codec is Opus, disables its internal DTX. // // Return value: // -1 if current send codec is not Opus or error occurred in disabling DTX. // 0 if Opus DTX is disabled successfully. // virtual int DisableOpusDtx() = 0; /////////////////////////////////////////////////////////////////////////// // statistics // /////////////////////////////////////////////////////////////////////////// // int32_t GetNetworkStatistics() // Get network statistics. Note that the internal statistics of NetEq are // reset by this call. // // Input: // -network_statistics : a structure that contains network statistics. // // Return value: // -1 if failed to set the network statistics, // 0 if statistics are set successfully. // virtual int32_t GetNetworkStatistics( NetworkStatistics* network_statistics) = 0; // // Enable NACK and set the maximum size of the NACK list. If NACK is already // enable then the maximum NACK list size is modified accordingly. // // If the sequence number of last received packet is N, the sequence numbers // of NACK list are in the range of [N - |max_nack_list_size|, N). // // |max_nack_list_size| should be positive (none zero) and less than or // equal to |Nack::kNackListSizeLimit|. Otherwise, No change is applied and -1 // is returned. 0 is returned at success. // virtual int EnableNack(size_t max_nack_list_size) = 0; // Disable NACK. virtual void DisableNack() = 0; // // Get a list of packets to be retransmitted. |round_trip_time_ms| is an // estimate of the round-trip-time (in milliseconds). Missing packets which // will be playout in a shorter time than the round-trip-time (with respect // to the time this API is called) will not be included in the list. // // Negative |round_trip_time_ms| results is an error message and empty list // is returned. // virtual std::vector<uint16_t> GetNackList( int64_t round_trip_time_ms) const = 0; virtual void GetDecodingCallStatistics( AudioDecodingCallStats* call_stats) const = 0; virtual ANAStats GetANAStats() const = 0; }; } // namespace webrtc #endif // MODULES_AUDIO_CODING_INCLUDE_AUDIO_CODING_MODULE_H_
{ "content_hash": "80186949e591f63f49fffa439bb6b3fe", "timestamp": "", "source": "github", "line_count": 802, "max_line_length": 124, "avg_line_length": 38.98503740648379, "alnum_prop": 0.5684129725580502, "repo_name": "koobonil/Boss2D", "id": "28edea1cbe347e8497499f69ee20ed9349b38f52", "size": "31678", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Boss2D/addon/_old/webrtc-qt5.11.2_for_boss/modules/audio_coding/include/audio_coding_module.h", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "4820445" }, { "name": "Awk", "bytes": "4272" }, { "name": "Batchfile", "bytes": "89930" }, { "name": "C", "bytes": "119747922" }, { "name": "C#", "bytes": "87505" }, { "name": "C++", "bytes": "272329620" }, { "name": "CMake", "bytes": "1199656" }, { "name": "CSS", "bytes": "42679" }, { "name": "Clojure", "bytes": "1487" }, { "name": "Cuda", "bytes": "1651996" }, { "name": "DIGITAL Command Language", "bytes": "239527" }, { "name": "Dockerfile", "bytes": "9638" }, { "name": "Emacs Lisp", "bytes": "15570" }, { "name": "Go", "bytes": "858185" }, { "name": "HLSL", "bytes": "3314" }, { "name": "HTML", "bytes": "2958385" }, { "name": "Java", "bytes": "2921052" }, { "name": "JavaScript", "bytes": "178190" }, { "name": "Jupyter Notebook", "bytes": "1833654" }, { "name": "LLVM", "bytes": "6536" }, { "name": "M4", "bytes": "775724" }, { "name": "MATLAB", "bytes": "74606" }, { "name": "Makefile", "bytes": "3941551" }, { "name": "Meson", "bytes": "2847" }, { "name": "Module Management System", "bytes": "2626" }, { "name": "NSIS", "bytes": "4505" }, { "name": "Objective-C", "bytes": "4090702" }, { "name": "Objective-C++", "bytes": "1702390" }, { "name": "PHP", "bytes": "3530" }, { "name": "Perl", "bytes": "11096338" }, { "name": "Perl 6", "bytes": "11802" }, { "name": "PowerShell", "bytes": "38571" }, { "name": "Python", "bytes": "24123805" }, { "name": "QMake", "bytes": "18188" }, { "name": "Roff", "bytes": "1261269" }, { "name": "Ruby", "bytes": "5890" }, { "name": "Scala", "bytes": "5683" }, { "name": "Shell", "bytes": "2879948" }, { "name": "TeX", "bytes": "243507" }, { "name": "TypeScript", "bytes": "1593696" }, { "name": "Verilog", "bytes": "1215" }, { "name": "Vim Script", "bytes": "3759" }, { "name": "Visual Basic", "bytes": "16186" }, { "name": "eC", "bytes": "9705" } ], "symlink_target": "" }
package Objects; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; /** * Created by enrico on 04/01/2017. */ public class Prodotto implements Serializable, Comparable<Prodotto> { private String codice; private String descrizione; private int quantità; private boolean eliminabile; // se è true è eliminabile, altrimenti è false private ArrayList<Aggiunta> aggiunte; public Prodotto(String codice, String descrizione) { this.codice = codice; eliminabile = true; this.descrizione = descrizione; quantità = 0; aggiunte = new ArrayList<>(6); } public void setQuantità(int quantità) { this.quantità = quantità; } public String getDescrizione() { return descrizione; } public String getCodice() { return codice; } public int getQuantità() { return quantità; } @Override public boolean equals(Object o) { Prodotto p = (Prodotto) o; if (o == null) return false; if (p.isEliminabile() == this.isEliminabile() && p.getCodice() == this.getCodice() && p.getDescrizione().equals(this.getDescrizione()) && p.getQuantità() == this.getQuantità() && p.getAggiunte().equals(this.getAggiunte())) { return true; } else { return false; } } @Override public String toString() { if (eliminabile) { } if (quantità == 0) { if (eliminabile) { return descrizione; } else { return "<u>" + descrizione + "</u>"; } } else { String s = quantità + "x " + descrizione; for (Aggiunta a : aggiunte) { s += " " + a.getConsenza() + " " + a.getDescrizione(); } if (eliminabile) { return s; } else { return "|" + s + "|"; } } } public ArrayList<Aggiunta> getAggiunte() { Collections.sort(aggiunte); return aggiunte; } public boolean addAggiunta(Aggiunta aggiunta) { if (aggiunte.size() < 7) { this.aggiunte.add(aggiunta); return true; } else { return false; } } @Override public int compareTo(Prodotto p2) { int n3 = this.getDescrizione().compareTo(p2.getDescrizione()); return n3; } public boolean rimuoviAggiunta(Aggiunta aggiunta) { if (aggiunte.contains(aggiunta)) { aggiunte.remove(aggiunta); return true; } else { return false; } } public boolean isEliminabile() { return eliminabile; } public void setEliminabile(boolean eliminabile) { this.eliminabile = eliminabile; } public boolean myIsEquals(Prodotto p) { if (p.isEliminabile() == this.isEliminabile() && p.getCodice().compareTo(this.getCodice())==0) { if (this.getAggiunte().size() == 0 && p.getAggiunte().size() == 0) { return true; } for (int i = 0; i < this.getAggiunte().size(); i++) { if (this.getAggiunte().get(i).getDescrizione().compareTo(p.getAggiunte().get(i).getDescrizione())==0 && this.getAggiunte().get(i).getConsenza().compareTo(p.getAggiunte().get(i).getConsenza())==0) { return true; } else { return false; } } } else { return false; } return false; } }
{ "content_hash": "24b28ba7d9ca6a3b1cb156ff6e55a25a", "timestamp": "", "source": "github", "line_count": 134, "max_line_length": 232, "avg_line_length": 27.067164179104477, "alnum_prop": 0.5357044389302453, "repo_name": "enricobiella/Software-gestionale-ordinazioni", "id": "c12730b9956f49afd57a0568d1d2214aa8e24d90", "size": "3642", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/Objects/Prodotto.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "77669" } ], "symlink_target": "" }
<?php namespace Illuminate\Tests\Database; use PDO; use Mockery as m; use PHPUnit\Framework\TestCase; use Illuminate\Database\Connection; use Illuminate\Database\Query\Builder; use Illuminate\Database\Query\Processors\Processor; class DatabaseProcessorTest extends TestCase { protected function tearDown(): void { m::close(); } public function testInsertGetIdProcessing() { $pdo = $this->createMock(ProcessorTestPDOStub::class); $pdo->expects($this->once())->method('lastInsertId')->with($this->equalTo('id'))->will($this->returnValue('1')); $connection = m::mock(Connection::class); $connection->shouldReceive('insert')->once()->with('sql', ['foo']); $connection->shouldReceive('getPdo')->once()->andReturn($pdo); $builder = m::mock(Builder::class); $builder->shouldReceive('getConnection')->andReturn($connection); $processor = new Processor; $result = $processor->processInsertGetId($builder, 'sql', ['foo'], 'id'); $this->assertSame(1, $result); } } class ProcessorTestPDOStub extends PDO { public function __construct() { // } public function lastInsertId($sequence = null) { // } }
{ "content_hash": "0c9ce63b699b51e55abdd2e21353ec6b", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 120, "avg_line_length": 27.68888888888889, "alnum_prop": 0.6420545746388443, "repo_name": "barryvdh/framework", "id": "dcc88c465b01a096bec9fa58de8c3f0c407dcae0", "size": "1246", "binary": false, "copies": "4", "ref": "refs/heads/5.8", "path": "tests/Database/DatabaseProcessorTest.php", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "4768" }, { "name": "HTML", "bytes": "30022" }, { "name": "Hack", "bytes": "37" }, { "name": "JavaScript", "bytes": "2966" }, { "name": "PHP", "bytes": "5880904" }, { "name": "Shell", "bytes": "3677" }, { "name": "Vue", "bytes": "552" } ], "symlink_target": "" }
/* emergency services featured news */ .hide { display: none; } .emergency-state #asides { margin-top: 0; margin-bottom: 2em; }
{ "content_hash": "7093c55f55027cb5bcf3e1c3873f7989", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 38, "avg_line_length": 14.2, "alnum_prop": 0.6267605633802817, "repo_name": "qld-gov-au/emergency-services", "id": "7216d90be69e685120fcbe82c0bb49f822986867", "size": "142", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/assets/style/featured.css", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "AppleScript", "bytes": "262" }, { "name": "CSS", "bytes": "142" }, { "name": "HTML", "bytes": "16837" }, { "name": "JavaScript", "bytes": "55277" }, { "name": "Shell", "bytes": "222" } ], "symlink_target": "" }
package com.emitrom.lienzo.client.core.event; import java.util.ArrayList; public class NodeTouchMoveEvent extends AbstractNodeTouchEvent<NodeTouchMoveHandler> { private static final Type<NodeTouchMoveHandler> TYPE = new Type<NodeTouchMoveHandler>(); public static Type<NodeTouchMoveHandler> getType() { return TYPE; } public NodeTouchMoveEvent(ArrayList<TouchPoint> touches) { super(touches); } @Override public final Type<NodeTouchMoveHandler> getAssociatedType() { return TYPE; } @Override protected void dispatch(NodeTouchMoveHandler handler) { handler.onNodeTouchMove(this); } }
{ "content_hash": "c0c422a291fe464ce12af1082ad75a4e", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 92, "avg_line_length": 21.34375, "alnum_prop": 0.7013177159590044, "repo_name": "manstis/rht-lienzo-core", "id": "d036c1c4ae9c36612daf1de3f82563bcece6510d", "size": "1369", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/com/emitrom/lienzo/client/core/event/NodeTouchMoveEvent.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "948442" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <!-- ================================================================== --> <!-- Copyright (c) 2006-2010 eBay Inc. All Rights Reserved. --> <!-- Licensed under the Apache License, Version 2.0 (the "License"); --> <!-- you may not use this file except in compliance with the License. --> <!-- You may obtain a copy of the License at --> <!-- --> <!-- http://www.apache.org/licenses/LICENSE-2.0 --> <!-- ================================================================== --> <client-config-list xmlns="http://www.ebayopensource.org/turmeric/common/config"> <client-config> <service-interface-class-name>org.ebayopensource.turmeric.qe.soaqetestimplfactoryservice.soaqetestimplfactoryservice.SOAQETestImplFactoryServiceV1</service-interface-class-name> <service-location>http://www.ebayopensource.org/turmeric/SOAQETestImplFactoryService</service-location> <client-instance-config> <invocation-options> <preferred-transport name="HTTP11"/> <request-data-binding>XML</request-data-binding> <response-data-binding>XML</response-data-binding> <invocation-use-case>SOAQETestImplFactoryServiceV1Client</invocation-use-case> </invocation-options> </client-instance-config> </client-config> </client-config-list>
{ "content_hash": "12dafcfc9b0238b5acd081359bbaff28", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 185, "avg_line_length": 66.1304347826087, "alnum_prop": 0.5575279421433268, "repo_name": "vthangathurai/SOA-Runtime", "id": "6627aa5d8c26b1c538db39a15fbcd71c7ae7036e", "size": "1521", "binary": false, "copies": "2", "ref": "refs/heads/soabranch", "path": "integration-tests/SOAQETestImplFactoryServiceV1Consumer/meta-src/META-INF/soa/client/config/SOAQETestImplFactoryServiceV1Consumer/production/SOAQETestImplFactoryServiceV1/ClientConfig.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "8734301" }, { "name": "Perl", "bytes": "2788" }, { "name": "Shell", "bytes": "621" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_60) on Sun Apr 24 20:15:47 JST 2016 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>twitter4j.examples.directmessage Class Hierarchy (twitter4j-examples 4.0.5-SNAPSHOT API)</title> <meta name="date" content="2016-04-24"> <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="twitter4j.examples.directmessage Class Hierarchy (twitter4j-examples 4.0.5-SNAPSHOT API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../twitter4j/examples/block/package-tree.html">Prev</a></li> <li><a href="../../../twitter4j/examples/favorite/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?twitter4j/examples/directmessage/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 class="title">Hierarchy For Package twitter4j.examples.directmessage</h1> <span class="packageHierarchyLabel">Package Hierarchies:</span> <ul class="horizontal"> <li><a href="../../../overview-tree.html">All Packages</a></li> </ul> </div> <div class="contentContainer"> <h2 title="Class Hierarchy">Class Hierarchy</h2> <ul> <li type="circle">java.lang.<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><span class="typeNameLink">Object</span></a> <ul> <li type="circle">twitter4j.examples.directmessage.<a href="../../../twitter4j/examples/directmessage/DestroyDirectMessage.html" title="class in twitter4j.examples.directmessage"><span class="typeNameLink">DestroyDirectMessage</span></a></li> <li type="circle">twitter4j.examples.directmessage.<a href="../../../twitter4j/examples/directmessage/GetDirectMessages.html" title="class in twitter4j.examples.directmessage"><span class="typeNameLink">GetDirectMessages</span></a></li> <li type="circle">twitter4j.examples.directmessage.<a href="../../../twitter4j/examples/directmessage/GetSentDirectMessages.html" title="class in twitter4j.examples.directmessage"><span class="typeNameLink">GetSentDirectMessages</span></a></li> <li type="circle">twitter4j.examples.directmessage.<a href="../../../twitter4j/examples/directmessage/SendDirectMessage.html" title="class in twitter4j.examples.directmessage"><span class="typeNameLink">SendDirectMessage</span></a></li> <li type="circle">twitter4j.examples.directmessage.<a href="../../../twitter4j/examples/directmessage/ShowDirectMessage.html" title="class in twitter4j.examples.directmessage"><span class="typeNameLink">ShowDirectMessage</span></a></li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../twitter4j/examples/block/package-tree.html">Prev</a></li> <li><a href="../../../twitter4j/examples/favorite/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?twitter4j/examples/directmessage/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2016. All rights reserved.</small></p> </body> </html>
{ "content_hash": "0ea5807077cb701913fa8ba560494bad", "timestamp": "", "source": "github", "line_count": 143, "max_line_length": 244, "avg_line_length": 41.95104895104895, "alnum_prop": 0.6621103517252875, "repo_name": "starsohan/Sentiment-Analysis-of-Extremist-Tweets", "id": "f480f8275199b7e9be7e502ebb49d63994f4361c", "size": "5999", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/twitter4j-4.0.5-SNAPSHOT/twitter4j-examples/javadoc/twitter4j/examples/directmessage/package-tree.html", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "16885" }, { "name": "CSS", "bytes": "20586" }, { "name": "HTML", "bytes": "301042" }, { "name": "Java", "bytes": "2214996" }, { "name": "JavaScript", "bytes": "18425" }, { "name": "Shell", "bytes": "20333" } ], "symlink_target": "" }
package de.intarsys.aaa.resource; /** * A VM singleton for the {@link IResourceAccessHandler}. * */ public class ResourceAccessHandler { private static IResourceAccessHandler ACTIVE = new GrantResourceAccessHandler(); static public void checkAccess(IResource resource) throws ResourceAccessException { if (get().isAccessGranted(resource)) { return; } throw new ResourceAccessException("access denied"); } static public IResourceAccessHandler get() { return ACTIVE; } static public void set(IResourceAccessHandler active) { ACTIVE = active; } }
{ "content_hash": "077c3ed11cc128e9f7d0ae285018008a", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 81, "avg_line_length": 20.642857142857142, "alnum_prop": 0.7474048442906575, "repo_name": "intarsys/runtime", "id": "f39747ece85a4282c80ce0e75cfdc45b77a2e3a3", "size": "2128", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/de/intarsys/aaa/resource/ResourceAccessHandler.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Java", "bytes": "2772267" } ], "symlink_target": "" }
<html lang="en"> <head> <title>Purgem - Using as</title> <meta http-equiv="Content-Type" content="text/html"> <meta name="description" content="Using as"> <meta name="generator" content="makeinfo 4.7"> <link title="Top" rel="start" href="index.html#Top"> <link rel="up" href="Pseudo-Ops.html#Pseudo-Ops" title="Pseudo Ops"> <link rel="prev" href="Psize.html#Psize" title="Psize"> <link rel="next" href="PushSection.html#PushSection" title="PushSection"> <link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage"> <!-- This file documents the GNU Assembler "as". Copyright (C) 1991, 92, 93, 94, 95, 96, 97, 98, 99, 2000, 2001, 2002, 2006, 2007 Free Software Foundation, Inc. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.1 or any later version published by the Free Software Foundation; with no Invariant Sections, with no Front-Cover Texts, and with no Back-Cover Texts. A copy of the license is included in the section entitled ``GNU Free Documentation License''. man end--> <meta http-equiv="Content-Style-Type" content="text/css"> <style type="text/css"><!-- pre.display { font-family:inherit } pre.format { font-family:inherit } pre.smalldisplay { font-family:inherit; font-size:smaller } pre.smallformat { font-family:inherit; font-size:smaller } pre.smallexample { font-size:smaller } pre.smalllisp { font-size:smaller } span.sc { font-variant:small-caps } span.roman { font-family: serif; font-weight: normal; } --></style> </head> <body> <div class="node"> <p> <a name="Purgem"></a>Next:&nbsp;<a rel="next" accesskey="n" href="PushSection.html#PushSection">PushSection</a>, Previous:&nbsp;<a rel="previous" accesskey="p" href="Psize.html#Psize">Psize</a>, Up:&nbsp;<a rel="up" accesskey="u" href="Pseudo-Ops.html#Pseudo-Ops">Pseudo Ops</a> <hr><br> </div> <h3 class="section">7.88 <code>.purgem </code><var>name</var></h3> <p><a name="index-_0040code_007bpurgem_007d-directive-426"></a>Undefine the macro <var>name</var>, so that later uses of the string will not be expanded. See <a href="Macro.html#Macro">Macro</a>. </body></html>
{ "content_hash": "b343eb47d9415343fadf48d8662df896", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 143, "avg_line_length": 41.56603773584906, "alnum_prop": 0.7117566954153427, "repo_name": "argets08/Roomba", "id": "61379172e16b24c699504bbc637fb159a777ca1d", "size": "2203", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "arduino/hardware/tools/avr/doc/binutils/as.html/Purgem.html", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "3099" }, { "name": "Batchfile", "bytes": "1258" }, { "name": "C", "bytes": "4256294" }, { "name": "C++", "bytes": "787089" }, { "name": "CSS", "bytes": "75678" }, { "name": "Groff", "bytes": "709140" }, { "name": "HTML", "bytes": "28333281" }, { "name": "Java", "bytes": "785542" }, { "name": "JavaScript", "bytes": "2786" }, { "name": "Logos", "bytes": "103306" }, { "name": "Makefile", "bytes": "218921" }, { "name": "Objective-C", "bytes": "32363" }, { "name": "Perl", "bytes": "2020" }, { "name": "PostScript", "bytes": "9568" }, { "name": "Processing", "bytes": "2031274" }, { "name": "Shell", "bytes": "73529" }, { "name": "Tcl", "bytes": "1430349" }, { "name": "TeX", "bytes": "510" } ], "symlink_target": "" }
package com.example.ericliu.weather2016.ui; import android.app.AlertDialog; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.example.ericliu.weather2016.R; import com.example.ericliu.weather2016.framework.mvp.Presenter; import com.example.ericliu.weather2016.ui.presenter.MainActivityPresenter; import com.example.ericliu.weather2016.ui.viewmodel.MainActivityViewModel; import com.example.ericliu.weather2016.util.NetworkUtil; public class MainActivity extends AppCompatActivity implements MainActivityPresenter.HomepageCallbacks{ private static final String VIEW_MODEL_TAG = "main.activity.viewmodel"; private EditText etCityName; private Button btnSearchWeatherCondition; private TextView tvCityName, tvWeatherCondition; private ProgressBar mProgressBar; private MainActivityPresenter mPresenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setupPresenter(savedInstanceState); initViews(); mPresenter.onViewCreated(); if (savedInstanceState != null) { mPresenter.loadInitialData(null, true); } } @Override protected void onDestroy() { mPresenter.onViewDestroyed(); super.onDestroy(); } private void initViews() { etCityName = (EditText) findViewById(R.id.etCityName); btnSearchWeatherCondition = (Button) findViewById(R.id.btnSearch); tvCityName = (TextView) findViewById(R.id.tvCityName); tvWeatherCondition = (TextView) findViewById(R.id.tvWeatherCondition); mProgressBar = (ProgressBar) findViewById(R.id.progressBar); btnSearchWeatherCondition.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!NetworkUtil.isOnline(MainActivity.this)) { NetworkUtil.checkNetworkAndShowErrorMsg(MainActivity.this); return; } String city = etCityName.getText().toString(); if (!TextUtils.isEmpty(city)) { mPresenter.onSearchButtonClicked(city); } else { Toast.makeText(MainActivity.this, "city name can't be empty!", Toast.LENGTH_SHORT).show(); } } }); } private void setupPresenter(Bundle savedInstanceState) { MainActivityViewModel viewModelFragment; if (savedInstanceState == null) { viewModelFragment = new MainActivityViewModel(); getFragmentManager().beginTransaction().add(viewModelFragment, VIEW_MODEL_TAG).commit(); } else { viewModelFragment = (MainActivityViewModel) getFragmentManager().findFragmentByTag(VIEW_MODEL_TAG); } mPresenter = new MainActivityPresenter(0, this, viewModelFragment); } @Override public void showCityName(String city) { tvCityName.setText(city); } @Override public void showWeatherCondition(String weatherCondition) { tvWeatherCondition.setText(weatherCondition); } @Override public void showDialog(String message) { displayDialog(message); } @Override public void hideProgressBar() { mProgressBar.setVisibility(View.GONE); } @Override public void showProgressBar() { mProgressBar.setVisibility(View.VISIBLE); } private void displayDialog(String errorMessage) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(errorMessage) .setPositiveButton(android.R.string.ok, null); builder.create().show(); } @Override public void setPresenter(Presenter presenter) { mPresenter = (MainActivityPresenter) presenter; } }
{ "content_hash": "08de940c60a2555605d773e0e7d5a432", "timestamp": "", "source": "github", "line_count": 132, "max_line_length": 111, "avg_line_length": 31.386363636363637, "alnum_prop": 0.6821144098479363, "repo_name": "Ericliu001/Weather2016", "id": "284cbbb824b537cd5b394b02034589ea6a500101", "size": "4143", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/example/ericliu/weather2016/ui/MainActivity.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "50768" } ], "symlink_target": "" }
/*global window */ var BLOCKS; if (BLOCKS === undefined) { BLOCKS = {}; } BLOCKS.block = function (options) { "use strict"; var block = BLOCKS.eventDispatcher(), // Private Properties slicesArr = [], slicesObj = {}, curSlice, motors = [], // The order of properties matters in cases of dependencies properties = ["stack", "worldX", "worldY", "x", "y", "scale", "width", "height", "centerRegistrationPoint", "mirrorX", "mirrorY", "angle", "alpha", "layer", "visible", "dirty", "justTapped", "justNotTapped", "dragging", "justReleased", "tapPos", "cropWidth", "cropHeight", "frameOffsetX", "frameOffsetY", "offsetX", "offsetY", "minHotspot", "hotspots", "currentFrameIndex"], methods = ["update", "render", "show", "hide", "pause", "unpause", "reset", "stop", "play", "isPointInside", "getBounds", "getBoundingBox", "isRectInside", "gotoLastFrame", "gotoFrame"], motorDestroyed = function (motor) { var i; motor.removeEventListener("destroyed", motorDestroyed); for (i = 0 ; i < motors.length; i += 1) { if (motors[i] === motor) { motors.splice(i, 1); } break; } }; options = options || {}; // Block Specific Public Properties block.name = options.name; // BLock Specific Public Methods block.addSlice = function (spec) { var i, slice; slice = BLOCKS.slice(spec); if (!spec.name) { slice.name = "unnamedSlice" + slicesArr.length; } slicesArr.push(slice); slicesObj[spec.name] = slice; slice.addEventListener("complete", function () { block.dispatchEvent("complete"); }); // If first slice then set the block to this slice if (slicesArr.length === 1) { // Assign the properties of the spec to the new slice for (i = 0; i < properties.length; i += 1) { if (options[properties[i]] !== undefined) { slice[properties[i]] = options[properties[i]]; } } block.setSlice(spec.name); } return slice; }; block.getSlice = function (name) { if (name === undefined) { return curSlice; } else { return slicesObj[name]; } }; block.setSlice = function (name, callback) { var i, newSlice; newSlice = slicesObj[name]; if (newSlice && newSlice !== curSlice) { // If there is a current slice if (curSlice) { // Assign the properties of the current slice to the new slice for (i = 0; i < properties.length; i += 1) { if (properties[i] !== "width" && properties[i] !== "height" && properties[i] !== "offsetX" && properties[i] !== "offsetY") { newSlice[properties[i]] = curSlice[properties[i]]; } } } // Make the new slice the block's current slice curSlice = newSlice; // If the current slice is an animation then reset and autoplay it curSlice.reset(); if (curSlice.autoPlay) { curSlice.play(callback); } curSlice.dirty = true; return true; } else { // If slice does not exist or it is already set then do nothing return false; } }; block.motorize = function (motor) { motor.addEventListener("destroyed", motorDestroyed); motors.push(motor); }; block.removeMotors = function (type) { var i, motorsToDestroy = [], newMotorArr = []; // Mark all motors to be destroyed. Don't destroy them yet because // the motors array will change because an event is dispatched // when the destroy method is called which alters the motor array for (i = 0 ; i < motors.length; i += 1) { if (type) { if (motors[i].type === type) { motorsToDestroy.push(motors[i]); } else { newMotorArr.push(motors[i]); } } else { motorsToDestroy.push(motors[i]); } } // Destroy all motors marked for destruction for (i = 0 ; i < motorsToDestroy.length; i += 1) { motorsToDestroy[i].destroy(); } motors = newMotorArr; }; block.destroy = function () { var i; if (block) { block.removeMotors(); for (i = 0; i < slicesArr.length; i += 1) { slicesArr[i].destroy(); } slicesArr = null; slicesObj = null; curSlice = null; block.dispatchEvent("destroyed", block); block = null; } }; (function () { var i, createPublicProperty = function (propertyName) { Object.defineProperty(block, propertyName, { get: function () { if (curSlice) { return curSlice[propertyName]; } }, set: function (value) { if (curSlice) { curSlice[propertyName] = value; } } }); }, createPublicMethod = function (methodName) { block[methodName] = function (parameter) { return curSlice[methodName](parameter); }; }; for (i = 0; i < properties.length; i += 1) { createPublicProperty(properties[i]); } for (i = 0; i < methods.length; i += 1) { createPublicMethod(methods[i]); } // If slices defined in the options if (options.slices) { for (i = 0; i < options.slices.length; i += 1) { block.addSlice(options.slices[i]); } } }()); return block; }; /* Copyright (c) 2013 William Malone (www.williammalone.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*global window */ var BLOCKS; if (BLOCKS === undefined) { BLOCKS = {}; } BLOCKS.camera = function (options) { "use strict"; var camera = BLOCKS.gear(); // Public Properties camera.x = (options && options.x) || 0; camera.y = (options && options.y) || 0; camera.width = (options && options.width) || 1024; camera.height = (options && options.height) || 768; return camera; }; /* Copyright (c) 2013 William Malone (www.williammalone.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*global window, document */ var BLOCKS; if (BLOCKS === undefined) { BLOCKS = {}; } BLOCKS.clock = function () { "use strict"; var clock = BLOCKS.eventDispatcher(), paused = true, id, // Private Methods loop = function () { if (!paused) { // Loop again on next animation frame id = window.requestAnimationFrame(loop); clock.dispatchEvent("tick"); } }; clock.stop = function () { window.cancelAnimationFrame(id); paused = true; }; clock.start = function () { if (paused) { paused = false; id = window.requestAnimationFrame(loop); } }; clock.destroy = function () { clock.stop(); clock = null; }; // http://paulirish.com/2011/requestanimationframe-for-smart-animating/ (function() { var lastTime = 0; var vendors = ['webkit', 'moz']; for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame']; window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame']; } if (!window.requestAnimationFrame) window.requestAnimationFrame = function(callback, element) { var currTime = new Date().getTime(); var timeToCall = Math.max(0, 16 - (currTime - lastTime)); var id = window.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; if (!window.cancelAnimationFrame) window.cancelAnimationFrame = function(id) { window.clearTimeout(id); }; }()); return clock; }; /* Copyright (c) 2013 William Malone (www.williammalone.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*global window */ var BLOCKS; if (BLOCKS === undefined) { BLOCKS = {}; } BLOCKS.container = function (game) { "use strict"; var container = BLOCKS.eventDispatcher(), // Private Properties motors = [], layers = [], views = [], layerLabels = {}, // Private Methods motorDestroyed = function (motor) { var i; motor.removeEventListener("destroyed", motorDestroyed); for (i = 0 ; i < motors.length; i += 1) { motors.splice(i, 1); break; } }; // Public Properties container.visible = true; container.dirty = true; container.assignLayers = function () { var i, args; args = Array.prototype.slice.call(arguments); layerLabels = {}; for (i = 0; i < args.length; i += 1) { layerLabels[args[i]] = game.getLayer(i); } }; container.getLayer = function (label) { if (layerLabels[label]) { return layerLabels[label]; } else { BLOCKS.error("Cannot find container layer: " + label); } }; container.addView = function (view) { var i, layerInArray; view.addEventListener("destroyed", container.removeView); views.push(view); for (i = 0; i < layers.length; i += 1) { if (view.layer === layers[i]) { layerInArray = true; break; } } if (!layerInArray && view.layer) { layers.push(view.layer); } }; container.removeView = function (view) { var i, layer, keepLayer; view.removeEventListener("destroyed", container.removeView); for (i = 0; i < views.length; i += 1) { if (view === views[i]) { layer = views.layer; views.splice(i, 1); break; } } for (i = 0; i < views.length; i += 1) { if (view.layer === layer) { keepLayer = true; break; } } if (!keepLayer) { for (i = 0; i < layers.length; i += 1) { if (layer === layers[i]) { layers.splice(i, 1); break; } } } }; container.setViewLayerIndex = function (view, newIndex) { var i, oldIndex; for (i = 0; i < views.length; i += 1) { if (views[i] === view) { oldIndex = i; break; } } if (i === undefined) { BLOCKS.warn("Cannot find view to set view's layer index."); } else { views.splice(oldIndex, 1); views.splice(newIndex, 0, view); // Redraw this view next time view.dirty = true; } }; container.getViewLayerIndex = function (view) { var i, index; for (i = 0; i < views.length; i += 1) { if (views[i] === view) { index = i; break; } } return index; }, container.clear = function () { var i; for (i = 0; i < layers.length; i += 1) { container.layers[i].clear(); } }; container.motorize = function (motor) { motor.addEventListener("destroyed", motorDestroyed); motors.push(motor); }; container.removeMotors = function (type) { var i, motorArr = []; for (i = 0 ; i < motors.length; i += 1) { if (type) { if (motors[i].type === type) { motors[i].destroy(); } else { motorArr.push(motors[i]); } } else { motors[i].destroy(); } } motors = motorArr; }; container.update = function () { var i; for (i = 0; i < views.length; i += 1) { views[i].update(); } }; container.render = function (e) { var i, key, dirtyLayers = {}; for (key in layerLabels) { if (layerLabels.hasOwnProperty(key)) { if (layerLabels[key].dirty || container.dirty) { dirtyLayers[layerLabels[key].name] = layerLabels[key]; } } } // Check if any layers were set to dirty (or the container is dirty) for (i = 0; i < layers.length; i += 1) { if (layers[i].dirty || container.dirty) { dirtyLayers[layers[i].name] = layers[i]; } } // If any view is dirty then mark its layer dirty for (i = 0; i < views.length; i += 1) { if (views[i].dirty) { dirtyLayers[views[i].layer.name] = views[i].layer; } } // Clear all dirty layers for (key in dirtyLayers) { if (dirtyLayers.hasOwnProperty(key)) { dirtyLayers[key].clear(); } } // Mark all container views dirty for (i = 0; i < views.length; i += 1) { if (dirtyLayers[views[i].layer.name]) { views[i].dirty = true; } if (container.visible) { views[i].render(e); } } container.dirty = false; }; container.destroy = function () { var i; for (i = 0; i < views.length; i += 1) { container.removeView(views[i]); views[i].destroy(); views[i] = null; } views = null; layers = null; motors = null; }; return container; }; /* Copyright (c) 2013 William Malone (www.williammalone.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*global window, document */ var BLOCKS; if (BLOCKS === undefined) { BLOCKS = {}; } BLOCKS.controller = function (element) { "use strict"; var controller = BLOCKS.eventDispatcher(), elementPos, getElementPos = function (element) { var parentOffset, pos; if (!element) { pos = { x: 0, y: 0 }; } else { pos = { x: element.offsetLeft, y: element.offsetTop }; if (element.offsetParent) { parentOffset = getElementPos(element.offsetParent); pos.x += parentOffset.x; pos.y += parentOffset.y; } } return pos; }, init = function () { var target; document.addEventListener("keydown", onKeyDownEvent, true); document.addEventListener("keyup", onKeyUpEvent, true); // Listen to the element if it exitst otherwise fall back to the document element target = element || document; target.addEventListener("orientationchange", onOrientationEvent, true); target.addEventListener("touchstart", onTouchEvent, true); target.addEventListener("touchmove", onTouchEvent, true); target.addEventListener("touchend", onTouchEvent, true); target.addEventListener("touchcancel", onTouchEvent, true); target.addEventListener("mousedown", onMouseEvent, true); target.addEventListener("mousemove", onMouseEvent, true); target.addEventListener("mouseup", onMouseEvent, true); target.addEventListener("mousecancel", onMouseEvent, true); target.addEventListener("mouseout", onMouseEvent, true); // Fire a mouseUpOutside event when mouse up detected outside the game document.addEventListener("mouseup", function (event) { onMouseEvent(event, true); }, false); }, onOrientationEvent = function () { if (controller.listening) { switch (window.orientation) { case -90: controller.orientation = "landscape"; break; case 0: controller.orientation = "portrait"; break; case 90: controller.orientation = "landscape"; break; case 180: controller.orientation = "portrait"; break; } controller.dispatchEvent("orientationChange", { orientation: controller.orientation }); } }, onKeyDownEvent = function (e) { if (controller.listening) { controller.dispatchEvent("keyDown", e); } }, onKeyUpEvent = function (e) { if (controller.listening) { controller.dispatchEvent("keyUp", e); } }, dispatchTapEvent = function (e, eventType) { switch (eventType) { case "tap": controller.drag = true; controller.dispatchEvent("tap", e); break; case "drag": controller.dispatchEvent("drag", e); break; case "release": controller.drag = false; controller.dispatchEvent("release", e); break; case "cancel": controller.drag = false; controller.dispatchEvent("cancel", e); break; default: break; } }, onTouchEvent = function (e) { var i, key, event, touch, eventType, firstFinger; if (controller.listening) { // Disable scrolling on mobile and prevent mouse event on touch if (e.preventDefault) { e.preventDefault(); } // TODO: ElementPos does not have to be calculated every time? elementPos = getElementPos(element); // Select the first changed touch and assign it as the default touch firstFinger = e.changedTouches[0]; // Make a copy of the touch event event = {}; for (key in firstFinger) { //if (firstFinger.hasOwnProperty(key)) { // Don't use due to Firefox and IE9 event[key] = firstFinger[key]; //} } event.x = (firstFinger.pageX - elementPos.x - controller.offsetX) * controller.scaleX; event.y = (firstFinger.pageY - elementPos.y - controller.offsetY) * controller.scaleY; event.type = e.type; event.touches = []; // For each touch currently on the screen for (i = 0; i < e.touches.length; i += 1) { event.touches[i] = {}; for (key in e.touches[i]) { if (e.touches[i].hasOwnProperty(key)) { event.touches[i][key] = e.touches[i][key]; } } event.touches[i].x = (event.touches[i].clientX - elementPos.x - controller.offsetX) * controller.scaleX; event.touches[i].y = (event.touches[i].clientY - elementPos.y - controller.offsetY) * controller.scaleY; } event.changedTouches = []; // For each touch invloved in this event on the screen for (i = 0; i < e.changedTouches.length; i += 1) { event.changedTouches[i] = {}; for (key in e.changedTouches[i]) { if (e.changedTouches[i].hasOwnProperty(key)) { event.changedTouches[i][key] = e.changedTouches[i][key]; } } event.changedTouches[i].x = (event.changedTouches[i].pageX - elementPos.x - controller.offsetX) * controller.scaleX; event.changedTouches[i].y = (event.changedTouches[i].pageY - elementPos.y - controller.offsetY) * controller.scaleY; } switch (event.type) { case "touchstart": eventType = "tap"; controller.dispatchEvent("touchStart", event); break; case "touchmove": eventType = "drag"; controller.dispatchEvent("touchMove", event); break; case "touchend": eventType = "release"; controller.dispatchEvent("touchEnd", event); break; case "touchcancel": eventType = "cancel"; controller.dispatchEvent("touchCancel", event); break; default: break; } dispatchTapEvent(event, eventType); } }, onMouseEvent = function (e, outsideGameBounds) { var i, key, eventType, event; if (controller.listening) { // Stop the mouse event from going to the any elements behind the game e.stopPropagation(); // Disable right click //if (e.button === 2) { // return; //} event = {}; for (key in e) { //if (e.hasOwnProperty(key)) { Don't use due to Firefox and IE9 event[key] = e[key]; //} } // TODO: ElementPos does not have to be calculated every time? elementPos = getElementPos(element); event.x = (event.pageX - elementPos.x - controller.offsetX) * controller.scaleX; event.y = (event.pageY - elementPos.y - controller.offsetY) * controller.scaleY; event.identifier = "mouse"; event.touches = [event]; event.changedTouches = [event]; if (outsideGameBounds) { event.type += "outside"; } switch (event.type) { case "mousedown": eventType = "tap"; controller.dispatchEvent("mouseDown", event); break; case "mousemove": eventType = "drag"; controller.dispatchEvent("mouseMove", event); break; case "mouseup": eventType = "release"; controller.dispatchEvent("mouseUp", event); break; case "mousecancel": eventType = "cancel"; controller.dispatchEvent("mouseCancel", event); break; case "mouseout": eventType = "mouseout"; controller.dispatchEvent("mouseOut", event); return; // Don't dispatch tap event case "mouseupoutside": eventType = "mouseupoutside"; controller.dispatchEvent("mouseUpOutside", event); return; // Don't dispatch tap event default: break; } dispatchTapEvent(event, eventType); } }; controller.scaleX = 1; controller.scaleY = 1; controller.offsetX = 0; controller.offsetY = 0; controller.listening = true; controller.simulateKeyDownEvent = function (keyCode) { onKeyDownEvent({ keyCode: keyCode }); }; controller.simulateKeyUpEvent = function (keyCode) { onKeyUpEvent({ keyCode: keyCode }); }; init(); return controller; }; /* Copyright (c) 2013 William Malone (www.williammalone.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*global window, Image */ var BLOCKS; if (BLOCKS === undefined) { BLOCKS = {}; } BLOCKS.eventDispatcher = function () { "use strict"; var that = {}, eventListeners = {}; // Public Methods that.dispatchEvent = function (eventName, parameters) { var i, callbacks = [], listenerArr = []; // If something is listening if (eventListeners[eventName]) { // For each item that is listening for (i = 0; i < eventListeners[eventName].length; i += 1) { // Invoke callback on the listener callbacks.push(eventListeners[eventName][i].callback); // If the event listener should persist if (!eventListeners[eventName][i].destroyOnDispatch) { listenerArr.push(eventListeners[eventName][i]); } } eventListeners[eventName] = listenerArr; for (i = 0; i < callbacks.length; i += 1) { // Invoke callback of dispatched event callbacks[i](parameters); } } }; that.addEventListener = function (eventName, callback, onlyOnce) { if (!eventListeners[eventName]) { eventListeners[eventName] = []; } eventListeners[eventName].push({ name: eventName, callback: callback, destroyOnDispatch: onlyOnce }); //BLOCKS.debug("Add event listener: " + eventName); }; that.removeEventListener = function (eventName, callback) { var i; if (eventListeners[eventName]) { for (i = 0; i < eventListeners[eventName].length; i += 1) { if (callback) { if (eventListeners[eventName][i].callback === callback) { //BLOCKS.debug("Remove event listener: " + eventName); eventListeners[eventName][i] = null; eventListeners[eventName].splice(i, 1); } } else { eventListeners[eventName][i] = null; eventListeners[eventName].splice(i, 1); } } } }; that.clearEventListeners = function () { eventListeners = {}; }; return that; }; /* Copyright (c) 2013 William Malone (www.williammalone.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*global window, document, navigator */ var BLOCKS; if (BLOCKS === undefined) { BLOCKS = {}; } BLOCKS.game = function (spec, element) { "use strict"; var game = BLOCKS.eventDispatcher(), clock = BLOCKS.clock(), gameContainer, gameCanvas, interactionContainer, paused = false, virtualKeyboard, motors = [], tickers = [], debugPressTimeout, lastUpdateTime, remainingUpdate, minWidth, minHeight, maxHeight, maxWidth, scaleLandscape, scalePortrait, debugLayer, gameTappedOnce, loaded, tickerIndex = 0, layerIndex = 0, maxLayers, prepared, wasMutedWhenPaused, loadStarted, handleTickers = function () { var i, tickerArr = [], callbacks = []; for (i = 0; i < tickers.length; i += 1) { tickers[i].curTick += 1; if (tickers[i].curTick >= tickers[i].totalTicks) { callbacks.push(tickers[i]); } else { tickerArr.push(tickers[i]); } } tickers = tickerArr; for (i = 0; i < callbacks.length; i += 1) { callbacks[i].callback(callbacks[i].parameters); } }, onOrientationChange = function () { // Remove the space on iPhone / iPod when in landscape and using minimal ui meta tag if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) { if (window.orientation === 90 || window.orientation === -90) { window.scrollTo(0, 0); resizeGame(); } } }, onVisibilityChange = function () { if (document.hidden || document.webkitHidden || document.mozHidden || document.msHidden) { game.pause(); } else { game.unpause(); } }, onFirstTap = function () { if (!gameTappedOnce) { game.controller.removeEventListener("tap", onFirstTap); game.dispatchEvent("firstTap"); gameTappedOnce = true; if (game.introScreen) { game.state = "loading"; game.introScreen.destroy(); game.introScreen = null; } game.speaker.load(); checkLoadProgress(); checkInitialScreenProgress(); } }, init = function () { var i; if (spec && spec.scaleLandscape !== undefined) { scaleLandscape = spec.scaleLandscape; } else { scaleLandscape = true; } if (spec && spec.scalePortrait !== undefined) { scalePortrait = spec.scalePortrait; } else { scalePortrait = true; } if (game.element) { gameContainer = document.createElement("article"); gameContainer.id = "BlocksGameContainer"; if (spec && spec.minWidth) { minWidth = spec.minWidth; gameContainer.style.minWidth = minWidth + "px"; } if (spec && spec.minHeight) { minHeight = spec.minHeight; gameContainer.style.minHeight = minHeight + "px"; } if (spec && spec.maxWidth) { maxWidth = spec.maxWidth; gameContainer.style.maxWidth = maxWidth + "px"; } if (spec && spec.maxHeight) { maxHeight = spec.maxHeight; gameContainer.style.maxHeight = maxHeight + "px"; } game.element.appendChild(gameContainer); interactionContainer = document.createElement("article"); interactionContainer.id = "BlocksInteractionContainer"; gameContainer.appendChild(interactionContainer); } game.controller = BLOCKS.controller(interactionContainer); // Resize the game the first time to initialize the game scale propetries resizeGame(); // Create virtual keyboard if (game.debug && game.virtualKeyboardEnabled) { virtualKeyboard = BLOCKS.virtualKeyboard(game.controller, { layer: game.getLayer(), customKeys: spec.customVirtualKeys }); } window.addEventListener("orientationchange", onOrientationChange); window.addEventListener("resize", resizeGame); game.controller.addEventListener("keyUp", onKeyUp); game.controller.addEventListener("keyDown", onKeyDown); game.controller.addEventListener("tap", onTap); game.controller.addEventListener("drag", onDrag); game.controller.addEventListener("release", onRelease); game.controller.addEventListener("cancel", onRelease); // Note cancel is retreated as a release game.controller.addEventListener("touchStart", onTouchStart); game.controller.addEventListener("touchMove", onTouchMove); game.controller.addEventListener("touchEnd", onTouchEnd); game.controller.addEventListener("touchCancel", onTouchEnd); // Note cancel is retreated as a touch end game.controller.addEventListener("mouseDown", onMouseDown); game.controller.addEventListener("mouseMove", onMouseMove); game.controller.addEventListener("mouseUp", onMouseUp); game.controller.addEventListener("mouseCancel", onMouseUp); // Note cancel is retreated as a mouse up game.controller.addEventListener("mouseOut", onMouseOut); game.controller.addEventListener("mouseUpOutside", mouseUpOutside); // Listen to the first time the game is tapped game.controller.addEventListener("tap", onFirstTap); // Mute and pause the game when the browser is not visible if (typeof document.hidden !== "undefined") { document.addEventListener("visibilitychange", onVisibilityChange); } else if (typeof document.mozHidden !== "undefined") { document.addEventListener("mozvisibilitychange", onVisibilityChange); } else if (typeof document.msHidden !== "undefined") { document.addEventListener("msvisibilitychange", onVisibilityChange); } else if (typeof document.webkitHidden !== "undefined") { document.addEventListener("webkitvisibilitychange", onVisibilityChange); } window.onunload = game.destroy; }, gameUpdate = function () { var now; if (!paused) { now = + new Date(); remainingUpdate += (now - lastUpdateTime); lastUpdateTime = now; // If too much update then crop it if (remainingUpdate > game.maxLoopDuration) { BLOCKS.warn("Cannot keep up with game loop. Chopping " + Math.ceil((remainingUpdate - game.maxLoopDuration) / 60) + " frames."); remainingUpdate = game.maxLoopDuration; } //if (remainingUpdate < 16.666666666666) { // BLOCKS.debug("No update this time: " + remainingUpdate); //} while (remainingUpdate >= 16.666666666666) { remainingUpdate -= 16.666666666666; game.dispatchEvent("tick"); // Simulate a clock game.dispatchEvent("preUpdate"); if (game.debug && virtualKeyboard) { virtualKeyboard.update(); } handleTickers(); game.update(); game.dispatchEvent("postUpdate"); } } }, gameRender = function () { var e = { camera: game.camera }; if (!paused) { game.dispatchEvent("preRender", e); if (game.debug && virtualKeyboard) { virtualKeyboard.render(e); } game.render(e); game.dispatchEvent("postRender", e); } }, onClockTick = function () { gameUpdate(); gameRender(); }, onKeyDown = function (e) { if (game.keyDown) { game.keyDown(e); } }, onKeyUp = function (e) { if (game.keyUp) { game.keyUp(e); } }, onTap = function (pos) { if (game.debug && virtualKeyboard) { if (pos.x < 100 && pos.y < 100) { debugPressTimeout = window.setTimeout(function () { virtualKeyboard.visible = !virtualKeyboard.visible; virtualKeyboard.dirty = true; }, 1000); } virtualKeyboard.onTap(pos); } if (game.tap) { game.tap(pos); } }, onDrag = function (pos) { if (game.debug) { window.clearTimeout(debugPressTimeout); } if (game.drag) { game.drag(pos); } }, onRelease = function (pos) { if (game.debug) { window.clearTimeout(debugPressTimeout); } if (game.release) { game.release(pos); } }, onTouchStart = function (pos) { if (game.touchStart) { game.touchStart(pos); } }, onTouchMove = function (pos) { if (game.touchMove) { game.touchMove(pos); } }, onTouchEnd = function (pos) { if (game.touchEnd) { game.touchEnd(pos); } }, onMouseDown = function (pos) { if (game.mouseDown) { game.mouseDown(pos); } }, onMouseMove = function (pos) { if (game.mouseMove) { game.mouseMove(pos); } }, onMouseUp = function (pos) { if (game.mouseUp) { game.mouseUp(pos); } }, onMouseOut = function (pos) { if (game.mouseOut) { game.mouseOut(pos); } }, mouseUpOutside = function (pos) { if (game.mouseUpOutside) { game.mouseUpOutside(pos); } }, checkLoadProgress = function () { //BLOCKS.debug("checkLoadProgress: " + gameTappedOnce + " " + game.imageLoader.isLoaded() + " " + game.speaker.isReady()); if (!loaded) { if ((game.introScreen && gameTappedOnce) || !game.introScreen) { // If all images are loaded and all sounds (or number of sounds is zero) are laoded if (game.imageLoader.isLoaded() && (game.speaker.isReady() || game.speaker.getNumFiles() === 0)) { loaded = true; if (game.loadingScreen) { game.loadingScreen.destroy(); game.loadingScreen = null; } // If autoLoad is not turned off then load if (game.autoStart !== false) { game.start(); } game.dispatchEvent("loaded"); } } } }, // See wmalone.com/scale for an article discussing this scaling approach resizeGame = function () { var i, viewport, newGameWidth, newGameHeight, newGameX, newGameY; // Get the dimensions of the viewport if (game.element) { viewport = { width: game.element.offsetWidth, height: game.element.offsetHeight }; } else { viewport = { width: window.innerWidth * game.pixelMultiplier, height: window.innerHeight * game.pixelMultiplier }; } // If the viewport is greater than a minimum or maximum game dimension use that instead if (minWidth && viewport.width < minWidth) { viewport.width = minWidth; } if (minHeight && viewport.height < minHeight) { viewport.height = minHeight; } if (maxWidth && viewport.width > maxWidth) { viewport.width = maxWidth; } if (maxHeight && viewport.height > maxHeight) { viewport.height = maxHeight; } // If the game should not be scaled if (!scaleLandscape && Math.abs(window.orientation) === 90 || !scalePortrait && Math.abs(window.orientation) !== 90) { newGameHeight = game.height; newGameWidth = game.width; } else { // Determine game size if (game.height / game.width > viewport.height / viewport.width) { if (game.safeHeight / game.width > viewport.height / viewport.width) { // A newGameHeight = viewport.height * game.height / game.safeHeight; newGameWidth = newGameHeight * game.width / game.height; } else { // B newGameWidth = viewport.width; newGameHeight = newGameWidth * game.height / game.width; } } else { if (game.height / game.safeWidth > viewport.height / viewport.width) { // C newGameHeight = viewport.height; newGameWidth = newGameHeight * game.width / game.height; } else { // D newGameWidth = viewport.width * game.width / game.safeWidth; newGameHeight = newGameWidth * game.height / game.width; } } } newGameX = (viewport.width - newGameWidth) / 2; newGameY = (viewport.height - newGameHeight) / 2; // Save the game scale amount game.scale = newGameWidth / game.width; // Define the camera game.camera.offsetX = -Math.min(newGameX, 0) / game.scale; game.camera.offsetY = -Math.min(newGameY, 0) / game.scale; game.camera.width = (viewport.width - Math.max(newGameX, 0) * 2) / game.scale; game.camera.height = (viewport.height - Math.max(newGameY, 0) * 2) / game.scale; if (gameContainer) { // Resize the game container gameContainer.style.width = (viewport.width - Math.max(newGameX, 0) * 2) + "px"; gameContainer.style.height = (viewport.height - Math.max(newGameY, 0) * 2)+ "px"; // Set the new padding of the game so it will be centered gameContainer.style.padding = Math.max(newGameY, 0) + "px " + Math.max(newGameX, 0) + "px"; } // Tell the controller the game dimensions game.controller.scaleX = (game.width / newGameWidth) * game.pixelMultiplier; game.controller.scaleY = (game.height / newGameHeight) * game.pixelMultiplier; game.controller.offsetX = -game.camera.offsetX * game.scale / game.pixelMultiplier; game.controller.offsetY = -game.camera.offsetY * game.scale / game.pixelMultiplier; for (i = 0; i < game.layers.length; i += 1) { game.layers[i].width = game.camera.width; game.layers[i].height = game.camera.height; } if (!loaded && game.loadingScreen) { game.loadingScreen.dirty = true; } game.dispatchEvent("resize"); }, initLoad = function () { if (!loadStarted) { // If autoLoad is not turned off then load if (game.autoLoad !== false) { game.load(); } } }, checkInitialScreenProgress = function () { if (game.introScreen) { if (!game.introScreen.loaded) { //BLOCKS.debug("waiting for intro screen to load"); return; } } if (game.loadingScreen) { if (!game.loadingScreen.loaded) { //BLOCKS.debug("waiting for loading screen to load"); return; } } //BLOCKS.debug("load game"); initLoad(); }; // Define spec as empty object if it was specified as a parameter spec = spec || {}; // The element in which the game markup will be injected will be the element with // the "BlockGame" id unless specified via a parameter of the game game.element = (element !== undefined) ? element : document.getElementById("BlocksGame"); // If no game element found with matching id, look for one with a matching class name if (!game.element) { if (document.getElementsByClassName && document.getElementsByClassName("BlocksGame")) { game.element = document.getElementsByClassName("BlocksGame")[0]; } } if (!game.element) { BLOCKS.error("Game does not have a game element"); } // If there is no game element to scale for us we will need to scale manually game.pixelMultiplier = !game.element && window.devicePixelRatio ? window.devicePixelRatio : 1; // The scale property represents the amount the game is scaled game.scale = 1; // The singleLayer property will render everything to one layer game.singleLayer = spec.singleLayer !== undefined ? spec.singleLayer : false; game.layers = []; game.width = spec.width !== undefined ? spec.width : 1024; game.height = spec.height !== undefined ? spec.height : 768; game.safeWidth = spec.safeWidth || game.width; game.safeHeight = spec.safeHeight || game.height; game.debug = spec.debug !== undefined ? spec.debug : false; game.maxLoopDuration = spec.maxLoopDuration !== undefined ? spec.maxLoopDuration : 500; game.stage = BLOCKS.container(game); game.camera = BLOCKS.camera({ width: game.width, height: game.height }); game.autoLoad = spec.autoLoad !== undefined ? spec.autoLoad : true; game.autoStart = spec.autoStart !== undefined ? spec.autoStart : true; game.state = ""; // A canvas can be specified to be used for all rendering gameCanvas = spec.canvas; // If a canvas is specifed then only one layer will be allowed if (gameCanvas) { maxLayers = 1; } else { maxLayers = spec.maxLayers !== undefined ? spec.maxLayers : 10; } game.pause = function () { if (!paused) { //BLOCKS.debug("Game not visible so pause"); paused = true; if (game.speaker) { wasMutedWhenPaused = game.speaker.isMuted(); game.speaker.mute(); game.speaker.pause(); game.dispatchEvent("pause"); } } }; game.resize = function () { resizeGame(); }; game.unpause = function () { if (paused) { //BLOCKS.debug("Game is visible again so unpause"); paused = false; lastUpdateTime = + new Date(); if (game.speaker) { if (!wasMutedWhenPaused) { game.speaker.unmute(); } game.speaker.unpause(); game.dispatchEvent("unpause"); } } }; game.update = function () { game.stage.update(); }; game.render = function (e) { game.stage.render(e); }; game.clearLayers = function () { var i; for (i = 0; i < game.layers.length; i += 1) { game.layers[i].clear(); } }; // Label can match a layer's name or id or index game.getLayer = function (label) { var i, layer, index; if (label === undefined) { label = 0; } if (typeof label === "number") { index = label; // If the index is larger than the number of layers if (index > game.layers.length - 1) { if (index > maxLayers - 1) { layer = game.layers[game.layers.length - 1]; if (!gameCanvas) { BLOCKS.warn("Layer index larger than maximum layers, using the top layer instead."); } } else { // Create a new layer layer = game.addLayer("FrameworkGameLayer" + index); } } else { layer = game.layers[index]; } } else { // Return the layer with the layer with the matching name for (i = 0; i < game.layers.length; i += 1) { if (game.layers[i].name === label || game.layers[i].id === label) { layer = game.layers[i]; } } } return layer; }; game.createLayer = function (name, options) { options = options || {}; options.name = name; options.id = (+ new Date()).toString() + tickerIndex; options.canvas = gameCanvas; if (!game.element) { options.scale = game.pixelMultiplier / game.scale; } if (interactionContainer) { options.parentElement = interactionContainer; } if (!options.width) { options.width = game.camera.width; } if (!options.height) { options.height = game.camera.height; } return BLOCKS.layer(options); }; game.addLayer = function (name, options) { var layer; // If using one layer then return that if (gameCanvas && game.layers.length) { return game.getLayer(); } else { layer = game.createLayer(name, options); game.layers.push(layer); return layer; } }; game.destroyLayer = function (layer) { if (layer) { layer.destroy(); layer = null; } }; game.removeLayer = function (name) { var i; for (i = 0; i < game.layers.length; i += 1) { if (game.layers[i].name === name) { game.destroyLayer(game.layers[i]); game.layers.splice(i, 1); return true; } } }; game.addMotor = function (type) { var key, motor, spec = arguments[1] || {}; spec.type = type; if (spec.type === "drag") { spec.controller = game.controller; } else { spec.clock = game; } motor = BLOCKS.motor(spec); if (motor) { motor.type = type; if (spec.object) { spec.object.motorize(motor); } motor.addEventListener("destroyed", game.removeMotor); motors.push(motor); } return motor; }; game.removeMotor = function (motor) { var i; for (i = 0; i < motors.length; i += 1) { if (motors[i] === motor) { motors.splice(i, 1); return true; } } }; game.addTicker = function (callback, duration, parameters) { var id = (+ new Date()).toString() + tickerIndex; tickerIndex += 1; if (tickerIndex > 99999999) { tickerIndex = 0; } tickers.push({ id: id, curTick: 0, totalTicks: Math.ceil(duration * 60 / 1000), callback: callback, parameters: parameters }); return id; }; game.removeTicker = function (id) { var i, existingTickers = []; for (i = 0; i < tickers.length; i += 1) { if (tickers[i].id === id) { tickers[i] = null; } else { existingTickers.push(tickers[i]); } } tickers = existingTickers; }; game.clearTickers = function () { tickers = []; }; game.load = function () { var i; if (!loadStarted) { loadStarted = true; game.imageLoader.loadFromTree(spec); // Define game sounds if (spec.sounds) { for (i = 0; i < spec.sounds.length; i += 1) { game.speaker.createSound(spec.sounds[i]); } } game.imageLoader.addEventListener("update", function () { var assetsLoaded = game.imageLoader.getNumFilesLoaded() + game.speaker.getNumFilesLoaded(); if (game.loadingScreen) { game.loadingScreen.setProgress(assetsLoaded, game.imageLoader.getNumFiles() + game.speaker.getNumFiles()); } }); game.imageLoader.addEventListener("complete", function () { checkLoadProgress(); }); game.imageLoader.load(); } }; game.stop = function () { clock.removeEventListener("tick", onClockTick); clock.stop(); }; game.start = function () { var i; lastUpdateTime = + new Date(); remainingUpdate = 0; if (!prepared) { prepared = true; if (game.prepare) { game.prepare(); } } clock.removeEventListener("tick", onClockTick); clock.addEventListener("tick", onClockTick); clock.start(); }; game.destroy = function () { var i; clock.destroy(); if (game.speaker) { game.speaker.stop(); } if (game.introScreen) { game.introScreen.destroy(); } if (game.loadingScreen) { game.loadingScreen.destroy(); } for (i = 0; i < game.layers; i += 1) { game.removeLayer(game.layers[i]); } }; // http://paulirish.com/2011/requestanimationframe-for-smart-animating/ (function() { var lastTime = 0; var vendors = ['webkit', 'moz']; for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame']; window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame']; } if (!window.requestAnimationFrame) window.requestAnimationFrame = function(callback, element) { var currTime = new Date().getTime(); var timeToCall = Math.max(0, 16 - (currTime - lastTime)); var id = window.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; if (!window.cancelAnimationFrame) window.cancelAnimationFrame = function(id) { window.clearTimeout(id); }; }()); init(); game.imageLoader = (spec && spec.imagesPath) ? BLOCKS.preloader(spec.imagesPath) : BLOCKS.preloader(); if (spec && spec.loading) { game.loadingScreen = BLOCKS.loadingScreen(spec.loading, game); game.intro = "loading"; } if (spec && spec.intro) { game.introScreen = BLOCKS.introScreen(spec.intro, game); game.intro = "intro"; } // Create sound player game.speaker = BLOCKS.speaker({ path: (spec && spec.audioPath !== undefined) ? spec.audioPath : "", src: (spec && spec.audioSpriteSrc !== undefined) ? spec.audioSpriteSrc : "", audioPlayerType: spec.audioPlayerType }); game.speaker.addEventListener("update", function (e) { var assetsLoaded = game.imageLoader.getNumFilesLoaded() + game.speaker.getNumFilesLoaded(); if (game.loadingScreen) { game.loadingScreen.setProgress(assetsLoaded, game.imageLoader.getNumFiles() + game.speaker.getNumFiles()); } }); game.speaker.addEventListener("ready", function () { checkLoadProgress(); }, true); Object.defineProperty(game, "paused", { get: function () { return paused; } }); if (game.loadingScreen) { game.loadingScreen.addEventListener("loaded", checkInitialScreenProgress); } if (game.introScreen) { game.introScreen.addEventListener("loaded", checkInitialScreenProgress); } checkInitialScreenProgress(); return game; }; /* Copyright (c) 2013 William Malone (www.williammalone.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*global window */ var BLOCKS; if (BLOCKS === undefined) { BLOCKS = {}; } BLOCKS.gear = function (options) { "use strict"; var view = BLOCKS.eventDispatcher(), // Properties motors = [], motorDestroyed = function (motor) { var i; motor.removeEventListener("destroyed", motorDestroyed); for (i = 0 ; i < motors.length; i += 1) { if (motors[i] === motor) { motors.splice(i, 1); } break; } }; view.motorize = function (motor) { motor.addEventListener("destroyed", motorDestroyed); motors.push(motor); }; view.removeMotors = function (type) { var i, destroyMotorArr = [], motorArr = []; for (i = 0 ; i < motors.length; i += 1) { if (type) { if (motors[i].type === type) { motors[i].destroy(); } else { motorArr.push(motors[i]); } } else { // Mark the motor to be destroyed destroyMotorArr.push(motors[i]); } } // Destroy all motors marked for destruction for (i = 0 ; i < destroyMotorArr.length; i += 1) { destroyMotorArr[i].destroy(); } // Update the motors array if only some motors destroyed motors = motorArr; }; view.destroy = function () { if (view) { view.removeMotors(); view.dispatchEvent("destroyed", view); view = null; } }; return view; }; /** * introScreen.js * _____________________________________________________________________________ * * @author William Malone (www.williammalone.com) */ /*global window, BLOCKS, Image */ BLOCKS.introScreen = function (spec, game) { "use strict"; var introScreen = BLOCKS.eventDispatcher(), bg, clock, layer, destroyed, button, buttonImageLoaded, createButton = function () { if (button === undefined && layer) { button = BLOCKS.slice({ layer: layer, image: spec.button.image, centerRegistrationPoint: true }); button.x = spec.button.x; button.y = spec.button.y; game.controller.addEventListener("mouseMove", onMouseMove); } }, loadBg = function () { spec.bg.image = game.imageLoader.loadNow(spec.bg); spec.bg.image.onload = bgLoaded; }, bgLoaded = function () { if (!destroyed) { if (spec.bg.image.width !== 0 && spec.bg.image.height !== 0) { prepare(); if (button || !spec.button) { introScreen.loaded = true; introScreen.dispatchEvent("loaded"); } } else { if (!destroyed) { window.setTimeout(bgLoaded, 10); } } } }, loadButton = function () { if (spec.button) { spec.button.image = game.imageLoader.loadNow(spec.button); spec.button.image.onload = buttonLoaded; } }, buttonLoaded = function () { if (!destroyed) { if (spec.button.image.width !== 0 && spec.button.image.height !== 0) { buttonImageLoaded = true; if (button === undefined) { createButton(); } if (bg && !destroyed) { introScreen.loaded = true; introScreen.dispatchEvent("loaded"); } } else { if (!destroyed) { window.setTimeout(buttonLoaded, 10); } } } }, load = function () { layer = game.addLayer("intro", { zIndex: 1 }); loadBg(); loadButton(); }, onTick = function () { update(); render(); }, prepare = function () { if (!destroyed) { bg = BLOCKS.slice({ layer: layer, image: spec.bg.image }); if (buttonImageLoaded) { createButton(); } clock = BLOCKS.clock(); clock.addEventListener("tick", onTick); clock.start(); } }, update = function () { bg.update(); if (button) { button.update(); } }, render = function () { if (layer.dirty || (button && button.dirty)) { bg.dirty = true; if (button) { button.dirty = true; } } bg.render(game); if (button) { button.render(game); } }, onMouseMove = function (pos) { if (button.isPointInside(pos)) { button.scale = 1.1; } else { button.scale = 1; } }; introScreen.destroy = function () { destroyed = true; if (clock) { clock.destroy(); } if (bg) { bg.destroy(); } if (button) { button.destroy(); game.controller.removeEventListener("mouseMove", onMouseMove); } if (layer) { game.removeLayer("intro"); } introScreen = null; }; load(); return introScreen; }; /* Copyright (c) 2013 William Malone (www.williammalone.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*global document */ var BLOCKS; if (BLOCKS === undefined) { BLOCKS = {}; } BLOCKS.layer = function (options) { "use strict"; var layer = {}, canvasElement, parentElement, width = (options && options.width) || 300, height = (options && options.height) || 150, zIndex = (options && options.zIndex !== undefined) ? options.zIndex : 0; // Public Properties layer.name = options && options.name; layer.id = options && options.id; layer.x = options && options.x; layer.y = options && options.y; layer.scale = (options && options.scale) || 1; // Public Methods layer.clear = function () { // TODO: Implement webGL for rendering //if (layer.webGLEnabled) { // // layer.ctx.colorMask(true, true, true, true); // layer.ctx.clearColor(0, 0, 0, 0); // layer.ctx.clear(layer.ctx.COLOR_BUFFER_BIT); // //} else { // Not using clear rect due to Samsung render issues //layer.ctx.clearRect(0, 0, layer.ctx.canvas.width, layer.ctx.canvas.height); canvasElement.width = canvasElement.width; //} layer.dirty = false; }; layer.destroy = function () { if (parentElement) { parentElement.removeChild(canvasElement); } canvasElement = null; layer.ctx = null; parentElement = null; layer = null; }; Object.defineProperty(layer, "width", { get: function () { return width; }, set: function (value) { if (value !== width) { layer.dirty = true; width = value; canvasElement.width = width; } } }); Object.defineProperty(layer, "height", { get: function () { return height; }, set: function (value) { if (value !== height) { layer.dirty = true; height = value; canvasElement.height = height; } } }); if (!options) { options = {}; } (function () { var i, children, layerInserted; // If a canvas element is specified if (options.canvas) { canvasElement = options.canvas; // No canvas element specified so create one } else { canvasElement = document.createElement("canvas"); canvasElement.width = width; canvasElement.height = height; canvasElement.className = "BlocksCanvas"; canvasElement.style.zIndex = zIndex; if (layer.name) { canvasElement.id = "BlocksCanvas_" + layer.name; } // If a parent is specified then attach the canvas to it if (options.parentElement) { parentElement = options.parentElement; children = parentElement.children; for (i = 0; i < children.length; i += 1) { if (children[i].style.zIndex > zIndex) { layerInserted = true; parentElement.insertBefore(canvasElement, children[i]); break; } } if (!layerInserted) { parentElement.appendChild(canvasElement); } } // TODO: Implement webGL for rendering //if (options.enableWebGL) { // try { // layer.ctx = canvasElement.getContext("webgl") || canvasElement.getContext("experimental-webgl"); // } catch(e) {} //} // //if (layer.ctx) { // layer.webGLEnabled = true; //} else { // layer.webGLEnabled = false; // // layer.ctx = canvasElement.getContext("2d"); //} } layer.ctx = canvasElement.getContext("2d"); }()); return layer; }; /** * loadingScreen.js * _____________________________________________________________________________ * * @author William Malone (www.williammalone.com) */ /*global window, BLOCKS, Image */ BLOCKS.loadingScreen = function (spec, game) { "use strict"; var loadingScreen = BLOCKS.eventDispatcher(), clock, bg, layers, progressBar, curPercentage = 0, fontFamily = "Arial,sans", animation, fontSize = "24px", fontWeight = "bold", fontColor = "#eee", messageX = 0, messageY = 0, messageText = "loading... ", progressBarImageLoaded, destroyed, loadAnimation = function () { if (spec.animation) { spec.bg.image = game.imageLoader.loadNow(spec.animation); spec.bg.image.onload = animationLoaded; } }, animationLoaded = function () { if (!destroyed) { if (spec.bg.image.width !== 0 && spec.bg.image.height !== 0) { prepare(); if (progressBar) { loadingScreen.loaded = true; loadingScreen.dispatchEvent("loaded"); } } else { if (!destroyed) { window.setTimeout(bgLoaded, 10); } } } }, loadBg = function () { if (spec.bg) { spec.bg.image = game.imageLoader.loadNow(spec.bg); spec.bg.image.onload = bgLoaded; } }, bgLoaded = function () { if (!destroyed) { if (spec.bg.image.width !== 0 && spec.bg.image.height !== 0) { prepare(); if (progressBar) { loadingScreen.loaded = true; loadingScreen.dispatchEvent("loaded"); } } else { if (!destroyed) { window.setTimeout(bgLoaded, 10); } } } }, loadBar = function () { if (spec.progressBar) { spec.progressBar.image = game.imageLoader.loadNow(spec.progressBar); spec.progressBar.image.onload = barLoaded; } }, barLoaded = function () { if (!destroyed) { if (spec.progressBar.image.width !== 0 && spec.progressBar.image.height !== 0) { progressBarImageLoaded = true; if (layers && layers.loading) { createProgressBar(); } if (bg) { loadingScreen.loaded = true; loadingScreen.dispatchEvent("loaded"); } } else { if (!destroyed) { window.setTimeout(barLoaded, 10); } } } }, createAnimation = function () { if (!animation) { spec.animation.layer = layers.loading; animation = BLOCKS.slice(spec.animation); animation.x = spec.animation.x; animation.y = spec.animation.y; loadingScreen.dirty = true; } }, createProgressBar = function () { if (!progressBar) { spec.progressBar.layer = layers.loading; progressBar = BLOCKS.slice(spec.progressBar); progressBar.x = spec.progressBar.x; progressBar.y = spec.progressBar.y; loadingScreen.dirty = true; } }, load = function () { layers = { loadingBg: game.addLayer("loadingBg", { enableWebGL: false }), loading: game.addLayer("loading") }; loadBg(); loadBar(); loadAnimation(); }, prepare = function () { if (!destroyed) { bg = BLOCKS.slice({ layer: layers.loadingBg, image: spec.bg.image }); // If the progress bar is ready to be created and was not already created if (progressBarImageLoaded && !progressBar) { createProgressBar(); } // If the animation is ready to be created and was not already created if (spec.animation && !animation) { createAnimation(); } clock = BLOCKS.clock(); clock.addEventListener("tick", function () { update(); render(); }); clock.start(); loadingScreen.dirty = true; } }, update = function () { bg.update(); if (progressBar) { progressBar.update(); } if (animation) { animation.update(); } }, render = function () { if (loadingScreen.dirty || bg.dirty || (animation && animation.dirty) || (progressBar && progressBar.dirty)) { layers.loading.clear(); bg.dirty = true; if (progressBar) { progressBar.cropWidth = progressBar.width * curPercentage; progressBar.dirty = true; } if (animation) { animation.dirty = true; } bg.render(game); layers.loading.ctx.fillStyle = fontColor; layers.loading.ctx.font = fontWeight + " " + fontSize + " " + fontFamily; layers.loading.ctx.textAlign = "right"; layers.loading.ctx.fillText(messageText, messageX, messageY); layers.loading.ctx.textAlign = "left"; layers.loading.ctx.fillText(Math.round(curPercentage * 100, 10) + "%", messageX, messageY); if (progressBar) { progressBar.render(game); } if (animation) { animation.render(game); } } loadingScreen.dirty = false; }; loadingScreen.dirty = true; loadingScreen.destroy = function () { destroyed = true; if (clock) { clock.destroy(); if (layers) { game.removeLayer("loadingBg"); game.removeLayer("loading"); } bg.destroy(); bg = null; if (progressBar) { progressBar.destroy(); progressBar = null; } if (animation) { animation.destroy(); animation = null; } } loadingScreen = null; }; loadingScreen.setProgress = function (loaded, total) { var percentage = loaded / total; if (curPercentage !== percentage) { curPercentage = percentage; loadingScreen.dirty = true; } }; if (spec.message) { if (spec.message.fontFamily) { fontFamily = spec.message.fontFamily; } if (spec.message.fontSize) { fontSize = spec.message.fontSize.toString().replace("px", "") + "px"; } if (spec.message.fontWeight) { fontWeight = spec.message.fontWeight; } if (spec.message.fontColor) { fontColor = spec.message.fontColor; } if (spec.message.x) { messageX = spec.message.x; } if (spec.message.y) { messageY = spec.message.y; } if (spec.message.text) { messageText = spec.message.text; } } load(); return loadingScreen; }; /* Copyright (c) 2013 William Malone (www.williammalone.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*global window */ var BLOCKS; if (BLOCKS === undefined) { BLOCKS = {}; } BLOCKS.tween = function (spec) { "use strict"; // Private Properties var tween = BLOCKS.eventDispatcher(), property = spec.property, clock = spec.clock, object = spec.object, total = spec.amount, duration = spec.duration / 1000 * 60, // Convert milliseconds to number of frames callback = spec.callback, easing = spec.easing, dirtyTolerance = spec.dirtyTolerance || 0, current = 0, lastDirtyValue = current, speed, easeAmt, curTick, destroyed; // Public Methods tween.tick = function () { if (!destroyed) { curTick += 1; tween.dispatchEvent("tick"); if (easing === "easeIn") { easeAmt = Math.pow(curTick / duration, 4) * total; } else if (easing === "easeOut") { easeAmt = -(Math.pow(curTick / duration - 1, 4) - 1) * total; } else if (easing === "easeInOut") { if (curTick / (duration / 2) < 1) { easeAmt = Math.pow(curTick / (duration / 2), 4) * total / 2; } else { easeAmt = -(Math.pow(curTick / (duration / 2) - 2, 4) - 2) * total / 2; } } else if (easing === "easeOutElastic") { easeAmt = (Math.pow(2, -10 * curTick / duration) * Math.sin((curTick / duration - 0.075) * (2 * Math.PI) / 0.3) + 1) * total; } else { easeAmt = current + speed; } object[property] += easeAmt - current; if (curTick === duration) { object.dirty = true; tween.dispatchEvent("complete", tween); if (callback) { callback(); } if (tween) { tween.destroy(); } } else { current = easeAmt; if (Math.abs(lastDirtyValue - current) > dirtyTolerance) { lastDirtyValue = current; object.dirty = true; } } } }; tween.destroy = function () { if (!destroyed) { destroyed = true; if (clock) { clock.removeEventListener("tick", tween.tick); } tween.dispatchEvent("destroyed", tween); tween = null; } }; (function () { if (!property) { BLOCKS.error("Tween property parameter required"); return null; } if (!object) { BLOCKS.error("Object is required for tween property: " + property); return null; } if (!duration) { BLOCKS.error("Duration is required for tween property: " + property); return null; } if (!total) { if (total !== 0) { BLOCKS.error("Amount is required for tween property: " + property); } return null; } if (object[property] === undefined) { BLOCKS.error("Tween property does not exist on object: " + property); return null; } if (clock) { clock.addEventListener("tick", tween.tick); } speed = total / duration; curTick = 0; }()); return tween; }; BLOCKS.motor = function (spec) { "use strict"; // Private Properties var motor, moveMotor = function (spec) { // Private Properties var motor = BLOCKS.eventDispatcher(), destroyed = false, clock = spec.clock, object = spec.object, callback = spec.callback, speed = spec.speed, easing = spec.easing, offset = { x: spec.x || 0, y: spec.y || 0 }, curOffset = { x: 0, y: 0 }, totalDist = BLOCKS.toolbox.dist(curOffset, offset), angle = BLOCKS.toolbox.angle(curOffset, offset), curTick, totalTicks, duration, deltaX, deltaY; // Public Methods motor.tick = function () { var distLeft, curTime, easeAmt, moveAmt = {}; if (!destroyed) { motor.dispatchEvent("tick"); distLeft = BLOCKS.toolbox.dist(curOffset, offset); curTick += 1; object.dirty = true; if (curTick >= totalTicks) { object.x += distLeft * Math.cos(angle); object.y += distLeft * Math.sin(angle); motor.dispatchEvent("complete", motor); if (callback) { callback(); } if (motor) { motor.destroy(); } } else { if (easing === "easeIn") { easeAmt = Math.pow(curTick / totalTicks, 4) * totalDist; deltaX = easeAmt * Math.cos(angle) - curOffset.x; deltaY = easeAmt * Math.sin(angle) - curOffset.y; } else if (easing === "easeOut") { easeAmt = -(Math.pow(curTick / totalTicks - 1, 4) - 1) * totalDist; deltaX = easeAmt * Math.cos(angle) - curOffset.x; deltaY = easeAmt * Math.sin(angle) - curOffset.y; } else if (easing === "easeInOut") { if (curTick / (totalTicks / 2) < 1) { easeAmt = Math.pow(curTick / (totalTicks / 2), 4) * totalDist / 2; } else { easeAmt = -(Math.pow(curTick / (totalTicks / 2) - 2, 4) - 2) * totalDist / 2; } deltaX = easeAmt * Math.cos(angle) - curOffset.x; deltaY = easeAmt * Math.sin(angle) - curOffset.y; } curOffset.x += deltaX; curOffset.y += deltaY; object.x += deltaX; object.y += deltaY; } } }; motor.destroy = function () { if (!destroyed) { destroyed = true; if (clock) { clock.removeEventListener("tick", motor.tick); } motor.dispatchEvent("destroyed", motor); motor = null; } }; (function () { if (!totalDist) { motor.destroy(); motor = null; return null; } if (clock) { clock.addEventListener("tick", motor.tick); } if (spec.duration) { duration = spec.duration; speed = totalDist / (spec.duration / 1000 * 60); } else { duration = (totalDist / speed) * (1000 / 60); } deltaX = speed * Math.cos(angle); deltaY = speed * Math.sin(angle); curTick = 0; totalTicks = totalDist / speed; Object.defineProperty(motor, "curOffset", { get: function () { return curOffset; } }); }()); return motor; }, vibrateMotor = function (spec) { // Private Properties var motor = BLOCKS.eventDispatcher(), destroyed = false, clock = spec.clock, object = spec.object, callback = spec.callback, amplitude = spec.amplitude || 10, angle = spec.angle * Math.PI / 180 || 0, duration = spec.duration, timesToVibrate = spec.amount, timesVibrated = 0, direction = 1, timesTillReverseDirection, curMoveMotor, curOffset = { x: 0, y: 0 }, vibrationComplete, createMoveMotor = function () { var dx, dy; dx = amplitude * direction * Math.cos(angle); dy = amplitude * direction * Math.sin(angle); curMoveMotor = moveMotor({ object: object, x: dx, y: dy, duration: duration / (timesToVibrate * 2), clock: clock, callback: function () { curOffset.x += dx; curOffset.y += dy; moveMotorComplete(); } }); curMoveMotor.addEventListener("tick", motor.tick); }, moveMotorComplete = function () { timesVibrated += 1; timesTillReverseDirection += 1; if (timesTillReverseDirection >= 2) { timesTillReverseDirection = 0; direction *= -1; } if (curMoveMotor) { curMoveMotor.removeEventListener("tick", motor.tick); } if (timesVibrated >= timesToVibrate) { vibrationComplete = true; motor.dispatchEvent("complete", motor); if (callback) { callback(); } if (motor) { motor.destroy(); } } else { createMoveMotor(); } }; // Public Methods motor.tick = function () { if (!destroyed) { motor.dispatchEvent("tick"); } }; motor.reset = function () { if (!destroyed) { if (timesTillReverseDirection === 1) { timesVibrated = -2; } else if (timesTillReverseDirection === 0) { timesVibrated = -1; } } }; motor.destroy = function () { if (!destroyed) { destroyed = true; if (curMoveMotor) { curOffset.x += curMoveMotor.curOffset.x; curOffset.y += curMoveMotor.curOffset.y; curMoveMotor.destroy(); } if (!vibrationComplete) { object.x -= curOffset.x; object.y -= curOffset.y; } motor.dispatchEvent("destroyed", motor); motor = null; } }; (function () { if (!object) { BLOCKS.error("A vibrate motor will not work without an object"); return null; } if (!duration) { BLOCKS.error("A vibrate motor will not work without a duration"); return null; } if (!spec.amount) { BLOCKS.error("A vibrate motor will not work without an amount"); return null; } timesTillReverseDirection = 1; createMoveMotor(); }()); return motor; }; if (spec.type === "move") { motor = moveMotor(spec); } else if (spec.type === "vibrate") { motor = vibrateMotor(spec); } else if (spec.type === "drag") { motor = (function (spec) { // Private Properties var motor = BLOCKS.eventDispatcher(), object = spec.object, controller = spec.controller, bounds = spec.bounds, horizontalOnly = spec.horizontalOnly, verticalOnly = spec.verticalOnly, draggingObject, destroyed = false, snapToRegistrationPoint = spec.snapToRegistrationPoint, offsetX, offsetY, convertToBoundedPos = function (point) { if (spec.bounds) { if (point.x < bounds.x) { point.x = bounds.x; } if (point.x > bounds.x + bounds.width) { point.x = bounds.x + bounds.width; } if (point.y < bounds.y) { point.y = bounds.y; } if (point.y > bounds.y + bounds.height) { point.y = bounds.y + bounds.height; } } return point; }, updatePos = function (point) { point = convertToBoundedPos(point); if (!verticalOnly) { object.x = Math.round(point.x - offsetX); } if (!horizontalOnly) { object.y = Math.round(point.y - offsetY); } object.dirty = true; }, onTap = function (point) { if (object.isPointInside(point)) { object.justTapped = true; object.dirty = true; if (snapToRegistrationPoint === false) { offsetX = point.x - object.x; offsetY = point.y - object.y; } else { offsetX = 0; offsetY = 0; } draggingObject = true; updatePos(point); } else { object.justNotTapped = true; object.dirty = true; } }, onDrag = function (point) { object.tapPos = point; if (controller.drag && draggingObject) { updatePos(point); if (!object.dragging) { object.dispatchEvent("onDragStart", object); } object.dragging = true; } }, onRelease = function (point) { if (object.justTapped) { object.justTapped = false; object.dirty = true; } if (object.justNotTapped) { object.justNotTapped = false; object.dirty = true; } if (draggingObject) { object.justReleased = true; object.dispatchEvent("onDragEnd", object); } object.dragging = false; draggingObject = false; }; // Public Properties motor.destroy = function () { if (!destroyed) { destroyed = true; controller.removeEventListener("tap", onTap); controller.removeEventListener("drag", onDrag); controller.removeEventListener("release", onRelease); controller.removeEventListener("cancel", onRelease); motor.dispatchEvent("destroyed", motor); motor = null; } }; (function () { if (controller) { controller.addEventListener("tap", onTap); controller.addEventListener("drag", onDrag); controller.addEventListener("release", onRelease); controller.addEventListener("cancel", onRelease); } else { BLOCKS.error("A drag motor will not work without a controller"); motor.destroy(); return false; } }()); return motor; }(spec)); } else { if (spec.type === "rotate") { if (spec.angle) { spec.amount = spec.angle; } spec.property = "angle"; } else { spec.property = spec.type; } motor = BLOCKS.tween(spec); } return motor; }; /* Copyright (c) 2013 William Malone (www.williammalone.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*global window, document, Image, HTMLElement */ var BLOCKS; if (BLOCKS === undefined) { BLOCKS = {}; } BLOCKS.preloader = function (path) { "use strict"; var preloader = BLOCKS.eventDispatcher(), imageList = [], imagesLoaded, // Private Methods imageLoaded = function () { imagesLoaded += 1; preloader.dispatchEvent("update", { loaded: imagesLoaded, total: imageList.length }); if (imagesLoaded === imageList.length) { preloader.dispatchEvent("complete"); } }, traverse = function (obj, callback) { var key, i; for (key in obj) { if (obj.hasOwnProperty(key) && !(obj[key] instanceof HTMLElement)) { callback.apply(this, [key, obj]); if (obj[key] instanceof Object && !(obj[key] instanceof Array)) { traverse(obj[key], callback); } else if (obj[key] instanceof Array) { for (i = 0; i < obj[key].length; i += 1) { traverse(obj[key][i], callback); } } } } }; // Public Properties preloader.path = path || ""; // Public Methods preloader.load = function () { var i; imagesLoaded = 0; for (i = 0; i < imageList.length; i += 1) { // If image not already loaded if (!imageList[i].loadStarted) { imageList[i].loadStarted = true; imageList[i].image.addEventListener("load", imageLoaded); imageList[i].image.src = preloader.path + imageList[i].src; } } }; preloader.loadFromTree = function (spec) { traverse(spec, function (key, obj) { if (key === "src") { preloader.add(obj); } }); }; preloader.add = function (spec) { var i, obj; if (spec && spec.src && (spec.src.toLowerCase().indexOf("jpg") !== -1 || spec.src.toLowerCase().indexOf("png") !== -1)) { // Check if the image is already in the list for (i = 0; i < imageList.length; i += 1) { if (imageList[i].src === spec.src) { spec.image = imageList[i].image; // Image already in list, so no need to add it again return imageList[i]; } } obj = { image: new Image(), src: spec.src, loadStarted: false }; spec.image = obj.image; if (spec.crossOrigin !== undefined) { spec.image.crossOrigin = spec.crossOrigin; } imageList.push(obj); return obj; } }; preloader.loadNow = function (spec) { var image; image = new Image(); if (spec.crossOrigin !== undefined) { image.crossOrigin = spec.crossOrigin; } image.src = preloader.path + spec.src; return image; }; preloader.getNumFiles = function () { return imageList.length; }; preloader.getNumFilesLoaded = function () { return imagesLoaded; }; preloader.isLoaded = function () { return (imagesLoaded >= imageList.length); }; return preloader; }; /* Copyright (c) 2013 William Malone (www.williammalone.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*global window, document, Image, Float32Array */ var BLOCKS; if (BLOCKS === undefined) { BLOCKS = {}; } BLOCKS.slice = function (options) { "use strict"; var slice = BLOCKS.view(options), // Properties imageResource, frameWidth, frameHeight, paused, texture, tmpCtx, cropWidth, cropHeight, frameOffsetX, frameOffsetY, mirrorX, mirrorY, drawBounds = false, frameCnt = 0, loopIndex = 0, rowIndex = 0, colIndex = 0, curFrameIndex = 0, // Private Methods onResourceLoaded = function () { // Will be used for webGL enabled contexts //if (slice.layer && slice.layer.webGLEnabled) { // prepareWebGLContext(slice.layer.ctx); //} // Set the sprite dimensions to the image dimensions // Note: Divide the width by the number of frames in the sprite sheet if an animation. If the sprite is only an image then the number of frames will be 1. if (imageResource) { frameWidth = imageResource.image.width / slice.numberOfColumns; frameHeight = imageResource.image.height / slice.numberOfRows; slice.width = imageResource.image.width / slice.numberOfColumns; slice.height = imageResource.image.height / slice.numberOfRows; } }, drawImage = function (spec) { if (spec.sourceWidth > frameWidth) { spec.sourceWidth = frameWidth; } if (spec.sourceHeight > frameHeight) { spec.sourceHeight = frameHeight; } if (spec.destWidth > slice.width / slice.layer.scale) { spec.destWidth = slice.width / slice.layer.scale; } if (spec.destHeight > slice.height / slice.layer.scale) { spec.destHeight = slice.height / slice.layer.scale; } //BLOCKS.debug("render: " + spec.image + ", " + spec.sourceX + ", " + spec.sourceY + ", " + spec.sourceWidth + ", " + spec.sourceHeight + ", " + spec.destX + ", " + spec.destY + ", " + spec.destWidth + ", " + spec.destHeight); spec.ctx.drawImage( spec.image, spec.sourceX, spec.sourceY, spec.sourceWidth, spec.sourceHeight, spec.destX, spec.destY, spec.destWidth, spec.destHeight ); }; slice.loop = options && options.loop; slice.frameDelay = (options && options.frameDelay !== undefined) ? options.frameDelay : 4; slice.numberOfFrames = (options && options.numberOfFrames) || 1; slice.numberOfRows = (options && options.numberOfRows) || 1; slice.numberOfColumns = (options && options.numberOfColumns) ? options.numberOfColumns : slice.numberOfFrames; slice.autoPlay = (options && options.autoPlay !== undefined) ? options.autoPlay : true; slice.resetOnComplete = (options && options.resetOnComplete !== undefined) ? options.resetOnComplete : true; // Public Methods slice.update = function () { if (!paused) { // If the slice has an image associated with it if (imageResource) { // If the sprite is an animation if (slice.numberOfFrames > 1) { frameCnt += 1; // If the current frame is the last frame if (curFrameIndex >= slice.numberOfFrames - 1) { if (frameCnt >= slice.frameDelay) { frameCnt = 0; loopIndex += 1; if (slice.loop === true || (typeof slice.loop === "number" && loopIndex < slice.loop)) { // Reset the frame back to the first frame curFrameIndex = 0; rowIndex = 0; colIndex = 0; slice.dirty = true; } else { if (slice.resetOnComplete) { // Reset the frame back to the first frame curFrameIndex = 0; rowIndex = 0; colIndex = 0; slice.dirty = true; } paused = true; (function () { var callback; if (slice.callback) { // Save the callback in case the slice is destroyed after the complete event callback = slice.callback; slice.callback = null; } // Dispatch the complete event before any callback slice.dispatchEvent("complete"); // If there is a callback then invoke it now if (callback) { callback(); } }()); } } // If the current frame is not the last frame } else { if (frameCnt >= slice.frameDelay) { // Go to the next frame curFrameIndex += 1; if (slice.numberOfColumns > 1) { if (curFrameIndex - rowIndex * slice.numberOfColumns === slice.numberOfColumns) { colIndex = 0; rowIndex += 1; } else { colIndex += 1; } } frameCnt = 0; slice.dirty = true; } } } } } // Go to the next frame in the animation }; slice.pause = function () { paused = true; }; slice.unpause = function () { paused = false; }; slice.reset = function () { slice.callback = null; if (frameCnt !== 0 || curFrameIndex !== 0 || loopIndex !== 0) { slice.dirty = true; } frameCnt = 0; curFrameIndex = 0; loopIndex = 0; rowIndex = 0; colIndex = 0; }; slice.stop = function () { paused = true; slice.reset(); }; slice.play = function (callback) { // If on the last frame then start over if (curFrameIndex >= slice.numberOfFrames - 1) { slice.stop(); } paused = false; // Assign an optional callback to be played once the animation is complete slice.callback = callback; }; slice.render = function (e) { var i, bounds, boundingBox, restoreNeeded, context, cameraOffset, x, y, destCropWidth, destCropHeight; // Prevent alpha from being negative if (slice.alpha < 0) { slice.alpha = 0; } else if (slice.alpha > 1) { slice.alpha = 1; } if (slice.dirty && slice.visible && slice.alpha !== 0 && slice.cropWidth !== 0 && slice.cropHeight !== 0) { cameraOffset = { x: (e && e.camera && e.camera.offsetX) || 0, y: (e && e.camera && e.camera.offsetY) || 0 }; // Set local x and y to increases performance when slice is associated to a stack x = slice.worldX; y = slice.worldY; // If the slice has an image associated with it if (imageResource) { if (slice.layer) { context = slice.layer.ctx; // Using webGL //if (slice.layer.webGLEnabled) { //context.bindTexture(context.TEXTURE_2D, texture); //setBufferData( // x, // y, // slice.cropWidth || slice.width, // slice.cropHeight || slice.height); //context.drawArrays(context.TRIANGLES, 0, 6); //context.bindTexture(context.TEXTURE_2D, null); // Using 2d Canvas //} else { if (slice.angle || slice.alpha !== 1 || slice.colorize || slice.mirrorX || slice.mirrorY) { context.save(); restoreNeeded = true; } context.globalAlpha = slice.alpha; if (slice.angle) { context.translate((x - cameraOffset.x) / slice.layer.scale, (y - cameraOffset.y) / slice.layer.scale); context.rotate(slice.angle * Math.PI / 180); context.translate((-x + cameraOffset.x) / slice.layer.scale, (-y + cameraOffset.y) / slice.layer.scale); } // Careful about performance when using mirroring if (slice.mirrorX || slice.mirrorY) { context.translate(x, y); if (slice.mirrorX && slice.mirrorY) { context.scale(-1, -1); } else if (slice.mirrorX) { context.scale(-1, 1); } else { context.scale(1, -1); } context.translate(-x, -y); } if (slice.colorize) { if (!tmpCtx) { tmpCtx = document.createElement("canvas").getContext("2d"); tmpCtx.canvas.width = context.canvas.width; tmpCtx.canvas.height = context.canvas.height; } context = tmpCtx; context.globalCompositeOperation = "copy"; } // If the sprite is an animation if (slice.numberOfFrames > 1) { drawImage({ ctx: context, image: imageResource.image, sourceX: colIndex * slice.width / slice.scale + slice.frameOffsetX, sourceY: rowIndex * slice.height / slice.scale + slice.frameOffsetY, sourceWidth: slice.cropWidth || frameWidth, sourceHeight: slice.cropHeight || frameHeight, destX: (x + slice.offsetX - cameraOffset.x) / slice.layer.scale, destY: (y + slice.offsetY - cameraOffset.y) / slice.layer.scale, destWidth: (slice.cropWidth * slice.scale || slice.width) / slice.layer.scale, destHeight: (slice.cropHeight * slice.scale || slice.height) / slice.layer.scale }); // If the sprite is not an animation } else { drawImage({ ctx: context, image: imageResource.image, sourceX: slice.frameOffsetX, sourceY: slice.frameOffsetY, sourceWidth: slice.cropWidth || frameWidth, sourceHeight: slice.cropHeight || frameHeight, destX: (x + slice.offsetX - cameraOffset.x) / slice.layer.scale, destY: (y + slice.offsetY - cameraOffset.y) / slice.layer.scale, destWidth: (slice.cropWidth * slice.scale || slice.width) / slice.layer.scale, destHeight: (slice.cropHeight * slice.scale || slice.height) / slice.layer.scale }); } if (slice.colorize) { // Draw the color that should be overlayed over the image context.fillStyle = slice.colorize; context.globalCompositeOperation = "source-in"; context.fillRect(x, y, slice.width, slice.height); context = slice.layer.ctx; // Change back from the temp context context.drawImage(tmpCtx.canvas, 0, 0); } if (restoreNeeded) { context.restore(); } } if (drawBounds && context) { bounds = slice.getBounds(); if (!bounds.length) { bounds = [bounds]; } context.lineWidth = 4; for (i = 0; i < bounds.length; i += 1) { if (slice.dragging) { context.beginPath(); context.fillStyle = "rgba(10, 255, 50, 0.4)"; context.fillRect((bounds[i].x - cameraOffset.x) / slice.layer.scale, (bounds[i].y - cameraOffset.y) / slice.layer.scale, bounds[i].width / slice.layer.scale, bounds[i].height / slice.layer.scale); context.closePath(); } else if (slice.justTapped) { context.beginPath(); context.fillStyle = "rgba(255, 10, 50, 0.4)"; context.fillRect((bounds[i].x - cameraOffset.x) / slice.layer.scale, (bounds[i].y - cameraOffset.y) / slice.layer.scale, bounds[i].width / slice.layer.scale, bounds[i].height / slice.layer.scale); context.closePath(); } else if (slice.justNotTapped) { context.beginPath(); context.fillStyle = "rgba(255, 10, 255, 0.4)"; context.fillRect((bounds[i].x - cameraOffset.x) / slice.layer.scale, (bounds[i].y - cameraOffset.y) / slice.layer.scale, bounds[i].width / slice.layer.scale, bounds[i].height / slice.layer.scale); context.closePath(); } else if (slice.justReleased) { context.beginPath(); context.fillStyle = "rgba(125, 10, 255, 0.4)"; context.fillRect((bounds[i].x - cameraOffset.x) / slice.layer.scale, (bounds[i].y - cameraOffset.y) / slice.layer.scale, bounds[i].width / slice.layer.scale, bounds[i].height / slice.layer.scale); context.closePath(); slice.justReleased = false; } context.beginPath(); context.strokeStyle = "rgba(96, 255, 0, 0.5)"; context.strokeRect((bounds[i].x - cameraOffset.x) / slice.layer.scale, (bounds[i].y - cameraOffset.y) / slice.layer.scale, bounds[i].width / slice.layer.scale, bounds[i].height / slice.layer.scale); context.closePath(); } context.beginPath(); context.arc((x - cameraOffset.x) / slice.layer.scale, (y - cameraOffset.y) / slice.layer.scale, 7, 0, 2 * Math.PI, false); context.fillStyle = "rgba(96, 255, 0, 0.5)"; context.fill(); boundingBox = slice.getBoundingBox(); if (boundingBox.x !== bounds[0].x || boundingBox.y !== bounds[0].y || boundingBox.width !== bounds[0].width || boundingBox.height !== bounds[0].height) { context.beginPath(); context.strokeStyle = "rgba(244, 246, 0, 0.5)"; context.strokeRect((boundingBox.x - cameraOffset.x) / slice.layer.scale, (boundingBox.y - cameraOffset.y) / slice.layer.scale, boundingBox.width / slice.layer.scale, boundingBox.height / slice.layer.scale); context.closePath(); } } //} } } slice.dirty = false; }; slice.gotoLastFrame = function () { if (curFrameIndex !== slice.numberOfFrames - 1) { curFrameIndex = slice.numberOfFrames - 1; rowIndex = slice.numberOfRows; colIndex = slice.numberOfColumns; slice.dirty = true; } }; slice.gotoFrame = function (frameIndex) { var newFrameCnt = Math.floor(slice.frameDelay * (frameIndex - Math.floor(frameIndex)) / 100); frameIndex = Math.floor(frameIndex); if (curFrameIndex !== frameIndex || frameCnt !== newFrameCnt) { curFrameIndex = frameIndex; rowIndex = Math.floor(curFrameIndex / slice.numberOfColumns); colIndex = curFrameIndex - rowIndex * slice.numberOfColumns; frameCnt = newFrameCnt; slice.dirty = true; } }; slice.destroy = function () { if (slice) { slice.removeMotors(); slice.dispatchEvent("destroyed", slice); } imageResource = null; options = null; slice = null; }; options = options || {}; Object.defineProperty(slice, "currentFrameIndex", { get: function () { return curFrameIndex; }, set: function (value) { slice.gotoFrame(value); } }); cropWidth = options.cropWidth; Object.defineProperty(slice, "cropWidth", { get: function () { return cropWidth; }, set: function (value) { if (cropWidth !== value) { slice.dirty = true; cropWidth = value; } } }); cropHeight = options.cropHeight; Object.defineProperty(slice, "cropHeight", { get: function () { return cropHeight; }, set: function (value) { if (cropHeight !== value) { slice.dirty = true; cropHeight = value; } } }); frameOffsetX = options.frameOffsetX || 0; Object.defineProperty(slice, "frameOffsetX", { get: function () { return frameOffsetX; }, set: function (value) { if (frameOffsetX !== value) { slice.dirty = true; frameOffsetX = value; } } }); frameOffsetY = options.frameOffsetY || 0; Object.defineProperty(slice, "frameOffsetY", { get: function () { return frameOffsetY; }, set: function (value) { if (frameOffsetY !== value) { slice.dirty = true; frameOffsetY = value; } } }); mirrorX = options.mirrorX; Object.defineProperty(slice, "mirrorX", { get: function () { return mirrorX; }, set: function (value) { if (mirrorX !== value) { slice.dirty = true; mirrorX = value; } } }); mirrorY = options.mirrorY; Object.defineProperty(slice, "mirrorY", { get: function () { return mirrorY; }, set: function (value) { if (mirrorY !== value) { slice.dirty = true; mirrorY = value; } } }); (function () { var image = options.image, imageSrc = options.imageSrc || (options.image && options.src), imagePreloaded = image ? true : false; options = options || {}; // Pause the slice if autoPlay property is set to false if (!slice.autoPlay) { paused = true; } if (image || imageSrc) { imageResource = { image: image, imageSrc: imageSrc, loaded: imagePreloaded }; // If the image is already loaded if (imageResource.loaded) { onResourceLoaded(); } else { // If there is no image object if (!imageResource.image) { // Instantiate a new image imageResource.image = new Image(); } imageResource.image.addEventListener("load", onResourceLoaded); imageResource.image.src = imageResource.imageSrc; } } else { onResourceLoaded(); } }()); return slice; }; /* Copyright (c) 2013 William Malone (www.williammalone.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*global window, document, navigator */ var BLOCKS; if (BLOCKS === undefined) { BLOCKS = {}; } BLOCKS.audio = {}; BLOCKS.audio.soundInstance = function (player) { "use strict"; var inst = {}; inst.stop = player.stopSoundInstance(inst); inst.play = player.playSoundInstance(inst); inst.getSoundGain = player.getSoundInstanceGain(); return inst; }; BLOCKS.audio.audioElementPlayer = function (spec) { "use strict"; var speaker = BLOCKS.eventDispatcher(), spriteSrc, curSoundInst, initialized = false, loadStarted = false, loadComplete = false, ready = false, loadPercentage = 0, prevLoadPercentage, audioElement, loadInterval, soundCompleteTimer, sounds = {}, muted = false, maybeReady = false, resetGainValue, pausedFirstTime, testSoundComplete = function () { if (!ready) { ready = true; if (speaker.debug) { BLOCKS.debug("audio ready"); } speaker.dispatchEvent("ready"); } }, setReady = function () { if (!maybeReady) { maybeReady = true; speaker.createSound({ name: "BlocksTestSound", start: 0, end: 0.5 }); playSound("BlocksTestSound", testSoundComplete); window.setTimeout(function () { if (!ready) { playSound("BlocksTestSound", testSoundComplete); window.setTimeout(function () { if (!ready) { testSoundComplete(); } }, 10000); } }, 10000); } }, onCanPlayThrough = function () { if (speaker.debug) { BLOCKS.debug("onCanPlayThrough"); } setReady(); }, load = function () { if (!audioElement) { return; } if (speaker.debug) { BLOCKS.debug("load audio sprite: " + spriteSrc); } if (loadInterval) { window.clearInterval(loadInterval); } loadInterval = window.setInterval(function () { var loadTime, loadPercentage; //if (speaker.debug) { // BLOCKS.debug("audioElement.buffered.length: " + audioElement.buffered.length); //} if (!audioElement.buffered.length) { return; } loadTime = audioElement.buffered.end(audioElement.buffered.length - 1); loadPercentage = loadTime / audioElement.duration * 100; if (!isNaN(loadPercentage) && prevLoadPercentage !== loadPercentage) { prevLoadPercentage = loadPercentage; speaker.dispatchEvent("loadUpdate"); if (speaker.debug) { BLOCKS.debug("loadUpdate: " + Math.round(loadPercentage) + "%"); } if (!pausedFirstTime) { pausedFirstTime = true; audioElement.pause(); } } if (window.Math.abs(loadTime - audioElement.duration) < 0.1) { window.clearInterval(loadInterval); setReady(); speaker.dispatchEvent("loadComplete"); if (speaker.debug) { BLOCKS.debug("loadComplete"); } } }, 100); audioElement.src = spriteSrc; audioElement.play(); }, endSound = function () { // Clear the sound complete timer window.clearInterval(soundCompleteTimer); soundCompleteTimer = null; //if (audioElement) { audioElement.pause(); //} }, stop = function () { endSound(); curSoundInst = null; }, soundCompleteChecker = function () { var inst, atEnd; // If a sound is playing if (curSoundInst) { // If the scrubber is past the sound end time then the sound is complete if (audioElement.currentTime >= curSoundInst.end || audioElement.currentTime >= audioElement.duration) { // If the sound is set to loop then move the scrubber to the beginning of the sound if (curSoundInst.loop === true) { if (audioElement.currentTime >= audioElement.duration) { atEnd = true; } audioElement.currentTime = curSoundInst.start; // If the current time is at the end then play after moving scrubber if (atEnd) { audioElement.play(); } } else { endSound(); speaker.dispatchEvent("played"); inst = curSoundInst; curSoundInst = null; if (inst.callback) { inst.callback(inst.name); } } } } else { window.clearInterval(soundCompleteTimer); } }, playSound = function (name, callback) { if (speaker.debug) { BLOCKS.debug("Play sound: " + name + " (" + sounds[name].start + " - " + sounds[name].end + ")"); } if (sounds[name].end >= audioElement.duration) { BLOCKS.warn("Sound ('" + sounds[name].name + "') end time is larger than sprite duration. Setting end time to the sprite duration."); sounds[name].end = audioElement.duration - 0.0001; } if (sounds[name].start >= 0 && sounds[name].end > 0) { // If the previous sound had a different volume set temporarily if (resetGainValue >= 0) { audioElement.volume = resetGainValue; resetGainValue = null; } // Save the sound about to play curSoundInst = { name: sounds[name].name, start: sounds[name].start, end: sounds[name].end, loop: sounds[name].loop, sound: sounds[name].sound, callback: callback }; // Move the scrubber to the start of the sound audioElement.currentTime = sounds[name].start; // Play the sound audioElement.play(); // Start a listener to check if the sound is complete if (soundCompleteTimer) { window.clearInterval(soundCompleteTimer); } soundCompleteTimer = window.setInterval(soundCompleteChecker, 100); return true; } else { BLOCKS.warn("Sound parameters not specified."); return false; } }, // Pause the audio element pause = function () { audioElement.pause(); }, // Play the audio element if a sound is currently playing unpause = function () { if (curSoundInst) { audioElement.play(); } }, // Mute all sound mute = function () { audioElement.volume = 0; }, // Unmute all sound unmute = function () { audioElement.volume = 1; }; speaker.setSoundGain = function (name, gain) { if (curSoundInst && curSoundInst.name === name) { // Save the current volume to be reset for next sound resetGainValue = audioElement.volume; audioElement.volume = gain; } }; speaker.play = function (name, callback) { if (sounds[name]) { return playSound(name, callback); } else { BLOCKS.warn("Cannot play sound '" + name + "' because it was not defined"); } }; // Pause the audio element speaker.pause = function () { pause(); }; // Unpause the audio element speaker.unpause = function () { unpause(); }; // Pause the audio element and clear the current sound speaker.stop = function () { stop(); }; // Mute all sound speaker.mute = function () { if (!muted) { mute(); } muted = true; }; // Unmute all sound speaker.unmute = function () { if (muted) { unmute(); } muted = false; }; speaker.isMuted = function () { return muted; }; // Return if audio is ready to be played speaker.isReady = function () { return ready; }; speaker.load = function () { if (!loadStarted) { loadStarted = true; load(); } }; speaker.createSound = function (spec) { // Support legacy startTime, endTime and duration properties if (spec.startTime !== undefined && spec.start === undefined) { spec.start = spec.startTime; } if (spec.endTime !== undefined && spec.end === undefined) { spec.end = spec.endTime; } if (spec.duration !== undefined && spec.end === undefined) { spec.end = spec.start + spec.duration; } if (spec.end > audioElement.duration) { BLOCKS.warn("Sound ('" + spec.name + "') end time is larger than sprite duration. Setting end time to the sprite duration."); spec.end = audioElement.duration - 0.0001; } sounds[spec.name] = { name: spec.name, start: spec.start, end: spec.end, loop: spec.loop }; }; speaker.getActiveSounds = function () { return [curSoundInst]; }; speaker.getNumFiles = function () { return 1; }; speaker.getNumFilesLoaded = function () { return ready ? 1 : 0; }; // Create audio element (function () { if (spec && spec.src) { // Add audio path if (spec.path) { spriteSrc = spec.path; } else { spriteSrc = ""; } // Add the sprite filename without extension spriteSrc += spec.src; audioElement = document.createElement("audio"); audioElement.addEventListener("canplaythrough", onCanPlayThrough); // Add the extension if (audioElement.canPlayType("audio/mpeg")) { spriteSrc += ".mp3"; } else if (audioElement.canPlayType("audio/ogg")) { spriteSrc += ".ogg"; } } else { BLOCKS.error("sprite filename not specified"); } }()); return speaker; }; BLOCKS.audio.webAudioPlayer = function (spec) { "use strict"; var speaker = BLOCKS.eventDispatcher(), initialized = false, loadStarted = false, loadComplete = false, ready = false, muted = false, extension, path = (spec && spec.path) || "", masterGain, ctx, sounds = {}, files = {}, instances = [], tracks = {}, loadTimeoutId, maxLoadTime = spec.maxLoadTime || 60000, // The maximum amount of time for all sounds to load loadTries = 0, maxLoadTries = 5, createTrack = function (name) { if (!tracks[name]) { tracks[name] = { name: name, gain: (ctx.createGain) ? ctx.createGain() : ctx.createGainNode() }; // Connect the track's gain node to the master node tracks[name].gain.connect(masterGain); } return tracks[name]; }, onFileLoaded = function (file) { var key, numFilesLoaded, totalNumFiles; numFilesLoaded = speaker.getNumFilesLoaded(); totalNumFiles = speaker.getNumFiles(); if (speaker.debug) { BLOCKS.debug("load: " + numFilesLoaded + " of " + totalNumFiles); } //BLOCKS.debug("load: " + numFilesLoaded + " of " + totalNumFiles + " (" + file.src + ")"); speaker.dispatchEvent("update", numFilesLoaded, totalNumFiles); if (numFilesLoaded === totalNumFiles) { if (!ready) { ready = true; // Clear the load timeout window.clearTimeout(loadTimeoutId); if (speaker.debug) { BLOCKS.debug("audio ready"); } //BLOCKS.debug("speaker is ready"); speaker.dispatchEvent("ready"); } } }, loadFile = function (file) { file.request = new window.XMLHttpRequest(); // For Internet Explorer if (!("withCredentials" in file.request)) { file.request = new window.XDomainRequest(); } file.request.open("get", path + file.src + extension, true); file.request.responseType = "arraybuffer"; file.request.onload = function() { //BLOCKS.debug("Sound Loaded: " + (path + file.src + extension) + " -> " + file.request); ctx.decodeAudioData(file.request.response, function(buffer) { //BLOCKS.debug("Sound Decoded: " + (path + file.src + extension) + " -> " + file.request); file.buffer = buffer; file.loaded = true; // TODO: Dispatch an notification that the file has been loaded for the first time, in case we want to play it after its loaded // TODO: Update the progress if we are waiting for pre-load onFileLoaded(file); file.request = null; }, function (error) { if (BLOCKS.debug) { BLOCKS.debug("Error decoding buffer: " + path + file.src + extension); } file.request = null; }); }; file.request.send(); }, load = function () { var source; loadStarted = true; source = ctx.createOscillator(); if (source.start) { source.start(0, 0, 1); } else if (source.noteGrainOn) { source.noteGrainOn(0, 0, 1); } }, destroyInstance = function (inst) { var i, index; for (i = 0; i < instances.length; i += 1) { if (instances[i] === inst) { instances[i] = null; index = i; break; } } instances.splice(index, 1); }, soundCompleteChecker = function (inst) { var callback, soundName; if (speaker.debug) { BLOCKS.debug("Sound '" + inst.sound.name + "' Complete"); } if (inst.callback) { callback = inst.callback; soundName = inst.name; } // Destroy the instance before calling a possible callback destroyInstance(inst); if (callback) { callback(soundName); } }, stopSound = function (inst) { window.clearTimeout(inst.timeout); if (inst.source.stop) { inst.source.stop(0); } else if (inst.source.noteGrainOff) { inst.source.noteGrainOff(0); } else { inst.source.noteOff(0); } destroyInstance(inst); }, getSoundGain = function (inst) { return inst.gain.gain.value; }, setSoundGain = function (inst, gainValue, delay) { // If the sound doesn't have its own gain then create its own gain we can change if (inst.gain === inst.track.gain) { // Disconnect the source from its track gain node inst.source.disconnect(0); // Create a new gain inst.gain = (ctx.createGain) ? ctx.createGain() : ctx.createGainNode(); inst.gain.connect(masterGain); // Connect the source to the new gain inst.source.connect(inst.gain); } if (speaker.debug) { BLOCKS.debug("speaker.setSoundGain of sound '" + inst.name + "' to '" + gainValue + "'"); } // If the gain should be faded out if (delay) { inst.gain.gain.linearRampToValueAtTime(inst.gain.gain.value, ctx.currentTime); inst.gain.gain.linearRampToValueAtTime(gainValue, ctx.currentTime + delay); } else { inst.gain.gain.value = gainValue; } }, pauseSound = function (inst) { window.clearTimeout(inst.timeout); inst.currentTime = ((+ new Date()) - inst.startTime) / 1000 % inst.source.buffer.duration; if (inst.source.stop) { inst.source.stop(0); } else if (inst.source.noteGrainOff) { inst.source.noteGrainOff(0); } else { inst.source.noteOff(0); } //if (speaker.debug) { // BLOCKS.debug("Pause sound: '" + inst.name + "' at scrubber position of " + inst.currentTime.toFixed(2)); //} }, unpauseSound = function (inst) { var newInst; //if (speaker.debug) { // BLOCKS.debug("Unpause sound: '" + inst.name + "'"); //} // Play a new instance of the sound newInst = playSound(inst.name, inst.callback, inst.track.name, inst.currentTime); if (inst.gain.gain.value !== 1) { setSoundGain(newInst, inst.gain.gain.value); } // Delete the old instance destroyInstance(inst); }, playSound = function (name, callback, trackName, currentTime, delay) { var inst = {}; if (sounds[name].file.loaded) { instances.push(inst); inst.sound = sounds[name]; inst.name = name; // If an offset is set (set when unpausing a sound) if (currentTime) { inst.currentTime = currentTime; } else { // Start from the beginning of the sound inst.currentTime = 0; } // Save when the sound starts, or would have started if started from the beginning inst.startTime = (+ new Date()) - inst.currentTime * 1000; if (delay) { // Play the sound after a delay inst.delay = ctx.currentTime + delay; } else { // Play the sound immediately delay = 0; inst.delay = 0; } if (trackName) { if (!tracks[trackName]) { createTrack(trackName); } inst.track = tracks[trackName]; } else { inst.track = tracks["default"]; } // Create a new source for this sound instance inst.source = ctx.createBufferSource(); inst.source.buffer = sounds[name].file.buffer; inst.source.loop = sounds[name].loop; inst.gain = inst.track.gain; // Connect the source to the gains inst.source.connect(inst.gain); if (!sounds[name].loop) { // Timeout at the end of the sound inst.timeout = window.setTimeout(soundCompleteChecker, (delay + inst.source.buffer.duration - inst.currentTime) * 1000, inst); // Assign a callback to be called once the sound is complete inst.callback = callback; } if (speaker.debug) { if (inst.currentTime) { BLOCKS.debug("Play sound: " + name + " (" + inst.currentTime + " - " + sounds[name].end + "), src: " + sounds[name].file.src + extension); } else { BLOCKS.debug("Play sound: " + name + " (" + sounds[name].start + " - " + sounds[name].end + "), src: " + sounds[name].file.src + extension); } } // Play the sound if (inst.source.start) { // If an offset is specified then add the start time and duration parameters if (inst.currentTime) { inst.source.start(inst.delay, inst.currentTime/*, inst.source.buffer.duration - inst.currentTime*/); } else { inst.source.start(inst.delay); } } else if (inst.source.noteGrainOn) { inst.source.noteGrainOn(inst.delay, inst.currentTime, inst.source.buffer.duration - inst.currentTime); } return inst; } else { // TODO: Play the unloaded sound once its loaded //if (speaker.debug) { BLOCKS.warn("Tried to play sound: " + name + ", but it is not loaded yet"); //} } }, createLoadTimer = function () { loadTimeoutId = window.setTimeout(function () { var key; for (key in files) { if (files.hasOwnProperty(key)) { if (!files[key].loaded) { // Cancel the request if (files[key].request) { BLOCKS.warn("Sound file load has timed out. Aborting request and trying again: " + files[key].src); files[key].request.abort(); } else { BLOCKS.warn("Sound file load has timed out. Sending additional request: " + files[key].src); } loadFile(files[key]); } } } loadTries += 1; if (loadTries < maxLoadTries) { createLoadTimer(); } }, maxLoadTime); }; speaker.play = function (name, callback, trackName, startTime, delay) { if (sounds[name]) { return playSound(name, callback, trackName, startTime, delay); } else { BLOCKS.warn("Cannot play sound '" + name + "' because it was not defined"); } }; speaker.getSoundDuration = function (name) { return sounds[name].file.buffer.duration; }; speaker.getSoundInstanceGain = function (inst) { return getSoundGain(inst); }; speaker.getSoundGain = function (name) { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { if (instanceArr[i].name === name) { return getSoundGain(instanceArr[i]); } } }; speaker.setSoundInstanceGain = function (inst, gainValue, delay) { setSoundGain(inst, gainValue, delay); }; speaker.setSoundGain = function (name, gainValue, delay) { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { if (instanceArr[i].name === name) { setSoundGain(instanceArr[i], gainValue, delay); } } }; speaker.stopSound = function (name) { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { if (instanceArr[i].name === name) { stopSound(instanceArr[i]); } } }; speaker.pauseSound = function (name) { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { if (instanceArr[i].name === name) { pauseSound(instanceArr[i]); } } }; speaker.unpauseSound = function (name) { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { if (instanceArr[i].name === name) { unpauseSound(instanceArr[i]); } } }; speaker.stopTrack = function (trackName) { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { if (instanceArr[i].track.name === trackName) { stopSound(instanceArr[i]); } } }; speaker.pauseTrack = function (trackName) { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { if (instanceArr[i].track.name === trackName) { pauseSound(instanceArr[i]); } } }; speaker.unpauseTrack = function (trackName) { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { if (instanceArr[i].track.name === trackName) { unpauseSound(instanceArr[i]); } } }; // Stop all sounds speaker.stop = function () { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { stopSound(instanceArr[i]); } }; // Pause all sounds speaker.pause = function () { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { pauseSound(instanceArr[i]); } }; // Unpause any paused sounds speaker.unpause = function () { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { unpauseSound(instanceArr[i]); } }; // Mute all sound speaker.mute = function () { if (!muted) { muted = true; masterGain.gain.value = 0; } }; // Unmute all sound speaker.unmute = function () { if (muted) { muted = false; masterGain.gain.value = 1; } }; speaker.isMuted = function () { return muted; }; // Load the audio element speaker.load = function () { if (!loadStarted) { loadStarted = true; createLoadTimer(); load(); } }; // Return if audio is ready to be played speaker.isReady = function () { return ready; }; speaker.createSound = function (spec) { sounds[spec.name] = { name: spec.name, start: spec.start, end: spec.end, loop: spec.loop }; //BLOCKS.debug("Create Sound: " + spec.name); if (!files[spec.src]) { files[spec.src] = { src: spec.src }; loadFile(files[spec.src]); //BLOCKS.debug("Load Sound: " + spec.src); } sounds[spec.name].file = files[spec.src]; }; speaker.getActiveSoundInstances = function () { return instances; }; speaker.getNumFiles = function () { var key, totalNumFiles; totalNumFiles = 0; // Determine load progress for (key in files) { if (files.hasOwnProperty(key)) { totalNumFiles += 1; } } return totalNumFiles; }; speaker.getNumFilesLoaded = function () { var key, numFilesLoaded; numFilesLoaded = 0; // Determine load progress for (key in files) { if (files.hasOwnProperty(key)) { if (files[key].loaded) { numFilesLoaded += 1; } } } return numFilesLoaded; }; speaker.getCurrentTime = function () { return ctx.currentTime; }; speaker.multipleTracksSupported = true; (function () { var tmpAudioElement = document.createElement("audio"), fireFoxDetected; // Use ogg for Firefox due to a bud decoding buffer data fireFoxDetected = (navigator.userAgent.toLowerCase().indexOf('firefox') > -1); if (tmpAudioElement.canPlayType("audio/mpeg;").replace(/no/, "") && !!(tmpAudioElement.canPlayType) && !fireFoxDetected) { extension = ".mp3"; } else { extension = ".ogg"; } if (typeof AudioContext !== "undefined") { ctx = new window.AudioContext(); } else if (typeof webkitAudioContext !== "undefined") { ctx = new window.webkitAudioContext(); } if (ctx) { // Create the master gain node masterGain = (ctx.createGain) ? ctx.createGain() : ctx.createGainNode(); // Connext the master gain node to the context's output masterGain.connect(ctx.destination); } else { BLOCKS.error("Cannot create audio context."); } createTrack("default"); }()); return speaker; }; BLOCKS.audio.multiAudioElementPlayer = function (spec) { "use strict"; var speaker = BLOCKS.eventDispatcher(), initialized = false, loadStarted = false, loadComplete = false, ready = false, muted = false, extension, path = (spec && spec.path) || "", masterGain, ctx, sounds = {}, files = {}, instances = [], tracks = {}, loadTimeoutId, maxLoadTime = spec.maxLoadTime || 60000, // The maximum amount of time for all sounds to load loadTries = 0, maxLoadTries = 5, createTrack = function (name) { if (!tracks[name]) { tracks[name] = { name: name, gain: (ctx.createGain) ? ctx.createGain() : ctx.createGainNode() }; // Connect the track's gain node to the master node tracks[name].gain.connect(masterGain); } return tracks[name]; }, onFileLoaded = function (file) { var key, numFilesLoaded, totalNumFiles; numFilesLoaded = speaker.getNumFilesLoaded(); totalNumFiles = speaker.getNumFiles(); if (speaker.debug) { BLOCKS.debug("load: " + numFilesLoaded + " of " + totalNumFiles); } speaker.dispatchEvent("update", numFilesLoaded, totalNumFiles); if (numFilesLoaded === totalNumFiles) { if (!ready) { ready = true; // Clear the load timeout window.clearTimeout(loadTimeoutId); if (speaker.debug) { BLOCKS.debug("audio ready"); } speaker.dispatchEvent("ready"); } } }, loadFile = function (file) { file.audioElement = document.createElement("audio"); file.audioElement.preload = true; file.audioElement.src = (path + file.src + extension); file.audioElement.load(); file.audioElement.addEventListener("canplaythrough", function () { BLOCKS.debug("Audio element loaded: " + (path + file.src + extension)); file.loaded = true; onFileLoaded(file); }); //document.body.appendChild(file.audioElement); }, load = function () { /* var source; loadStarted = true; source = ctx.createOscillator(); if (source.start) { source.start(0, 0, 1); } else if (source.noteGrainOn) { source.noteGrainOn(0, 0, 1); } */ }, destroyInstance = function (inst) { var i, index; for (i = 0; i < instances.length; i += 1) { if (instances[i] === inst) { instances[i] = null; index = i; break; } } instances.splice(index, 1); }, soundCompleteChecker = function (inst) { var callback, soundName; if (speaker.debug) { BLOCKS.debug("Sound '" + inst.sound.name + "' Complete"); } if (inst.callback) { callback = inst.callback; soundName = inst.name; } // Destroy the instance before calling a possible callback destroyInstance(inst); if (callback) { callback(soundName); } }, stopSound = function (inst) { if (inst.timeout) { window.clearTimeout(inst.timeout); } if (inst.fadeTimeout) { window.clearTimeout(inst.fadeTimeout); } /* if (inst.source.stop) { inst.source.stop(0); } else if (inst.source.noteGrainOff) { inst.source.noteGrainOff(0); } else { inst.source.noteOff(0); } */ inst.sound.file.audioElement.pause(); destroyInstance(inst); }, getSoundGain = function (inst) { return inst.sound.file.audioElement.volume; }, setSoundGain = function (inst, gainValue, delay) { var fadeInterval = 10; // Clear previous fade if it's still going if (inst.fadeTimeout) { inst.sound.file.audioElement.volume = inst.fadeTarget; window.clearInterval(inst.fadeTimeout); inst.fadeTarget = 0; inst.fadeAmount = 0; } if (delay) { // Create timer to fade the gain over time inst.fadeTarget = gainValue; inst.fadeAmount = (gainValue - inst.sound.file.audioElement.volume) / ((delay * 1000) / fadeInterval); inst.fadeTimeout = window.setInterval(function () { if (inst.sound.file.audioElement.volume === inst.fadeTarget) { window.clearInterval(inst.fadeTimeout); } inst.sound.file.audioElement.volume += inst.fadeAmount; }, fadeInterval); } else { inst.sound.file.audioElement.volume = gainValue; } }, pauseSound = function (inst) { window.clearTimeout(inst.timeout); inst.currentTime = ((+ new Date()) - inst.startTime) / 1000 % inst.sound.file.audioElement.duration; inst.sound.file.audioElement.pause(); }, unpauseSound = function (inst) { var newInst; //if (speaker.debug) { // BLOCKS.debug("Unpause sound: '" + inst.name + "'"); //} newInst = playSound(inst.name, inst.callback, null, inst.currentTime); // Delete the old instance destroyInstance(inst); }, playSound = function (name, callback, trackName, currentTime, delay) { var inst = {}; if (sounds[name].file.loaded) { instances.push(inst); inst.sound = sounds[name]; inst.name = name; // If an offset is set (set when unpausing a sound) if (currentTime) { inst.currentTime = currentTime; } else { // Start from the beginning of the sound inst.currentTime = 0; } // Save when the sound starts, or would have started if started from the beginning inst.startTime = (+ new Date()) - inst.currentTime * 1000; if (delay) { // Play the sound after a delay inst.delay = ctx.currentTime + delay; } else { // Play the sound immediately delay = 0; inst.delay = 0; } if (trackName) { if (!tracks[trackName]) { createTrack(trackName); } inst.track = tracks[trackName]; } else { inst.track = tracks["default"]; } // Create a new source for this sound instance //inst.source = ctx.createBufferSource(); //inst.source.buffer = sounds[name].file.buffer; //inst.source.loop = sounds[name].loop; //inst.gain = inst.track.gain; // Connect the source to the gains //inst.source.connect(inst.gain); if (!sounds[name].loop) { // Timeout at the end of the sound //inst.timeout = window.setTimeout(soundCompleteChecker, (delay + inst.source.buffer.duration - inst.currentTime) * 1000, inst); // Assign a callback to be called once the sound is complete inst.callback = callback; } else { inst.sound.file.audioElement.loop = true; } if (speaker.debug) { if (inst.currentTime) { BLOCKS.debug("Play sound: " + name + " (" + inst.currentTime + " - " + sounds[name].end + "), src: " + sounds[name].file.src + extension); } else { BLOCKS.debug("Play sound: " + name + " (" + sounds[name].start + " - " + sounds[name].end + "), src: " + sounds[name].file.src + extension); } } inst.sound.file.audioElement.currentTime = inst.currentTime; inst.sound.file.audioElement.play(); /* // Play the sound if (inst.source.start) { // If an offset is specified then add the start time and duration parameters if (inst.currentTime) { inst.source.start(inst.delay, inst.currentTime, inst.source.buffer.duration - inst.currentTime); } else { inst.source.start(inst.delay); } } else if (inst.source.noteGrainOn) { inst.source.noteGrainOn(inst.delay, inst.currentTime, inst.source.buffer.duration - inst.currentTime); } */ return inst; } else { // TODO: Play the unloaded sound once its loaded //if (speaker.debug) { BLOCKS.warn("Tried to play sound: " + name + ", but it is not loaded yet"); //} } }, createLoadTimer = function () { loadTimeoutId = window.setTimeout(function () { var key; for (key in files) { if (files.hasOwnProperty(key)) { if (!files[key].loaded) { // Cancel the request if (files[key].request) { BLOCKS.warn("Sound file load has timed out. Aborting request and trying again: " + files[key].src); files[key].request.abort(); } else { BLOCKS.warn("Sound file load has timed out. Sending additional request: " + files[key].src); } loadFile(files[key]); } } } loadTries += 1; if (loadTries < maxLoadTries) { createLoadTimer(); } }, maxLoadTime); }; speaker.play = function (name, callback, trackName, startTime, delay) { if (sounds[name]) { return playSound(name, callback, trackName, startTime, delay); } else { BLOCKS.warn("Cannot play sound '" + name + "' because it was not defined"); } }; speaker.getSoundDuration = function (name) { return sounds[name].file.buffer.duration; }; speaker.getSoundInstanceGain = function (inst) { return getSoundGain(inst); }; speaker.getSoundGain = function (name) { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { if (instanceArr[i].name === name) { return getSoundGain(instanceArr[i]); } } }; speaker.setSoundInstanceGain = function (inst, gainValue, delay) { setSoundGain(inst, gainValue, delay); }; speaker.setSoundGain = function (name, gainValue, delay) { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { if (instanceArr[i].name === name) { setSoundGain(instanceArr[i], gainValue, delay); } } }; speaker.stopSound = function (name) { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { if (instanceArr[i].name === name) { stopSound(instanceArr[i]); } } }; speaker.pauseSound = function (name) { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { if (instanceArr[i].name === name) { pauseSound(instanceArr[i]); } } }; speaker.unpauseSound = function (name) { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { if (instanceArr[i].name === name) { unpauseSound(instanceArr[i]); } } }; speaker.stopTrack = function (trackName) { //var i, instanceArr = instances.slice(0); // //for (i = 0; i < instanceArr.length; i += 1) { // if (instanceArr[i].track.name === trackName) { // stopSound(instanceArr[i]); // } //} }; speaker.pauseTrack = function (trackName) { //var i, instanceArr = instances.slice(0); // //for (i = 0; i < instanceArr.length; i += 1) { // if (instanceArr[i].track.name === trackName) { // pauseSound(instanceArr[i]); // } //} }; speaker.unpauseTrack = function (trackName) { //var i, instanceArr = instances.slice(0); // //for (i = 0; i < instanceArr.length; i += 1) { // if (instanceArr[i].track.name === trackName) { // unpauseSound(instanceArr[i]); // } //} }; // Stop all sounds speaker.stop = function () { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { stopSound(instanceArr[i]); } }; // Pause all sounds speaker.pause = function () { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { pauseSound(instanceArr[i]); } }; // Unpause any paused sounds speaker.unpause = function () { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { unpauseSound(instanceArr[i]); } }; // Mute all sound speaker.mute = function () { if (!muted) { muted = true; // TODO: mute all sounds } }; // Unmute all sound speaker.unmute = function () { if (muted) { muted = false; // TODO: unmute all sounds } }; speaker.isMuted = function () { return muted; }; // Load the audio element speaker.load = function () { if (!loadStarted) { loadStarted = true; createLoadTimer(); load(); } }; // Return if audio is ready to be played speaker.isReady = function () { return ready; }; speaker.createSound = function (spec) { sounds[spec.name] = { name: spec.name, start: spec.start, end: spec.end, loop: spec.loop }; //BLOCKS.debug("Create Sound: " + spec.name); if (!files[spec.src]) { files[spec.src] = { src: spec.src }; loadFile(files[spec.src]); //BLOCKS.debug("Load Sound: " + spec.src); } sounds[spec.name].file = files[spec.src]; }; speaker.getActiveSoundInstances = function () { return instances; }; speaker.getNumFiles = function () { var key, totalNumFiles; totalNumFiles = 0; // Determine load progress for (key in files) { if (files.hasOwnProperty(key)) { totalNumFiles += 1; } } return totalNumFiles; }; speaker.getNumFilesLoaded = function () { var key, numFilesLoaded; numFilesLoaded = 0; // Determine load progress for (key in files) { if (files.hasOwnProperty(key)) { if (files[key].loaded) { numFilesLoaded += 1; } } } return numFilesLoaded; }; speaker.getCurrentTime = function () { // Since multiple sounds could be playing this returns nothing return null; }; speaker.multipleTracksSupported = true; (function () { extension = ".mp3"; }()); return speaker; }; BLOCKS.speaker = function (spec) { "use strict"; var speaker; // Create audio element (function () { if (!spec) { spec = {}; } if (spec.audioPlayerType === "multiAudioElementPlayer") { speaker = BLOCKS.audio.multiAudioElementPlayer(spec); } else if (spec.audioPlayerType !== "audioElementPlayer" && (typeof AudioContext !== 'undefined' || typeof webkitAudioContext !== 'undefined') && spec.webAudioEnabled !== false) { speaker = BLOCKS.audio.webAudioPlayer(spec); } else { speaker = BLOCKS.audio.audioElementPlayer(spec); } }()); speaker.debug = false; return speaker; }; /* Copyright (c) 2013 William Malone (www.williammalone.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*global window */ var BLOCKS; if (BLOCKS === undefined) { BLOCKS = {}; } BLOCKS.stack = function (options) { "use strict"; var stack = BLOCKS.eventDispatcher(), views = [], dirty, alpha, motors = [], x, y, visible, motorDestroyed = function (motor) { var i; motor.removeEventListener("destroyed", motorDestroyed); for (i = 0 ; i < motors.length; i += 1) { motors.splice(i, 1); break; } }, setViewsDirty = function (value) { var i; for (i = 0; i < views.length; i += 1) { views[i].dirty = value; } }; options = options || {}; // Public Methods stack.addView = function (view) { view.stack = stack; views.push(view); }; stack.getView = function (name) { var i; for (i = 0; i < views.length; i += 1) { if (views[i].name === name) { return views[i]; } } }; stack.removeView = function (view) { var i; for (i = 0; i < views.length; i += 1) { if (views[i] === view) { views[i].splice(i, 1); break; } } }; stack.show = function () { var i; if (!visible) { visible = true; for (i = 0; i < views.length; i += 1) { views[i].show(); } } }; stack.hide = function () { var i; if (visible) { visible = false; dirty = true; for (i = 0; i < views.length; i += 1) { views[i].hide(); } } }; stack.isPointInside = function (pos) { var i; for (i = 0; i < views.length; i += 1) { if (views[i].visible && views[i].isPointInside(pos)) { return true; } } return false; }; stack.motorize = function (motor) { motor.addEventListener("destroyed", motorDestroyed); motors.push(motor); }; stack.removeMotors = function (type) { var i, motorArr = []; for (i = 0 ; i < motors.length; i += 1) { if (type) { if (motors[i].type === type) { motors[i].destroy(); } else { motorArr.push(motors[i]); } } else { motors[i].destroy(); } } motors = motorArr; }; stack.destroy = function () { var i; for (i = 0; i < views.length; i += 1) { views[i].destroy(); } views = []; stack = null; }; Object.defineProperty(stack, "dirty", { get: function () { return dirty; }, set: function (value) { setViewsDirty(value); } }); Object.defineProperty(stack, "alpha", { get: function () { return alpha !== undefined ? alpha : 1; }, set: function (value) { var i; alpha = value; for (i = 0; i < views.length; i += 1) { views[i].alpha = value; } } }); Object.defineProperty(stack, "width", { get: function () { var i, largestWidth = 0; for (i = 0; i < views.length; i += 1) { if (views[i].visible && views[i].width > largestWidth) { largestWidth = views[i].width; } } return largestWidth; } }); Object.defineProperty(stack, "height", { get: function () { var i, largestHeight = 0; for (i = 0; i < views.length; i += 1) { if (views[i].visible && views[i].height > largestHeight) { largestHeight = views[i].height; } } return largestHeight; } }); x = options.x || 0; Object.defineProperty(stack, "x", { get: function () { return x; }, set: function (value) { if (x !== value) { x = value; setViewsDirty(true); } } }); y = options.y || 0; Object.defineProperty(stack, "y", { get: function () { return y; }, set: function (value) { if (y !== value) { y = value; setViewsDirty(true); } } }); visible = options.visible || true; Object.defineProperty(stack, "visible", { get: function () { return visible; }, set: function (value) { if (value) { stack.show(); } else { stack.hide(); } } }); return stack; }; /* Copyright (c) 2013 William Malone (www.williammalone.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*global window, JSON */ var BLOCKS; if (BLOCKS === undefined) { BLOCKS = {}; } BLOCKS.storage = function () { "use strict"; var storage = BLOCKS.eventDispatcher(); storage.get = function (item) { if (!window.localStorage) { return null; } return JSON.parse(window.localStorage.getItem(item)); }; storage.save = function (item, str) { window.localStorage.setItem(item, JSON.stringify(str)); }; storage.destroy = function () { storage = null; }; return storage; }; /* Copyright (c) 2013 William Malone (www.williammalone.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*global window, Image */ var BLOCKS; if (BLOCKS === undefined) { BLOCKS = {}; } BLOCKS.textField = function (options) { "use strict"; var textField = BLOCKS.view(options), drawBounds = false, motors = [], // Private Method motorDestroyed = function (motor) { var i; motor.removeEventListener("destroyed", motorDestroyed); for (i = 0 ; i < motors.length; i += 1) { motors.splice(i, 1); break; } }; // Public Properties //textField.name = (options && options.name !== undefined) ? options.name : undefined; //textField.width = options.width || 0; //textField.height = options.height || 0; //textField.x = options.x || 0; //textField.y = options.y || 0; //textField.layer = options && options.layer; //textField.angle = (options && options.angle); //textField.alpha = (options && options.alpha); //textField.scale = (options && options.scale) || 1; //textField.visible = true; //textField.dirty = true; // Public Methods textField.render = function () { var i, bounds, restoreNeeded, wordArr, curLine, tempLine, xLoc, yLoc, context; if (textField.dirty && textField.visible && textField.layer) { context = textField.layer.ctx; if (textField.angle || textField.alpha !== 1) { context.save(); restoreNeeded = true; } if (textField.alpha !== 1) { context.globalAlpha = textField.alpha; } if (textField.angle) { context.translate(textField.x, textField.y); context.rotate(textField.angle * Math.PI / 180); context.translate(-textField.x, -textField.y); } context.fillStyle = textField.fontColor; context.font = textField.fontWeight + " " + (Number(textField.fontSize.toString().replace("px", "")) * textField.scale + "px") + " " + textField.fontFamily; context.textAlign = textField.textAlign; wordArr = (textField.prependText + textField.text).split(" "); curLine = ""; xLoc = textField.x; yLoc = textField.y; context.textBaseline = textField.textBaseline; for (i = 0; i < wordArr.length; i += 1) { tempLine = curLine + wordArr[i] + " "; if (i && textField.width && context.measureText(tempLine).width > textField.width) { context.fillText(curLine, xLoc, yLoc); curLine = wordArr[i] + " "; yLoc += 20; } else { curLine = tempLine; } } context.fillText(curLine, xLoc, yLoc); //context.fillText(textField.prependText + textField.text, textField.x, textField.y); if (restoreNeeded) { context.restore(); } if (drawBounds) { context.beginPath(); context.strokeStyle = "rgba(255, 80, 0, 0.5)"; context.strokeRect(textField.x, textField.y, textField.width, textField.height); context.closePath(); } } textField.dirty = false; }; textField.destroy = function () { textField.stopMotors(); options = null; textField = null; }; textField.motorize = function (motor) { motor.addEventListener("destroyed", motorDestroyed); motors.push(motor); }; textField.stopMotors = function (type) { var i, motorArr = motors.slice(0); for (i = 0 ; i < motorArr.length; i += 1) { if (type) { if (motorArr[i].type === type) { motorArr[i].destroy(); } } else { motorArr[i].destroy(); } } }; (function () { options = options || {}; textField.fontColor = options.fontColor || "#000000"; textField.fontFamily = options.fontFamily || "Arial,sans"; textField.fontSize = (options.fontSize && Number(options.fontSize.toString().replace("px", ""))) || 24; textField.fontWeight = options.fontWeight || "bold"; textField.textAlign = options.textAlign || "center"; textField.prependText = options.prependText || ""; textField.textBaseline = options.textBaseline || "top"; textField.text = options.text || ""; }()); return textField; }; /* Copyright (c) 2013 William Malone (www.williammalone.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*global window */ var BLOCKS; if (BLOCKS === undefined) { BLOCKS = {}; } BLOCKS.tileCollection = function (options) { "use strict"; var collection = BLOCKS.eventDispatcher(), tiles = [], tileWidth, tileHeight, tileIndexArray = [], visibleTiles = [], dirty, layer, alpha, motors = [], width, height, x, y, visible, prevCamera, speed, loopX, motorDestroyed = function (motor) { var i; motor.removeEventListener("destroyed", motorDestroyed); for (i = 0 ; i < motors.length; i += 1) { motors.splice(i, 1); break; } }, setTilesDirty = function (value) { var i; for (i = 0; i < visibleTiles.length; i += 1) { visibleTiles[i].dirty = value; } }, init = function () { var i, tmpSlice; if (options.tiles) { for (i = 0; i < options.tiles.length; i += 1) { // If the tile has an id if (options.tiles[i].id) { tiles[options.tiles[i].id] = options.tiles[i]; } else { tiles[i] = options.tiles[i]; } } // If an image is loaded for the first tile if (options.tiles[0].image) { tileWidth = options.tiles[0].image.width; tileHeight = options.tiles[0].image.height; } } else { BLOCKS.error("No tiles specified in tile collection."); } if (options.order) { tileIndexArray = options.order; } else { BLOCKS.error("No tile order specified in tile collection."); } }, drawTile = function (spec) { var tilePos; if (tileWidth && tileHeight) { // Determine the tile position relative to the collection tilePos = { x: -(spec.camera.x * speed - tileWidth * spec.column), y: -(spec.camera.y * speed - tileHeight * spec.row) }; spec.image = tiles[spec.id].image; // If tile outside bounds on the left (maybe right too) if (tilePos.x + x + spec.camera.offsetX < 0) { spec.sourceX = x - tilePos.x + spec.camera.offsetX; spec.destX = 0; // If outside bounds on the right too if (tilePos.x + tileWidth > spec.camera.width + spec.camera.offsetX) { spec.sourceWidth = spec.camera.width; //BLOCKS.debug(collection.name + ":If tile outside bounds on the left and right: sourceX: " + spec.sourceX + ", sourceWidth: " + spec.sourceWidth + ", x: " + x +", tilePos.x: " + tilePos.x + ", spec.camera.x: " + spec.camera.x + ", (sourceX + sourceWidth > tileWidth): " + Boolean(spec.sourceX + spec.sourceWidth > tileWidth)); // If outside bounds on the left but not the right } else { spec.sourceWidth = tileWidth + tilePos.x - spec.camera.offsetX; //BLOCKS.debug(collection.name + ":If tile outside bounds on the left: sourceX: " + spec.sourceX + ", sourceWidth: " + spec.sourceWidth + ", x: " + x +", tilePos.x: " + tilePos.x + ", spec.camera.x: " + spec.camera.x + ", (sourceX + sourceWidth > tileWidth): " + Boolean(spec.sourceX + spec.sourceWidth > tileWidth) + ", spec.camera.offsetX;: " + spec.camera.offsetX); } // If tile outside bounds on the right only } else if (tilePos.x + tileWidth > x + spec.camera.offsetX + spec.camera.width) { spec.sourceX = 0; spec.destX = tilePos.x + x - spec.camera.offsetX; spec.sourceWidth = spec.camera.width + spec.camera.offsetX - (tilePos.x + x); //BLOCKS.debug(collection.name + ": If tile outside bounds on the right only: sourceX: " + spec.sourceX + ", sourceWidth: " + spec.sourceWidth + ", x: " + x +", tilePos.x: " + tilePos.x + ", spec.camera.x: " + spec.camera.x); // If tile is inside bounds on the left and right } else { spec.sourceX = 0; spec.destX = x - spec.camera.offsetX + tilePos.x; spec.sourceWidth = tileWidth; //BLOCKS.debug(collection.name + ": If tile inside horizontal bounds: sourceX: " + spec.sourceX + ", sourceWidth: " + spec.sourceWidth + ", x: " + x +", tilePos.x: " + tilePos.x + ", spec.camera.x: " + spec.camera.x); } // If tile outside bounds on the top (maybe bottom too) if (tilePos.y + y + spec.camera.offsetY < 0) { spec.sourceY = -tilePos.y - y + spec.camera.offsetY; spec.destY = 0; // If outside bounds on the bottom too if (tilePos.y + tileHeight > spec.camera.height) { spec.sourceHeight = spec.camera.height; // If outside bounds on the top but not the bottom } else { spec.sourceHeight = tileHeight - tilePos.y; } //BLOCKS.debug(collection.name + "(" + spec.id + "): If tile outside bounds on the top: sourceY: " + spec.sourceY + ", sourceHeight: " + spec.sourceHeight + ", y: " + y +", tilePos.y: " + tilePos.y + ", spec.camera.y: " + spec.camera.y); // If tile outside bounds on the bottom only } else if (tilePos.y + tileHeight > y + spec.camera.offsetY + spec.camera.height) { spec.sourceY = 0; spec.destY = tilePos.y + y - spec.camera.offsetY; spec.sourceHeight = spec.camera.height + spec.camera.offsetY - (tilePos.y + y); //BLOCKS.debug(collection.name + ": If tile outside bounds on the bottom: destY: " + spec.destY); // If tile is inside bounds on the top and bottom } else { spec.sourceY = 0; spec.destY = y - spec.camera.offsetY + tilePos.y; spec.sourceHeight = tileHeight; //BLOCKS.debug(collection.name + ": If tile inside vertical bounds: destY: " + spec.destY); } spec.destWidth = spec.sourceWidth; spec.destHeight = spec.sourceHeight; //BLOCKS.debug(spec.id + ": " + spec.sourceWidth + ", x: " + x + ", spec.sourceX: " + spec.sourceX + ", spec.destX: " + spec.destX); //BLOCKS.debug(spec.id + " > spec.sourceHeight: " + spec.sourceHeight + ", y: " + y + ", spec.sourceY: " + spec.sourceY + ", spec.destY: " + spec.destY); if (spec.sourceWidth && spec.sourceHeight) { collection.layer.ctx.drawImage( spec.image, spec.sourceX, spec.sourceY, spec.sourceWidth, spec.sourceHeight, spec.destX / layer.scale, spec.destY / layer.scale, spec.destWidth / layer.scale, spec.destHeight / layer.scale ); } } else { // If an image is loaded for the first tile if (options.tiles[0].image) { tileWidth = options.tiles[0].image.width; tileHeight = options.tiles[0].image.height; } } }; options = options || {}; // Public Methods collection.update = function () { }; collection.render = function (e) { var i, j, minColIndex, maxColIndex, minRowIndex, maxRowIndex, col, row, previousAlpha; if (dirty && visible) { previousAlpha = collection.layer.ctx.globalAlpha; collection.layer.ctx.globalAlpha = alpha; minColIndex = Math.floor((e.camera.x * speed - x) / tileWidth); if (loopX) { //BLOCKS.debug("minColIndex: " + minColIndex); maxColIndex = Math.ceil((e.camera.x + e.camera.width + e.camera.offsetX) / tileWidth) - 1; //BLOCKS.debug("maxColIndex: " + maxColIndex); //BLOCKS.debug(Math.floor((e.camera.x * speed - x) / tileWidth) + " - " + minColIndex + " > " + maxColIndex + " - " + tileIndexArray[0].length); } else { maxColIndex = Math.floor((e.camera.x * speed + e.camera.width + e.camera.offsetX) / tileWidth); } minRowIndex = Math.floor((e.camera.y * speed - y) / tileHeight); maxRowIndex = Math.floor((e.camera.y * speed - y + e.camera.height + e.camera.offsetY) / tileHeight); for (i = minColIndex; i <= maxColIndex; i += 1) { for (j = minRowIndex; j <= maxRowIndex; j += 1) { // Enable looping if (loopX && tileIndexArray[j]) { //BLOCKS.debug("(" + i + ", " + j + "): " + i + " >=" + tileIndexArray[j].length); if (i >= tileIndexArray[j].length) { col = i % tileIndexArray[j].length; //BLOCKS.debug(j + ": minColIndex out of range: " + minColIndex + ", " + i + " > " + col); } else { col = i; //BLOCKS.debug(j + ": minColIndex in range: " + i); } } else { col = i; } row = j; if (tileIndexArray && tileIndexArray[row] && tileIndexArray[row][col]) { drawTile({ id: tileIndexArray[row][col], row: j, column: i, camera: { x: e.camera.x, y: e.camera.y, offsetX: e.camera.offsetX, offsetY: e.camera.offsetY, width: e.camera.width, height: e.camera.height } }); } } } collection.layer.ctx.globalAlpha = previousAlpha; } dirty = false; }; collection.show = function () { collection.visible = true; }; collection.hide = function () { collection.visible = false; }; collection.isPointInside = function (pos) { var i; for (i = 0; i < visibleTiles.length; i += 1) { if (visibleTiles[i].visible && visibleTiles[i].isPointInside(pos)) { return true; } } return false; }; collection.motorize = function (motor) { motor.addEventListener("destroyed", motorDestroyed); motors.push(motor); }; collection.removeMotors = function (type) { var i, motorArr = []; for (i = 0 ; i < motors.length; i += 1) { if (type) { if (motors[i].type === type) { motors[i].destroy(); } else { motorArr.push(motors[i]); } } else { motors[i].destroy(); } } motors = motorArr; }; collection.destroy = function () { var i; for (i = 0; i < visibleTiles.length; i += 1) { visibleTiles[i].destroy(); } visibleTiles = []; collection = null; }; Object.defineProperty(collection, "dirty", { get: function () { return dirty; }, set: function (value) { if (dirty !== value) { dirty = value; } } }); alpha = options.alpha || 1; Object.defineProperty(collection, "alpha", { get: function () { return alpha !== undefined ? alpha : 1; }, set: function (value) { if (alpha !== value) { // Round the alpha value if it is really close if (value < 0.0001) { value = 0; } else if (value > 0.9999) { value = 1; } alpha = value; dirty = true; } } }); Object.defineProperty(collection, "width", { get: function () { return tileIndexArray[0].length * tileWidth; } }); Object.defineProperty(collection, "height", { get: function () { return tileIndexArray.length * tileHeight; } }); x = options.x || 0; Object.defineProperty(collection, "x", { get: function () { return x; }, set: function (value) { if (x !== value) { x = value; dirty = true; } } }); y = options.y || 0; Object.defineProperty(collection, "y", { get: function () { return y; }, set: function (value) { if (y !== value) { y = value; dirty = true; } } }); layer = options.layer; Object.defineProperty(collection, "layer", { get: function () { return layer; }, set: function (value) { if (layer !== value) { layer = value; dirty = true; } } }); visible = options.visible || true; Object.defineProperty(collection, "visible", { get: function () { return visible; }, set: function (value) { if (visible !== value) { visible = value; dirty = true; } } }); speed = options.speed || 1; Object.defineProperty(collection, "speed", { get: function () { return speed; }, set: function (value) { if (speed !== value) { speed = value; } } }); loopX = options.loopX; Object.defineProperty(collection, "loopX", { get: function () { return loopX; }, set: function (value) { if (loopX !== value) { loopX = value; } } }); Object.defineProperty(collection, "tileWidth", { get: function () { return tileWidth; } }); Object.defineProperty(collection, "tileHeight", { get: function () { return tileHeight; } }); init(); return collection; }; /* Copyright (c) 2013 William Malone (www.williammalone.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*global window, document */ var BLOCKS; if (BLOCKS === undefined) { BLOCKS = {}; } BLOCKS.toolbox = {}; BLOCKS.toolbox.angle = function (p1, p2) { "use strict"; var angle, dx = p2.x - p1.x, dy = p2.y - p1.y; if (dx === 0) { angle = dy > 0 ? Math.PI / 2 : -Math.PI / 2; } else { // Quadrant 1 angle = Math.atan(dy / dx); if (dy > 0) { if (dx < 0) { // Quadrant 2 angle = Math.PI + angle; } } else { if (dx < 0) { // Quadrant 3 angle = Math.PI + angle; } else { // Quadrant 4 angle = 2 * Math.PI + angle; } } } return angle; }; BLOCKS.toolbox.randomizeArr = function (arr) { var i, j, k; for (i = arr.length; i; j = parseInt(Math.random() * i, 10), k = arr[--i], arr[i] = arr[j], arr[j] = k) { // Loop until randomized } }; BLOCKS.toolbox.isPointInsideRect = function (point, rect) { return (point.x > rect.x && point.x < rect.x + rect.width && point.y > rect.y && point.y < rect.y + rect.height); }; BLOCKS.toolbox.isRectInsideRect = function (rect1, rect2) { return (rect1.x + rect1.width > rect2.x && rect1.x < rect2.x + rect2.width && rect1.y + rect1.height > rect2.y && rect1.y < rect2.y + rect2.height); }; BLOCKS.toolbox.dist = function (p1, p2) { "use strict"; var dx = p1.x - p2.x, dy = p1.y - p2.y; return Math.sqrt(dx * dx + dy * dy); }; BLOCKS.toolbox.vector = function (x, y) { var vector = { x: x, y: y }; vector.scale = function(factor) { vector.x *= factor; vector.y *= factor; return vector; }; vector.normalize = function () { return vector.scale(1 / vector.magnitude()); }; vector.magnitude = function () { return Math.sqrt(vector.x * vector.x + vector.y * vector.y); }; return vector; }; BLOCKS.toolbox.sum = function(p1, p2) { return { x: p1.x + p2.x, y: p1.y + p2.y }; }; BLOCKS.toolbox.diff = function(p1, p2) { return { x: p1.x - p2.x, y: p1.y - p2.y }; }; BLOCKS.toolbox.dot = function (p1, p2) { return p1.x * p2.x + p1.y * p2.y; }; /* Copyright (c) 2013 William Malone (www.williammalone.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*global window */ var BLOCKS; if (BLOCKS === undefined) { BLOCKS = {}; } BLOCKS.log = function (message) { if (window.console) { if (window.console.log) { window.console.log(message); } } }; BLOCKS.warn = function (message) { if (window.console) { if (window.console.warn) { window.console.warn(message); } else if (window.console.log) { window.console.log(message); } } }; BLOCKS.debug = function (message) { if (window.console) { if (window.console.debug) { window.console.debug(message); } else if (window.console.log) { window.console.log(message); } } }; BLOCKS.error = function (message) { if (window.console) { if (window.console.error) { window.console.error(message); } else if (window.console.log) { window.console.log(message); } } }; BLOCKS.dir = function (obj) { if (window.console) { if (window.console.dir) { window.console.dir(obj); } else if (window.console.log) { window.console.log(obj); } } }; /* Copyright (c) 2013 William Malone (www.williammalone.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*global window */ var BLOCKS; if (BLOCKS === undefined) { BLOCKS = {}; } BLOCKS.view = function (options) { "use strict"; var view = BLOCKS.eventDispatcher(), // Properties x, y, width, height, offsetX, offsetY, angle, scale, alpha, visible, layer, hotspots, minHotspot, stack, centerRegistrationPoint, motors = [], motorDestroyed = function (motor) { var i; motor.removeEventListener("destroyed", motorDestroyed); for (i = 0 ; i < motors.length; i += 1) { if (motors[i] === motor) { motors.splice(i, 1); } break; } }; // Public Methods view.update = function () { }; view.render = function (e) { view.dirty = false; }; view.show = function () { if (!view.visible) { view.dirty = true; } view.visible = true; }; view.hide = function () { if (view.visible) { view.dirty = true; } view.visible = false; }; view.motorize = function (motor) { motor.addEventListener("destroyed", motorDestroyed); motors.push(motor); }; view.removeMotors = function (type) { var i, motorsToDestroy = [], newMotorArr = []; // Mark all motors to be destroyed. Don't destroy them yet because // the motors array will change because an event is dispatched // when the destroy method is called which alters the motor array for (i = 0 ; i < motors.length; i += 1) { if (type) { if (motors[i].type === type) { motorsToDestroy.push(motors[i]); } else { newMotorArr.push(motors[i]); } } else { motorsToDestroy.push(motors[i]); } } // Destroy all motors marked for destruction for (i = 0 ; i < motorsToDestroy.length; i += 1) { motorsToDestroy[i].destroy(); } motors = newMotorArr; }; view.isPointInside = function (point) { var i, bounds = view.getBounds(), collision = false; if (!point) { BLOCKS.warn("view.isPointInside point is falsy: " + point); return; } if (!bounds.length) { bounds = [bounds]; } for (i = 0; i < bounds.length; i += 1) { if (point.x >= bounds[i].x && point.x <= bounds[i].x + bounds[i].width && point.y >= bounds[i].y && point.y <= bounds[i].y + bounds[i].height) { collision = true; break; } } return collision; }; view.getBounds = function () { var i, bounds, extraWidth, extraHeight, x, y, width, height; x = view.worldX; y = view.worldY; width = view.cropWidth !== undefined ? view.cropWidth : view.width; height = view.cropHeight !== undefined ? view.cropHeight : view.height; if (!view.hotspots && !view.minHotspot) { bounds = { x: x + view.offsetX, y: y + view.offsetY, width: width, height: height }; } else { bounds = []; if (view.hotspots) { for (i = 0; i < view.hotspots.length; i += 1) { bounds.push({ x: x + view.offsetX + view.hotspots[i].x, y: y + view.offsetY + view.hotspots[i].y, width: view.hotspots[i].width, height: view.hotspots[i].height }); } } if (view.minHotspot) { extraWidth = width < view.minHotspot ? view.minHotspot - width : 0; extraHeight = height < view.minHotspot ? view.minHotspot - height : 0; bounds.push({ x: x + view.offsetX - extraWidth / 2, y: y + view.offsetY - extraHeight / 2, width: width + extraWidth, height: height + extraHeight }); } if (bounds.length === 1) { bounds = bounds[0]; } } return bounds; }; view.getBoundingBox = function () { return { x: view.worldX + view.offsetX, y: view.worldY + view.offsetY, width: view.cropWidth !== undefined ? view.cropWidth : view.width, height: view.cropHeight !== undefined ? view.cropHeight : view.height }; }; view.isRectInside = function (rect) { var i, result, bounds; if (!rect) { BLOCKS.warn("view.isRectangleInside rect is falsy: " + rect); return false; } bounds = view.getBounds(); if (!bounds.length) { bounds = [bounds]; } for (i = 0; i < bounds.length; i += 1) { if (rect.x + rect.width > bounds[i].x && rect.x < bounds[i].x + bounds[i].width && rect.y + rect.height > bounds[i].y && rect.y < bounds[i].y + bounds[i].height) { result = true; break; } } return result; }; view.destroy = function () { if (view) { view.removeMotors(); view.dispatchEvent("destroyed", view); view = null; } }; // Create public properties (function () { options = options || {}; view.name = options.name; view.dirty = true; stack = options.stack; Object.defineProperty(view, "stack", { get: function () { return stack; }, set: function (value) { if (stack !== value) { view.dirty = true; stack = value; } } }); Object.defineProperty(view, "worldX", { get: function () { return view.stack ? view.stack.x + view.x : view.x; }, set: function (value) { if (view.x !== value) { view.dirty = true; view.x = view.stack ? value - view.stack.x : value; } } }); Object.defineProperty(view, "worldY", { get: function () { return view.stack ? view.stack.y + view.y : view.y; }, set: function (value) { if (view.y !== value) { view.dirty = true; view.y = view.stack ? value - view.stack.y : value; } } }); scale = options.scale !== undefined ? options.scale : 1; Object.defineProperty(view, "scale", { get: function () { return scale; }, set: function (value) { if (scale !== value) { view.dirty = true; scale = value; } } }); width = options.width || 0; Object.defineProperty(view, "width", { get: function () { return width * view.scale; }, set: function (value) { if (width !== view.scale ? value / view.scale : value) { view.dirty = true; width = view.scale ? value / view.scale : value; } } }); height = options.height || 0; Object.defineProperty(view, "height", { get: function () { return height * view.scale; }, set: function (value) { if (height !== view.scale ? value / view.scale : value) { view.dirty = true; height = view.scale ? value / view.scale : value; } } }); offsetX = options.offsetX || 0; Object.defineProperty(view, "offsetX", { get: function () { return view.centerRegistrationPoint ? -view.width / 2 : offsetX; }, set: function (value) { if (offsetX !== value) { view.dirty = true; offsetX = value; } } }); offsetY = options.offsetY || 0; Object.defineProperty(view, "offsetY", { get: function () { return view.centerRegistrationPoint ? -view.height / 2 : offsetY; }, set: function (value) { if (offsetY !== value) { view.dirty = true; offsetY = value; } } }); angle = options.angle || 0; Object.defineProperty(view, "angle", { get: function () { return angle; }, set: function (value) { value = value % 360; if (value < 0) { value = 360 + value; } if (angle !== value) { view.dirty = true; angle = value; } } }); x = options.x || 0; Object.defineProperty(view, "x", { get: function () { return x; }, set: function (value) { if (x !== value) { view.dirty = true; x = value; } } }); y = options.y || 0; Object.defineProperty(view, "y", { get: function () { return y; }, set: function (value) { if (y !== value) { view.dirty = true; y = value; } } }); alpha = options.alpha !== undefined ? options.alpha : 1; Object.defineProperty(view, "alpha", { get: function () { return alpha; }, set: function (value) { if (alpha !== value) { // Round the alpha value if it is really close if (alpha < 0.0001) { alpha = 0; } else if (alpha > 0.9999) { alpha = 1; } view.dirty = true; alpha = value; } } }); visible = options.visible !== undefined ? options.visible : true; Object.defineProperty(view, "visible", { get: function () { return visible; }, set: function (value) { if (visible !== value) { view.dirty = true; visible = value; } } }); layer = options.layer; Object.defineProperty(view, "layer", { get: function () { return layer; }, set: function (value) { if (layer !== value) { view.dirty = true; layer = value; } } }); hotspots = options.hotspots; Object.defineProperty(view, "hotspots", { get: function () { return hotspots; }, set: function (value) { if (hotspots !== value) { view.dirty = true; hotspots = value; } } }); minHotspot = options.minHotspot; Object.defineProperty(view, "minHotspot", { get: function () { return minHotspot; }, set: function (value) { if (minHotspot !== value) { view.dirty = true; minHotspot = value; } } }); centerRegistrationPoint = options.centerRegistrationPoint || false; Object.defineProperty(view, "centerRegistrationPoint", { get: function () { return centerRegistrationPoint; }, set: function (value) { if (centerRegistrationPoint !== value) { view.dirty = true; centerRegistrationPoint = value; } } }); }()); return view; }; /** * keyboard.js * _____________________________________________________________________________ * * @author William Malone (www.williammalone.com) */ /*global window, BLOCKS, Image */ BLOCKS.key = function (spec) { "use strict"; var key = BLOCKS.eventDispatcher(); key.name = spec.name; key.keyCode = spec.keyCode; key.layer = spec.layer; key.x = spec.x || 0; key.y = spec.y || 0; key.width = spec.width || 80; key.height = spec.height || 80; key.scale = spec.scale || 1; key.visible = spec.visible || false; key.alpha = spec.alpha || 1; key.color = spec.color || "#333"; key.textColor = spec.textColor || "#eee"; key.dirty = true; key.update = function () { }; key.render = function () { if (key.dirty && key.visible) { key.layer.ctx.save(); // Draw key background key.layer.ctx.globalAlpha = key.alpha; key.layer.ctx.fillStyle = key.color; key.layer.ctx.fillRect(key.x, key.y, key.width, key.height); // Draw key name key.layer.ctx.fillStyle = key.textColor; key.layer.ctx.font = "bold 24px sans-serif"; key.layer.ctx.textAlign = "center"; key.layer.ctx.fillText(key.name, key.x + key.width / 2, key.y + key.height / 2 + 7); key.layer.ctx.restore(); } }; key.destroy = function () { key = null; }; return key; }; BLOCKS.virtualKeyboard = function (controller, spec) { "use strict"; var keyboard = BLOCKS.eventDispatcher(), layer = spec.layer, keySpec = [ [{ name: "1", keyCode: 49 }, { name: "2", keyCode: 50 }, { name: "3", keyCode: 51 }, { name: "4", keyCode: 52 }, { name: "5", keyCode: 53 }, { name: "6", keyCode: 54 }, { name: "7", keyCode: 55 }, { name: "8", keyCode: 56 }, { name: "9", keyCode: 57 }, { name: "0", keyCode: 48 }]/*, [{ name: "space", keyCode: 32, scale: 5 }]*/ ], keys = [], init = function () { var i, j, key, margin = 20, padding = 20; // If any custom keys if (spec.customKeys) { for (i = 0; i < spec.customKeys.length; i += 1) { keySpec.push(spec.customKeys[i]); } } for (i = 0; i < keySpec.length; i += 1) { for (j = 0; j < keySpec[i].length; j += 1) { keySpec[i][j].layer = layer; key = BLOCKS.key(keySpec[i][j]); key.width = (key.width * key.scale); if (key.scale < 1) { key.width += (key.scale - 1) * (padding * j); } key.x = keyboard.x + margin + key.width * j; if (j <= keySpec[i].length - 1) { key.x += padding * j; } key.y = keyboard.y + margin + key.height * i; if (i <= keySpec.length - 1) { key.y += padding * i; } keys.push(key); } } }; keyboard.x = spec.x || 0; keyboard.y = spec.y || 0; keyboard.width = spec.width || 640; keyboard.height = spec.height || 480; keyboard.dirty = false; keyboard.alpha = 0.8; keyboard.visible = false; keyboard.update = function () { var i; for (i = 0; i < keys.length; i += 1) { keys[i].update(); } }, keyboard.render = function () { var i; if (keyboard.dirty) { layer.clear(); // Set all the keys dirty for (i = 0; i < keys.length; i += 1) { keys[i].visible = keyboard.visible; keys[i].dirty = true; } if (keyboard.visible) { // Draw background layer.ctx.save(); layer.ctx.globalAlpha = keyboard.alpha; layer.ctx.fillStyle = "white"; layer.ctx.fillRect(keyboard.x, keyboard.y, keyboard.width, keyboard.height); layer.ctx.restore(); } keyboard.dirty = false; } for (i = 0; i < keys.length; i += 1) { keys[i].render(); } }; keyboard.destroy = function () { var i; for (i = 0; i < keys.length; i += 1) { keys[i].destroy(); } }; keyboard.onTap = function (pos) { var i; if (keyboard.visible) { for (i = 0; i < keys.length; i += 1) { if (BLOCKS.toolbox.isPointInsideRect(pos, keys[i])) { controller.simulateKeyDownEvent(keys[i].keyCode); break; } } } keyboard.visible = false; keyboard.dirty = true; }; init(); return keyboard; };
{ "content_hash": "3c88d085ed4789b260e55a3b00e5d631", "timestamp": "", "source": "github", "line_count": 7600, "max_line_length": 460, "avg_line_length": 24.36671052631579, "alnum_prop": 0.6180779428361602, "repo_name": "sojs/BlocksJS", "id": "4989ef50f550a61d59e28b909c2d29c7fa436bcf", "size": "186274", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "build/0.5.27/js/blocksjs-0.5.27.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "31218" }, { "name": "HTML", "bytes": "172625" }, { "name": "JavaScript", "bytes": "7739195" } ], "symlink_target": "" }
package com.oprisnik.semdroid.feature.value; import com.oprisnik.semdroid.app.LocalVariable; import org.junit.Test; import static org.junit.Assert.assertEquals; public class LocalVarPackageFVGTest { @Test public void testFeatureValueGenerator() throws Exception { LocalVarFeatureValueGenerator generator = new LocalVarPackageFVG(); LocalVariable basic = new LocalVariable("hello", "B", null); LocalVariable composite = new LocalVariable("hello1", "Lcom/my/Clazz", null); LocalVariable composite2 = new LocalVariable("hello2", "Lcom/my/package/is/large/ThisIsASpecialClass", null); assertEquals("B", generator.getFeatureValue(basic)); assertEquals("Lcom/my", generator.getFeatureValue(composite)); assertEquals("Lcom/my/package/is/large", generator.getFeatureValue(composite2)); } }
{ "content_hash": "0252c3894e49f7086cefbce3b787d3a6", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 117, "avg_line_length": 34.36, "alnum_prop": 0.7345750873108265, "repo_name": "oprisnik/semdroid", "id": "658b5862b449d66885db6b10a8feabd7ddbc0413", "size": "1459", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "semdroid-plugin-spa/src/test/java/com/oprisnik/semdroid/feature/value/LocalVarPackageFVGTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "11264" }, { "name": "Java", "bytes": "969252" }, { "name": "JavaScript", "bytes": "2576" }, { "name": "Shell", "bytes": "155" }, { "name": "XSLT", "bytes": "17601" } ], "symlink_target": "" }
//----------------------------------------------------------------------- // <copyright file="ScalingCheckBox.cs" company="None"> // Copyright (c) Brandon Wallace and Jesse Calhoun. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace TQVaultAE.GUI { using System.Drawing; using System.Windows.Forms; /// <summary> /// CheckBox class to support scaling of the fonts. /// </summary> public class ScalingCheckBox : CheckBox { /// <summary> /// Override of ScaleControl which supports font scaling. /// </summary> /// <param name="factor">SizeF for the scale factor</param> /// <param name="specified">BoundsSpecified value.</param> protected override void ScaleControl(SizeF factor, BoundsSpecified specified) { this.Font = new Font(this.Font.Name, this.Font.SizeInPoints * factor.Height, this.Font.Style); base.ScaleControl(factor, specified); } } }
{ "content_hash": "eb986324b6ab64bb04690e83f2da0f55", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 97, "avg_line_length": 34.035714285714285, "alnum_prop": 0.5991605456453305, "repo_name": "NorthFury/TQVaultAE", "id": "d23887dcf198b1eddd7b220c7f0fdef6ef7087ac", "size": "955", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/TQVaultAE.GUI/ScalingCheckBox.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "1074949" } ], "symlink_target": "" }
<?php namespace Guzzle\Service\Resource; use Guzzle\Common\Collection; use Guzzle\Service\Description\Parameter; /** * Default model created when commands create service description model responses */ class Model extends Collection { /** @var Parameter Structure of the model */ protected $structure; /** * @param array $data Data contained by the model * @param Parameter $structure The structure of the model */ public function __construct(array $data = array(), Parameter $structure = null) { $this->data = $data; $this->structure = $structure ?: new Parameter(); } /** * Get the structure of the model * * @return Parameter */ public function getStructure() { return $this->structure; } /** * Provides debug information about the model object * * @return string */ public function __toString() { $output = 'Debug output of ' . ($this->structure->getName() ?: ' the model'); $output = str_repeat('=', strlen($output)) . "\n" . $output . "\n" . str_repeat('=', strlen($output)) . "\n\n"; $output .= "Model data\n-----------\n\n"; $output .= "This data can be retrieved from the model object using the get() method of the model " . "(e.g. \$model->get(\$key)) or accessing the model like an associative array (e.g. \$model['key']).\n\n"; $lines = array_slice(explode("\n", trim(print_r($this->toArray(), true))), 2, -1); $output .= implode("\n", $lines) . "\n\n"; $output .= "Model structure\n---------------\n\n"; $output .= "The following JSON document defines how the model was parsed from an HTTP response into the " . "associative array strucure you see above.\n\n"; $output .= ' ' . json_encode($this->structure->toArray()) . "\n\n"; return $output; } }
{ "content_hash": "861f7bb68d5f904e4649bac1a7d4882d", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 119, "avg_line_length": 34.68421052631579, "alnum_prop": 0.5629742033383915, "repo_name": "lekster/md_new", "id": "70f6591d46d988124c85bf88c735d925773fadcb", "size": "1977", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "new/libraries/common/Guzzle/vendor/guzzle/guzzle/src/Guzzle/Service/Resource/Model.php", "mode": "33261", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "20439" }, { "name": "Awk", "bytes": "5471" }, { "name": "Batchfile", "bytes": "176" }, { "name": "C", "bytes": "5632" }, { "name": "C++", "bytes": "65663" }, { "name": "CSS", "bytes": "1567317" }, { "name": "Cucumber", "bytes": "118867" }, { "name": "HTML", "bytes": "4120360" }, { "name": "JavaScript", "bytes": "7316517" }, { "name": "Makefile", "bytes": "190597" }, { "name": "PHP", "bytes": "18464769" }, { "name": "Perl", "bytes": "5146" }, { "name": "PostScript", "bytes": "23931" }, { "name": "Shell", "bytes": "1038311" }, { "name": "TeX", "bytes": "470410" } ], "symlink_target": "" }
namespace Google.Cloud.Dataplex.V1.Snippets { // [START dataplex_v1_generated_DataplexService_ListLakeActions_async_flattened] using Google.Api.Gax; using System; using System.Linq; using System.Threading.Tasks; using gcdv = Google.Cloud.Dataplex.V1; public sealed partial class GeneratedDataplexServiceClientSnippets { /// <summary>Snippet for ListLakeActionsAsync</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public async Task ListLakeActionsAsync() { // Create client DataplexServiceClient dataplexServiceClient = await DataplexServiceClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/lakes/[LAKE]"; // Make the request PagedAsyncEnumerable<ListActionsResponse, gcdv::Action> response = dataplexServiceClient.ListLakeActionsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((gcdv::Action item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListActionsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (gcdv::Action item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<gcdv::Action> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (gcdv::Action item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; } } // [END dataplex_v1_generated_DataplexService_ListLakeActions_async_flattened] }
{ "content_hash": "9756fa7d20283a1abc7801a8b7d8c002", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 130, "avg_line_length": 44.35, "alnum_prop": 0.6102968808718526, "repo_name": "jskeet/gcloud-dotnet", "id": "2ad71c6ea1046f1875cc2625cf5ce93650d8a0a4", "size": "3315", "binary": false, "copies": "1", "ref": "refs/heads/bq-migration", "path": "apis/Google.Cloud.Dataplex.V1/Google.Cloud.Dataplex.V1.GeneratedSnippets/DataplexServiceClient.ListLakeActionsAsyncSnippet.g.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1725" }, { "name": "C#", "bytes": "1829733" } ], "symlink_target": "" }
package ucar.units; /** * Provides support for unit prefixes (e.g. "centi", "c"). * * Instances of this class are immutable. * * @author Steven R. Emmerson */ public abstract class Prefix implements Comparable<Object> { /** * The value of this prefix. * * @serial */ private final double value; /** * The identifier of this prefix. * * @serial */ private final String id; /** * Constructs from an identifier and a value. * * @param id * The prefix identifier (e.g. "milli" or "m"). * @param value * The prefix value (e.g. 1e-3). */ protected Prefix(final String id, final double value) { this.id = id; this.value = value; } /** * Gets the prefix identifier. * * @return The prefix identifier. */ public final String getID() { return id; } /** * Returns the string representation of this prefix. * * @return The string representation of this prefix. */ @Override public final String toString() { return getID(); } /** * Gets the prefix value. * * @return The prefix value. */ public final double getValue() { return value; } /** * Compares this prefix to another. * * @param obj * The other prefix. * @return A negative value, zero, or a positive value depending on whether * this prefix is less than equal to, or greater than * <code>obj</code>. */ public abstract int compareTo(Object obj); /** * Compares this prefix to a string. * * @param string * The string. * @return A negative value, zero, or a positive value depending on whether * this prefix is less than equal to, or greater than the string. */ public abstract int compareTo(String string); /** * Return the length of the prefix identifier. * * @return The length of the prefix identifier. */ public final int length() { return id.length(); } }
{ "content_hash": "5edc558c7d6dcae9a4fc8e271aa8b85a", "timestamp": "", "source": "github", "line_count": 97, "max_line_length": 76, "avg_line_length": 19.90721649484536, "alnum_prop": 0.6183324702226826, "repo_name": "0nirvana0/grib2reader", "id": "3aeea82fad86eac9071fda245769d0e94b3a813f", "size": "3922", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/ucar/units/Prefix.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "490" }, { "name": "Java", "bytes": "2068831" }, { "name": "Python", "bytes": "1798" } ], "symlink_target": "" }
#ifndef _LINUX_SERIAL_H #define _LINUX_SERIAL_H #include <linux/types.h> #ifdef __KERNEL__ #include <asm/page.h> /* * Counters of the input lines (CTS, DSR, RI, CD) interrupts */ struct async_icount { __u32 cts, dsr, rng, dcd, tx, rx; __u32 frame, parity, overrun, brk; __u32 buf_overrun; }; /* * The size of the serial xmit buffer is 1 page, or 4096 bytes */ #define SERIAL_XMIT_SIZE PAGE_SIZE #endif struct serial_struct { int type; int line; unsigned int port; int irq; int flags; int xmit_fifo_size; int custom_divisor; int baud_base; unsigned short close_delay; char io_type; char reserved_char[1]; int hub6; unsigned short closing_wait; /* time to wait before closing */ unsigned short closing_wait2; /* no longer used... */ unsigned char *iomem_base; unsigned short iomem_reg_shift; unsigned int port_high; unsigned long iomap_base; /* cookie passed into ioremap */ }; /* * For the close wait times, 0 means wait forever for serial port to * flush its output. 65535 means don't wait at all. */ #define ASYNC_CLOSING_WAIT_INF 0 #define ASYNC_CLOSING_WAIT_NONE 65535 /* * These are the supported serial types. */ #define PORT_UNKNOWN 0 #define PORT_8250 1 #define PORT_16450 2 #define PORT_16550 3 #define PORT_16550A 4 #define PORT_CIRRUS 5 /* usurped by cyclades.c */ #define PORT_16650 6 #define PORT_16650V2 7 #define PORT_16750 8 #define PORT_STARTECH 9 /* usurped by cyclades.c */ #define PORT_16C950 10 /* Oxford Semiconductor */ #define PORT_16654 11 #define PORT_16850 12 #define PORT_RSA 13 /* RSA-DV II/S card */ #define PORT_MAX 13 #define SERIAL_IO_PORT 0 #define SERIAL_IO_HUB6 1 #define SERIAL_IO_MEM 2 struct serial_uart_config { char *name; int dfl_xmit_fifo_size; int flags; }; #define UART_CLEAR_FIFO 0x01 #define UART_USE_FIFO 0x02 #define UART_STARTECH 0x04 #define UART_NATSEMI 0x08 /* * Definitions for async_struct (and serial_struct) flags field * * Define ASYNCB_* for convenient use with {test,set,clear}_bit. */ #define ASYNCB_HUP_NOTIFY 0 /* Notify getty on hangups and closes * on the callout port */ #define ASYNCB_FOURPORT 1 /* Set OU1, OUT2 per AST Fourport settings */ #define ASYNCB_SAK 2 /* Secure Attention Key (Orange book) */ #define ASYNCB_SPLIT_TERMIOS 3 /* Separate termios for dialin/callout */ #define ASYNCB_SPD_HI 4 /* Use 56000 instead of 38400 bps */ #define ASYNCB_SPD_VHI 5 /* Use 115200 instead of 38400 bps */ #define ASYNCB_SKIP_TEST 6 /* Skip UART test during autoconfiguration */ #define ASYNCB_AUTO_IRQ 7 /* Do automatic IRQ during * autoconfiguration */ #define ASYNCB_SESSION_LOCKOUT 8 /* Lock out cua opens based on session */ #define ASYNCB_PGRP_LOCKOUT 9 /* Lock out cua opens based on pgrp */ #define ASYNCB_CALLOUT_NOHUP 10 /* Don't do hangups for cua device */ #define ASYNCB_HARDPPS_CD 11 /* Call hardpps when CD goes high */ #define ASYNCB_SPD_SHI 12 /* Use 230400 instead of 38400 bps */ #define ASYNCB_LOW_LATENCY 13 /* Request low latency behaviour */ #define ASYNCB_BUGGY_UART 14 /* This is a buggy UART, skip some safety * checks. Note: can be dangerous! */ #define ASYNCB_AUTOPROBE 15 /* Port was autoprobed by PCI or PNP code */ #define ASYNCB_LAST_USER 15 /* Internal flags used only by kernel */ #define ASYNCB_INITIALIZED 31 /* Serial port was initialized */ #define ASYNCB_SUSPENDED 30 /* Serial port is suspended */ #define ASYNCB_NORMAL_ACTIVE 29 /* Normal device is active */ #define ASYNCB_BOOT_AUTOCONF 28 /* Autoconfigure port on bootup */ #define ASYNCB_CLOSING 27 /* Serial port is closing */ #define ASYNCB_CTS_FLOW 26 /* Do CTS flow control */ #define ASYNCB_CHECK_CD 25 /* i.e., CLOCAL */ #define ASYNCB_SHARE_IRQ 24 /* for multifunction cards, no longer used */ #define ASYNCB_CONS_FLOW 23 /* flow control for console */ #define ASYNCB_FIRST_KERNEL 22 #define ASYNC_HUP_NOTIFY (1U << ASYNCB_HUP_NOTIFY) #define ASYNC_SUSPENDED (1U << ASYNCB_SUSPENDED) #define ASYNC_FOURPORT (1U << ASYNCB_FOURPORT) #define ASYNC_SAK (1U << ASYNCB_SAK) #define ASYNC_SPLIT_TERMIOS (1U << ASYNCB_SPLIT_TERMIOS) #define ASYNC_SPD_HI (1U << ASYNCB_SPD_HI) #define ASYNC_SPD_VHI (1U << ASYNCB_SPD_VHI) #define ASYNC_SKIP_TEST (1U << ASYNCB_SKIP_TEST) #define ASYNC_AUTO_IRQ (1U << ASYNCB_AUTO_IRQ) #define ASYNC_SESSION_LOCKOUT (1U << ASYNCB_SESSION_LOCKOUT) #define ASYNC_PGRP_LOCKOUT (1U << ASYNCB_PGRP_LOCKOUT) #define ASYNC_CALLOUT_NOHUP (1U << ASYNCB_CALLOUT_NOHUP) #define ASYNC_HARDPPS_CD (1U << ASYNCB_HARDPPS_CD) #define ASYNC_SPD_SHI (1U << ASYNCB_SPD_SHI) #define ASYNC_LOW_LATENCY (1U << ASYNCB_LOW_LATENCY) #define ASYNC_BUGGY_UART (1U << ASYNCB_BUGGY_UART) #define ASYNC_AUTOPROBE (1U << ASYNCB_AUTOPROBE) #define ASYNC_FLAGS ((1U << (ASYNCB_LAST_USER + 1)) - 1) #define ASYNC_USR_MASK (ASYNC_SPD_MASK|ASYNC_CALLOUT_NOHUP| \ ASYNC_LOW_LATENCY) #define ASYNC_SPD_CUST (ASYNC_SPD_HI|ASYNC_SPD_VHI) #define ASYNC_SPD_WARP (ASYNC_SPD_HI|ASYNC_SPD_SHI) #define ASYNC_SPD_MASK (ASYNC_SPD_HI|ASYNC_SPD_VHI|ASYNC_SPD_SHI) #define ASYNC_INITIALIZED (1U << ASYNCB_INITIALIZED) #define ASYNC_NORMAL_ACTIVE (1U << ASYNCB_NORMAL_ACTIVE) #define ASYNC_BOOT_AUTOCONF (1U << ASYNCB_BOOT_AUTOCONF) #define ASYNC_CLOSING (1U << ASYNCB_CLOSING) #define ASYNC_CTS_FLOW (1U << ASYNCB_CTS_FLOW) #define ASYNC_CHECK_CD (1U << ASYNCB_CHECK_CD) #define ASYNC_SHARE_IRQ (1U << ASYNCB_SHARE_IRQ) #define ASYNC_CONS_FLOW (1U << ASYNCB_CONS_FLOW) #define ASYNC_INTERNAL_FLAGS (~((1U << ASYNCB_FIRST_KERNEL) - 1)) /* * Multiport serial configuration structure --- external structure */ struct serial_multiport_struct { int irq; int port1; unsigned char mask1, match1; int port2; unsigned char mask2, match2; int port3; unsigned char mask3, match3; int port4; unsigned char mask4, match4; int port_monitor; int reserved[32]; }; /* * Serial input interrupt line counters -- external structure * Four lines can interrupt: CTS, DSR, RI, DCD */ struct serial_icounter_struct { int cts, dsr, rng, dcd; int rx, tx; int frame, overrun, parity, brk; int buf_overrun; int reserved[9]; }; /* * Serial interface for controlling RS485 settings on chips with suitable * support. Set with TIOCSRS485 and get with TIOCGRS485 if supported by your * platform. The set function returns the new state, with any unsupported bits * reverted appropriately. */ struct serial_rs485 { __u32 flags; /* RS485 feature flags */ #define SER_RS485_ENABLED (1 << 0) /* If enabled */ #define SER_RS485_RTS_ON_SEND (1 << 1) /* Logical level for RTS pin when sending */ #define SER_RS485_RTS_AFTER_SEND (1 << 2) /* Logical level for RTS pin after sent*/ #define SER_RS485_RX_DURING_TX (1 << 4) __u32 delay_rts_before_send; /* Delay before send (milliseconds) */ __u32 delay_rts_after_send; /* Delay after send (milliseconds) */ __u32 padding[5]; /* Memory is cheap, new structs are a royal PITA .. */ }; #ifdef __KERNEL__ #include <linux/compiler.h> #endif /* __KERNEL__ */ #endif /* _LINUX_SERIAL_H */
{ "content_hash": "e52b58a5f87f052f2e87386ebb9193b4", "timestamp": "", "source": "github", "line_count": 218, "max_line_length": 78, "avg_line_length": 32.30275229357798, "alnum_prop": 0.7043453564328316, "repo_name": "endplay/omniplay", "id": "90e9f981358a90ec25e844a4e3376b1d9c70bf1f", "size": "7217", "binary": false, "copies": "131", "ref": "refs/heads/master", "path": "linux-lts-quantal-3.5.0/include/linux/serial.h", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "ASP", "bytes": "4528" }, { "name": "Assembly", "bytes": "17491433" }, { "name": "Awk", "bytes": "79791" }, { "name": "Batchfile", "bytes": "903" }, { "name": "C", "bytes": "444772157" }, { "name": "C++", "bytes": "10631343" }, { "name": "GDB", "bytes": "17950" }, { "name": "HTML", "bytes": "47935" }, { "name": "Java", "bytes": "2193" }, { "name": "Lex", "bytes": "44513" }, { "name": "M4", "bytes": "9029" }, { "name": "Makefile", "bytes": "1758605" }, { "name": "Objective-C", "bytes": "5278898" }, { "name": "Perl", "bytes": "649746" }, { "name": "Perl 6", "bytes": "1101" }, { "name": "Python", "bytes": "585875" }, { "name": "RPC", "bytes": "97869" }, { "name": "Roff", "bytes": "2522798" }, { "name": "Scilab", "bytes": "21433" }, { "name": "Shell", "bytes": "426172" }, { "name": "TeX", "bytes": "283872" }, { "name": "UnrealScript", "bytes": "6143" }, { "name": "XS", "bytes": "1240" }, { "name": "Yacc", "bytes": "93190" }, { "name": "sed", "bytes": "9202" } ], "symlink_target": "" }
/usr/local/sbin/mosquitto -c /etc/mosquitto/mosquitto.conf -d
{ "content_hash": "59adccab189c5f64d127a58215500aea", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 61, "avg_line_length": 62, "alnum_prop": 0.7741935483870968, "repo_name": "UedaTakeyuki/gc_setups", "id": "d7771fc0e55031535a7861ef266d4abaa8e5bdeb", "size": "174", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "start.mosquitto.sh", "mode": "33261", "license": "mit", "language": [ { "name": "Shell", "bytes": "17242" } ], "symlink_target": "" }
/* * Generated by asn1c-0.9.23 (http://lionet.info/asn1c) * From ASN.1 module "CDR" * found in "../cdr.asn1" * `asn1c -fskeletons-copy -fnative-types` */ #ifndef _SGSNPDPRecord_H_ #define _SGSNPDPRecord_H_ #include <asn_application.h> /* Including external dependencies */ #include "CallEventRecordType.h" #include "NetworkInitiatedPDPContext.h" #include "IMSI.h" #include "IMEI.h" #include "GSNAddress.h" #include "MSNetworkCapability.h" #include "RoutingAreaCode.h" #include "LocationAreaCode.h" #include "CellId.h" #include "ChargingID.h" #include "AccessPointNameNI.h" #include "PDPType.h" #include "TimeStamp.h" #include "CallDuration.h" #include "SGSNChange.h" #include "CauseForRecClosing.h" #include <NativeInteger.h> #include "NodeID.h" #include "LocalSequenceNumber.h" #include "APNSelectionMode.h" #include "AccessPointNameOI.h" #include "MSISDN.h" #include "ChargingCharacteristics.h" #include "SystemType.h" #include "DataVolumeGPRS.h" #include <asn_SEQUENCE_OF.h> #include <constr_SEQUENCE_OF.h> #include <constr_SET.h> #ifdef __cplusplus extern "C" { #endif /* Dependencies */ /* * Method of determining the components presence */ typedef enum SGSNPDPRecord_PR { SGSNPDPRecord_PR_recordType, /* Member recordType is present */ SGSNPDPRecord_PR_networkInitiation, /* Member networkInitiation is present */ SGSNPDPRecord_PR_servedIMSI, /* Member servedIMSI is present */ SGSNPDPRecord_PR_servedIMEI, /* Member servedIMEI is present */ SGSNPDPRecord_PR_sgsnAddress, /* Member sgsnAddress is present */ SGSNPDPRecord_PR_msNetworkCapability, /* Member msNetworkCapability is present */ SGSNPDPRecord_PR_routingArea, /* Member routingArea is present */ SGSNPDPRecord_PR_locationAreaCode, /* Member locationAreaCode is present */ SGSNPDPRecord_PR_cellIdentifier, /* Member cellIdentifier is present */ SGSNPDPRecord_PR_chargingID, /* Member chargingID is present */ SGSNPDPRecord_PR_ggsnAddressUsed, /* Member ggsnAddressUsed is present */ SGSNPDPRecord_PR_accessPointNameNI, /* Member accessPointNameNI is present */ SGSNPDPRecord_PR_pdpType, /* Member pdpType is present */ SGSNPDPRecord_PR_servedPDPAddress, /* Member servedPDPAddress is present */ SGSNPDPRecord_PR_listOfTrafficVolumes, /* Member listOfTrafficVolumes is present */ SGSNPDPRecord_PR_recordOpeningTime, /* Member recordOpeningTime is present */ SGSNPDPRecord_PR_duration, /* Member duration is present */ SGSNPDPRecord_PR_sgsnChange, /* Member sgsnChange is present */ SGSNPDPRecord_PR_causeForRecClosing, /* Member causeForRecClosing is present */ SGSNPDPRecord_PR_diagnostics, /* Member diagnostics is present */ SGSNPDPRecord_PR_recordSequenceNumber, /* Member recordSequenceNumber is present */ SGSNPDPRecord_PR_nodeID, /* Member nodeID is present */ SGSNPDPRecord_PR_recordExtensions, /* Member recordExtensions is present */ SGSNPDPRecord_PR_localSequenceNumber, /* Member localSequenceNumber is present */ SGSNPDPRecord_PR_apnSelectionMode, /* Member apnSelectionMode is present */ SGSNPDPRecord_PR_accessPointNameOI, /* Member accessPointNameOI is present */ SGSNPDPRecord_PR_servedMSISDN, /* Member servedMSISDN is present */ SGSNPDPRecord_PR_chargingCharacteristics, /* Member chargingCharacteristics is present */ SGSNPDPRecord_PR_systemType, /* Member systemType is present */ SGSNPDPRecord_PR_cAMELInformationPDP, /* Member cAMELInformationPDP is present */ SGSNPDPRecord_PR_rNCUnsentDownlinkVolume, /* Member rNCUnsentDownlinkVolume is present */ } SGSNPDPRecord_PR; /* Forward declarations */ struct PDPAddress; struct Diagnostics; struct ManagementExtensions; struct CAMELInformationPDP; struct ChangeOfCharCondition; /* SGSNPDPRecord */ typedef struct SGSNPDPRecord { CallEventRecordType_t recordType; NetworkInitiatedPDPContext_t *networkInitiation /* OPTIONAL */; IMSI_t servedIMSI; IMEI_t *servedIMEI /* OPTIONAL */; GSNAddress_t sgsnAddress; MSNetworkCapability_t *msNetworkCapability /* OPTIONAL */; RoutingAreaCode_t *routingArea /* OPTIONAL */; LocationAreaCode_t *locationAreaCode /* OPTIONAL */; CellId_t *cellIdentifier /* OPTIONAL */; ChargingID_t chargingID; GSNAddress_t ggsnAddressUsed; AccessPointNameNI_t accessPointNameNI; PDPType_t pdpType; struct PDPAddress *servedPDPAddress /* OPTIONAL */; struct SGSNPDPRecord__listOfTrafficVolumes { A_SEQUENCE_OF(struct ChangeOfCharCondition) list; /* Context for parsing across buffer boundaries */ asn_struct_ctx_t _asn_ctx; } listOfTrafficVolumes; TimeStamp_t recordOpeningTime; CallDuration_t duration; SGSNChange_t *sgsnChange /* OPTIONAL */; CauseForRecClosing_t causeForRecClosing; struct Diagnostics *diagnostics /* OPTIONAL */; long *recordSequenceNumber /* OPTIONAL */; NodeID_t *nodeID /* OPTIONAL */; struct ManagementExtensions *recordExtensions /* OPTIONAL */; LocalSequenceNumber_t *localSequenceNumber /* OPTIONAL */; APNSelectionMode_t *apnSelectionMode /* OPTIONAL */; AccessPointNameOI_t accessPointNameOI; MSISDN_t *servedMSISDN /* OPTIONAL */; ChargingCharacteristics_t *chargingCharacteristics /* OPTIONAL */; SystemType_t *systemType /* OPTIONAL */; struct CAMELInformationPDP *cAMELInformationPDP /* OPTIONAL */; DataVolumeGPRS_t *rNCUnsentDownlinkVolume /* OPTIONAL */; /* Presence bitmask: ASN_SET_ISPRESENT(pSGSNPDPRecord, SGSNPDPRecord_PR_x) */ unsigned int _presence_map [((31+(8*sizeof(unsigned int))-1)/(8*sizeof(unsigned int)))]; /* Context for parsing across buffer boundaries */ asn_struct_ctx_t _asn_ctx; } SGSNPDPRecord_t; /* Implementation */ extern asn_TYPE_descriptor_t asn_DEF_SGSNPDPRecord; #ifdef __cplusplus } #endif /* Referred external types */ #include "PDPAddress.h" #include "Diagnostics.h" #include "ManagementExtensions.h" #include "CAMELInformationPDP.h" #include "ChangeOfCharCondition.h" #endif /* _SGSNPDPRecord_H_ */ #include <asn_internal.h>
{ "content_hash": "0c509edfdaeadbf05496c58fe9f079b4", "timestamp": "", "source": "github", "line_count": 156, "max_line_length": 90, "avg_line_length": 37.58974358974359, "alnum_prop": 0.7704638472032742, "repo_name": "vlm/3G-TS-32.015", "id": "792cc852bb31975a92ae8296af1c9e95b1308e0f", "size": "5864", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/SGSNPDPRecord.h", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C", "bytes": "843298" } ], "symlink_target": "" }
I've realized that there is no point in criticizing Ember, because at this point criticisn of Ember isn't new to those not working with Ember, and those who _are_ working with Ember are already stuck. I'll therefore try to keep my comments minimal. I may not do a very good job; I find Ember is extremely frustrating to work with, and I'm going to at least describe how. If you're in the Ember world and it's working for you, that's fine. I don't mean to suggest that it was never a good idea to use Ember. This is just one guy's experience. But I'm _evaluating_ these frameworks, I'm not a cheerleader. --- # Performance Under no circumstance can you claim to care about mobile performance and use Ember. On my Samsung Galaxy S3, there's an automatic 1.1 second penalty between page load and before the user sees anything under the **best case** (with successful cache hits): 600 ms to **parse/execute** ember.min.js and jquery.min.js, and 500 ms for the initialization. You can run these tests yourself: go [here](http://ember.threaditjs.com/depload.html) to see how long it takes for dependencies to load on your machine. Note how the first visit is expensive; subsequent visits will use the cache. And check the console in the [Ember implementation](http://ember.threaditjs.com) to see setup time. (On Android you can put about:debug into the address bar to access the console.) In the worst case scenario, it took 1.7 seconds for my phone to download (4G) and parse the dependencies. I also commonly saw a whole second for initialization time. **Under no circumstance can you use Ember and also claim to care about mobile performance.** --- # Less objective criticisms. In declining order of rigor. ## Bloat Two years ago I wrote: >> But are we ever going to see a release where Ember's codebase _decreases_ by 2000 lines or so? Much to my surprise, [they _kindof_ accomplished this](http://iao.fi/ember-size/) with 2.0.0. But it bears mentioning that: * Most of that was just reversing the spike in June 2015 * At the time of my writing, Ember was only ('only') 36,000 lines of code, and now it's over 50,000. * It's since resumed its steady increase. ## Documentation. It's true that the documentation is kept rigorously tagged with version numbers. Sometimes, however, links for one version are just not valid in the newest version, so whatever question you have that might be resolved by the earlier documentation is left unanswered, and you have to roll the dice and see if following old advice works. Everything is changing, all the time. And it's even worse than the first time I looked at Ember over two years ago, because now even more of the scattered informal information on Ember is out of date. ## Implied code isn't a good idea. You still have to keep the automatically generated controllers/routes/ in your head anyway. It _might as well_ be written explicitly. If anyone is impressed with how short Ember's implementation is compared to the others, they need to think long and hard about how it's possible for that implementation to be the largest and worst performing overall. ## ember-cli ember-cli is the recommended way to manage an Ember app. It wasn't even installing 2.1.0 (released October 4th) until November 10th. (It also defaulted to installing jQuery 1.11.1 instead of 1.11.3, but that's a little less pressing in my mind. Although, in a codebase the size of Ember's, just how confident are you in upgrading to a newer version of jQuery on your own?) (The answer is, you should feel comfortable bringing any problems you have to the Ember community, and maybe you'll even be able to contribute a solution!) (That's how they get you.) As a consequence of moving everything to ember-cli, the basics of declaring a Helper seem to have gotten lost. With ember-cli you just run a command and the file is generated and automatically called in the right way. Since (for reasons discussed elsewhere) I was committed to not using ember-cli, I was left to declare it manually. I got to Ember.Helper.helper (which has shifted [mechanisms](http://www.thegreatcodeadventure.com/writing-a-handlebars-helper-for-ember-js/) at [least](https://www.codehive.io/boards/lI27GF4) three [times](http://stackoverflow.com/questions/28624800/how-to-write-helpers-in-htmlbars)) and couldn't get it to work. Apparently this is where I'm just deficient: I have no idea how anyone thinks Ember's documentation is good, and I love Angular's documentation. Someone very helpfully improved my Ember code to its current state, and of course I was supposed to store what Ember.Helper.helper returned on my application to make it available to the template. That's easy. With Ember, everything is easy... _once you know how to do it_. The documentation is great, _once you know it very well_. But look at those three instructions, above, on creating a helper. Would you have guessed that? I even tried to find how ember-cli's generators declared Helpers internally and couldn't quite do it. So ember-cli actively obstructs how to do common tasks with Ember, trying to push _even more_ into the mystery of its abyssal fold. ## Ember Data is never going to be sensible. I tried with Ember Data, I really did. In my frustration I put the Ember implementation away to work on the Angular one, and guess what? Angular's data services are phenomenal. Ember Data has no excuse at this late stage of its existence. From what I hear, within Ember no one wants to work on Ember Data. # Bottom Line Ember is an active treadmill of code for code's sake without any direction or restraint. And Ember has wasted enough of my time. I included it out of a nod to the 2.0 release and to prove I gave it as fair an evaluation as I can give it. --- Believe it or not, the above was all written prior to the main performance article. ### A few further reflections having completed the [preliminary performance](https://koglerjs.com/verbiage/performance) review. I don't see what value I'm supposed to get from Ember's mass. Mithril is a framework: it is a one-stop solution for everything an SPA needs. I'm not even sure I like Mithril that much, with all the nested m() calls. It just seems to do the least amount of needless handwaving of any solution out there right now. ### Not all bytes of code are created equal. What am I not making use of that a single page application needs? Every bit of code does something for someone. This may be technically true. I simply do not believe that this is so. Some programs are more efficient than others. Computer science is full of these lessons. If you want to convince me Ember has merit, you're going to have to point to something ThreaditJS should be doing that it isn't currently. What could an SPA be getting out of Ember's massive constantly changing codebase that I'm currently not using? What I mean by specifying what an SPA could get out of Ember: something like 'server side rendering' is not an answer I'll accept here. What does Ember, the SPA technology, provide that I'm not utilizing? While I'm thinking about it, though, Mithril could render once on the server so it has something to show while it **regenerates everything entirely on the client** before Ember would even be done _running its minified dependencies_. The most straightforward blunt implementation of server-side rendering with Mithril would be a performance improvement over Ember. --- ## HTMLBars in the client and ember-cli As said elsewhere: this should affect only the initialization time I believe, there's no reason for it to affect the render pipeline. I would be a little curious to see how an ember-cli generated application would perform. However, Vue, Backbone, and Angular all parse their templates in the client. Pre-processing Ember's templates would have to be _incredbly_ efficient in order to take the initialization time to even Angular's 300 milliseconds. It's possible that this is unfair to Ember and Ember suffers from this (in my view) reasonable but admittedly arbitrary restriction more than the other solutions. But is it unfair _enough_? Ember's benefits may be entirely social, which cold heartless milliseconds cannot measure. You might accuse me of coming into this with a bias against kilobytes. Maybe I'm thus biased, coming from a Backbone perspective where things are small and not magically linked, and my inability to see much of the benefit of being on the other side of the fence is a downside. I can certainly understand the concept that Ember has provided a permanence that is of value to a long-term thinking entity like a corporation. But there's also the possibility that the other side of the fence has its own biases, and this should be considered a friendly but pointed ping back from my side of the fence, a side focused on basic performance and simplicity. I'm not trying to be mean. I really enjoy playing with Javascript tech and believe it's certainly possible that Ember has been the right decision for some teams in some circumstances. But revisiting all of this, my conclusion remains the same: **you cannot use Ember and claim to care about mobile performance**.
{ "content_hash": "ec774dca03d4a24c7b385e9ab2e2ea49", "timestamp": "", "source": "github", "line_count": 127, "max_line_length": 366, "avg_line_length": 73.40944881889764, "alnum_prop": 0.7691730129786549, "repo_name": "koglerjs/threaditjs", "id": "1aae3fe41f73e6dd33a11c211276d7c154af6db1", "size": "9337", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/ember/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3136" }, { "name": "HTML", "bytes": "5939" }, { "name": "JavaScript", "bytes": "44212" } ], "symlink_target": "" }
#include "tensorflow/compiler/tf2xla/literal_util.h" #include "tensorflow/compiler/tf2xla/shape_util.h" #include "tensorflow/compiler/tf2xla/type_util.h" #include "tensorflow/compiler/xla/literal.h" #include "tensorflow/core/common_runtime/dma_helper.h" namespace tensorflow { Status HostTensorToBorrowingLiteral(const Tensor& host_tensor, xla::BorrowingLiteral* literal) { xla::Shape xla_shape; TF_RETURN_IF_ERROR(TensorShapeToXLAShape(host_tensor.dtype(), host_tensor.shape(), &xla_shape)); *literal = xla::BorrowingLiteral( static_cast<const char*>(DMAHelper::base(&host_tensor)), xla_shape); return Status::OK(); } xla::StatusOr<xla::Literal> HostTensorToLiteral(const Tensor& host_tensor) { xla::BorrowingLiteral literal; TF_RETURN_IF_ERROR(HostTensorToBorrowingLiteral(host_tensor, &literal)); return literal.Clone(); } Status HostTensorToMutableBorrowingLiteral( Tensor* host_tensor, xla::MutableBorrowingLiteral* literal) { xla::Shape xla_shape; TF_RETURN_IF_ERROR(TensorShapeToXLAShape(host_tensor->dtype(), host_tensor->shape(), &xla_shape)); return HostTensorToMutableBorrowingLiteral(xla_shape, host_tensor, literal); } Status HostTensorToMutableBorrowingLiteral( const xla::Shape& xla_shape, Tensor* host_tensor, xla::MutableBorrowingLiteral* literal) { *literal = xla::MutableBorrowingLiteral( static_cast<const char*>(DMAHelper::base(host_tensor)), xla_shape); return Status::OK(); } Status HostTensorsToBorrowingLiteralTuple(absl::Span<const Tensor> host_tensors, xla::BorrowingLiteral* literal) { std::vector<const char*> buf_ptrs; buf_ptrs.reserve(host_tensors.size()); std::vector<xla::Shape> tensor_shapes(host_tensors.size()); for (int i = 0; i < host_tensors.size(); i++) { // Validate runtime shapes and fail if it doesn't match the contract. const Tensor* tensor = &host_tensors[i]; buf_ptrs.emplace_back(static_cast<const char*>(DMAHelper::base(tensor))); TF_RETURN_IF_ERROR(TensorShapeToXLAShape(tensor->dtype(), tensor->shape(), &tensor_shapes[i])); } *literal = xla::BorrowingLiteral( buf_ptrs, xla::ShapeUtil::MakeTupleShape(tensor_shapes)); return Status::OK(); } Status CopyLiteralToHostTensor(const xla::LiteralSlice& literal, Tensor* host_tensor) { TF_RET_CHECK(xla::ShapeUtil::IsArray(literal.shape()) && xla::ShapeUtil::ElementsIn(literal.shape()) == host_tensor->NumElements()); xla::PrimitiveType primitive_type; TF_RETURN_IF_ERROR( DataTypeToPrimitiveType(host_tensor->dtype(), &primitive_type)); if (literal.shape().element_type() != primitive_type) { return errors::InvalidArgument( "Cannot convert literal of type ", xla::PrimitiveType_Name(literal.shape().element_type()), " to tensor of type ", DataTypeString(host_tensor->dtype())); } size_t total_bytes = host_tensor->TotalBytes(); if (total_bytes > 0) { const void* src_ptr = literal.untyped_data(); void* dst_ptr = DMAHelper::base(host_tensor); memcpy(dst_ptr, src_ptr, total_bytes); } return Status::OK(); } Status LiteralToHostTensor(const xla::LiteralSlice& literal, DataType target_type, Tensor* host_tensor) { TensorShape shape; TF_RETURN_IF_ERROR(XLAShapeToTensorShape(literal.shape(), &shape)); *host_tensor = Tensor(target_type, shape); return CopyLiteralToHostTensor(literal, host_tensor); } } // namespace tensorflow
{ "content_hash": "96089632143930736cd3e53bbf4e3faf", "timestamp": "", "source": "github", "line_count": 96, "max_line_length": 80, "avg_line_length": 38.520833333333336, "alnum_prop": 0.6663061114115738, "repo_name": "brchiu/tensorflow", "id": "67d08290033361f16dfff42b06af9b253e84963a", "size": "4366", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "tensorflow/compiler/tf2xla/literal_util.cc", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "4882" }, { "name": "Batchfile", "bytes": "10132" }, { "name": "C", "bytes": "473950" }, { "name": "C#", "bytes": "8446" }, { "name": "C++", "bytes": "51674376" }, { "name": "CMake", "bytes": "199085" }, { "name": "Dockerfile", "bytes": "36908" }, { "name": "Go", "bytes": "1285435" }, { "name": "HTML", "bytes": "4680032" }, { "name": "Java", "bytes": "875500" }, { "name": "Jupyter Notebook", "bytes": "2623054" }, { "name": "LLVM", "bytes": "6536" }, { "name": "Makefile", "bytes": "63390" }, { "name": "Objective-C", "bytes": "15634" }, { "name": "Objective-C++", "bytes": "101475" }, { "name": "PHP", "bytes": "5191" }, { "name": "Pascal", "bytes": "221" }, { "name": "Perl", "bytes": "7536" }, { "name": "PureBasic", "bytes": "25356" }, { "name": "Python", "bytes": "41718475" }, { "name": "RobotFramework", "bytes": "891" }, { "name": "Ruby", "bytes": "553" }, { "name": "Shell", "bytes": "490100" }, { "name": "Smarty", "bytes": "6976" } ], "symlink_target": "" }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.databoxedge.models; import com.azure.core.annotation.Fluent; import com.azure.core.util.logging.ClientLogger; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; /** Authentication mechanism for IoT devices. */ @Fluent public final class Authentication { @JsonIgnore private final ClientLogger logger = new ClientLogger(Authentication.class); /* * Symmetric key for authentication. */ @JsonProperty(value = "symmetricKey") private SymmetricKey symmetricKey; /** * Get the symmetricKey property: Symmetric key for authentication. * * @return the symmetricKey value. */ public SymmetricKey symmetricKey() { return this.symmetricKey; } /** * Set the symmetricKey property: Symmetric key for authentication. * * @param symmetricKey the symmetricKey value to set. * @return the Authentication object itself. */ public Authentication withSymmetricKey(SymmetricKey symmetricKey) { this.symmetricKey = symmetricKey; return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { if (symmetricKey() != null) { symmetricKey().validate(); } } }
{ "content_hash": "d2d2fa7cef8fa586a65807e1b8dcf347", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 91, "avg_line_length": 29.20754716981132, "alnum_prop": 0.6886304909560723, "repo_name": "Azure/azure-sdk-for-java", "id": "3a30ccd8fd48e50c95d5154b1226ce8efeffa455", "size": "1548", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "sdk/databoxedge/azure-resourcemanager-databoxedge/src/main/java/com/azure/resourcemanager/databoxedge/models/Authentication.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "8762" }, { "name": "Bicep", "bytes": "15055" }, { "name": "CSS", "bytes": "7676" }, { "name": "Dockerfile", "bytes": "2028" }, { "name": "Groovy", "bytes": "3237482" }, { "name": "HTML", "bytes": "42090" }, { "name": "Java", "bytes": "432409546" }, { "name": "JavaScript", "bytes": "36557" }, { "name": "Jupyter Notebook", "bytes": "95868" }, { "name": "PowerShell", "bytes": "737517" }, { "name": "Python", "bytes": "240542" }, { "name": "Scala", "bytes": "1143898" }, { "name": "Shell", "bytes": "18488" }, { "name": "XSLT", "bytes": "755" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>icharate: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / extra-dev</a></li> <li class="active"><a href="">dev / icharate - 8.7.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> icharate <small> 8.7.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-06-09 02:07:39 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-06-09 02:07:39 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-gmp 4 Virtual package relying on a GMP lib system installation coq dev Formal proof management system dune 3.2.0 Fast, portable, and opinionated build system ocaml 4.14.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.14.0 Official release 4.14.0 ocaml-config 2 OCaml Switch Configuration ocaml-options-vanilla 1 Ensure that OCaml is compiled with no special options enabled ocamlfind 1.9.3 A library manager for OCaml zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;[email protected]&quot; homepage: &quot;https://github.com/coq-contribs/icharate&quot; license: &quot;LGPL 2.1&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Icharate&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.7&quot; &amp; &lt; &quot;8.8~&quot;} ] tags: [ &quot;keyword: multimodal categorial grammars&quot; &quot;keyword: syntax/semantics interface&quot; &quot;keyword: higher-order logic&quot; &quot;keyword: meta-linguistics&quot; &quot;category: Computer Science/Formal Languages Theory and Automata&quot; &quot;date: 2003-2006&quot; ] authors: [ &quot;Houda Anoun &lt;[email protected]&gt;&quot; &quot;Pierre Casteran &lt;[email protected]&gt;&quot; ] bug-reports: &quot;https://github.com/coq-contribs/icharate/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/icharate.git&quot; synopsis: &quot;Icharate: A logical Toolkit for Multimodal Categorial Grammars&quot; description: &quot;&quot;&quot; http://www.labri.fr/perso/anoun/Icharate The logical toolkit ICHARATE is built upon a formalization of multimodal categorial grammars in Coq proof assistant. This toolkit aims at facilitating the study of these complicated formalisms by allowing users to build interactively the syntactic derivations of different sentences, compute their semantic interpretations and also prove universal properties of entire classes of grammars using a collection of already established derived rules. Several tactics are defined to ease the interaction with users.&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/icharate/archive/v8.7.0.tar.gz&quot; checksum: &quot;md5=f44792af68f28a3d25a9f462d7c1d176&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-icharate.8.7.0 coq.dev</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is dev). The following dependencies couldn&#39;t be met: - coq-icharate -&gt; coq &lt; 8.8~ -&gt; ocaml &lt; 4.10 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-icharate.8.7.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "47b2d2e2dfa1e785bfbf8b0b62842d19", "timestamp": "", "source": "github", "line_count": 181, "max_line_length": 159, "avg_line_length": 42.85635359116022, "alnum_prop": 0.5686476730694856, "repo_name": "coq-bench/coq-bench.github.io", "id": "2dd17dd94b2b73c1c1ff699de851eb04f3d280ef", "size": "7782", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.14.0-2.0.10/extra-dev/dev/icharate/8.7.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
# Modelos e Camadas Em machine learning, um _modelo_ é uma função com [parâmetros](https://developers.google.com/machine-learning/glossary/#parameter) _"aprendíveis"_ que mapeia uma entrada para uma saída. Os parâmetros ótimos são obtidos treinando o modelo com dados. Um modelo bem treinado fornecerá um mapeamento preciso de uma entrada até a saída desejada. No TensorFlow.js, existem duas maneiras de criar um modelo de machine learning: 1. Usando a API de camadas onde você constrói um modelo usando _camadas_. 2. Usando a API principal com operações de baixo nível como `tf.matMul()`, `tf.add()`, etc. Primeiro, veremos a API de camadas, que é uma API de alto nível para construir modelos. Em seguida, mostraremos como construir o mesmo modelo usando a API Principal. ## Criando modelos com a API de camadas Existem duas formas de criar um modelo usando a API de camadas: Um modelo _sequencial_ e um modelo _funcional_. As próximas duas seções examinam cada tipo mais de perto. ### O modelo sequencial O tipo mais comum de modelo é o modelo <code>[Sequencial](https://js.tensorflow.org/api/0.15.1/#class:Sequential)</code>, que é uma pilha linear de camadas. Você pode criar um modelo `Sequencial` passando uma lista de camadas para a função <code>[sequential()](https://js.tensorflow.org/api/0.15.1/#sequential)</code>: ```js const model = tf.sequential({ layers: [ tf.layers.dense({inputShape: [784], units: 32, activation: 'relu'}), tf.layers.dense({units: 10, activation: 'softmax'}), ] }); ``` Ou através do método `add()`: ```js const model = tf.sequential(); model.add(tf.layers.dense({inputShape: [784], units: 32, activation: 'relu'})); model.add(tf.layers.dense({units: 10, activation: 'softmax'})); ``` > IMPORTANTE: A primeira camada no modelo precisa de um `inputShape`. Certifique-se de excluir o tamanho do lote quando fornecer o `inputShape`. Por exemplo, se você planeja alimentar o modelo com tensores de formato `[B, 784]`, onde `B` pode ser qualquer tamanho de lote, especifique `inputShape` como `[784]` ao criar o modelo. Você pode acessar as camadas do modelo em `model.layers`, a mais especificamente em `model.inputLayers` e `model.outputLayers`. ### O modelo funcional Uma outra forma de criar um `LayersModel` é através da função `tf.model()`. A diferença chave entre `tf.model()` e `tf.sequential()` é que `tf.model()` permite você criar um grafo arbitrário de camadas, desde que elas não tenham ciclos. Aqui está um trecho de código que define o mesmo modelo acima, usando a API `tf.model()`: ```js /* Cria um grafo de camadas arbitrário, conectando-as através do método apply(). */ const input = tf.input({shape: [784]}); const dense1 = tf.layers.dense({units: 32, activation: 'relu'}).apply(input); const dense2 = tf.layers.dense({units: 10, activation: 'softmax'}).apply(dense1); const model = tf.model({inputs: input, outputs: dense2}); ``` Nós chamamos `apply()` em cada camada para conectá-la à saída de outra camada. O resultado de `apply()` nesse caso é um `SymbolicTensor`, que age como um `Tensor`, mas sem valores concretos. Perceba que, diferente do modelo sequencial, nós criamos um `SymbolicTensor` através de `tf.input()` em vez de fornecer um `inputShape` para a primeira camada. `apply()` também pode fornecer um `Tensor` concreto, se você passar um `Tensor` concreto para ela: ```js const t = tf.tensor([-2, 1, 0, 5]); const o = tf.layers.activation({activation: 'relu'}).apply(t); o.print(); // [0, 1, 0, 5] ``` Isso pode ser útil ao testar camadas de forma isolada e ver sua saída. Assim como em um modelo sequencial, você pode acessar as camadas de um modelo através de `model.layers`, e mais especificamente `model.inputLayers` e `model.outputLayers`. ## Validação O modelo sequencial e o modelo funcional são instâncias da classe `LayersModel`. Um dos maiores benefícios de trabalhar com uma `LayersModel` é a validação: obriga a especificar o formato da entrada e o utilizará posteriormente para validar sua entrada. A `LayersModel` também faz inferência automática do formato à medida que os dados fluem pelas camadas. O conhecimento prévio do formato permite que o modelo crie automaticamente seu parâmetros e pode informar se duas camadas consecutivas não são compatíveis entre si. ## Resumo do modelo Chame `model.summary` para imprimir um resumo útil do modelo, que inclue: * Nome e tipo de todas as camadas no modelo. * Formato da saída para cada camada. * Número de pesos de cada camada. * Se o modelo tem topologia geral (discutida abaixo), as entradas que cada camada recebe. * O número total de parâmetros aprendíveis e não aprendíveis do modelo. Para o modelo que definimos acima, nós obtemos a seguinte saída no console: <table> <tr> <td>Layer (type) </td> <td>Output shape </td> <td>Param # </td> </tr> <tr> <td>dense_Dense1 (Dense) </td> <td>[null,32] </td> <td>25120 </td> </tr> <tr> <td>dense_Dense2 (Dense) </td> <td>[null,10] </td> <td>330 </td> </tr> <tr> <td colspan="3" >Total params: 25450<br/>Trainable params: 25450<br/> Non-trainable params: 0 </td> </tr> </table> Observe os valores `null` nos formatos da saída: um lembrete de que o modelo espera que a entrada tenha um tamanho do lote como a dimensão mais externa, que neste caso pode ser flexível devido ao valor `null`. ## Serialização Um dos maiores benefícios de usar uma `LayersModel` sobre a API de baixo nível é a capacidade de salvar e carregar um modelo. Uma `LayersModel` sabe sobre: * A arquitetura do modelo, permitindo recriar o modelo. * Os pesos do modelo. * A configuração de treinamento (função de perda, otimizador, métricas). * O estado do otimizador, permitindo que você retome o treinamento. Salvar ou carregar um modelo é apenas 1 linha de código: ```js const saveResult = await model.save('localstorage://my-model-1'); const model = await tf.loadLayersModel('localstorage://my-model-1'); ``` O exemplo acima salva o modelo no local storage do navegador. Veja a <code>[documentação de model.save()](https://js.tensorflow.org/api/latest/#tf.Model.save)</code> e o guia de [salvar e carregar](save_load.md) para saber como salvar em diferentes mídias (Por exemplo, armazenamento de arquivos, IndexedDB, acionar o download de um navegador, etc.) ## Camadas personalizadas Camadas são os blocos de construção de um modelo. Se o seu modelo estiver fazendo um cálculo personalizado, você pode definir uma camada personalizada, que interage bem com o resto das camadas. Abaixo, nós definimos uma camada personalizada que calcula a soma dos quadrados: ```js class SquaredSumLayer extends tf.layers.Layer { constructor() { super({}); } // Nesse caso, a saída é um escalar. computeOutputShape(inputShape) { return []; } // call() é onde fazemos o cálculo. call(input, kwargs) { return input.square().sum();} // Todas as camadas precisam de um nome único. getClassName() { return 'SquaredSum'; } } ``` Para testar isso, podemos chamar o método `apply()` com um tensor concreto: ```js const t = tf.tensor([-2, 1, 0, 5]); const o = new SquaredSumLayer().apply(t); o.print(); // imprime 30 ``` > IMPORTANTE: Se você adicionar uma camada personalizada, você perde a capacidade de serializar o modelo. ## Criando modelos com a API principal No início deste guia, mencionamos que há duas maneiras de criar um modelo de machine learning no TensorFlow.js. A regra geral é sempre tentar usar a API de camadas primeiro, pois ela é modelada em cima da bem adotada API Keras que segue as [melhores práticas e reduz carga cognitiva](https://keras.io/why-use-keras/). A API de camadas também oferece várias soluções prontas para uso, como inicialização de peso, serialização de modelo, treinamento de monitoramento, portabilidade e verificação de segurança. Você pode usar a API principal sempre que: * Você precisa do máximo de flexibilidade ou controle. * Você não precisa de serialização ou pode implementar sua própria lógica de serialização. Os modelos na API principal são apenas funções que pegam um ou mais `Tensors` e retornam um `Tensor`. O mesmo modelo descrito acima, usando a API principal, se parece com isso: ```js // Os pesos e viéses para as duas camadas densas. const w1 = tf.variable(tf.randomNormal([784, 32])); const b1 = tf.variable(tf.randomNormal([32])); const w2 = tf.variable(tf.randomNormal([32, 10])); const b2 = tf.variable(tf.randomNormal([10])); function model(x) { return x.matMul(w1).add(b1).relu().matMul(w2).add(b2).softmax(); } ``` Observe que na API principal nós somos responsáveis por criar e inicializar os pesos do modelo. Todos os pesos são apoiados por uma `Variable`, que sinaliza ao TensorFlow.js que estes tensores são aprendíveis. Você pode criar uma `Variable` usando [tf.variable()](https://js.tensorflow.org/api/latest/#variable) e passando um `Tensor` existente. Neste guia, você se familiarizou com as diferentes maneiras de criar um modelo usando as camadas e a API principal. A seguir, consulte o guia [Treinando Modelos](train_models.md) para saber como treinar um modelo.
{ "content_hash": "33ea56ac9a12e9e24b21ef1138c01f7a", "timestamp": "", "source": "github", "line_count": 222, "max_line_length": 521, "avg_line_length": 41.265765765765764, "alnum_prop": 0.7357275406614998, "repo_name": "tensorflow/docs-l10n", "id": "ebf95ddfade133e92d2208845ec3086ab281c0f9", "size": "9318", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "site/pt-br/js/guide/models_and_layers.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Jupyter Notebook", "bytes": "256924604" }, { "name": "Shell", "bytes": "17783" } ], "symlink_target": "" }
<?php /** * File implementation of \Corelib\Config\ConfigDAOInterface * * @author Patrick Forget <patforg at geekpad.ca> */ namespace Corelib\Config\Data; /** * File implementation of \Corelib\Config\Data\ConfigDAOInterface * * @author Patrick Forget <patforg at geekpad.ca> */ class ConfigDAOFile extends \Corelib\Data\AccessFile implements ConfigDAOInterface { /** * @var string */ private $env = ''; /** * class constructor * * @author Patrick Forget <patforg at geekpad.ca> */ public function __construct(\Zend\Filter\FilterInterface $keyToFileFilter, $env) { parent::__construct($keyToFileFilter); $this->env = strtolower($env); } // __construct() /** * @author Patrick Forget <patforg at geekpad.ca> */ public function search($condition = null, $options = array()) { return new \Corelib\Config\Model\ConfigCollection(); } // search() /** * @author Patrick Forget <patforg at geekpad.ca> */ public function getElementById($id, $options = array()) { $env = (isset($options['env']) ? strtolower($options['env']) : ''); $loadKey = (strlen($env) > 0 ? "{$id}.{$env}" : $id); $values = $this->commonLoad($loadKey); return new \Corelib\Config\Model\ConfigBO(array( 'id' => $id, 'env' => $env, 'values' => &$values )); } // getElementById() /** * @author Patrick Forget <patforg at geekpad.ca> */ public function getElementValuesById($id, $options = array()) { $env = (isset($options['env']) ? strtolower($options['env']) : ''); $loadKey = (strlen($env) > 0 ? "{$id}.{$env}" : $id); return $this->commonLoad($loadKey); } // getElementById() /** * @author Patrick Forget <patforg at geekpad.ca> */ public function getElementEnvValuesById($id, $options = array()) { return $this->commonLoad("{$id}.{$this->env}"); } // getElementById() } // \Corelib\Config\ConfigDAOFile class
{ "content_hash": "571f8d3321dc251a9a34d6384b68db4d", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 86, "avg_line_length": 27.350649350649352, "alnum_prop": 0.5721747388414055, "repo_name": "corelibphp/core", "id": "a56533f14e775ac1b98db934562bd03df06f557f", "size": "2106", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Corelib/Config/Data/ConfigDAOFile.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "102526" } ], "symlink_target": "" }
package io.reactivex.internal.operators.flowable; import static org.junit.Assert.*; import java.util.concurrent.*; import java.util.concurrent.atomic.*; import io.reactivex.annotations.NonNull; import org.junit.*; import org.reactivestreams.*; import io.reactivex.*; import io.reactivex.Scheduler.Worker; import io.reactivex.disposables.Disposable; import io.reactivex.internal.functions.Functions; import io.reactivex.internal.operators.flowable.FlowableSubscribeOn.SubscribeOnSubscriber; import io.reactivex.internal.subscriptions.BooleanSubscription; import io.reactivex.schedulers.*; import io.reactivex.subscribers.*; public class FlowableSubscribeOnTest { @Test(timeout = 2000) public void testIssue813() throws InterruptedException { // https://github.com/ReactiveX/RxJava/issues/813 final CountDownLatch scheduled = new CountDownLatch(1); final CountDownLatch latch = new CountDownLatch(1); final CountDownLatch doneLatch = new CountDownLatch(1); TestSubscriber<Integer> observer = new TestSubscriber<Integer>(); Flowable .unsafeCreate(new Publisher<Integer>() { @Override public void subscribe( final Subscriber<? super Integer> subscriber) { subscriber.onSubscribe(new BooleanSubscription()); scheduled.countDown(); try { try { latch.await(); } catch (InterruptedException e) { // this means we were unsubscribed (Scheduler shut down and interrupts) // ... but we'll pretend we are like many Flowables that ignore interrupts } subscriber.onComplete(); } catch (Throwable e) { subscriber.onError(e); } finally { doneLatch.countDown(); } } }).subscribeOn(Schedulers.computation()).subscribe(observer); // wait for scheduling scheduled.await(); // trigger unsubscribe observer.dispose(); latch.countDown(); doneLatch.await(); observer.assertNoErrors(); observer.assertComplete(); } @Test @Ignore("Publisher.subscribe can't throw") public void testThrownErrorHandling() { TestSubscriber<String> ts = new TestSubscriber<String>(); Flowable.unsafeCreate(new Publisher<String>() { @Override public void subscribe(Subscriber<? super String> s) { throw new RuntimeException("fail"); } }).subscribeOn(Schedulers.computation()).subscribe(ts); ts.awaitTerminalEvent(1000, TimeUnit.MILLISECONDS); ts.assertTerminated(); } @Test public void testOnError() { TestSubscriber<String> ts = new TestSubscriber<String>(); Flowable.unsafeCreate(new Publisher<String>() { @Override public void subscribe(Subscriber<? super String> s) { s.onSubscribe(new BooleanSubscription()); s.onError(new RuntimeException("fail")); } }).subscribeOn(Schedulers.computation()).subscribe(ts); ts.awaitTerminalEvent(1000, TimeUnit.MILLISECONDS); ts.assertTerminated(); } public static class SlowScheduler extends Scheduler { final Scheduler actual; final long delay; final TimeUnit unit; public SlowScheduler() { this(Schedulers.computation(), 2, TimeUnit.SECONDS); } public SlowScheduler(Scheduler actual, long delay, TimeUnit unit) { this.actual = actual; this.delay = delay; this.unit = unit; } @NonNull @Override public Worker createWorker() { return new SlowInner(actual.createWorker()); } private final class SlowInner extends Worker { private final Scheduler.Worker actualInner; private SlowInner(Worker actual) { this.actualInner = actual; } @Override public void dispose() { actualInner.dispose(); } @Override public boolean isDisposed() { return actualInner.isDisposed(); } @NonNull @Override public Disposable schedule(@NonNull final Runnable action) { return actualInner.schedule(action, delay, unit); } @NonNull @Override public Disposable schedule(@NonNull final Runnable action, final long delayTime, @NonNull final TimeUnit delayUnit) { TimeUnit common = delayUnit.compareTo(unit) < 0 ? delayUnit : unit; long t = common.convert(delayTime, delayUnit) + common.convert(delay, unit); return actualInner.schedule(action, t, common); } } } @Test(timeout = 5000) public void testUnsubscribeInfiniteStream() throws InterruptedException { TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); final AtomicInteger count = new AtomicInteger(); Flowable.unsafeCreate(new Publisher<Integer>() { @Override public void subscribe(Subscriber<? super Integer> sub) { BooleanSubscription bs = new BooleanSubscription(); sub.onSubscribe(bs); for (int i = 1; !bs.isCancelled(); i++) { count.incrementAndGet(); sub.onNext(i); } } }).subscribeOn(Schedulers.newThread()).take(10).subscribe(ts); ts.awaitTerminalEvent(1000, TimeUnit.MILLISECONDS); ts.dispose(); Thread.sleep(200); // give time for the loop to continue ts.assertValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); assertEquals(10, count.get()); } @Test public void testBackpressureReschedulesCorrectly() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(10); TestSubscriber<Integer> ts = new TestSubscriber<Integer>(new DefaultSubscriber<Integer>() { @Override public void onComplete() { } @Override public void onError(Throwable e) { } @Override public void onNext(Integer t) { latch.countDown(); } }); ts.request(10); Flowable.range(1, 10000000).subscribeOn(Schedulers.newThread()).take(20).subscribe(ts); latch.await(); Thread t = ts.lastThread(); System.out.println("First schedule: " + t); assertTrue(t.getName().startsWith("Rx")); ts.request(10); ts.awaitTerminalEvent(); System.out.println("After reschedule: " + ts.lastThread()); assertEquals(t, ts.lastThread()); } @Test public void testSetProducerSynchronousRequest() { TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); Flowable.just(1, 2, 3).lift(new FlowableOperator<Integer, Integer>() { @Override public Subscriber<? super Integer> apply(final Subscriber<? super Integer> child) { final AtomicLong requested = new AtomicLong(); child.onSubscribe(new Subscription() { @Override public void request(long n) { if (!requested.compareAndSet(0, n)) { child.onError(new RuntimeException("Expected to receive request before onNext but didn't")); } } @Override public void cancel() { } }); Subscriber<Integer> parent = new DefaultSubscriber<Integer>() { @Override public void onComplete() { child.onComplete(); } @Override public void onError(Throwable e) { child.onError(e); } @Override public void onNext(Integer t) { if (requested.compareAndSet(0, -99)) { child.onError(new RuntimeException("Got values before requested")); } } }; return parent; } }).subscribeOn(Schedulers.newThread()).subscribe(ts); ts.awaitTerminalEvent(); ts.assertNoErrors(); } @Test public void cancelBeforeActualSubscribe() { TestScheduler test = new TestScheduler(); TestSubscriber<Integer> ts = Flowable.just(1).hide() .subscribeOn(test).test(Long.MAX_VALUE, true); test.advanceTimeBy(1, TimeUnit.SECONDS); ts .assertSubscribed() .assertNoValues() .assertNotTerminated(); } @Test public void dispose() { TestHelper.checkDisposed(Flowable.just(1).subscribeOn(Schedulers.single())); } @Test public void deferredRequestRace() { for (int i = 0; i < 500; i++) { final TestSubscriber<Integer> ts = new TestSubscriber<Integer>(0L); Worker w = Schedulers.computation().createWorker(); final SubscribeOnSubscriber<Integer> so = new SubscribeOnSubscriber<Integer>(ts, w, Flowable.<Integer>never(), true); ts.onSubscribe(so); final BooleanSubscription bs = new BooleanSubscription(); try { Runnable r1 = new Runnable() { @Override public void run() { so.onSubscribe(bs); } }; Runnable r2 = new Runnable() { @Override public void run() { so.request(1); } }; TestHelper.race(r1, r2); } finally { w.dispose(); } } } @Test public void nonScheduledRequests() { TestSubscriber<Object> ts = Flowable.create(new FlowableOnSubscribe<Object>() { @Override public void subscribe(FlowableEmitter<Object> s) throws Exception { for (int i = 1; i < 1001; i++) { s.onNext(i); Thread.sleep(1); } s.onComplete(); } }, BackpressureStrategy.DROP) .subscribeOn(Schedulers.single()) .observeOn(Schedulers.computation()) .test() .awaitDone(5, TimeUnit.SECONDS) .assertNoErrors() .assertComplete(); int c = ts.valueCount(); assertTrue("" + c, c > Flowable.bufferSize()); } @Test public void scheduledRequests() { Flowable.create(new FlowableOnSubscribe<Object>() { @Override public void subscribe(FlowableEmitter<Object> s) throws Exception { for (int i = 1; i < 1001; i++) { s.onNext(i); Thread.sleep(1); } s.onComplete(); } }, BackpressureStrategy.DROP) .map(Functions.identity()) .subscribeOn(Schedulers.single()) .observeOn(Schedulers.computation()) .test() .awaitDone(5, TimeUnit.SECONDS) .assertValueCount(Flowable.bufferSize()) .assertNoErrors() .assertComplete(); } }
{ "content_hash": "292421ee54743db20f485f82d29e7f00", "timestamp": "", "source": "github", "line_count": 364, "max_line_length": 129, "avg_line_length": 32.3489010989011, "alnum_prop": 0.5470063694267516, "repo_name": "AttwellBrian/RxJava", "id": "c505c7610db3c92c77a37816648678bd4fe14f86", "size": "12379", "binary": false, "copies": "1", "ref": "refs/heads/2.x", "path": "src/test/java/io/reactivex/internal/operators/flowable/FlowableSubscribeOnTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "11138" }, { "name": "Java", "bytes": "12229238" }, { "name": "Shell", "bytes": "1328" } ], "symlink_target": "" }
// Copyright 2022 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. /** * @fileoverview Classes related to telemetry */ import { DiagnosticsParams, RoutineStatus } from '@common/dpsl'; import { DiagnosticsRoutineName, ResponseErrorInfoMessage, } from '@common/message'; import { dpsl } from './fake_dpsl'; import { Routine } from './fake_routine'; /** * Abstract class reprensenting the interface of * service to run diagnostic routines */ export abstract class DiagnosticsService { abstract runRoutine( name: DiagnosticsRoutineName, params?: DiagnosticsParams ): Promise<number>; abstract stopRoutine(id: number): Promise<RoutineStatus>; abstract resumeRoutine(id: number): Promise<RoutineStatus>; abstract getRoutineStatus(id: number): Promise<RoutineStatus>; } const mapRoutineNameToMethod = (name: DiagnosticsRoutineName) => { switch (name) { case DiagnosticsRoutineName.RUN_BATTERY_CAPACITY_ROUTINE: return dpsl.diagnostics.battery.runCapacityRoutine; default: return null; } }; /** * Fake implementation of DiagnosticsService * @extends DiagnosticsService */ export class FakeDiagnosticsService implements DiagnosticsService { private _activeRoutines: { [key: number]: Routine } = {}; private _fetchRoutineById = (id: number) => { if (!(id in this._activeRoutines)) { throw ResponseErrorInfoMessage.InvalidDiagnosticsRoutineId; } return this._activeRoutines[id]; }; runRoutine = async ( name: DiagnosticsRoutineName, params?: DiagnosticsParams ): Promise<number> => { params && console.log('Recieved params', params); const dpslRoutineMethod = mapRoutineNameToMethod(name); if (!dpslRoutineMethod) { throw ResponseErrorInfoMessage.InvalidDiagnosticsRoutineName; } return dpslRoutineMethod().then((routine: Routine) => { this._activeRoutines[routine.id] = routine; return routine.id; }); }; stopRoutine = (id: number): Promise<RoutineStatus> => { const routine = this._fetchRoutineById(id); delete this._activeRoutines[id]; return routine.stop(); }; resumeRoutine = (id: number): Promise<RoutineStatus> => { const routine = this._fetchRoutineById(id); return routine.resume(); }; getRoutineStatus = (id: number): Promise<RoutineStatus> => { const routine = this._fetchRoutineById(id); return routine.getStatus(); }; } export class DiagnosticsServiceProvider { private static instance: DiagnosticsService; // eslint-disable-next-line @typescript-eslint/no-empty-function private constructor() {} public static getDiagnosticsService(): DiagnosticsService { if (!this.instance) { this.instance = new FakeDiagnosticsService(); } return this.instance; } }
{ "content_hash": "7e461dfe71d729e3c7118c0727828f44", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 73, "avg_line_length": 30.157894736842106, "alnum_prop": 0.7137870855148342, "repo_name": "GoogleChromeLabs/cros-sample-telemetry-extension", "id": "45a6e43aeec2c4aab6349b091ebf9dcc305228b2", "size": "2865", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "diagnostics-extension/src/services/diagnostics.ts", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "8713" }, { "name": "HTML", "bytes": "8088" }, { "name": "JavaScript", "bytes": "2110" }, { "name": "Shell", "bytes": "178" }, { "name": "TypeScript", "bytes": "94640" } ], "symlink_target": "" }
/* * * * */ package com.yhy.medicine.mapper; import static org.junit.Assert.assertNull; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ActiveProfiles; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.yhy.core.constants.PROFILES; import com.yhy.medicine.MedicineApplication; import com.yhy.medicine.domain.MedicineMed; /** * 药品管理表Mapper测试. * 禁用事务回滚使用@Rollback(false). * * @author yhy * @version 2016-05-22 * @---------------------------------------------------------------------------------------- * @updated 修改描述. * @updated by yhy * @updated at 2016-05-22 */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = MedicineApplication.class) @ActiveProfiles({ PROFILES.COMM, PROFILES.JUNIT, PROFILES.DEV }) public class MedicineMedMapperTests { @Autowired private MedicineMedMapper medicineMedMapper; @Test public void findById() throws Exception { MedicineMed medicineMed = medicineMedMapper.findById("1"); assertNull(medicineMed); } }
{ "content_hash": "24ad3a55fe091330492df7105e09c0f0", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 92, "avg_line_length": 26.347826086956523, "alnum_prop": 0.7260726072607261, "repo_name": "snxamdf/gdmedicine", "id": "9c823d1fb5bdc45fd3a37ef385e35b234de83690", "size": "1250", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "web-medicine/src/test/java/com/yhy/medicine/mapper/MedicineMedMapperTests.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "256" }, { "name": "CSS", "bytes": "82046" }, { "name": "FreeMarker", "bytes": "43593" }, { "name": "HTML", "bytes": "200034" }, { "name": "Java", "bytes": "553341" }, { "name": "JavaScript", "bytes": "600722" }, { "name": "Shell", "bytes": "111" } ], "symlink_target": "" }
package com.braintreepayments.api; import org.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.IOException; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collection; import java.util.Locale; import static org.junit.Assert.*; @RunWith(Enclosed.class) public class HttpRequestUnitTest { public static class NonParameterizedScenarios { @Test public void getPath_returnsPath() { HttpRequest sut = HttpRequest.newInstance() .path("sample/path"); assertEquals("sample/path", sut.getPath()); } @Test public void getData_returnsData() { HttpRequest sut = HttpRequest.newInstance() .data("sample data"); assertEquals("sample data", new String(sut.getData(), StandardCharsets.UTF_8)); } @Test public void dispose_whenDataIsNull_doesNothing() { HttpRequest sut = HttpRequest.newInstance(); sut.dispose(); assertNull(sut.getData()); } @Test public void dispose_whenDataExists_zeroesOutData() { HttpRequest sut = HttpRequest.newInstance() .data("sample data"); sut.dispose(); byte[] actual = sut.getData(); assertArrayEquals(new byte[actual.length], actual); } @Test public void getMethod_returnsMethod() { HttpRequest sut = HttpRequest.newInstance() .method("GET"); assertEquals("GET", sut.getMethod()); } @Test public void getHeaders_containsADefaultSetOfHeaders() { HttpRequest sut = HttpRequest.newInstance(); assertEquals(2, sut.getHeaders().size()); assertEquals("gzip", sut.getHeaders().get("Accept-Encoding")); assertEquals(Locale.getDefault().getLanguage(), sut.getHeaders().get("Accept-Language")); } @Test public void addHeaders_allowsForMoreHeadersToBeAddedToDefaultSet() { HttpRequest sut = HttpRequest.newInstance() .addHeader("Header-0", "0") .addHeader("Header-1", "1"); assertEquals("0", sut.getHeaders().get("Header-0")); assertEquals("1", sut.getHeaders().get("Header-1")); } @Test public void getURL_whenPathStartsWithHttp_returnsPathWithNoModification() throws MalformedURLException, URISyntaxException { HttpRequest sut = HttpRequest.newInstance() .path("https://anothersite.com/path"); URL expectedURL = new URL("https://anothersite.com/path"); assertEquals(expectedURL, sut.getURL()); } @Test public void constructor_setsConnectTimeoutTo30SecondsByDefault() { HttpRequest sut = HttpRequest.newInstance(); assertEquals(30000, sut.getConnectTimeout()); } @Test public void constructor_setsReadTimeoutTo30SecondsByDefault() { HttpRequest sut = HttpRequest.newInstance(); assertEquals(30000, sut.getReadTimeout()); } @Test public void getURL_throwsMalformedURLExceptionIfBaseURLIsNull() { HttpRequest sut = HttpRequest.newInstance() .baseUrl(null) .path("sample/path"); try { sut.getURL(); fail("should throw an error"); } catch (Exception e) { assertTrue(e instanceof MalformedURLException); } } @Test public void getURL_throwsMalformedURLExceptionIfBaseURLIsEmpty() { HttpRequest sut = HttpRequest.newInstance() .baseUrl("") .path("sample/path"); try { sut.getURL(); fail("should throw an error"); } catch (Exception e) { assertTrue(e instanceof MalformedURLException); } } } @RunWith(Parameterized.class) public static class GetURLScenarios { private final String baseUrl; private final String path; private final URL expectedURL; public GetURLScenarios(String baseUrl, String path, URL expectedURL) { this.baseUrl = baseUrl; this.path = path; this.expectedURL = expectedURL; } @Parameterized.Parameters(name = "Joins baseUrl: {0} and path: {1}") public static Collection<Object[]> urlScenarios() throws IOException { return Arrays.asList(new Object[][]{ {"https://www.example.com", "sample/path?param=1#fragment", new URL("https://www.example.com/sample/path?param=1#fragment")}, {"https://www.example.com/", "sample/path?param=1#fragment", new URL("https://www.example.com/sample/path?param=1#fragment")}, {"https://www.example.com", "/sample/path?param=1#fragment", new URL("https://www.example.com/sample/path?param=1#fragment")}, {"https://www.example.com/", "/sample/path?param=1#fragment", new URL("https://www.example.com/sample/path?param=1#fragment")}, {"https://www.example.com/existing/path", "sample/path?param=1#fragment", new URL("https://www.example.com/existing/path/sample/path?param=1#fragment")}, {"https://www.example.com/existing/path/", "sample/path?param=1#fragment", new URL("https://www.example.com/existing/path/sample/path?param=1#fragment")}, {"https://www.example.com/existing/path", "/sample/path?param=1#fragment", new URL("https://www.example.com/existing/path/sample/path?param=1#fragment")}, {"https://www.example.com/existing/path/", "/sample/path?param=1#fragment", new URL("https://www.example.com/existing/path/sample/path?param=1#fragment")}, {"https://www.example.com:123", "sample/path?param=1#fragment", new URL("https://www.example.com:123/sample/path?param=1#fragment")}, {"https://www.example.com:123/", "sample/path?param=1#fragment", new URL("https://www.example.com:123/sample/path?param=1#fragment")}, {"https://www.example.com:123", "/sample/path?param=1#fragment", new URL("https://www.example.com:123/sample/path?param=1#fragment")}, {"https://www.example.com:123/", "/sample/path?param=1#fragment", new URL("https://www.example.com:123/sample/path?param=1#fragment")}, {"https://www.example.com:123/existing/path", "sample/path?param=1#fragment", new URL("https://www.example.com:123/existing/path/sample/path?param=1#fragment")}, {"https://www.example.com:123/existing/path/", "sample/path?param=1#fragment", new URL("https://www.example.com:123/existing/path/sample/path?param=1#fragment")}, {"https://www.example.com:123/existing/path", "/sample/path?param=1#fragment", new URL("https://www.example.com:123/existing/path/sample/path?param=1#fragment")}, {"https://www.example.com:123/existing/path/", "/sample/path?param=1#fragment", new URL("https://www.example.com:123/existing/path/sample/path?param=1#fragment")}, }); } @Test public void getURL() throws Exception { HttpRequest sut = HttpRequest.newInstance() .baseUrl(baseUrl) .path(path); assertEquals(expectedURL, sut.getURL()); } } }
{ "content_hash": "c7a7042b4479837eddd7d66c9fd9f0ad", "timestamp": "", "source": "github", "line_count": 179, "max_line_length": 183, "avg_line_length": 43.57541899441341, "alnum_prop": 0.6006410256410256, "repo_name": "braintree/braintree_android", "id": "d8a86b273ffcea5c2f855ed4ead451707105e29e", "size": "7800", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SharedUtils/src/test/java/com/braintreepayments/api/HttpRequestUnitTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "2142842" }, { "name": "Kotlin", "bytes": "122659" }, { "name": "Ruby", "bytes": "9177" }, { "name": "Shell", "bytes": "205" } ], "symlink_target": "" }
package org.elasticsearch.index.store.fs; import com.google.common.collect.Sets; import org.apache.lucene.store.*; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.index.settings.IndexSettings; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.index.store.IndexStore; import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.Set; /** */ public class DefaultFsDirectoryService extends FsDirectoryService { /* * We are mmapping docvalues as well as term dictionaries, all other files are served through NIOFS * this provides good random access performance while not creating unnecessary mmaps for files like stored * fields etc. */ private static final Set<String> PRIMARY_EXTENSIONS = Collections.unmodifiableSet(Sets.newHashSet("dvd", "tim")); @Inject public DefaultFsDirectoryService(ShardId shardId, @IndexSettings Settings indexSettings, IndexStore indexStore) { super(shardId, indexSettings, indexStore); } @Override protected Directory newFSDirectory(File location, LockFactory lockFactory) throws IOException { return new FileSwitchDirectory(PRIMARY_EXTENSIONS, new MMapDirectory(location.toPath(), lockFactory), new NIOFSDirectory(location.toPath(), lockFactory), true); } }
{ "content_hash": "84b9ee1af618a81ee2b4ebd640741095", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 168, "avg_line_length": 37.62162162162162, "alnum_prop": 0.7751436781609196, "repo_name": "opendatasoft/elasticsearch", "id": "f81b8c4a0108b5fb08a5276e5c8c5597fb9934e2", "size": "2180", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/org/elasticsearch/index/store/fs/DefaultFsDirectoryService.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "299" }, { "name": "HTML", "bytes": "5724" }, { "name": "Java", "bytes": "25713322" }, { "name": "Perl", "bytes": "6858" }, { "name": "Python", "bytes": "52250" }, { "name": "Ruby", "bytes": "32034" }, { "name": "Shell", "bytes": "31101" } ], "symlink_target": "" }
name: cljs.core/ns-publics see also: --- ## Summary ## Details ## Examples
{ "content_hash": "6c4e686e1494b0245a1d08082d1c1e9c", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 26, "avg_line_length": 8.666666666666666, "alnum_prop": 0.6410256410256411, "repo_name": "cljs/api", "id": "827ef6930e2816bc57f8e089e4f1de4a727e4aef", "size": "82", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "docfiles/cljs.core/ns-publics.md", "mode": "33188", "license": "mit", "language": [ { "name": "Clojure", "bytes": "164565" }, { "name": "JavaScript", "bytes": "400169" } ], "symlink_target": "" }
import _ from 'lodash'; import profileFormSteps from '../../../../app/pages/prescription/profileFormSteps'; /* global chai */ /* global describe */ /* global it */ /* global sinon */ const expect = chai.expect; const values = { phoneNumber: { number: 'goodField', }, mrn: 'goodField', sex: 'goodField', initialSettings: { pumpId: 'goodField', cgmId: 'goodField', }, }; const validateSyncAt = sinon.stub().callsFake((fieldKey, values) => { if (_.get(values, fieldKey) === 'badField') { throw('error'); } }); const schema = { validateSyncAt }; const invalidateValue = fieldPath => _.set({ ...values }, fieldPath, 'badField'); describe('profileFormSteps', function() { it('should export a profileFormSteps function', function() { expect(profileFormSteps).to.be.a('function'); }); it('should include the step label', () => { expect(profileFormSteps().label).to.equal('Complete Patient Profile'); }); it('should include the step subSteps with devices passed to 4th substep', () => { const subSteps = profileFormSteps(schema, 'myDevices', values).subSteps; expect(subSteps).to.be.an('array').and.have.lengthOf(4); _.each(subSteps, (subStep, index) => { expect(subStep.panelContent.type).to.be.a('function'); if (index === 3) expect(subStep.panelContent.props.devices).to.equal('myDevices'); }); }); it('should disable the complete button for any invalid fields within a subStep', () => { const subSteps = profileFormSteps(schema, null, values).subSteps; expect(subSteps[0].disableComplete).to.be.false; expect(subSteps[1].disableComplete).to.be.false; expect(subSteps[2].disableComplete).to.be.false; expect(subSteps[3].disableComplete).to.be.false; expect(profileFormSteps(schema, null, invalidateValue('phoneNumber.number')).subSteps[0].disableComplete).to.be.true; expect(profileFormSteps(schema, null, invalidateValue('mrn')).subSteps[1].disableComplete).to.be.true; expect(profileFormSteps(schema, null, invalidateValue('sex')).subSteps[2].disableComplete).to.be.true; expect(profileFormSteps(schema, null, invalidateValue('initialSettings.pumpId')).subSteps[3].disableComplete).to.be.true; expect(profileFormSteps(schema, null, invalidateValue('initialSettings.cgmId')).subSteps[3].disableComplete).to.be.true; }); it('should not hide the back button for the any subSteps', () => { expect(profileFormSteps().subSteps[0].hideBack).to.be.undefined; expect(profileFormSteps().subSteps[1].hideBack).to.be.undefined; expect(profileFormSteps().subSteps[2].hideBack).to.be.undefined; expect(profileFormSteps().subSteps[3].hideBack).to.be.undefined; }); });
{ "content_hash": "0271e423aac909083a4e7245143b1e84", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 125, "avg_line_length": 36.608108108108105, "alnum_prop": 0.6950904392764858, "repo_name": "tidepool-org/blip", "id": "bb5804982c1062e82bf4ab34e2a29f7b96c09801", "size": "2709", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "test/unit/pages/prescription/profileFormSteps.test.js", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "CSS", "bytes": "2491" }, { "name": "Dockerfile", "bytes": "4339" }, { "name": "EJS", "bytes": "1268" }, { "name": "HTML", "bytes": "53" }, { "name": "JavaScript", "bytes": "3775503" }, { "name": "Less", "bytes": "134183" }, { "name": "Shell", "bytes": "2681" } ], "symlink_target": "" }
<?php namespace ZendTest\View\Assets; use Zend\View\Assets\AssetsRouter; use Zend\View\Assets\AssetsManager; use Zend\View\Assets\Asset; use Zend\ServiceManager\ServiceManager; /** * @group Zend_View */ class AssetsRouterTest extends \PHPUnit_Framework_TestCase { /** * @var AssetsRouter */ protected $router; public function setUp() { $this->router = new AssetsRouter(); $this->router->setAssetsManager(new AssetsManager(new ServiceManager)); } public function testMatch() { $this->assertEquals([ 'collection' => 'foo', 'ns' => 'bar', 'source' => 'css/baz.css', ], $this->router->match('/assets/collection-foo/ns-bar/css/baz.css')); $this->assertEquals([ 'collection' => null, 'ns' => 'bar', 'source' => 'css/baz.css', ], $this->router->match('/assets/ns-bar/css/baz.css')); $this->assertEquals([ 'collection' => 'foo', 'ns' => null, 'source' => 'css/baz.css', ], $this->router->match('/assets/collection-foo/css/baz.css')); $this->assertEquals([ 'collection' => null, 'ns' => null, 'source' => 'css/baz.css', ], $this->router->match('/assets/css/baz.css')); $this->assertNull($this->router->match('/other_path')); } public function testAssemble() { $this->assertEquals( 'http://com.com/css/bar.css', $this->router->assemble(['source' => new Asset\Asset('http://com.com/css/bar.css')]) ); $this->assertEquals( '/css/bar.css', $this->router->assemble(['source' => new Asset\Asset('css/bar.css')]) ); $this->assertEquals( '/assets/ns-foo/css/bar.css', $this->router->assemble(['source' => new Asset\Asset('foo::css/bar.css')]) ); $collection = new Asset\AssetCollection([ 'name' => 'foo', 'assets' => [ 'asset-1' => ['source' => 'css/bar.css'], 'asset-2' => ['source' => 'bar::css/bat.css'], ], ]); $this->assertEquals( '/assets/collection-foo/css/bar.css', $this->router->assemble(['source' => $collection->getAsset('asset-1')]) ); $this->assertEquals( '/assets/collection-foo/ns-bar/css/bat.css', $this->router->assemble(['source' => $collection->getAsset('asset-2')]) ); } }
{ "content_hash": "b2ed232d934f1eacb01ef98e507345d5", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 96, "avg_line_length": 28.857142857142858, "alnum_prop": 0.5003808073115004, "repo_name": "turrsis/zend-view-assets", "id": "cf90dd06e1f2c887c8cb57e19c0ab312bac60f34", "size": "2928", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/AssetsRouterTest.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "55" }, { "name": "PHP", "bytes": "131151" } ], "symlink_target": "" }
var ColorSelector = function(cardId, onSuccess, onFailure) { this.element = $('<div class="color-selector"></div>'); this.element.append(new ColorSelectorButton(cardId, 'red', onSuccess, onFailure).element); this.element.append(new ColorSelectorButton(cardId, 'blue', onSuccess, onFailure).element); this.element.append(new ColorSelectorButton(cardId, 'green', onSuccess, onFailure).element); this.element.append(new ColorSelectorButton(cardId, 'yellow', onSuccess, onFailure).element); }; ColorSelector.prototype.remove = function() { this.element.remove(); }; ColorSelector.prototype.show = function() { if (!this.element.hasClass('color-selector-active')) { this.element.addClass('color-selector-active'); var element = this.element; setTimeout(function() { element.removeClass('color-selector-active'); }, 3000); } };
{ "content_hash": "2cca8f438f8e520480877c8338099d97", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 97, "avg_line_length": 42.857142857142854, "alnum_prop": 0.6955555555555556, "repo_name": "richgieg/runo", "id": "8721e363da61ea53b9f788f87ca9899eb11ef56c", "size": "900", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "frontend-src/js/colorselector.js", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "539" }, { "name": "CSS", "bytes": "9530" }, { "name": "EJS", "bytes": "7588" }, { "name": "JavaScript", "bytes": "21604" }, { "name": "PLpgSQL", "bytes": "740" }, { "name": "Shell", "bytes": "474" }, { "name": "TypeScript", "bytes": "36340" } ], "symlink_target": "" }
http4s is an open source project, and depends on its users to continue to improve. We are thrilled that you are interested in helping! <!-- markdown-toc start - Don't edit this section. Run M-x markdown-toc-generate-toc again --> **Table of Contents** - [Submitting issues](#submitting-issues) - [Submitting pull requests](#submitting-pull-requests) - [Claim an issue](#claim-an-issue) - [Build the project](#build-the-project) - [Testing](#testing) - [Contributing documentation](#contributing-documentation) - [Targeting a branch](#targeting-a-branch) - [Attributions](#attributions) - [Grant of license](#grant-of-license) - [Building the Community](#building-the-community) - [Join the adopters list](#join-the-adopters-list) - [Spread the word](#spread-the-word) - [Code of Conduct](#code-of-conduct) - [Acknowledgements](#acknowledgements) <!-- markdown-toc end --> ## Submitting issues If you notice a bug, have an idea for a feature, or have a question about the code, please don't hesitate to [create a GitHub issue]. Many of the good ideas in http4s were introduced by one user and later implemented by another. ## Submitting pull requests ### Claim an issue If there is already a GitHub issue for the task you are working on, please leave a comment to let people know that you are working on it. If there isn't already an issue and it is a non-trivial task, it's a good idea to create one (and note that you're working on it). This prevents contributors from duplicating effort. ### Build the project First you'll need to checkout a local copy of the code base: ```sh git clone [email protected]:http4s/http4s.git ``` To build http4s you should have [sbt installed]. Run `sbt`, and then use any of the following commands: * `compile`: compile the code * `console`: launch a REPL * `test`: run the tests * `makeSite`: generate the documentation, including scaladoc. * `scalastyle`: run the style-checker on the code. ### Testing - We use Specs2 and Scalacheck for our tests. - Tests go under the `src/test/scala` in the module that is being tested. - Most http4s tests should extend `Http4sSpec`. `Http4sSpec` creates a sensible stack of `Specs2` traits and imports syntax and instances for convenience. - Try to think of properties that should always hold for your code, and let Scalacheck generate your tests for you: ```scala "parses own string rendering to equal value" in { forAll(tokens) { token => fromString(token).map(_.renderString) must be_\/-(token) } } ``` - Some code is hard to write properties for, or the properties echo the implementation. We accept and encourage traditional example-based tests as well. - Code coverage stats are published to [codecov.io]. We don't enforce any arbitrary metrics, but the code coverage reports are helpful in finding where new tests can deliver the most value. ### Contributing documentation Often neglected but always deeply appreciated, documentation is a great way to begin contributing to http4s. The documentation at [http4s.org] is stored alongside the source, in the [docs subproject], where you will find a README that describes how the site is developed. For quick enhancements, most pages on the site have an edit link directly to the GitHub source for quick cleanups. ### Targeting a branch http4s actively maintains three branches: * [master]: the mainline of development; where docs/src/hugo is published from * [release-0.16.x]: the last scalaz-stream based release. Merges to [master]. * [release-0.15.x]: the current production release. Merges to [release-0.16.x]. The guide below helps find the most appropriate branch for your change. My change is... | Branch ----------------------------------------------|------------------- Documentation of existing features | [release-0.15.x] Documentation of unreleased features | [release-0.16.x] Binary compatible with current release | [release-0.15.x] Binary incompatible with current release | [release-0.16.x] Specific to cats or fs2 | [master] Change to docs/src/hugo | [master] Still unsure? Don't worry! Send us that PR, and we'll cherry-pick it to the right place. After v0.16.0, we will simplify to maintaining two branches: the last production release and the current master. ### Attributions If your contribution has been derived from or inspired by other work, please state this in its scaladoc comment and provide proper attribution. When possible, include the original authors' names and a link to the original work. ### Grant of license http4s is licensed under the [Apache License 2.0]. Opening a pull request signifies your consent to license your contributions under the Apache License 2.0. ## Building the Community ### Join the adopters list It's easy to [add yourself as an adopter]. You get free advertising on the [adopters list], and a robust list encourages gives new users the confidence to try http4s and grows the community for all. ### Spread the word We watch [Gitter] and [GitHub issues] closely, but it's a bubble. If you like http4s, a blog post, meetup presentation, or appreciative tweet helps reach new people, some of whom go on to contribute and build a better http4s for you. ### Code of Conduct Discussion around http4s is currently happening on [Gitter] as well as [Github issues]. We hope that our community will be respectful, helpful, and kind. People are expected to follow the [Typelevel Code of Conduct] when discussing http4s on Github, Gitter, or in other venues. If you find yourself embroiled in a situation that becomes heated, or that fails to live up to our expectations, you should disengage and contact one of the [community staff] in private. We hope to avoid letting minor aggressions and misunderstandings escalate into larger problems. If you are being harassed, please contact one of the [community staff] immediately so that we can support you. ## Acknowledgements This document is heavily based on the [Cats contributor's guide]. [Apache License 2.0]: https://github.com/http4s/http4s/blob/master/LICENSE [Cats contributor's guide]: https://github.com/typelevel/cats/blob/master/CONTRIBUTING.md [Github issues]: https://github.com/http4s/http4s/issues [Gitter]: http://gitter.im/http4s/http4s [Typelevel Code of Conduct]: http://typelevel.org/conduct.html [add yourself as an adopter]: https://github.com/http4s/http4s/edit/master/docs/src/hugo/content/adopters.md [adopters list]: http://http4s.org/adopters/ [cats]: https://github.com/http4s/http4s/tree/cats [codecov.io]: https://codecov.io/gh/http4s/http4s [community staff]: http://http4s.org/community/conduct.html#community-staff [create a GitHub issue]: https://github.com/http4s/http4s/issues/new [docs subproject]: https://github.com/http4s/http4s/tree/master/docs [http4s.org]: http://http4s.org/ [issues page]: https://github.com/http4s/http4s/issues [master]: https://github.com/http4s/http4s/tree/master [release-0.15.x]: https://github.com/http4s/http4s/tree/release-0.15.x [release-0.16.x]: https://github.com/http4s/http4s/tree/release-0.16.x [sbt installed]: http://www.scala-sbt.org/0.13/tutorial/Setup.html
{ "content_hash": "ff581bbb6fd66cadba7787482c234689", "timestamp": "", "source": "github", "line_count": 179, "max_line_length": 108, "avg_line_length": 40.70391061452514, "alnum_prop": 0.738127916552292, "repo_name": "ZizhengTai/http4s", "id": "44fc8310a747ead597b67d8984ddea866ad167fc", "size": "7307", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CONTRIBUTING.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "18" }, { "name": "JavaScript", "bytes": "9" }, { "name": "Scala", "bytes": "1465514" }, { "name": "Shell", "bytes": "3023" } ], "symlink_target": "" }
<?php namespace Mrk\Bc; use Illuminate\Support\ServiceProvider; class BcServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Bootstrap the application events. * * @return void */ public function boot() { $this->package('mrk/bc'); } /** * Register the service provider. * * @return void */ public function register() { // } /** * Get the services provided by the provider. * * @return array */ public function provides() { return []; } }
{ "content_hash": "74fa87f4e6f649859df15a8c74be6a7c", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 53, "avg_line_length": 13.409090909090908, "alnum_prop": 0.6237288135593221, "repo_name": "M-R-K-Development/bc-v3-laravel", "id": "ee45e0cc59f36ee6923e2e2a1c553e149bb0eacc", "size": "590", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "workbench/mrk/bc/src/Mrk/Bc/BcServiceProvider.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "356" }, { "name": "CSS", "bytes": "131116" }, { "name": "JavaScript", "bytes": "503" }, { "name": "PHP", "bytes": "91375" } ], "symlink_target": "" }
'use strict'; let axios = require('axios'); export default { create: (data) => { return axios.post('/files', data) .then(function(response) { return response.data; }); }, update: (id, data) => { return axios.put('/files/' + id, data) .then(function(response) { return response.data; }); }, remove: (id) => { return axios.delete('/files/' + id) .then((response) => { return response.data; }); } };
{ "content_hash": "7fa2cf633e235cfed26802162847e261", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 40, "avg_line_length": 19.130434782608695, "alnum_prop": 0.5704545454545454, "repo_name": "zdizzle6717/battle-comm", "id": "1dff37f392e45b1388825188564038c0c40144cb", "size": "440", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/services/FileService.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "155340" }, { "name": "HTML", "bytes": "36351" }, { "name": "JavaScript", "bytes": "1007261" } ], "symlink_target": "" }
create table tab_new ( id number(15) ); comment on table tab_new is 'id1';
{ "content_hash": "e6d02ddd7e0876e87ca7d637cccc03de", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 34, "avg_line_length": 10, "alnum_prop": 0.65, "repo_name": "opitzconsulting/orcas", "id": "24f08ed979c909a8cd1839d103af227779c01228", "size": "80", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "orcas_integrationstest/testspool/tests/test_table_comment/a.sql", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "2107" }, { "name": "Groovy", "bytes": "49636" }, { "name": "Java", "bytes": "1278394" }, { "name": "PLSQL", "bytes": "56568" }, { "name": "Shell", "bytes": "3405" }, { "name": "XSLT", "bytes": "33637" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Chapter 11</title> </head> <body> <p>click me to start event flow</p> <script> // 1 capture phase window.addEventListener('click', function(){console.log(1);},true); // 2 capture phase document.addEventListener('click', function(){console.log(2);},true); // 3 capture phase document.documentElement.addEventListener('click', function(){console.log(3);},true); // 4 capture phase document.body.addEventListener('click', function(){console.log(4);},true); // 5 target phase occurs during capture phase document.querySelector('p').addEventListener('click', function(){console.log(5);},true); // 6 target phase occurs during bubbling phase document.querySelector('p').addEventListener('click',function(){console.log(6);},false); // 7 bubbling phase document.body.addEventListener('click', function(){console.log(7);}, false); // 8 bubbling phase document.documentElement.addEventListener('click', function(){console.log(8);}, false); // 9 bubbling phase document.addEventListener('click', function(){console.log(9);}, false); // 10 bubbling phase window.addEventListener('click', function(){console.log(10);}, false); </script> </body> </html>
{ "content_hash": "80756c9068a49810aa5a32b0fb3fe35f", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 92, "avg_line_length": 27.93617021276596, "alnum_prop": 0.6717440974866717, "repo_name": "cssidy/javascript-practice", "id": "b1b76848fdd77b46468b39e50d46e1f877eb245c", "size": "1313", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "DOM Enlightenment/chapter_11_11.3.html", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "82153" }, { "name": "JavaScript", "bytes": "5015" }, { "name": "Roff", "bytes": "4357" } ], "symlink_target": "" }
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this notice and otherwise comply with the Use Terms. /*--- es5id: 15.2.3.6-4-280 description: > Object.defineProperty - 'O' is an Array, 'name' is generic own data property of 'O', and 'desc' is data descriptor, test updating multiple attribute values of 'name' (15.4.5.1 step 5) includes: [propertyHelper.js] ---*/ var arrObj = []; arrObj.property = 12; // default value of attributes: writable: true, configurable: true, enumerable: true Object.defineProperty(arrObj, "property", { writable: false, enumerable: false, configurable: false }); verifyEqualTo(arrObj, "property", 12); verifyNotWritable(arrObj, "property"); verifyNotEnumerable(arrObj, "property"); verifyNotConfigurable(arrObj, "property");
{ "content_hash": "71bfdf4f6e997a35304b073bf098cf7b", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 106, "avg_line_length": 31, "alnum_prop": 0.7248576850094877, "repo_name": "PiotrDabkowski/Js2Py", "id": "da869b279ada99816a876a836e2da7ac930aebac", "size": "1054", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/test_cases/built-ins/Object/defineProperty/15.2.3.6-4-280.js", "mode": "33261", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "289" }, { "name": "JavaScript", "bytes": "8556970" }, { "name": "Python", "bytes": "4583980" }, { "name": "Shell", "bytes": "457" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>reduction-effects: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.9.1 / reduction-effects - 0.1.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> reduction-effects <small> 0.1.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-10-17 13:17:37 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-10-17 13:17:37 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 2 Virtual package relying on perl coq 8.9.1 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.08.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.08.1 Official release 4.08.1 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.5 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; name: &quot;coq-reduction-effects&quot; version: &quot;0.1.0&quot; synopsis: &quot;A Coq plugin to add reduction side effects to some Coq reduction strategies&quot; maintainer: &quot;Yishuai Li &lt;[email protected]&gt;&quot; authors: &quot;Hugo Herbelin &lt;[email protected]&gt;&quot; license: &quot;LGPL-2.1&quot; homepage: &quot;https://github.com/coq-community/reduction-effects&quot; bug-reports: &quot;https://github.com/coq-community/reduction-effects/issues&quot; depends: [ &quot;coq&quot; { &gt;= &quot;8.7&quot; &lt; &quot;8.9~&quot; } ] build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;-j%{jobs}%&quot; &quot;install&quot;] run-test:[make &quot;-j%{jobs}%&quot; &quot;test&quot;] remove: [make &quot;-j%{jobs}%&quot; &quot;uninstall&quot;] dev-repo: &quot;git+https://github.com/coq-community/reduction-effects&quot; url { src: &quot;https://github.com/coq-community/reduction-effects/archive/v0.1.0.tar.gz&quot; checksum: &quot;md5=20becd7b8910a4f7fefd7dfc24fbc33f&quot; } flags: light-uninstall tags: [ &quot;logpath:ReductionEffect&quot; ] </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-reduction-effects.0.1.0 coq.8.9.1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.9.1). The following dependencies couldn&#39;t be met: - coq-reduction-effects -&gt; coq &lt; 8.9~ -&gt; ocaml &lt; 4.06.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-reduction-effects.0.1.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "cb8d30009de1f551e339a7daf7b0a49f", "timestamp": "", "source": "github", "line_count": 167, "max_line_length": 159, "avg_line_length": 41.461077844311376, "alnum_prop": 0.5413056036972848, "repo_name": "coq-bench/coq-bench.github.io", "id": "5dcdfb65fde32d7c6e1230a2fa3bd3fea41f5fd8", "size": "6949", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.08.1-2.0.5/released/8.9.1/reduction-effects/0.1.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
cask 'font-material-icons' do version '3.0.1' sha256 '722e3b09121b82a3746f3da2ecd3a2db8d7d24153b8433324315695a45f06a90' # github.com/google/material-design-icons was verified as official when first introduced to the cask url "https://github.com/google/material-design-icons/archive/#{version}.zip" appcast 'https://github.com/google/material-design-icons/releases.atom', checkpoint: '1a2afb3d184a8e227aab60ae40443ff253a10eea1276ae475629d121c50bde14' name 'Material Icons' homepage 'http://google.github.io/material-design-icons/' font "material-design-icons-#{version}/iconfont/MaterialIcons-Regular.ttf" end
{ "content_hash": "e9be4bc9bd601447b81f68baac85381b", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 102, "avg_line_length": 49, "alnum_prop": 0.7896389324960753, "repo_name": "guerrero/homebrew-fonts", "id": "efa6342bbb01231532dc6e87dfd43310e3977c0c", "size": "637", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Casks/font-material-icons.rb", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Ruby", "bytes": "536809" }, { "name": "Shell", "bytes": "2394" } ], "symlink_target": "" }
package com.opengamma.util.money; import static org.testng.Assert.assertNotEquals; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.opengamma.util.test.TestGroup; /** * Test CurrencyAmount. */ @Test(groups = TestGroup.UNIT) public class CurrencyAmountTest { private static final Currency CCY1 = Currency.AUD; private static final Currency CCY2 = Currency.CAD; private static final double A1 = 100; private static final double A2 = 200; private static final CurrencyAmount CCY_AMOUNT = CurrencyAmount.of(CCY1, A1); /** * Tests the getCurrency and getAmount methods. */ @Test public void testFixture() { assertEquals(CCY1, CCY_AMOUNT.getCurrency()); assertEquals(A1, CCY_AMOUNT.getAmount(), 0); } //------------------------------------------------------------------------- // factories //------------------------------------------------------------------------- /** * Tests factory construction. */ public void testOfCurrency() { final CurrencyAmount test = CurrencyAmount.of(Currency.USD, A1); assertEquals(Currency.USD, test.getCurrency()); assertEquals(A1, test.getAmount(), 0.0001d); } /** * Tests that the currency cannot be null. */ @Test(expectedExceptions = IllegalArgumentException.class) public void testOfCurrencyNullCurrency() { CurrencyAmount.of((Currency) null, A1); } //------------------------------------------------------------------------- /** * Tests construction from a currency string and amount. */ public void testOfString() { final CurrencyAmount test = CurrencyAmount.of("USD", A1); assertEquals(Currency.USD, test.getCurrency()); assertEquals(A1, test.getAmount(), 0.0001d); } /** * Tests that the currency string cannot be null. */ @Test(expectedExceptions = IllegalArgumentException.class) public void testOfStringNullCurrency() { CurrencyAmount.of((String) null, A1); } //------------------------------------------------------------------------- // parse(String) //------------------------------------------------------------------------- /** * Tests the parsing of a currency amount string. */ @Test public void testParseString() { assertEquals(CurrencyAmount.of(Currency.AUD, 100.001), CurrencyAmount.parse("AUD 100.001")); assertEquals(CurrencyAmount.of(Currency.AUD, 123.3), CurrencyAmount.parse("AUD 123.3")); assertEquals(CCY_AMOUNT, CurrencyAmount.parse(CCY_AMOUNT.toString())); } /** * Provides values that cannot be parsed. * * @return unparseable values */ @DataProvider(name = "badParse") Object[][] dataBadParse() { return new Object[][] { {"AUD"}, {"AUD aa"}, {"123"}, {null}, }; } /** * Tests the behaviour when values cannot be parsed. * * @param input unparseable values */ @Test(dataProvider = "badParse", expectedExceptions = IllegalArgumentException.class) public void testParseStringBad(final String input) { CurrencyAmount.parse(input); } //------------------------------------------------------------------------- /** * Tests that addition of two currency amounts with the same currency. */ public void testPlus() { final CurrencyAmount ccyAmount = CurrencyAmount.of(CCY1, A2); final CurrencyAmount test = CCY_AMOUNT.plus(ccyAmount); assertEquals(CCY1, test.getCurrency()); assertEquals(A1 + A2, test.getAmount()); } /** * Tests that null cannot be added. */ @Test(expectedExceptions = IllegalArgumentException.class) public void testPlusAddNullOther() { CCY_AMOUNT.plus(null); } /** * Tests that the currencies must be the same. */ @Test(expectedExceptions = IllegalArgumentException.class) public void testPlusWrongCurrency() { CCY_AMOUNT.plus(CurrencyAmount.of(CCY2, A2)); } //------------------------------------------------------------------------- /** * Tests multiplication of the amount by a constant. */ public void testMultipliedBy() { final CurrencyAmount test = CCY_AMOUNT.multipliedBy(3.5); assertEquals(CCY1, test.getCurrency()); assertEquals(A1 * 3.5, test.getAmount()); } //------------------------------------------------------------------------- /** * Tests the object methods. */ @Test public void testObject() { CurrencyAmount other = CurrencyAmount.of(CCY1, A1); assertTrue(CCY_AMOUNT.equals(CCY_AMOUNT)); assertTrue(CCY_AMOUNT.equals(other)); assertTrue(other.equals(CCY_AMOUNT)); assertEquals(other.hashCode(), CCY_AMOUNT.hashCode()); other = CurrencyAmount.of(CCY1, A1); assertEquals(other, CCY_AMOUNT); assertEquals(other.hashCode(), CCY_AMOUNT.hashCode()); other = CurrencyAmount.of(CCY2, A1); assertFalse(CCY_AMOUNT.equals(other)); other = CurrencyAmount.of(CCY1, A2); assertFalse(CCY_AMOUNT.equals(other)); } /** * Tests not equal values. */ @Test public void testEqualsRubbish() { assertNotEquals("", CCY_AMOUNT); assertNotEquals(null, CCY_AMOUNT); } /** * Tests the bean. */ @Test public void testBean() { assertEquals(CCY_AMOUNT.metaBean().amount().get(CCY_AMOUNT), A1); assertEquals(CCY_AMOUNT.metaBean().currency().get(CCY_AMOUNT), CCY1); assertEquals(CCY_AMOUNT.property("amount").get(), A1); assertEquals(CCY_AMOUNT.property("currency").get(), CCY1); } }
{ "content_hash": "46b7f8a7ce14c1769871940855937543", "timestamp": "", "source": "github", "line_count": 187, "max_line_length": 96, "avg_line_length": 29.93048128342246, "alnum_prop": 0.6097909594425586, "repo_name": "McLeodMoores/starling", "id": "39db4fb1d91c3c9401536764c0a740a6f15221cf", "size": "5734", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "projects/util/src/test/java/com/opengamma/util/money/CurrencyAmountTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2505" }, { "name": "CSS", "bytes": "213501" }, { "name": "FreeMarker", "bytes": "310184" }, { "name": "GAP", "bytes": "1490" }, { "name": "Groovy", "bytes": "11518" }, { "name": "HTML", "bytes": "318295" }, { "name": "Java", "bytes": "79541905" }, { "name": "JavaScript", "bytes": "1511230" }, { "name": "PLSQL", "bytes": "398" }, { "name": "PLpgSQL", "bytes": "26901" }, { "name": "Shell", "bytes": "11481" }, { "name": "TSQL", "bytes": "604117" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.ApplicationModel; using Windows.ApplicationModel.Activation; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.Storage; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Media.Animation; using Windows.UI.Xaml.Navigation; // The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=234227 namespace Ph.WinRtFileHelper.Sample { /// <summary> /// Provides application-specific behavior to supplement the default Application class. /// </summary> public sealed partial class App : Application { #if WINDOWS_PHONE_APP private TransitionCollection transitions; #endif /// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public App() { this.InitializeComponent(); this.Suspending += this.OnSuspending; InitDemoFiles(); } public static async void InitDemoFiles(bool force = false) { if (force) { StorageFolder demoFolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("DemoFiles", CreationCollisionOption.OpenIfExists); await demoFolder.DeleteAsync(); } if (!(await FileHelper.FolderExistsAsync(Path.Combine(ApplicationData.Current.LocalFolder.Path, "DemoFiles")))) { StorageFolder destinationFolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("DemoFiles", CreationCollisionOption.OpenIfExists); await destinationFolder.CreateFolderAsync("Zip"); await destinationFolder.CreateFolderAsync("Folder 1"); await destinationFolder.CreateFolderAsync("Folder 2"); await destinationFolder.CreateFolderAsync("Folder 3"); StorageFile txtOne = await destinationFolder.CreateFileAsync("1.txt"); await destinationFolder.CreateFileAsync("2.txt"); await destinationFolder.CreateFileAsync("3.txt"); await destinationFolder.CreateFileAsync("4.txt"); await FileHelper.WriteToFileAsync(txtOne, "<file>Content</file>"); } } /// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used when the application is launched to open a specific file, to display /// search results, and so forth. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override void OnLaunched(LaunchActivatedEventArgs e) { Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); // TODO: change this value to a cache size that is appropriate for your application rootFrame.CacheSize = 1; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { // TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { #if WINDOWS_PHONE_APP // Removes the turnstile navigation for startup. if (rootFrame.ContentTransitions != null) { this.transitions = new TransitionCollection(); foreach (var c in rootFrame.ContentTransitions) { this.transitions.Add(c); } } rootFrame.ContentTransitions = null; rootFrame.Navigated += this.RootFrame_FirstNavigated; #endif // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter if (!rootFrame.Navigate(typeof(MainPage), e.Arguments)) { throw new Exception("Failed to create initial page"); } } // Ensure the current window is active Window.Current.Activate(); } #if WINDOWS_PHONE_APP /// <summary> /// Restores the content transitions after the app has launched. /// </summary> /// <param name="sender">The object where the handler is attached.</param> /// <param name="e">Details about the navigation event.</param> private void RootFrame_FirstNavigated(object sender, NavigationEventArgs e) { var rootFrame = sender as Frame; rootFrame.ContentTransitions = this.transitions ?? new TransitionCollection() { new NavigationThemeTransition() }; rootFrame.Navigated -= this.RootFrame_FirstNavigated; } #endif /// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> private void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); // TODO: Save application state and stop any background activity deferral.Complete(); } } }
{ "content_hash": "c8b7b1d862562ae53172d16f53aa8e61", "timestamp": "", "source": "github", "line_count": 158, "max_line_length": 161, "avg_line_length": 40.5253164556962, "alnum_prop": 0.6201780415430267, "repo_name": "phsoftware/WinRtFileHelper", "id": "7ceac48f4a5b571b3b66eb7489765eee8f694759", "size": "6405", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Ph.WinRtFileHelper.Sample/Ph.WinRtFileHelper.Sample.Shared/App.xaml.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "31428" } ], "symlink_target": "" }
""" A utility for guessing which file and line of a local source repo are the best referent for a line in a diffscuss file. Intended mainly for use in editors to facilitate jumping to source from a diffscuss file. """ from collections import namedtuple from optparse import OptionParser import os import re import sys from textwrap import dedent from diffscuss.walker import walk, DIFF, DIFF_HEADER # exit codes for various error conditions NO_GIT_DIR = 2 CANNOT_FIND_CANDIDATES = 3 Candidate = namedtuple('Candidate', 'fname line_num line_text') LocalCandidate = namedtuple('LocalCandidate', 'found_match local_line_num candidate') def _exit(msg, exit_code): print >> sys.stderr, msg sys.exit(exit_code) # used to indicate some default args DEFAULT = '-' def _fil_or_default(fname, default_f): if fname == DEFAULT: return default_f, False else: return open(fname, 'rb'), True def _str_or_default(s, default_s): if s == DEFAULT: return default_s else: return s def _has_git_dir(directory): """ True if @directory exists and contains a '.git' subdir. """ return os.path.isdir(os.path.join(directory, '.git')) def _find_git_repo(starting_dir): """ Starting from @starting_dir, find the lowest directory which represents the top of a git repo (that is, which contains a '.git' subdir). If no such directory is found before walking up to the root directory, return None. """ cur_dir = os.path.abspath(starting_dir) while cur_dir != os.path.dirname(cur_dir): if _has_git_dir(cur_dir): return cur_dir cur_dir = os.path.dirname(cur_dir) return None FNAME_RE = re.compile(r'^(---|\+\+\+) (.*)') REL_FNAME_RE = re.compile(r'^(a|b)/(.*)') def _parse_fname(line): """ Parse the file name out of a git diff @line, stripping the leading a/ or b/ if it's present. """ line = line.strip() fname = FNAME_RE.match(line).group(2) rel_match = REL_FNAME_RE.match(fname) if rel_match: return rel_match.group(2) else: return fname def _maybe_update_fname(item, prefix, cur_fname): """ If @item is a diff header which starts with @prefix, parse and return the file name from it. Otherwise, return cur_fname. """ if item[0] == DIFF_HEADER and item[1].startswith(prefix): return _parse_fname(item[1]) else: return cur_fname def _maybe_update_old_fname(item, cur_old_fname): """ If @item is a diff header which starts with ---, parse and return the file name from it. Otherwise, return cur_fname. """ return _maybe_update_fname(item, '---', cur_old_fname) def _maybe_update_new_fname(item, cur_new_fname): """ If @item is a diff header which starts with +++, parse and return the file name from it. Otherwise, return cur_fname. """ return _maybe_update_fname(item, '+++', cur_new_fname) RANGE_RE = re.compile(r'^@@ -(\d+),\d+ \+(\d+),\d+ @@') def _line_applies(item, old_or_new): """ Return 1 if the line in @item applies in the context of @old_or_new, else 0. A line applies in the case that it's a DIFF line and: - if @old_or_new is 'old', the diff line doesn't begin with + - if @old_or_new is 'new', the diff line doesn't begin with - """ if old_or_new == 'old': exclude = '+' else: exclude = '-' if item[0] == DIFF and not item[1].startswith(exclude): return 1 else: return 0 def _maybe_update_diff_line_num(item, cur_line_num, old_or_new): """ Return the possibly adjusted @cur_line_num, where the adjustment rules are: - bumping it by 1 if @item represents a diff line in the @old_or_new context. - if @item represents a range line in a diff header, parsing out the appropriate line number for the @old_or_new context """ if old_or_new == 'old': group_num = 1 else: group_num = 2 if item[0] == DIFF_HEADER: match = RANGE_RE.match(item[1]) if match: return int(match.group(group_num)) if item[0] == DIFF: return cur_line_num + _line_applies(item, old_or_new) else: return cur_line_num def _maybe_update_old_line_num(item, cur_old_line_num): """ Return @cur_old_line_num, possibly bumped by one if @item is a an old line. """ return _maybe_update_diff_line_num(item, cur_old_line_num, 'old') def _maybe_update_new_line_num(item, cur_new_line_num): """ Return @cur_new_line_num, possibly bumped by one if @item is a a new line. """ return _maybe_update_diff_line_num(item, cur_new_line_num, 'new') def _safe_decr(line_num): """ Return @line_num decremented by 1, if @line_num is non None, else None. """ if line_num is not None: return line_num - 1 def _maybe_update_old_line(item, cur_old_line): """ Return the line from @item if it's an old line, otherwise return @cur_old_line. """ if _line_applies(item, 'old'): return item[1] else: return cur_old_line def _maybe_update_new_line(item, cur_new_line): """ Return the line from @item if it's a new line, otherwise return @cur_new_line. """ if _line_applies(item, 'new'): return item[1] else: return cur_new_line def _find_candidates(input_f, line_number): """ If @line_number is a line number in the diffscuss file in @input_f, return a list of two Candidate tuples: - one for the new version of the source in the diffscuss file - one for the old version of the source in the diffscuss file The new version is always listed first. If line_number ends up being greater than the number of lines in input_f, returns an empty list. """ cur_old_fname = None cur_new_fname = None cur_old_line_num = None cur_new_line_num = None cur_old_line = None cur_new_line = None for (index, item) in enumerate(walk(input_f)): # walk the diffscuss file line by line, maintaing the updated # file names, line numbers, and line texts for both the old # and new versions of the source cur_old_fname = _maybe_update_old_fname(item, cur_old_fname) cur_new_fname = _maybe_update_new_fname(item, cur_new_fname) cur_old_line_num = _maybe_update_old_line_num(item, cur_old_line_num) cur_new_line_num = _maybe_update_new_line_num(item, cur_new_line_num) cur_old_line = _maybe_update_old_line(item, cur_old_line) cur_new_line = _maybe_update_new_line(item, cur_new_line) cur_line_num = index + 1 # once we've walked past the line number in the diffscuss # file, maintaining the file / line number context for both # old and new versions of the source as we went, we have our # candidates for matching source. if cur_line_num >= line_number: return [Candidate(fname=cur_new_fname, line_num=_safe_decr(cur_new_line_num), line_text=cur_new_line), Candidate(fname=cur_old_fname, line_num=_safe_decr(cur_old_line_num), line_text=cur_old_line)] return list() def _candidate_exists(candidate, git_repo): """ Return true if the @candidate.fname is not /dev/null, and exists under git_repo. """ # this is how git diffs represent a file that didn't exist in an # earlier revision if not candidate.fname or candidate.fname == '/dev/null': return False try: with open(os.path.join(git_repo, candidate.fname), 'rb'): return True except IOError: return False def _best_local_candidate(local_candidates, git_repo): """ Given @local_candidates, a list of LocalCandidate named tuples, scraped from a diffscuss file, return the best candidate. The best candidate is: * the earliest candidate in the list where the matching line was found * or the earliest candidate in the list, if none of the matching lines were found """ best_candidate = None for candidate in local_candidates: if best_candidate is None: best_candidate = candidate elif candidate.found_match and not best_candidate.found_match: best_candidate = candidate return best_candidate def _closest_line_num(fil, orig_line_num, orig_line): """ Find the line in @fil that best matches the @orig_line found at @orig_line_num. This is currently done by: - finding all the lines in @fil that, when stripped, match the @orig_line exactly - returning the number the matching line with the smallest absolutely distance from @orig_line_num, in a tuple (True, line_num) - if no matching lines are found, returning (False, @orig_line_num) This works decently for a broad number of cases, but could also be improved for cases in which the @orig_line has subsequently been modified. """ # skip the first char, which is either +, -, or ' ', since # orig_line is a diff line orig_line = orig_line[1:].strip() matching_line_nums = [] for ind, line in enumerate(fil): line = line.strip() if orig_line and orig_line == line: matching_line_nums.append(ind + 1) if not matching_line_nums: return (False, orig_line_num) matching_line_nums = [(abs(line_num - orig_line_num), line_num) for line_num in matching_line_nums] matching_line_nums.sort() return (True, matching_line_nums[0][1]) def _localize_candidate(candidate, git_repo): """ Given @candidate, return a LocalCandidate, which includes the best guess for a local_line_num matching the line_text in @candidate, and whether or not the local line matches the text exactly. """ with open(os.path.join(git_repo, candidate.fname), 'rU') as fil: (found_match, local_line_num) = _closest_line_num(fil, candidate.line_num, candidate.line_text) return LocalCandidate(found_match=found_match, local_line_num=local_line_num, candidate=candidate) def main(args): directory = args.directory input_fname = args.input_file output_fname = args.output_file line_number = args.line_number input_f, close_input = _fil_or_default(input_fname, sys.stdin) output_f, close_output = _fil_or_default(output_fname, sys.stdout) directory = _str_or_default(directory, os.getcwd()) git_repo = _find_git_repo(directory) if git_repo is None: _exit("Cannot find git repo at or above %s" % directory, NO_GIT_DIR) candidates = _find_candidates(input_f, line_number) existing_candidates = [c for c in candidates if _candidate_exists(c, git_repo)] local_candidates = [_localize_candidate(c, git_repo) for c in existing_candidates] best_candidate = _best_local_candidate(local_candidates, git_repo) if not best_candidate: _exit("Cannot find any candidate files.", CANNOT_FIND_CANDIDATES) output_f.write("%s %d" % (os.path.join(git_repo, best_candidate.candidate.fname), best_candidate.local_line_num)) if close_input: input_f.close() if close_output: output_f.close()
{ "content_hash": "65e76325af768548915a6f14e8f2158a", "timestamp": "", "source": "github", "line_count": 406, "max_line_length": 78, "avg_line_length": 29.236453201970445, "alnum_prop": 0.6099410278011794, "repo_name": "tomheon/diffscuss", "id": "001a5109e8e67578979d900e60bccccc36b7a9be", "size": "11870", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "diffscuss/find_local.py", "mode": "33188", "license": "mit", "language": [ { "name": "Emacs Lisp", "bytes": "56631" }, { "name": "Python", "bytes": "135176" }, { "name": "Shell", "bytes": "1117" }, { "name": "Vim script", "bytes": "5454" } ], "symlink_target": "" }
var jsx = require('../../index').jsxTranspile(process.env.COVERAGE); var assert = require('assert'); describe('UnnamedComponent', function() { var UnnamedComponent = require('../UnnamedComponent.jsx'); describe('#render', function () { it('renders with <div>UNNAMED_COMPONENT</div>', function () { jsx.assertRender(UnnamedComponent, {}, '<div>UNNAMED_COMPONENT</div>'); }); }); });
{ "content_hash": "08acea9b808a244a51fb76473009db1e", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 83, "avg_line_length": 35.333333333333336, "alnum_prop": 0.625, "repo_name": "longlho/jsx-test", "id": "257e1db12e75021c4883c5ac25b320161411035d", "size": "436", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "example/test/UnnamedComponent.test.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "22245" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using FastColoredTextBoxNS; namespace SwdPageRecorder.UI { public partial class FullHtmlSourceTabView : UserControl, IView { private FullHtmlSourceTabPresenter presenter; public FullHtmlSourceTabView() { InitializeComponent(); this.presenter = Presenters.PageObjectSourceCodePresenter; presenter.InitWithView(this); txtHtmlPageSource.Language = Language.HTML; } private void btnGetHtmlSource_Click(object sender, EventArgs e) { presenter.DisplayHtmlPageSource(); } internal void FillHtmlCodeBox(string htmlText) { txtHtmlPageSource.Clear(); txtHtmlPageSource.Text = htmlText; } private void txtHtmlPageSource_KeyDown(object sender, KeyEventArgs e) { if (e.Control && e.KeyCode == Keys.A) { txtHtmlPageSource.SelectAll(); } } } }
{ "content_hash": "2ad24710549c14fc04bc757c9fbd9f7f", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 77, "avg_line_length": 25.5, "alnum_prop": 0.6342710997442456, "repo_name": "dzharii/swd-recorder", "id": "82b079a718ade986dad15c7e686956a5e5532423", "size": "1175", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "SwdPageRecorder/SwdPageRecorder.UI/SwdMain/Tabs/FullHtmlSourceTabView.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "5498" }, { "name": "C#", "bytes": "295389" }, { "name": "HTML", "bytes": "23358" }, { "name": "JavaScript", "bytes": "40130" }, { "name": "PowerShell", "bytes": "274" } ], "symlink_target": "" }
/** Tracks Thumbnails **/ [data-display-mode="list"] .track-titlespan { color: white; /* * The font size of this selector * determines the height of the line, * and height+width of the thumb image */ /* font-size: 12px;*/ } [data-display-mode="list"] { counter-reset: oursophone-track-counter; } [data-display-mode="list"] div.track:before { color: white; content: counter(oursophone-track-counter, decimal); counter-increment: oursophone-track-counter; font-size: 0.9em; font-weight: bold; height: 100%; left: -0.3em; position: absolute; text-align: right; top: 0; width: 1.5em; } [data-display-mode="list"] .track { display: block; margin: 0; padding-left: 1.5em; } div.track:last-of-type {/* display:block; float:left; position:relative; width:100%; outline:2px solid red; content: "blah";*/ } [data-display-mode="thumb"] .track-picture, [data-display-mode="thumb"] .track-nopicture { /* * the width of this selector * determines the width *and* height * of the image thumbnail block */ width:100px; } [data-display-mode="thumb"] .track-picture { /* background-color: currentColor; */ /* border:5px solid; */ } [data-display-mode="thumb"] .track-title { /* background-color: rgba(255, 255, 255, 1); */ /* text-shadow:0 0 0 #fff; */ /* font-size: .9em; */ /* line-height: 10px; */ /* color: #000000; */ /* line-height: 100px; */ } /** Vertical volume control **/ .volume-control { margin: 1em; padding: 0; display:inline-block; float:left; -webkit-transform: rotate(-90deg) scale(0.4); -ms-transform: rotate(-90deg) scale(0.4); transform: rotate(-90deg) scale(0.4); -webkit-transform-origin: left bottom; -ms-transform-origin: left bottom; transform-origin: left bottom; z-index: 100000; position: absolute; left: 0; } .volume-control label { -webkit-transform: rotate(-90deg) scale(2); -ms-transform: rotate(-90deg) scale(2); transform: rotate(-90deg) scale(2); /*width:1em; height:1em; line-height:1em;*/ } .volume-control input { -webkit-transform: scale(1, 2); -ms-transform: scale(1, 2); transform: scale(1, 2); } #controls { margin-bottom: 10px; margin-top: 10px; } #controls span { /* use 'em' unit rather than % (relative to width, which is bad as we're on a responsive box) */ border-radius: 0.3em; } [data-action="play"] span:hover { background-color: #ccc; } [data-action="pause"] span:hover { background-color: #ccc; } /** Playlist customizations (desktop only as they rely on mouseover effects) **/ #playlist { background-color: #333; } /* #playlist:hover { background-color: #444; }*/
{ "content_hash": "bb2b7f531894867384d615764271b1f7", "timestamp": "", "source": "github", "line_count": 133, "max_line_length": 98, "avg_line_length": 20.533834586466167, "alnum_prop": 0.6360307579641157, "repo_name": "tobozo/oursophone", "id": "b97bdf6d79737a79227c9bbe48c8c099347f898a", "size": "2731", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "www/css/oursophone.theme.default.css", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "55175" }, { "name": "CoffeeScript", "bytes": "2873" }, { "name": "HTML", "bytes": "6968" }, { "name": "JavaScript", "bytes": "230985" }, { "name": "PHP", "bytes": "3437" }, { "name": "Ruby", "bytes": "1256" }, { "name": "Smarty", "bytes": "5562" } ], "symlink_target": "" }
'use strict'; var parse = require('js-yaml/lib/js-yaml/loader').load , stringify = JSON.stringify; exports.extension = 'yaml'; exports.type = 'json'; exports.compile = function (src) { return { code: stringify(parse(src)) }; };
{ "content_hash": "f0c60c629e16d1f481e460974c1ee908", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 77, "avg_line_length": 25.88888888888889, "alnum_prop": 0.6781115879828327, "repo_name": "medikoo/webmake-yaml", "id": "dbecbafb7dafedc6716fbc5371fad8ac94e7f655", "size": "233", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "index.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "1011" }, { "name": "Makefile", "bytes": "75" } ], "symlink_target": "" }
 #pragma once #include <aws/wafv2/WAFV2_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/wafv2/model/ExcludedRule.h> #include <aws/wafv2/model/ManagedRuleGroupConfig.h> #include <utility> #include <memory> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace WAFV2 { namespace Model { class Statement; /** * <p>A rule statement used to run the rules that are defined in a managed rule * group. To use this, provide the vendor name and the name of the rule group in * this statement. You can retrieve the required names by calling * <a>ListAvailableManagedRuleGroups</a>.</p> <p>You cannot nest a * <code>ManagedRuleGroupStatement</code>, for example for use inside a * <code>NotStatement</code> or <code>OrStatement</code>. It can only be referenced * as a top-level statement within a rule.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/wafv2-2019-07-29/ManagedRuleGroupStatement">AWS * API Reference</a></p> */ class AWS_WAFV2_API ManagedRuleGroupStatement { public: ManagedRuleGroupStatement(); ManagedRuleGroupStatement(Aws::Utils::Json::JsonView jsonValue); ManagedRuleGroupStatement& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>The name of the managed rule group vendor. You use this, along with the rule * group name, to identify the rule group.</p> */ inline const Aws::String& GetVendorName() const{ return m_vendorName; } /** * <p>The name of the managed rule group vendor. You use this, along with the rule * group name, to identify the rule group.</p> */ inline bool VendorNameHasBeenSet() const { return m_vendorNameHasBeenSet; } /** * <p>The name of the managed rule group vendor. You use this, along with the rule * group name, to identify the rule group.</p> */ inline void SetVendorName(const Aws::String& value) { m_vendorNameHasBeenSet = true; m_vendorName = value; } /** * <p>The name of the managed rule group vendor. You use this, along with the rule * group name, to identify the rule group.</p> */ inline void SetVendorName(Aws::String&& value) { m_vendorNameHasBeenSet = true; m_vendorName = std::move(value); } /** * <p>The name of the managed rule group vendor. You use this, along with the rule * group name, to identify the rule group.</p> */ inline void SetVendorName(const char* value) { m_vendorNameHasBeenSet = true; m_vendorName.assign(value); } /** * <p>The name of the managed rule group vendor. You use this, along with the rule * group name, to identify the rule group.</p> */ inline ManagedRuleGroupStatement& WithVendorName(const Aws::String& value) { SetVendorName(value); return *this;} /** * <p>The name of the managed rule group vendor. You use this, along with the rule * group name, to identify the rule group.</p> */ inline ManagedRuleGroupStatement& WithVendorName(Aws::String&& value) { SetVendorName(std::move(value)); return *this;} /** * <p>The name of the managed rule group vendor. You use this, along with the rule * group name, to identify the rule group.</p> */ inline ManagedRuleGroupStatement& WithVendorName(const char* value) { SetVendorName(value); return *this;} /** * <p>The name of the managed rule group. You use this, along with the vendor name, * to identify the rule group.</p> */ inline const Aws::String& GetName() const{ return m_name; } /** * <p>The name of the managed rule group. You use this, along with the vendor name, * to identify the rule group.</p> */ inline bool NameHasBeenSet() const { return m_nameHasBeenSet; } /** * <p>The name of the managed rule group. You use this, along with the vendor name, * to identify the rule group.</p> */ inline void SetName(const Aws::String& value) { m_nameHasBeenSet = true; m_name = value; } /** * <p>The name of the managed rule group. You use this, along with the vendor name, * to identify the rule group.</p> */ inline void SetName(Aws::String&& value) { m_nameHasBeenSet = true; m_name = std::move(value); } /** * <p>The name of the managed rule group. You use this, along with the vendor name, * to identify the rule group.</p> */ inline void SetName(const char* value) { m_nameHasBeenSet = true; m_name.assign(value); } /** * <p>The name of the managed rule group. You use this, along with the vendor name, * to identify the rule group.</p> */ inline ManagedRuleGroupStatement& WithName(const Aws::String& value) { SetName(value); return *this;} /** * <p>The name of the managed rule group. You use this, along with the vendor name, * to identify the rule group.</p> */ inline ManagedRuleGroupStatement& WithName(Aws::String&& value) { SetName(std::move(value)); return *this;} /** * <p>The name of the managed rule group. You use this, along with the vendor name, * to identify the rule group.</p> */ inline ManagedRuleGroupStatement& WithName(const char* value) { SetName(value); return *this;} /** * <p>The version of the managed rule group to use. If you specify this, the * version setting is fixed until you change it. If you don't specify this, WAF * uses the vendor's default version, and then keeps the version at the vendor's * default when the vendor updates the managed rule group settings. </p> */ inline const Aws::String& GetVersion() const{ return m_version; } /** * <p>The version of the managed rule group to use. If you specify this, the * version setting is fixed until you change it. If you don't specify this, WAF * uses the vendor's default version, and then keeps the version at the vendor's * default when the vendor updates the managed rule group settings. </p> */ inline bool VersionHasBeenSet() const { return m_versionHasBeenSet; } /** * <p>The version of the managed rule group to use. If you specify this, the * version setting is fixed until you change it. If you don't specify this, WAF * uses the vendor's default version, and then keeps the version at the vendor's * default when the vendor updates the managed rule group settings. </p> */ inline void SetVersion(const Aws::String& value) { m_versionHasBeenSet = true; m_version = value; } /** * <p>The version of the managed rule group to use. If you specify this, the * version setting is fixed until you change it. If you don't specify this, WAF * uses the vendor's default version, and then keeps the version at the vendor's * default when the vendor updates the managed rule group settings. </p> */ inline void SetVersion(Aws::String&& value) { m_versionHasBeenSet = true; m_version = std::move(value); } /** * <p>The version of the managed rule group to use. If you specify this, the * version setting is fixed until you change it. If you don't specify this, WAF * uses the vendor's default version, and then keeps the version at the vendor's * default when the vendor updates the managed rule group settings. </p> */ inline void SetVersion(const char* value) { m_versionHasBeenSet = true; m_version.assign(value); } /** * <p>The version of the managed rule group to use. If you specify this, the * version setting is fixed until you change it. If you don't specify this, WAF * uses the vendor's default version, and then keeps the version at the vendor's * default when the vendor updates the managed rule group settings. </p> */ inline ManagedRuleGroupStatement& WithVersion(const Aws::String& value) { SetVersion(value); return *this;} /** * <p>The version of the managed rule group to use. If you specify this, the * version setting is fixed until you change it. If you don't specify this, WAF * uses the vendor's default version, and then keeps the version at the vendor's * default when the vendor updates the managed rule group settings. </p> */ inline ManagedRuleGroupStatement& WithVersion(Aws::String&& value) { SetVersion(std::move(value)); return *this;} /** * <p>The version of the managed rule group to use. If you specify this, the * version setting is fixed until you change it. If you don't specify this, WAF * uses the vendor's default version, and then keeps the version at the vendor's * default when the vendor updates the managed rule group settings. </p> */ inline ManagedRuleGroupStatement& WithVersion(const char* value) { SetVersion(value); return *this;} /** * <p>The rules in the referenced rule group whose actions are set to * <code>Count</code>. When you exclude a rule, WAF evaluates it exactly as it * would if the rule action setting were <code>Count</code>. This is a useful * option for testing the rules in a rule group without modifying how they handle * your web traffic.</p> */ inline const Aws::Vector<ExcludedRule>& GetExcludedRules() const{ return m_excludedRules; } /** * <p>The rules in the referenced rule group whose actions are set to * <code>Count</code>. When you exclude a rule, WAF evaluates it exactly as it * would if the rule action setting were <code>Count</code>. This is a useful * option for testing the rules in a rule group without modifying how they handle * your web traffic.</p> */ inline bool ExcludedRulesHasBeenSet() const { return m_excludedRulesHasBeenSet; } /** * <p>The rules in the referenced rule group whose actions are set to * <code>Count</code>. When you exclude a rule, WAF evaluates it exactly as it * would if the rule action setting were <code>Count</code>. This is a useful * option for testing the rules in a rule group without modifying how they handle * your web traffic.</p> */ inline void SetExcludedRules(const Aws::Vector<ExcludedRule>& value) { m_excludedRulesHasBeenSet = true; m_excludedRules = value; } /** * <p>The rules in the referenced rule group whose actions are set to * <code>Count</code>. When you exclude a rule, WAF evaluates it exactly as it * would if the rule action setting were <code>Count</code>. This is a useful * option for testing the rules in a rule group without modifying how they handle * your web traffic.</p> */ inline void SetExcludedRules(Aws::Vector<ExcludedRule>&& value) { m_excludedRulesHasBeenSet = true; m_excludedRules = std::move(value); } /** * <p>The rules in the referenced rule group whose actions are set to * <code>Count</code>. When you exclude a rule, WAF evaluates it exactly as it * would if the rule action setting were <code>Count</code>. This is a useful * option for testing the rules in a rule group without modifying how they handle * your web traffic.</p> */ inline ManagedRuleGroupStatement& WithExcludedRules(const Aws::Vector<ExcludedRule>& value) { SetExcludedRules(value); return *this;} /** * <p>The rules in the referenced rule group whose actions are set to * <code>Count</code>. When you exclude a rule, WAF evaluates it exactly as it * would if the rule action setting were <code>Count</code>. This is a useful * option for testing the rules in a rule group without modifying how they handle * your web traffic.</p> */ inline ManagedRuleGroupStatement& WithExcludedRules(Aws::Vector<ExcludedRule>&& value) { SetExcludedRules(std::move(value)); return *this;} /** * <p>The rules in the referenced rule group whose actions are set to * <code>Count</code>. When you exclude a rule, WAF evaluates it exactly as it * would if the rule action setting were <code>Count</code>. This is a useful * option for testing the rules in a rule group without modifying how they handle * your web traffic.</p> */ inline ManagedRuleGroupStatement& AddExcludedRules(const ExcludedRule& value) { m_excludedRulesHasBeenSet = true; m_excludedRules.push_back(value); return *this; } /** * <p>The rules in the referenced rule group whose actions are set to * <code>Count</code>. When you exclude a rule, WAF evaluates it exactly as it * would if the rule action setting were <code>Count</code>. This is a useful * option for testing the rules in a rule group without modifying how they handle * your web traffic.</p> */ inline ManagedRuleGroupStatement& AddExcludedRules(ExcludedRule&& value) { m_excludedRulesHasBeenSet = true; m_excludedRules.push_back(std::move(value)); return *this; } /** * <p>An optional nested statement that narrows the scope of the web requests that * are evaluated by the managed rule group. Requests are only evaluated by the rule * group if they match the scope-down statement. You can use any nestable * <a>Statement</a> in the scope-down statement, and you can nest statements at any * level, the same as you can for a rule statement. </p> */ const Statement& GetScopeDownStatement() const; /** * <p>An optional nested statement that narrows the scope of the web requests that * are evaluated by the managed rule group. Requests are only evaluated by the rule * group if they match the scope-down statement. You can use any nestable * <a>Statement</a> in the scope-down statement, and you can nest statements at any * level, the same as you can for a rule statement. </p> */ bool ScopeDownStatementHasBeenSet() const; /** * <p>An optional nested statement that narrows the scope of the web requests that * are evaluated by the managed rule group. Requests are only evaluated by the rule * group if they match the scope-down statement. You can use any nestable * <a>Statement</a> in the scope-down statement, and you can nest statements at any * level, the same as you can for a rule statement. </p> */ void SetScopeDownStatement(const Statement& value); /** * <p>An optional nested statement that narrows the scope of the web requests that * are evaluated by the managed rule group. Requests are only evaluated by the rule * group if they match the scope-down statement. You can use any nestable * <a>Statement</a> in the scope-down statement, and you can nest statements at any * level, the same as you can for a rule statement. </p> */ void SetScopeDownStatement(Statement&& value); /** * <p>An optional nested statement that narrows the scope of the web requests that * are evaluated by the managed rule group. Requests are only evaluated by the rule * group if they match the scope-down statement. You can use any nestable * <a>Statement</a> in the scope-down statement, and you can nest statements at any * level, the same as you can for a rule statement. </p> */ ManagedRuleGroupStatement& WithScopeDownStatement(const Statement& value); /** * <p>An optional nested statement that narrows the scope of the web requests that * are evaluated by the managed rule group. Requests are only evaluated by the rule * group if they match the scope-down statement. You can use any nestable * <a>Statement</a> in the scope-down statement, and you can nest statements at any * level, the same as you can for a rule statement. </p> */ ManagedRuleGroupStatement& WithScopeDownStatement(Statement&& value); /** * <p>Additional information that's used by a managed rule group. Most managed rule * groups don't require this.</p> <p>Use this for the account takeover prevention * managed rule group <code>AWSManagedRulesATPRuleSet</code>, to provide * information about the sign-in page of your application. </p> <p>You can provide * multiple individual <code>ManagedRuleGroupConfig</code> objects for any rule * group configuration, for example <code>UsernameField</code> and * <code>PasswordField</code>. The configuration that you provide depends on the * needs of the managed rule group. For the ATP managed rule group, you provide the * following individual configuration objects: <code>LoginPath</code>, * <code>PasswordField</code>, <code>PayloadType</code> and * <code>UsernameField</code>.</p> */ inline const Aws::Vector<ManagedRuleGroupConfig>& GetManagedRuleGroupConfigs() const{ return m_managedRuleGroupConfigs; } /** * <p>Additional information that's used by a managed rule group. Most managed rule * groups don't require this.</p> <p>Use this for the account takeover prevention * managed rule group <code>AWSManagedRulesATPRuleSet</code>, to provide * information about the sign-in page of your application. </p> <p>You can provide * multiple individual <code>ManagedRuleGroupConfig</code> objects for any rule * group configuration, for example <code>UsernameField</code> and * <code>PasswordField</code>. The configuration that you provide depends on the * needs of the managed rule group. For the ATP managed rule group, you provide the * following individual configuration objects: <code>LoginPath</code>, * <code>PasswordField</code>, <code>PayloadType</code> and * <code>UsernameField</code>.</p> */ inline bool ManagedRuleGroupConfigsHasBeenSet() const { return m_managedRuleGroupConfigsHasBeenSet; } /** * <p>Additional information that's used by a managed rule group. Most managed rule * groups don't require this.</p> <p>Use this for the account takeover prevention * managed rule group <code>AWSManagedRulesATPRuleSet</code>, to provide * information about the sign-in page of your application. </p> <p>You can provide * multiple individual <code>ManagedRuleGroupConfig</code> objects for any rule * group configuration, for example <code>UsernameField</code> and * <code>PasswordField</code>. The configuration that you provide depends on the * needs of the managed rule group. For the ATP managed rule group, you provide the * following individual configuration objects: <code>LoginPath</code>, * <code>PasswordField</code>, <code>PayloadType</code> and * <code>UsernameField</code>.</p> */ inline void SetManagedRuleGroupConfigs(const Aws::Vector<ManagedRuleGroupConfig>& value) { m_managedRuleGroupConfigsHasBeenSet = true; m_managedRuleGroupConfigs = value; } /** * <p>Additional information that's used by a managed rule group. Most managed rule * groups don't require this.</p> <p>Use this for the account takeover prevention * managed rule group <code>AWSManagedRulesATPRuleSet</code>, to provide * information about the sign-in page of your application. </p> <p>You can provide * multiple individual <code>ManagedRuleGroupConfig</code> objects for any rule * group configuration, for example <code>UsernameField</code> and * <code>PasswordField</code>. The configuration that you provide depends on the * needs of the managed rule group. For the ATP managed rule group, you provide the * following individual configuration objects: <code>LoginPath</code>, * <code>PasswordField</code>, <code>PayloadType</code> and * <code>UsernameField</code>.</p> */ inline void SetManagedRuleGroupConfigs(Aws::Vector<ManagedRuleGroupConfig>&& value) { m_managedRuleGroupConfigsHasBeenSet = true; m_managedRuleGroupConfigs = std::move(value); } /** * <p>Additional information that's used by a managed rule group. Most managed rule * groups don't require this.</p> <p>Use this for the account takeover prevention * managed rule group <code>AWSManagedRulesATPRuleSet</code>, to provide * information about the sign-in page of your application. </p> <p>You can provide * multiple individual <code>ManagedRuleGroupConfig</code> objects for any rule * group configuration, for example <code>UsernameField</code> and * <code>PasswordField</code>. The configuration that you provide depends on the * needs of the managed rule group. For the ATP managed rule group, you provide the * following individual configuration objects: <code>LoginPath</code>, * <code>PasswordField</code>, <code>PayloadType</code> and * <code>UsernameField</code>.</p> */ inline ManagedRuleGroupStatement& WithManagedRuleGroupConfigs(const Aws::Vector<ManagedRuleGroupConfig>& value) { SetManagedRuleGroupConfigs(value); return *this;} /** * <p>Additional information that's used by a managed rule group. Most managed rule * groups don't require this.</p> <p>Use this for the account takeover prevention * managed rule group <code>AWSManagedRulesATPRuleSet</code>, to provide * information about the sign-in page of your application. </p> <p>You can provide * multiple individual <code>ManagedRuleGroupConfig</code> objects for any rule * group configuration, for example <code>UsernameField</code> and * <code>PasswordField</code>. The configuration that you provide depends on the * needs of the managed rule group. For the ATP managed rule group, you provide the * following individual configuration objects: <code>LoginPath</code>, * <code>PasswordField</code>, <code>PayloadType</code> and * <code>UsernameField</code>.</p> */ inline ManagedRuleGroupStatement& WithManagedRuleGroupConfigs(Aws::Vector<ManagedRuleGroupConfig>&& value) { SetManagedRuleGroupConfigs(std::move(value)); return *this;} /** * <p>Additional information that's used by a managed rule group. Most managed rule * groups don't require this.</p> <p>Use this for the account takeover prevention * managed rule group <code>AWSManagedRulesATPRuleSet</code>, to provide * information about the sign-in page of your application. </p> <p>You can provide * multiple individual <code>ManagedRuleGroupConfig</code> objects for any rule * group configuration, for example <code>UsernameField</code> and * <code>PasswordField</code>. The configuration that you provide depends on the * needs of the managed rule group. For the ATP managed rule group, you provide the * following individual configuration objects: <code>LoginPath</code>, * <code>PasswordField</code>, <code>PayloadType</code> and * <code>UsernameField</code>.</p> */ inline ManagedRuleGroupStatement& AddManagedRuleGroupConfigs(const ManagedRuleGroupConfig& value) { m_managedRuleGroupConfigsHasBeenSet = true; m_managedRuleGroupConfigs.push_back(value); return *this; } /** * <p>Additional information that's used by a managed rule group. Most managed rule * groups don't require this.</p> <p>Use this for the account takeover prevention * managed rule group <code>AWSManagedRulesATPRuleSet</code>, to provide * information about the sign-in page of your application. </p> <p>You can provide * multiple individual <code>ManagedRuleGroupConfig</code> objects for any rule * group configuration, for example <code>UsernameField</code> and * <code>PasswordField</code>. The configuration that you provide depends on the * needs of the managed rule group. For the ATP managed rule group, you provide the * following individual configuration objects: <code>LoginPath</code>, * <code>PasswordField</code>, <code>PayloadType</code> and * <code>UsernameField</code>.</p> */ inline ManagedRuleGroupStatement& AddManagedRuleGroupConfigs(ManagedRuleGroupConfig&& value) { m_managedRuleGroupConfigsHasBeenSet = true; m_managedRuleGroupConfigs.push_back(std::move(value)); return *this; } private: Aws::String m_vendorName; bool m_vendorNameHasBeenSet; Aws::String m_name; bool m_nameHasBeenSet; Aws::String m_version; bool m_versionHasBeenSet; Aws::Vector<ExcludedRule> m_excludedRules; bool m_excludedRulesHasBeenSet; std::shared_ptr<Statement> m_scopeDownStatement; bool m_scopeDownStatementHasBeenSet; Aws::Vector<ManagedRuleGroupConfig> m_managedRuleGroupConfigs; bool m_managedRuleGroupConfigsHasBeenSet; }; } // namespace Model } // namespace WAFV2 } // namespace Aws
{ "content_hash": "39222eb21e2089d5d4eeda348c5c2dc4", "timestamp": "", "source": "github", "line_count": 482, "max_line_length": 213, "avg_line_length": 51.21576763485477, "alnum_prop": 0.7008020740500689, "repo_name": "cedral/aws-sdk-cpp", "id": "9eb3a22c33733414579905fe5e969facfc54cc5d", "size": "24805", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-cpp-sdk-wafv2/include/aws/wafv2/model/ManagedRuleGroupStatement.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "294220" }, { "name": "C++", "bytes": "428637022" }, { "name": "CMake", "bytes": "862025" }, { "name": "Dockerfile", "bytes": "11688" }, { "name": "HTML", "bytes": "7904" }, { "name": "Java", "bytes": "352201" }, { "name": "Python", "bytes": "106761" }, { "name": "Shell", "bytes": "10891" } ], "symlink_target": "" }
package com.amazonaws.services.route53resolver.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.route53resolver.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.protocol.*; import com.amazonaws.protocol.Protocol; import com.amazonaws.annotation.SdkInternalApi; /** * CreateFirewallRuleGroupRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class CreateFirewallRuleGroupRequestProtocolMarshaller implements Marshaller<Request<CreateFirewallRuleGroupRequest>, CreateFirewallRuleGroupRequest> { private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.AWS_JSON).requestUri("/") .httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true) .operationIdentifier("Route53Resolver.CreateFirewallRuleGroup").serviceName("AmazonRoute53Resolver").build(); private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory; public CreateFirewallRuleGroupRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) { this.protocolFactory = protocolFactory; } public Request<CreateFirewallRuleGroupRequest> marshall(CreateFirewallRuleGroupRequest createFirewallRuleGroupRequest) { if (createFirewallRuleGroupRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { final ProtocolRequestMarshaller<CreateFirewallRuleGroupRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller( SDK_OPERATION_BINDING, createFirewallRuleGroupRequest); protocolMarshaller.startMarshalling(); CreateFirewallRuleGroupRequestMarshaller.getInstance().marshall(createFirewallRuleGroupRequest, protocolMarshaller); return protocolMarshaller.finishMarshalling(); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
{ "content_hash": "f767d415ec9806bf866b3ebafb1311c3", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 158, "avg_line_length": 43.30769230769231, "alnum_prop": 0.7770870337477798, "repo_name": "aws/aws-sdk-java", "id": "bae50f90336df738e176c847e74d7b358b1f70bc", "size": "2832", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-route53resolver/src/main/java/com/amazonaws/services/route53resolver/model/transform/CreateFirewallRuleGroupRequestProtocolMarshaller.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
var exec = require('child_process').exec; var execFile = require('child_process').execFile; var path = require('path'); var args = process.argv; var root = path.dirname(args[1]) + '/'; /** * */ function run(command, success, failure) { exec(command, { encoding: 'utf8' }, function(error, stdout, stderr) { if (error) { failure(stderr); } else { if (stdout.length > 1) { success(stdout); } else { success(stderr) } } }); } function runScript(file, args, success, fail) { execFile(file, args,function(error, stdout, stderr) { if (stdout.length > 1) { success(stdout); } if (error) { fail(stderr); } }); } exports.root = root; exports.run = run; exports.runScript = runScript;
{ "content_hash": "76af293d4bce992696af974aad68882b", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 55, "avg_line_length": 17.59090909090909, "alnum_prop": 0.582687338501292, "repo_name": "chone/mem", "id": "5ec3b9da2b8009d058067e23c5aff3403a062a8f", "size": "774", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "proton-library/bin/lib/cmd.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2290" }, { "name": "CSS", "bytes": "125232" }, { "name": "Emacs Lisp", "bytes": "2410" }, { "name": "HTML", "bytes": "1096665" }, { "name": "JavaScript", "bytes": "20392128" }, { "name": "Python", "bytes": "80606" }, { "name": "Shell", "bytes": "11050" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "750ddd02c5ee28235032488f0f17fc52", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "a282681a43e4ddafa8ea831f3b08e4f017e633e2", "size": "182", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Euphorbiaceae/Tragia/Tragia urens/ Syn. Tragia discolor latifolia/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<header> <h3> Welcome to the Sme UP {{user.name}}!</h3> </header> <section> <form [formGroup]="form" autocomplete="off"> <md-input formControlName="name" [placeholder]="nameLabel" maxlength="32"></md-input><br> <md-input formControlName="password" [placeholder]="passwordLabel" type="password" maxlength="32"></md-input><br> <button md-raised-button color="primary" (click)="login()">Login</button> </form> </section>
{ "content_hash": "40c7147785600b69de402682aef45435", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 121, "avg_line_length": 45.3, "alnum_prop": 0.6534216335540839, "repo_name": "fioletti-smeup/ng-smeup", "id": "9de4019968f26385a5c95d21b1a1795be82efdc2", "size": "453", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/app/login/login.component.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5328" }, { "name": "HTML", "bytes": "6158" }, { "name": "JavaScript", "bytes": "16562" }, { "name": "TypeScript", "bytes": "58290" } ], "symlink_target": "" }
<script> $(document).ready(function(){ $("#icon-nav").click(function(){ $(".nav").toggleClass("responsive"); }); }); </script> <div class='container'> <ul class='nav navbar-fixed-top'> <li> <a href='../index.php'><i class='fa fa-users'></i> Home</a> </li> <li> <a href='php/about.php'><i class='fa fa-info-circle'></i> About</a> </li> <?php session_start(); if (isset($_SESSION["first"])){?> <li> <a href='../php/logout.php'><i class='fa fa-sign-out'></i> Logout</a> </li> <form class='navbar-form navbar-right' action='../php/checkTag.php' method='POST'> <div class='form-group'> <input type='search' name='searchinput' class='form-control' placeholder='Search users or hashtags'> </div> <button type='submit' class='btn btn-default'><i class='fa fa-search'></i> Search</button> </form> <!--<ul class='nav navbar-nav navbar-right'>--> <li> <a href='http://chitchatonline.esy.es/profile.php?uid=<?=$_SESSION["id"]?>'><i class='fa fa-user-circle-o'></i> <?= $_SESSION["first"] ?></a> </li> <li id='icon-nav'> <a href="javascript:void(0);" onclick="navCollapse()">&#9776;</a> </li> <!--</ul>--> <?php } else {?> <ul class='nav navbar-nav navbar-right'> <li><a href='../php/signup_page.php'><i class='fa fa-user'></i> Sign Up</a></li> <li id='icon-nav'> <a href="javascript:void(0);" onclick="myFunction()">&#9776;</a> </li> </ul> <form class='navbar-form navbar-right' action='../php/login.php' method='POST'> <div class='form-group'> <?= $error ?> <input type='text' name='uname' class='form-control' placeholder='Username'> <input type='password' name='pwd' class='form-control' placeholder='Password'> </div> <button type='submit' class='btn btn-default'><a href='#'><i class='fa fa-sign-in'></i> Login</a></button> </form> <?php } echo "</ul>"; ?>
{ "content_hash": "fce632d1fbd0ed7cf8f836837cf64748", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 149, "avg_line_length": 36.03703703703704, "alnum_prop": 0.5678314491264131, "repo_name": "bjornkeyser/ChitChat", "id": "bbbfb9de91c1c49a6109b164e32c6dc6f9ef889c", "size": "1946", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "includes/header.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1640" }, { "name": "JavaScript", "bytes": "330" }, { "name": "PHP", "bytes": "77978" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Physcia integrata var. ulcerata Zahlbr. ### Remarks null
{ "content_hash": "56a431ab42a5d2adae6fecc3bbab154c", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 11.076923076923077, "alnum_prop": 0.7152777777777778, "repo_name": "mdoering/backbone", "id": "d7993dafb59214a4fab0e638782b1437330dfe81", "size": "207", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Lecanoromycetes/Teloschistales/Physciaceae/Physcia/Physcia integrata/Physcia integrata ulcerata/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
FROM balenalib/firefly-rk3288-ubuntu:disco-run # remove several traces of debian python RUN apt-get purge -y python.* # http://bugs.python.org/issue19846 # > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK. ENV LANG C.UTF-8 # install python dependencies RUN apt-get update && apt-get install -y --no-install-recommends \ ca-certificates \ netbase \ && rm -rf /var/lib/apt/lists/* # key 63C7CC90: public key "Simon McVittie <[email protected]>" imported # key 3372DCFA: public key "Donald Stufft (dstufft) <[email protected]>" imported RUN gpg --keyserver keyring.debian.org --recv-keys 4DE8FF2A63C7CC90 \ && gpg --keyserver keyserver.ubuntu.com --recv-key 6E3CBCE93372DCFA \ && gpg --keyserver keyserver.ubuntu.com --recv-keys 0x52a43a1e4b77b059 ENV PYTHON_VERSION 2.7.18 # if this is called "PIP_VERSION", pip explodes with "ValueError: invalid truth value '<VERSION>'" ENV PYTHON_PIP_VERSION 21.0.1 ENV SETUPTOOLS_VERSION 56.0.0 RUN set -x \ && buildDeps=' \ curl \ ' \ && apt-get update && apt-get install -y $buildDeps --no-install-recommends && rm -rf /var/lib/apt/lists/* \ && curl -SLO "http://resin-packages.s3.amazonaws.com/python/v$PYTHON_VERSION/Python-$PYTHON_VERSION.linux-armv7hf-openssl1.1.tar.gz" \ && echo "95b85360b746dae2f418859a4003589d6436381d4389d128c811de70082f4e6a Python-$PYTHON_VERSION.linux-armv7hf-openssl1.1.tar.gz" | sha256sum -c - \ && tar -xzf "Python-$PYTHON_VERSION.linux-armv7hf-openssl1.1.tar.gz" --strip-components=1 \ && rm -rf "Python-$PYTHON_VERSION.linux-armv7hf-openssl1.1.tar.gz" \ && ldconfig \ && if [ ! -e /usr/local/bin/pip ]; then : \ && curl -SLO "https://raw.githubusercontent.com/pypa/get-pip/430ba37776ae2ad89f794c7a43b90dc23bac334c/get-pip.py" \ && echo "19dae841a150c86e2a09d475b5eb0602861f2a5b7761ec268049a662dbd2bd0c get-pip.py" | sha256sum -c - \ && python get-pip.py \ && rm get-pip.py \ ; fi \ && pip install --no-cache-dir --upgrade --force-reinstall pip=="$PYTHON_PIP_VERSION" setuptools=="$SETUPTOOLS_VERSION" \ && find /usr/local \ \( -type d -a -name test -o -name tests \) \ -o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \ -exec rm -rf '{}' + \ && cd / \ && rm -rf /usr/src/python ~/.cache # https://github.com/docker-library/python/issues/147 ENV PYTHONIOENCODING UTF-8 # set PYTHONPATH to point to dist-packages ENV PYTHONPATH /usr/lib/python2.7/dist-packages:/usr/lib/python2.7/site-packages:$PYTHONPATH RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'As of January 1st, 2020, Python 2 was end-of-life, we will change the latest tag for Balenalib Python base image to Python 3.x and drop support for Python 2 soon. So after 1st July, 2020, all the balenalib Python latest tag will point to the latest Python 3 version and no changes, or fixes will be made to balenalib Python 2 base image. If you are using Python 2 for your application, please upgrade to Python 3 before 1st July.' > /.balena/messages/python-deprecation-warnin CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/[email protected]" \ && echo "Running test-stack@python" \ && chmod +x [email protected] \ && bash [email protected] \ && rm -rf [email protected] RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Ubuntu disco \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v2.7.18, Pip v21.0.1, Setuptools v56.0.0 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
{ "content_hash": "1c255c139ed829e69bc4faa5d86b1497", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 708, "avg_line_length": 59.78378378378378, "alnum_prop": 0.721745027124774, "repo_name": "nghiant2710/base-images", "id": "1766d4b771ad491d49bc57111aff10a50eac0e1a", "size": "4445", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "balena-base-images/python/firefly-rk3288/ubuntu/disco/2.7.18/run/Dockerfile", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "144558581" }, { "name": "JavaScript", "bytes": "16316" }, { "name": "Shell", "bytes": "368690" } ], "symlink_target": "" }
This is the public Twilio REST API. ## Overview This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project from the OpenAPI specs located at [twilio/twilio-oai](https://github.com/twilio/twilio-oai/tree/main/spec). By using the [OpenAPI-spec](https://www.openapis.org/) from a remote server, you can easily generate an API client. - API version: 1.37.3 - Package version: 1.0.0 - Build package: com.twilio.oai.TwilioGoGenerator For more information, please visit [https://support.twilio.com](https://support.twilio.com) ## Installation Install the following dependencies: ```shell go get github.com/stretchr/testify/assert go get golang.org/x/net/context ``` Put the package under your project folder and add the following in import: ```golang import "./openapi" ``` ## Documentation for API Endpoints All URIs are relative to *https://frontline-api.twilio.com* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- *UsersApi* | [**FetchUser**](docs/UsersApi.md#fetchuser) | **Get** /v1/Users/{Sid} | *UsersApi* | [**UpdateUser**](docs/UsersApi.md#updateuser) | **Post** /v1/Users/{Sid} | ## Documentation For Models - [FrontlineV1User](docs/FrontlineV1User.md) ## Documentation For Authorization ## accountSid_authToken - **Type**: HTTP basic authentication Example ```golang auth := context.WithValue(context.Background(), sw.ContextBasicAuth, sw.BasicAuth{ UserName: "username", Password: "password", }) r, err := client.Service.Operation(auth, args) ```
{ "content_hash": "c251cbb86060dfe43ca63863dc9aa7aa", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 321, "avg_line_length": 27.25862068965517, "alnum_prop": 0.702719797596458, "repo_name": "twilio/twilio-go", "id": "6a6b5b19f0fb812e1e4494fda43ac12d2fb30ab4", "size": "1610", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "rest/frontline/v1/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "200" }, { "name": "Go", "bytes": "4840470" }, { "name": "Makefile", "bytes": "1414" } ], "symlink_target": "" }
<?php namespace ICS\AppServerBundle\Entity; class SourceDisk extends Entity { protected $id; protected $pcSpecsID; protected $application; protected $os; //get functions public function getID() { return $this->id; } public function getPCSpecsID() { return $this->pcSpecsID; } public function getApplication() { return $this->application; } public function getOS() { return $this->os; } //set functions public function setID() { } public function setPCSpecsID() { } public function setApplication() { } public function setOS() { } }
{ "content_hash": "be04b959d34eb2195383f07381fabe51", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 37, "avg_line_length": 13.981818181818182, "alnum_prop": 0.5149544863459038, "repo_name": "dricho/ICSAppServer", "id": "e35fe0036b6c331ed7b71f179bfcde04ff53b621", "size": "769", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/ICS/AppServerBundle/Entity/SourceDisk.php", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
default_target: all .PHONY : default_target #============================================================================= # Special targets provided by cmake. # Disable implicit rules so canonical targets will work. .SUFFIXES: # Remove some rules from gmake that .SUFFIXES does not remove. SUFFIXES = .SUFFIXES: .hpux_make_needs_suffix_list # Suppress display of executed commands. $(VERBOSE).SILENT: # A target that is always out of date. cmake_force: .PHONY : cmake_force #============================================================================= # Set environment variables for the build. # The shell in which to execute make rules. SHELL = /bin/sh # The CMake executable. CMAKE_COMMAND = /usr/bin/cmake # The command to remove a file. RM = /usr/bin/cmake -E remove -f # Escaping for special characters. EQUALS = = # The program to use to edit the cache. CMAKE_EDIT_COMMAND = /usr/bin/ccmake # The top-level source directory on which CMake was run. CMAKE_SOURCE_DIR = /home/nitin/CMSC733/dlib-19.2/tools/python # The top-level build directory on which CMake was run. CMAKE_BINARY_DIR = /home/nitin/CMSC733/dlib-19.2/tools/python/build #============================================================================= # Targets provided globally by CMake. # Special rule for the target edit_cache edit_cache: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake cache editor..." /usr/bin/ccmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) .PHONY : edit_cache # Special rule for the target edit_cache edit_cache/fast: edit_cache .PHONY : edit_cache/fast # Special rule for the target install install: preinstall @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Install the project..." /usr/bin/cmake -P cmake_install.cmake .PHONY : install # Special rule for the target install install/fast: preinstall/fast @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Install the project..." /usr/bin/cmake -P cmake_install.cmake .PHONY : install/fast # Special rule for the target install/local install/local: preinstall @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing only the local directory..." /usr/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake .PHONY : install/local # Special rule for the target install/local install/local/fast: install/local .PHONY : install/local/fast # Special rule for the target install/strip install/strip: preinstall @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing the project stripped..." /usr/bin/cmake -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake .PHONY : install/strip # Special rule for the target install/strip install/strip/fast: install/strip .PHONY : install/strip/fast # Special rule for the target list_install_components list_install_components: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Available install components are: \"Unspecified\"" .PHONY : list_install_components # Special rule for the target list_install_components list_install_components/fast: list_install_components .PHONY : list_install_components/fast # Special rule for the target rebuild_cache rebuild_cache: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..." /usr/bin/cmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) .PHONY : rebuild_cache # Special rule for the target rebuild_cache rebuild_cache/fast: rebuild_cache .PHONY : rebuild_cache/fast # The main all target all: cmake_check_build_system $(CMAKE_COMMAND) -E cmake_progress_start /home/nitin/CMSC733/dlib-19.2/tools/python/build/CMakeFiles /home/nitin/CMSC733/dlib-19.2/tools/python/build/CMakeFiles/progress.marks $(MAKE) -f CMakeFiles/Makefile2 all $(CMAKE_COMMAND) -E cmake_progress_start /home/nitin/CMSC733/dlib-19.2/tools/python/build/CMakeFiles 0 .PHONY : all # The main clean target clean: $(MAKE) -f CMakeFiles/Makefile2 clean .PHONY : clean # The main clean target clean/fast: clean .PHONY : clean/fast # Prepare targets for installation. preinstall: all $(MAKE) -f CMakeFiles/Makefile2 preinstall .PHONY : preinstall # Prepare targets for installation. preinstall/fast: $(MAKE) -f CMakeFiles/Makefile2 preinstall .PHONY : preinstall/fast # clear depends depend: $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1 .PHONY : depend #============================================================================= # Target rules for targets named dlib_ # Build rule for target. dlib_: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 dlib_ .PHONY : dlib_ # fast build rule for target. dlib_/fast: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/build .PHONY : dlib_/fast #============================================================================= # Target rules for targets named dlib # Build rule for target. dlib: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 dlib .PHONY : dlib # fast build rule for target. dlib/fast: $(MAKE) -f dlib_build/CMakeFiles/dlib.dir/build.make dlib_build/CMakeFiles/dlib.dir/build .PHONY : dlib/fast src/basic.o: src/basic.cpp.o .PHONY : src/basic.o # target to build an object file src/basic.cpp.o: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/basic.cpp.o .PHONY : src/basic.cpp.o src/basic.i: src/basic.cpp.i .PHONY : src/basic.i # target to preprocess a source file src/basic.cpp.i: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/basic.cpp.i .PHONY : src/basic.cpp.i src/basic.s: src/basic.cpp.s .PHONY : src/basic.s # target to generate assembly for a file src/basic.cpp.s: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/basic.cpp.s .PHONY : src/basic.cpp.s src/cca.o: src/cca.cpp.o .PHONY : src/cca.o # target to build an object file src/cca.cpp.o: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/cca.cpp.o .PHONY : src/cca.cpp.o src/cca.i: src/cca.cpp.i .PHONY : src/cca.i # target to preprocess a source file src/cca.cpp.i: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/cca.cpp.i .PHONY : src/cca.cpp.i src/cca.s: src/cca.cpp.s .PHONY : src/cca.s # target to generate assembly for a file src/cca.cpp.s: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/cca.cpp.s .PHONY : src/cca.cpp.s src/correlation_tracker.o: src/correlation_tracker.cpp.o .PHONY : src/correlation_tracker.o # target to build an object file src/correlation_tracker.cpp.o: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/correlation_tracker.cpp.o .PHONY : src/correlation_tracker.cpp.o src/correlation_tracker.i: src/correlation_tracker.cpp.i .PHONY : src/correlation_tracker.i # target to preprocess a source file src/correlation_tracker.cpp.i: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/correlation_tracker.cpp.i .PHONY : src/correlation_tracker.cpp.i src/correlation_tracker.s: src/correlation_tracker.cpp.s .PHONY : src/correlation_tracker.s # target to generate assembly for a file src/correlation_tracker.cpp.s: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/correlation_tracker.cpp.s .PHONY : src/correlation_tracker.cpp.s src/decision_functions.o: src/decision_functions.cpp.o .PHONY : src/decision_functions.o # target to build an object file src/decision_functions.cpp.o: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/decision_functions.cpp.o .PHONY : src/decision_functions.cpp.o src/decision_functions.i: src/decision_functions.cpp.i .PHONY : src/decision_functions.i # target to preprocess a source file src/decision_functions.cpp.i: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/decision_functions.cpp.i .PHONY : src/decision_functions.cpp.i src/decision_functions.s: src/decision_functions.cpp.s .PHONY : src/decision_functions.s # target to generate assembly for a file src/decision_functions.cpp.s: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/decision_functions.cpp.s .PHONY : src/decision_functions.cpp.s src/dlib.o: src/dlib.cpp.o .PHONY : src/dlib.o # target to build an object file src/dlib.cpp.o: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/dlib.cpp.o .PHONY : src/dlib.cpp.o src/dlib.i: src/dlib.cpp.i .PHONY : src/dlib.i # target to preprocess a source file src/dlib.cpp.i: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/dlib.cpp.i .PHONY : src/dlib.cpp.i src/dlib.s: src/dlib.cpp.s .PHONY : src/dlib.s # target to generate assembly for a file src/dlib.cpp.s: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/dlib.cpp.s .PHONY : src/dlib.cpp.s src/gui.o: src/gui.cpp.o .PHONY : src/gui.o # target to build an object file src/gui.cpp.o: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/gui.cpp.o .PHONY : src/gui.cpp.o src/gui.i: src/gui.cpp.i .PHONY : src/gui.i # target to preprocess a source file src/gui.cpp.i: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/gui.cpp.i .PHONY : src/gui.cpp.i src/gui.s: src/gui.cpp.s .PHONY : src/gui.s # target to generate assembly for a file src/gui.cpp.s: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/gui.cpp.s .PHONY : src/gui.cpp.s src/image.o: src/image.cpp.o .PHONY : src/image.o # target to build an object file src/image.cpp.o: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/image.cpp.o .PHONY : src/image.cpp.o src/image.i: src/image.cpp.i .PHONY : src/image.i # target to preprocess a source file src/image.cpp.i: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/image.cpp.i .PHONY : src/image.cpp.i src/image.s: src/image.cpp.s .PHONY : src/image.s # target to generate assembly for a file src/image.cpp.s: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/image.cpp.s .PHONY : src/image.cpp.s src/matrix.o: src/matrix.cpp.o .PHONY : src/matrix.o # target to build an object file src/matrix.cpp.o: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/matrix.cpp.o .PHONY : src/matrix.cpp.o src/matrix.i: src/matrix.cpp.i .PHONY : src/matrix.i # target to preprocess a source file src/matrix.cpp.i: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/matrix.cpp.i .PHONY : src/matrix.cpp.i src/matrix.s: src/matrix.cpp.s .PHONY : src/matrix.s # target to generate assembly for a file src/matrix.cpp.s: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/matrix.cpp.s .PHONY : src/matrix.cpp.s src/object_detection.o: src/object_detection.cpp.o .PHONY : src/object_detection.o # target to build an object file src/object_detection.cpp.o: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/object_detection.cpp.o .PHONY : src/object_detection.cpp.o src/object_detection.i: src/object_detection.cpp.i .PHONY : src/object_detection.i # target to preprocess a source file src/object_detection.cpp.i: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/object_detection.cpp.i .PHONY : src/object_detection.cpp.i src/object_detection.s: src/object_detection.cpp.s .PHONY : src/object_detection.s # target to generate assembly for a file src/object_detection.cpp.s: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/object_detection.cpp.s .PHONY : src/object_detection.cpp.s src/other.o: src/other.cpp.o .PHONY : src/other.o # target to build an object file src/other.cpp.o: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/other.cpp.o .PHONY : src/other.cpp.o src/other.i: src/other.cpp.i .PHONY : src/other.i # target to preprocess a source file src/other.cpp.i: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/other.cpp.i .PHONY : src/other.cpp.i src/other.s: src/other.cpp.s .PHONY : src/other.s # target to generate assembly for a file src/other.cpp.s: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/other.cpp.s .PHONY : src/other.cpp.s src/rectangles.o: src/rectangles.cpp.o .PHONY : src/rectangles.o # target to build an object file src/rectangles.cpp.o: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/rectangles.cpp.o .PHONY : src/rectangles.cpp.o src/rectangles.i: src/rectangles.cpp.i .PHONY : src/rectangles.i # target to preprocess a source file src/rectangles.cpp.i: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/rectangles.cpp.i .PHONY : src/rectangles.cpp.i src/rectangles.s: src/rectangles.cpp.s .PHONY : src/rectangles.s # target to generate assembly for a file src/rectangles.cpp.s: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/rectangles.cpp.s .PHONY : src/rectangles.cpp.s src/sequence_segmenter.o: src/sequence_segmenter.cpp.o .PHONY : src/sequence_segmenter.o # target to build an object file src/sequence_segmenter.cpp.o: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/sequence_segmenter.cpp.o .PHONY : src/sequence_segmenter.cpp.o src/sequence_segmenter.i: src/sequence_segmenter.cpp.i .PHONY : src/sequence_segmenter.i # target to preprocess a source file src/sequence_segmenter.cpp.i: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/sequence_segmenter.cpp.i .PHONY : src/sequence_segmenter.cpp.i src/sequence_segmenter.s: src/sequence_segmenter.cpp.s .PHONY : src/sequence_segmenter.s # target to generate assembly for a file src/sequence_segmenter.cpp.s: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/sequence_segmenter.cpp.s .PHONY : src/sequence_segmenter.cpp.s src/shape_predictor.o: src/shape_predictor.cpp.o .PHONY : src/shape_predictor.o # target to build an object file src/shape_predictor.cpp.o: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/shape_predictor.cpp.o .PHONY : src/shape_predictor.cpp.o src/shape_predictor.i: src/shape_predictor.cpp.i .PHONY : src/shape_predictor.i # target to preprocess a source file src/shape_predictor.cpp.i: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/shape_predictor.cpp.i .PHONY : src/shape_predictor.cpp.i src/shape_predictor.s: src/shape_predictor.cpp.s .PHONY : src/shape_predictor.s # target to generate assembly for a file src/shape_predictor.cpp.s: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/shape_predictor.cpp.s .PHONY : src/shape_predictor.cpp.s src/svm_c_trainer.o: src/svm_c_trainer.cpp.o .PHONY : src/svm_c_trainer.o # target to build an object file src/svm_c_trainer.cpp.o: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/svm_c_trainer.cpp.o .PHONY : src/svm_c_trainer.cpp.o src/svm_c_trainer.i: src/svm_c_trainer.cpp.i .PHONY : src/svm_c_trainer.i # target to preprocess a source file src/svm_c_trainer.cpp.i: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/svm_c_trainer.cpp.i .PHONY : src/svm_c_trainer.cpp.i src/svm_c_trainer.s: src/svm_c_trainer.cpp.s .PHONY : src/svm_c_trainer.s # target to generate assembly for a file src/svm_c_trainer.cpp.s: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/svm_c_trainer.cpp.s .PHONY : src/svm_c_trainer.cpp.s src/svm_rank_trainer.o: src/svm_rank_trainer.cpp.o .PHONY : src/svm_rank_trainer.o # target to build an object file src/svm_rank_trainer.cpp.o: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/svm_rank_trainer.cpp.o .PHONY : src/svm_rank_trainer.cpp.o src/svm_rank_trainer.i: src/svm_rank_trainer.cpp.i .PHONY : src/svm_rank_trainer.i # target to preprocess a source file src/svm_rank_trainer.cpp.i: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/svm_rank_trainer.cpp.i .PHONY : src/svm_rank_trainer.cpp.i src/svm_rank_trainer.s: src/svm_rank_trainer.cpp.s .PHONY : src/svm_rank_trainer.s # target to generate assembly for a file src/svm_rank_trainer.cpp.s: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/svm_rank_trainer.cpp.s .PHONY : src/svm_rank_trainer.cpp.s src/svm_struct.o: src/svm_struct.cpp.o .PHONY : src/svm_struct.o # target to build an object file src/svm_struct.cpp.o: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/svm_struct.cpp.o .PHONY : src/svm_struct.cpp.o src/svm_struct.i: src/svm_struct.cpp.i .PHONY : src/svm_struct.i # target to preprocess a source file src/svm_struct.cpp.i: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/svm_struct.cpp.i .PHONY : src/svm_struct.cpp.i src/svm_struct.s: src/svm_struct.cpp.s .PHONY : src/svm_struct.s # target to generate assembly for a file src/svm_struct.cpp.s: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/svm_struct.cpp.s .PHONY : src/svm_struct.cpp.s src/vector.o: src/vector.cpp.o .PHONY : src/vector.o # target to build an object file src/vector.cpp.o: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/vector.cpp.o .PHONY : src/vector.cpp.o src/vector.i: src/vector.cpp.i .PHONY : src/vector.i # target to preprocess a source file src/vector.cpp.i: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/vector.cpp.i .PHONY : src/vector.cpp.i src/vector.s: src/vector.cpp.s .PHONY : src/vector.s # target to generate assembly for a file src/vector.cpp.s: $(MAKE) -f CMakeFiles/dlib_.dir/build.make CMakeFiles/dlib_.dir/src/vector.cpp.s .PHONY : src/vector.cpp.s # Help Target help: @echo "The following are some of the valid targets for this Makefile:" @echo "... all (the default if no target is provided)" @echo "... clean" @echo "... depend" @echo "... dlib_" @echo "... edit_cache" @echo "... install" @echo "... install/local" @echo "... install/strip" @echo "... list_install_components" @echo "... rebuild_cache" @echo "... dlib" @echo "... src/basic.o" @echo "... src/basic.i" @echo "... src/basic.s" @echo "... src/cca.o" @echo "... src/cca.i" @echo "... src/cca.s" @echo "... src/correlation_tracker.o" @echo "... src/correlation_tracker.i" @echo "... src/correlation_tracker.s" @echo "... src/decision_functions.o" @echo "... src/decision_functions.i" @echo "... src/decision_functions.s" @echo "... src/dlib.o" @echo "... src/dlib.i" @echo "... src/dlib.s" @echo "... src/gui.o" @echo "... src/gui.i" @echo "... src/gui.s" @echo "... src/image.o" @echo "... src/image.i" @echo "... src/image.s" @echo "... src/matrix.o" @echo "... src/matrix.i" @echo "... src/matrix.s" @echo "... src/object_detection.o" @echo "... src/object_detection.i" @echo "... src/object_detection.s" @echo "... src/other.o" @echo "... src/other.i" @echo "... src/other.s" @echo "... src/rectangles.o" @echo "... src/rectangles.i" @echo "... src/rectangles.s" @echo "... src/sequence_segmenter.o" @echo "... src/sequence_segmenter.i" @echo "... src/sequence_segmenter.s" @echo "... src/shape_predictor.o" @echo "... src/shape_predictor.i" @echo "... src/shape_predictor.s" @echo "... src/svm_c_trainer.o" @echo "... src/svm_c_trainer.i" @echo "... src/svm_c_trainer.s" @echo "... src/svm_rank_trainer.o" @echo "... src/svm_rank_trainer.i" @echo "... src/svm_rank_trainer.s" @echo "... src/svm_struct.o" @echo "... src/svm_struct.i" @echo "... src/svm_struct.s" @echo "... src/vector.o" @echo "... src/vector.i" @echo "... src/vector.s" .PHONY : help #============================================================================= # Special targets to cleanup operation of make. # Special rule to run CMake to check the build system integrity. # No rule that depends on this can have commands that come from listfiles # because they might be regenerated. cmake_check_build_system: $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0 .PHONY : cmake_check_build_system
{ "content_hash": "2467da69982ef1b3ecd84cbe8e82ded4", "timestamp": "", "source": "github", "line_count": 653, "max_line_length": 176, "avg_line_length": 30.575803981623277, "alnum_prop": 0.7106080336572173, "repo_name": "ncos/hometasks", "id": "35078de49f7721ad4bd6cfddc68364bb9922118c", "size": "20128", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CMSC733/amitrokh_P2/Code/FaceDetectorCodes/DLib/tools/python/build/Makefile", "mode": "33261", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "846" }, { "name": "C", "bytes": "136175" }, { "name": "C++", "bytes": "15667540" }, { "name": "CMake", "bytes": "146756" }, { "name": "CSS", "bytes": "29217" }, { "name": "Cuda", "bytes": "31470" }, { "name": "HTML", "bytes": "48174258" }, { "name": "Java", "bytes": "19162" }, { "name": "JavaScript", "bytes": "122517" }, { "name": "M", "bytes": "908" }, { "name": "Makefile", "bytes": "3905195" }, { "name": "Matlab", "bytes": "140691" }, { "name": "Perl", "bytes": "554" }, { "name": "Python", "bytes": "349464" }, { "name": "Shell", "bytes": "1944" }, { "name": "TeX", "bytes": "1236610" }, { "name": "XSLT", "bytes": "18442" } ], "symlink_target": "" }
namespace peloton { Statement::Statement(const std::string& statement_name, const std::string& query_string) : statement_name(statement_name), query_string(query_string) { } Statement::~Statement() { } std::vector<FieldInfoType> Statement::GetTupleDescriptor() const { return tuple_descriptor; } void Statement::SetStatementName(const std::string& statement_name_){ statement_name = statement_name_; } std::string Statement::GetStatementName() const { return statement_name; } void Statement::SetQueryString(const std::string& query_string_){ query_string = query_string_; } std::string Statement::GetQueryString() const { return query_string; } void Statement::SetQueryType(const std::string& query_type_){ query_type = query_type_; } std::string Statement::GetQueryType() const { return query_type; } void Statement::SetParamTypes(const std::vector<int32_t>& param_types_){ param_types = param_types_; } std::vector<int32_t> Statement::GetParamTypes() const { return param_types; } void Statement::SetTupleDescriptor(const std::vector<FieldInfoType>& tuple_descriptor_){ tuple_descriptor = tuple_descriptor_; } void Statement::SetPlanTree(std::shared_ptr<planner::AbstractPlan> plan_tree_){ plan_tree = std::move(plan_tree_); } const std::shared_ptr<planner::AbstractPlan>& Statement::GetPlanTree() const { return plan_tree; } } // namespace peloton
{ "content_hash": "1524c959a8a642043271a0386fb38e99", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 88, "avg_line_length": 22.85483870967742, "alnum_prop": 0.7233592095977417, "repo_name": "ranxian/peloton", "id": "a7423c82a1c19c7a07d449ab8bc235529595e6b1", "size": "1853", "binary": false, "copies": "1", "ref": "refs/heads/inc", "path": "src/common/statement.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "1873" }, { "name": "C++", "bytes": "3185493" }, { "name": "CMake", "bytes": "100254" }, { "name": "Java", "bytes": "20995" }, { "name": "Lex", "bytes": "5079" }, { "name": "PLpgSQL", "bytes": "5855" }, { "name": "Protocol Buffer", "bytes": "74081" }, { "name": "Python", "bytes": "28077" }, { "name": "Ruby", "bytes": "1035" }, { "name": "Shell", "bytes": "5000" }, { "name": "Yacc", "bytes": "24062" } ], "symlink_target": "" }
<div class="ephox-polish-help-article"> <div class="ephox-polish-help-h1" role="heading" aria-level="1">Anleitung für die Eingabehilfen</div> <div class="ephox-polish-help-h2" role="heading" aria-level="2">Aktivierung der Tastaturnavigation</div> <p>Um die Tastaturnavigation auf der Symbolleiste zu aktivieren, drücken Sie F10 bei Windows oder ALT + F10 bei Mac OSX. Das erste Element auf der Symbolleiste wird durch eine blaue Umrahmung hervorgehen, die einen ausgewählten Status anzeigt. </p> <div class="ephox-polish-help-h2" role="heading" aria-level="2">Bewegen zwischen Gruppen</div> <p>Die Schaltflächen auf der Symbolleiste sind in Gruppen ähnlicher Aktionen aufgeteilt. Wenn die Tastaturnavigation aktiviert ist, wird die Auswahl durch Drücken der TAB-Taste zur nächsten und durch Drücken der TAB- und Umschalttaste zur vorherigen Gruppe bewegt. Durch Drücken der TAB-Taste bei der letzten Gruppe gelangt man wieder zurück zur ersten Gruppe von Schaltflächen.</p> <div class="ephox-polish-help-h2" role="heading" aria-level="2">Bewegen zwischen Elementen und Schaltflächen</div> <p>Das Bewegen zwischen Elementen erfolgt mit Hilfe der Pfeiltasten. Das Bewegen zwischen Elementen erfolgt innerhalb einer Gruppe. Um zur nächsten Gruppe zu gelangen, drücken Sie die TAB-Taste und bewegen Sie sich dann wieder mit Hilfe der Pfeiltasten durch diese Gruppe.</p> <div class="ephox-polish-help-h2" role="heading" aria-level="2">Ausführen von Befehlen</div> <p>Um einen Befehl auszuführen, bewegen Sie die Auswahl zur gewünschten Schaltfläche und drücken Sie dann die Leer- oder Eingabetaste.</p> <div class="ephox-polish-help-h2" role="heading" aria-level="2">Öffnen, Navigieren und Schließen von Menüs</div> <p>Enthält eine Schaltfläche auf der Symbolleiste ein Menü, kann dieses durch Drücken der Leer- oder Eingabetaste geöffnet werden. Beim Öffnen des Menüs wird das erste Element ausgewählt. Die Navigation des Menüs erfolgt über die Pfeiltasten. Um sich im Menü nach oben oder unten zu bewegen, müssen Sie die Nach-Oben- bzw. Nach-Unten-Taste drücken. Das gilt auch für die Untermenüs.</p> <p>Menüelemente, die ein Untermenü aufweisen, sind durch ein Chevron-Symbol gekennzeichnet. Sie können das Untermenü erweitern, indem Sie die Pfeiltaste verwenden, die der Richtung des Chevron-Symbols entspricht, bzw. es schließen, indem Sie die Pfeiltaste in die entgegengesetzte Richtung verwenden.</p> <p>Um ein aktives Menü zu schließen, drücken Sie die ESC-Taste. Wenn ein Menü geschlossen wird, wird die vorherige Auswahl wiederhergestellt.</p> <div class="ephox-polish-help-h2" role="heading" aria-level="2">Bearbeiten und Entfernen von Hyperlinks</div> <p>Um einen Hyperlink zu bearbeiten bzw. zu entfernen, gehen Sie zum Menü "Einfügen" und wählen Sie die Verknüpfung "Einfügen" aus. Der Editor zeigt den Dialog "Hyperlink bearbeiten" an. </p> <p>Bearbeiten Sie den Hyperlink, indem Sie eine neue URL im Eingabefeld "Hyperlink aktualisieren" eingeben und die Eingabetaste drücken. Sie können den Hyperlink aus dem Dokument entfernen, indem Sie die Schaltfläche "Entfernen" auswählen. Um den Dialog ohne Änderungen zu beenden, drücken Sie die ESC-Taste.</p> <div class="ephox-polish-help-h2" role="heading" aria-level="2">Ändern der Schrift- und Tabellenrahmengröße</div> <p>Um die Schriftgröße zu ändern, gehen Sie zum Menü "Schriftart" und wählen Sie "Schriftgröße" aus. Der Editor zeigt im Menü den Dialog "Größe" an. Der Dialog ist im Fokus.</p> <p>Sie können die Rahmengröße ändern, indem Sie zum Symbolleistenelement "Größe des Tabellenrahmens" gehen und "Tabellenrahmengröße" auswählen. Der Editor zeigt im Menü den Dialog "Größe" an. Der Dialog ist im Fokus. Hinweis: Das Symbolleistenelement "Größe des Tabellenrahmens" wird nur angezeigt, wenn sich der Cursor innerhalb einer Tabelle befindet.</p> <p>Wenn Sie sich im Dialog "Größe" befinden, drücken Sie die TAB-Taste, um die Auswahl zum nächsten Steuerelement zu bewegen. Um die Auswahl zum vorherigen Steuerelement zu bewegen, drücken Sie die TAB- und Umschalttaste.</p> <p>Ändern Sie die Stärke, indem Sie den neuen Wert im Eingabefeld "Größe" eingeben. Beispiel: 14px bzw. 1em. Um die Änderungen abzusenden, drücken Sie die Eingabetaste. Nachdem Sie die Eingabetaste gedrückt haben, wird der Dialog geschlossen und der Fokus kehrt zum Dokument zurück.</p> <p>Sie können die Größe ändern, ohne den Dialog zu schließen, indem Sie die Schaltflächen "Größe erhöhen" oder "Größe verringern" aktivieren. Wenn Sie die Größe mithilfe der Schaltflächen "Größe erhöhen" oder "Größe verringern" verändern, wird automatisch die Größe des ausgewählten Elements verändert, während der aktuelle Einheitenwert beibehalten wird. Beenden Sie den Dialog, indem Sie die ESC-Taste drücken. </p> <table cellpadding="0" cellspacing="0" class="ephox-polish-tabular ephox-polish-help-table ephox-polish-help-table-shortcuts" role="grid" aria-readonly="true"> <caption>Tastaturnavigation</caption> <thead> <tr role="row"> <th scope="col" role="columnheader">Aktion</th> <th scope="col" role="columnheader">Windows</th> <th scope="col" role="columnheader">Mac OS</th> </tr> </thead> <tbody> <tr role="row"> <td role="gridcell">Symbolleiste aktivieren</td> <td role="gridcell">F10</td> <td role="gridcell">ALT + F10</td> </tr> <tr role="row"> <td role="gridcell">Nächste/Vorherige Gruppe auswählen</td> <td role="gridcell">← oder →</td> <td role="gridcell">← oder →</td> </tr> <tr role="row"> <td role="gridcell">Zu nächster Gruppe wechseln</td> <td role="gridcell">TAB-Taste</td> <td role="gridcell">TAB-Taste</td> </tr> <tr role="row"> <td role="gridcell">Zu vorheriger Gruppe wechseln</td> <td role="gridcell">SHIFT + TAB</td> <td role="gridcell">SHIFT + TAB</td> </tr> <tr role="row"> <td role="gridcell">Befehl ausführen</td> <td role="gridcell">Leertaste oder Eingabetaste</td> <td role="gridcell">Leertaste oder Eingabetaste</td> </tr> <tr role="row"> <td role="gridcell">Hauptmenü öffnen</td> <td role="gridcell">Leertaste oder Eingabetaste</td> <td role="gridcell">Leertaste oder Eingabetaste</td> </tr> <tr role="row"> <td role="gridcell">Untermenü öffnen/erweitern</td> <td role="gridcell">LEERZEICHEN oder EINGABE oder →</td> <td role="gridcell">LEERZEICHEN oder EINGABE oder →</td> </tr> <tr role="row"> <td role="gridcell">Nächsten/Vorherigen Menüpunkt auswählen</td> <td role="gridcell">↓ oder ↑</td> <td role="gridcell">↓ oder ↑</td> </tr> <tr role="row"> <td role="gridcell">Menü schließen</td> <td role="gridcell">ESC</td> <td role="gridcell">ESC</td> </tr> <tr role="row"> <td role="gridcell">Untermenü schließen/reduzieren</td> <td role="gridcell">ESC oder ←</td> <td role="gridcell">ESC oder ←</td> </tr> </tbody> </table> </div>
{ "content_hash": "d4fdd78a57cbae47b88d76c98b543144", "timestamp": "", "source": "github", "line_count": 102, "max_line_length": 419, "avg_line_length": 70.52941176470588, "alnum_prop": 0.7136502641089797, "repo_name": "alexrosepizant/lescoqssoccer", "id": "004530428535c734638b60480e8f504607e14d01", "size": "7358", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/libs/textboxio/resources/html/help/de/accessibility.html", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "153" }, { "name": "CSS", "bytes": "447151" }, { "name": "CoffeeScript", "bytes": "217775" }, { "name": "HTML", "bytes": "870090" }, { "name": "JavaScript", "bytes": "4203847" }, { "name": "Makefile", "bytes": "611" }, { "name": "PHP", "bytes": "4937" } ], "symlink_target": "" }
//// [commentsBeforeVariableStatement1.ts] /** b's comment*/ export var b: number; //// [commentsBeforeVariableStatement1.js] define(["require", "exports"], function (require, exports) { });
{ "content_hash": "f07241bdfee9500154a163c17fe0f357", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 60, "avg_line_length": 24.125, "alnum_prop": 0.6994818652849741, "repo_name": "freedot/tstolua", "id": "2f81d19ef0c5e85b662f43c8fb89f02cc973f5d9", "size": "193", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/baselines/reference/commentsBeforeVariableStatement1.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1125" }, { "name": "HTML", "bytes": "4659" }, { "name": "JavaScript", "bytes": "85" }, { "name": "Lua", "bytes": "68588" }, { "name": "PowerShell", "bytes": "2780" }, { "name": "TypeScript", "bytes": "22883724" } ], "symlink_target": "" }
/** * @provides javelin-behavior-phabricator-keyboard-shortcuts * @requires javelin-behavior * javelin-workflow * javelin-json * javelin-dom * phabricator-keyboard-shortcut */ /** * Define global keyboard shortcuts. */ JX.behavior('phabricator-keyboard-shortcuts', function(config) { var workflow = null; var desc = 'Show keyboard shortcut help for the current page.'; new JX.KeyboardShortcut('?', desc) .setHandler(function(manager) { if (workflow) { // Already showing the dialog. return; } var desc = manager.getShortcutDescriptions(); var data = {keys : JX.JSON.stringify(desc)}; workflow = new JX.Workflow(config.helpURI, data) .setCloseHandler(function() { workflow = null; }); workflow.start(); }) .register(); });
{ "content_hash": "55fdb44ab1a8cfe547b71b5a8556aa16", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 65, "avg_line_length": 26.363636363636363, "alnum_prop": 0.6103448275862069, "repo_name": "tanglu-org/tracker-phabricator", "id": "a2f7ca172b6e054cc5a15cfb7dc64f28b83dd0a4", "size": "870", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "webroot/rsrc/js/core/behavior-keyboard-shortcuts.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "160255" }, { "name": "CSS", "bytes": "317297" }, { "name": "Groff", "bytes": "30134" }, { "name": "JavaScript", "bytes": "820499" }, { "name": "Makefile", "bytes": "9933" }, { "name": "PHP", "bytes": "13589954" }, { "name": "Python", "bytes": "7385" }, { "name": "Shell", "bytes": "15980" } ], "symlink_target": "" }
layout: post title: "Amazon And Microsoft Just Made A Major Bet On User-Friendly Design" posturl: https://www.fastcodesign.com/90138636/amazon-and-microsoft-just-made-a-major-bet-on-user-friendly-design tags: - Amazon - Microsoft - Voice UI --- {% include post_info_header.md %} No, actually they didn't. In theory connecting Alexa and Cortana might sound like a good idea, there are too many walled gardens after all. But this will complicate the clunky voice UIs in these product - for starters how will the users know whom do they talk to at any given time? This is not user-friendly design at all. <!--more--> {% include post_info_footer.md %}
{ "content_hash": "88f66485b1bcd075f54566514919390d", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 323, "avg_line_length": 43.46666666666667, "alnum_prop": 0.7576687116564417, "repo_name": "polgarp/alg-exp", "id": "d4aed5e66cb883cdf0ff0c33da15c3e8c518126b", "size": "656", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/archive/24-20170912/2017-09-11-Amazon-And-Microsoft-Just-Made-A-Major-Bet-On-User-Friendly-Design.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "125" }, { "name": "HTML", "bytes": "3702" } ], "symlink_target": "" }
 #pragma once #include <aws/sagemaker/SageMaker_EXPORTS.h> #include <aws/sagemaker/SageMakerRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/sagemaker/model/InstanceType.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/sagemaker/model/DirectInternetAccess.h> #include <aws/sagemaker/model/Tag.h> #include <utility> namespace Aws { namespace SageMaker { namespace Model { /** */ class AWS_SAGEMAKER_API CreateNotebookInstanceRequest : public SageMakerRequest { public: CreateNotebookInstanceRequest(); // Service request name is the Operation name which will send this request out, // each operation should has unique request name, so that we can get operation's name from this request. // Note: this is not true for response, multiple operations may have the same response name, // so we can not get operation's name from response. inline virtual const char* GetServiceRequestName() const override { return "CreateNotebookInstance"; } Aws::String SerializePayload() const override; Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override; /** * <p>The name of the new notebook instance.</p> */ inline const Aws::String& GetNotebookInstanceName() const{ return m_notebookInstanceName; } /** * <p>The name of the new notebook instance.</p> */ inline void SetNotebookInstanceName(const Aws::String& value) { m_notebookInstanceNameHasBeenSet = true; m_notebookInstanceName = value; } /** * <p>The name of the new notebook instance.</p> */ inline void SetNotebookInstanceName(Aws::String&& value) { m_notebookInstanceNameHasBeenSet = true; m_notebookInstanceName = std::move(value); } /** * <p>The name of the new notebook instance.</p> */ inline void SetNotebookInstanceName(const char* value) { m_notebookInstanceNameHasBeenSet = true; m_notebookInstanceName.assign(value); } /** * <p>The name of the new notebook instance.</p> */ inline CreateNotebookInstanceRequest& WithNotebookInstanceName(const Aws::String& value) { SetNotebookInstanceName(value); return *this;} /** * <p>The name of the new notebook instance.</p> */ inline CreateNotebookInstanceRequest& WithNotebookInstanceName(Aws::String&& value) { SetNotebookInstanceName(std::move(value)); return *this;} /** * <p>The name of the new notebook instance.</p> */ inline CreateNotebookInstanceRequest& WithNotebookInstanceName(const char* value) { SetNotebookInstanceName(value); return *this;} /** * <p>The type of ML compute instance to launch for the notebook instance.</p> */ inline const InstanceType& GetInstanceType() const{ return m_instanceType; } /** * <p>The type of ML compute instance to launch for the notebook instance.</p> */ inline void SetInstanceType(const InstanceType& value) { m_instanceTypeHasBeenSet = true; m_instanceType = value; } /** * <p>The type of ML compute instance to launch for the notebook instance.</p> */ inline void SetInstanceType(InstanceType&& value) { m_instanceTypeHasBeenSet = true; m_instanceType = std::move(value); } /** * <p>The type of ML compute instance to launch for the notebook instance.</p> */ inline CreateNotebookInstanceRequest& WithInstanceType(const InstanceType& value) { SetInstanceType(value); return *this;} /** * <p>The type of ML compute instance to launch for the notebook instance.</p> */ inline CreateNotebookInstanceRequest& WithInstanceType(InstanceType&& value) { SetInstanceType(std::move(value)); return *this;} /** * <p>The ID of the subnet in a VPC to which you would like to have a connectivity * from your ML compute instance. </p> */ inline const Aws::String& GetSubnetId() const{ return m_subnetId; } /** * <p>The ID of the subnet in a VPC to which you would like to have a connectivity * from your ML compute instance. </p> */ inline void SetSubnetId(const Aws::String& value) { m_subnetIdHasBeenSet = true; m_subnetId = value; } /** * <p>The ID of the subnet in a VPC to which you would like to have a connectivity * from your ML compute instance. </p> */ inline void SetSubnetId(Aws::String&& value) { m_subnetIdHasBeenSet = true; m_subnetId = std::move(value); } /** * <p>The ID of the subnet in a VPC to which you would like to have a connectivity * from your ML compute instance. </p> */ inline void SetSubnetId(const char* value) { m_subnetIdHasBeenSet = true; m_subnetId.assign(value); } /** * <p>The ID of the subnet in a VPC to which you would like to have a connectivity * from your ML compute instance. </p> */ inline CreateNotebookInstanceRequest& WithSubnetId(const Aws::String& value) { SetSubnetId(value); return *this;} /** * <p>The ID of the subnet in a VPC to which you would like to have a connectivity * from your ML compute instance. </p> */ inline CreateNotebookInstanceRequest& WithSubnetId(Aws::String&& value) { SetSubnetId(std::move(value)); return *this;} /** * <p>The ID of the subnet in a VPC to which you would like to have a connectivity * from your ML compute instance. </p> */ inline CreateNotebookInstanceRequest& WithSubnetId(const char* value) { SetSubnetId(value); return *this;} /** * <p>The VPC security group IDs, in the form sg-xxxxxxxx. The security groups must * be for the same VPC as specified in the subnet. </p> */ inline const Aws::Vector<Aws::String>& GetSecurityGroupIds() const{ return m_securityGroupIds; } /** * <p>The VPC security group IDs, in the form sg-xxxxxxxx. The security groups must * be for the same VPC as specified in the subnet. </p> */ inline void SetSecurityGroupIds(const Aws::Vector<Aws::String>& value) { m_securityGroupIdsHasBeenSet = true; m_securityGroupIds = value; } /** * <p>The VPC security group IDs, in the form sg-xxxxxxxx. The security groups must * be for the same VPC as specified in the subnet. </p> */ inline void SetSecurityGroupIds(Aws::Vector<Aws::String>&& value) { m_securityGroupIdsHasBeenSet = true; m_securityGroupIds = std::move(value); } /** * <p>The VPC security group IDs, in the form sg-xxxxxxxx. The security groups must * be for the same VPC as specified in the subnet. </p> */ inline CreateNotebookInstanceRequest& WithSecurityGroupIds(const Aws::Vector<Aws::String>& value) { SetSecurityGroupIds(value); return *this;} /** * <p>The VPC security group IDs, in the form sg-xxxxxxxx. The security groups must * be for the same VPC as specified in the subnet. </p> */ inline CreateNotebookInstanceRequest& WithSecurityGroupIds(Aws::Vector<Aws::String>&& value) { SetSecurityGroupIds(std::move(value)); return *this;} /** * <p>The VPC security group IDs, in the form sg-xxxxxxxx. The security groups must * be for the same VPC as specified in the subnet. </p> */ inline CreateNotebookInstanceRequest& AddSecurityGroupIds(const Aws::String& value) { m_securityGroupIdsHasBeenSet = true; m_securityGroupIds.push_back(value); return *this; } /** * <p>The VPC security group IDs, in the form sg-xxxxxxxx. The security groups must * be for the same VPC as specified in the subnet. </p> */ inline CreateNotebookInstanceRequest& AddSecurityGroupIds(Aws::String&& value) { m_securityGroupIdsHasBeenSet = true; m_securityGroupIds.push_back(std::move(value)); return *this; } /** * <p>The VPC security group IDs, in the form sg-xxxxxxxx. The security groups must * be for the same VPC as specified in the subnet. </p> */ inline CreateNotebookInstanceRequest& AddSecurityGroupIds(const char* value) { m_securityGroupIdsHasBeenSet = true; m_securityGroupIds.push_back(value); return *this; } /** * <p> When you send any requests to AWS resources from the notebook instance, * Amazon SageMaker assumes this role to perform tasks on your behalf. You must * grant this role necessary permissions so Amazon SageMaker can perform these * tasks. The policy must allow the Amazon SageMaker service principal * (sagemaker.amazonaws.com) permissions to assume this role. For more information, * see <a * href="http://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-roles.html">Amazon * SageMaker Roles</a>. </p> <note> <p>To be able to pass this role to Amazon * SageMaker, the caller of this API must have the <code>iam:PassRole</code> * permission.</p> </note> */ inline const Aws::String& GetRoleArn() const{ return m_roleArn; } /** * <p> When you send any requests to AWS resources from the notebook instance, * Amazon SageMaker assumes this role to perform tasks on your behalf. You must * grant this role necessary permissions so Amazon SageMaker can perform these * tasks. The policy must allow the Amazon SageMaker service principal * (sagemaker.amazonaws.com) permissions to assume this role. For more information, * see <a * href="http://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-roles.html">Amazon * SageMaker Roles</a>. </p> <note> <p>To be able to pass this role to Amazon * SageMaker, the caller of this API must have the <code>iam:PassRole</code> * permission.</p> </note> */ inline void SetRoleArn(const Aws::String& value) { m_roleArnHasBeenSet = true; m_roleArn = value; } /** * <p> When you send any requests to AWS resources from the notebook instance, * Amazon SageMaker assumes this role to perform tasks on your behalf. You must * grant this role necessary permissions so Amazon SageMaker can perform these * tasks. The policy must allow the Amazon SageMaker service principal * (sagemaker.amazonaws.com) permissions to assume this role. For more information, * see <a * href="http://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-roles.html">Amazon * SageMaker Roles</a>. </p> <note> <p>To be able to pass this role to Amazon * SageMaker, the caller of this API must have the <code>iam:PassRole</code> * permission.</p> </note> */ inline void SetRoleArn(Aws::String&& value) { m_roleArnHasBeenSet = true; m_roleArn = std::move(value); } /** * <p> When you send any requests to AWS resources from the notebook instance, * Amazon SageMaker assumes this role to perform tasks on your behalf. You must * grant this role necessary permissions so Amazon SageMaker can perform these * tasks. The policy must allow the Amazon SageMaker service principal * (sagemaker.amazonaws.com) permissions to assume this role. For more information, * see <a * href="http://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-roles.html">Amazon * SageMaker Roles</a>. </p> <note> <p>To be able to pass this role to Amazon * SageMaker, the caller of this API must have the <code>iam:PassRole</code> * permission.</p> </note> */ inline void SetRoleArn(const char* value) { m_roleArnHasBeenSet = true; m_roleArn.assign(value); } /** * <p> When you send any requests to AWS resources from the notebook instance, * Amazon SageMaker assumes this role to perform tasks on your behalf. You must * grant this role necessary permissions so Amazon SageMaker can perform these * tasks. The policy must allow the Amazon SageMaker service principal * (sagemaker.amazonaws.com) permissions to assume this role. For more information, * see <a * href="http://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-roles.html">Amazon * SageMaker Roles</a>. </p> <note> <p>To be able to pass this role to Amazon * SageMaker, the caller of this API must have the <code>iam:PassRole</code> * permission.</p> </note> */ inline CreateNotebookInstanceRequest& WithRoleArn(const Aws::String& value) { SetRoleArn(value); return *this;} /** * <p> When you send any requests to AWS resources from the notebook instance, * Amazon SageMaker assumes this role to perform tasks on your behalf. You must * grant this role necessary permissions so Amazon SageMaker can perform these * tasks. The policy must allow the Amazon SageMaker service principal * (sagemaker.amazonaws.com) permissions to assume this role. For more information, * see <a * href="http://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-roles.html">Amazon * SageMaker Roles</a>. </p> <note> <p>To be able to pass this role to Amazon * SageMaker, the caller of this API must have the <code>iam:PassRole</code> * permission.</p> </note> */ inline CreateNotebookInstanceRequest& WithRoleArn(Aws::String&& value) { SetRoleArn(std::move(value)); return *this;} /** * <p> When you send any requests to AWS resources from the notebook instance, * Amazon SageMaker assumes this role to perform tasks on your behalf. You must * grant this role necessary permissions so Amazon SageMaker can perform these * tasks. The policy must allow the Amazon SageMaker service principal * (sagemaker.amazonaws.com) permissions to assume this role. For more information, * see <a * href="http://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-roles.html">Amazon * SageMaker Roles</a>. </p> <note> <p>To be able to pass this role to Amazon * SageMaker, the caller of this API must have the <code>iam:PassRole</code> * permission.</p> </note> */ inline CreateNotebookInstanceRequest& WithRoleArn(const char* value) { SetRoleArn(value); return *this;} /** * <p> If you provide a AWS KMS key ID, Amazon SageMaker uses it to encrypt data at * rest on the ML storage volume that is attached to your notebook instance. </p> */ inline const Aws::String& GetKmsKeyId() const{ return m_kmsKeyId; } /** * <p> If you provide a AWS KMS key ID, Amazon SageMaker uses it to encrypt data at * rest on the ML storage volume that is attached to your notebook instance. </p> */ inline void SetKmsKeyId(const Aws::String& value) { m_kmsKeyIdHasBeenSet = true; m_kmsKeyId = value; } /** * <p> If you provide a AWS KMS key ID, Amazon SageMaker uses it to encrypt data at * rest on the ML storage volume that is attached to your notebook instance. </p> */ inline void SetKmsKeyId(Aws::String&& value) { m_kmsKeyIdHasBeenSet = true; m_kmsKeyId = std::move(value); } /** * <p> If you provide a AWS KMS key ID, Amazon SageMaker uses it to encrypt data at * rest on the ML storage volume that is attached to your notebook instance. </p> */ inline void SetKmsKeyId(const char* value) { m_kmsKeyIdHasBeenSet = true; m_kmsKeyId.assign(value); } /** * <p> If you provide a AWS KMS key ID, Amazon SageMaker uses it to encrypt data at * rest on the ML storage volume that is attached to your notebook instance. </p> */ inline CreateNotebookInstanceRequest& WithKmsKeyId(const Aws::String& value) { SetKmsKeyId(value); return *this;} /** * <p> If you provide a AWS KMS key ID, Amazon SageMaker uses it to encrypt data at * rest on the ML storage volume that is attached to your notebook instance. </p> */ inline CreateNotebookInstanceRequest& WithKmsKeyId(Aws::String&& value) { SetKmsKeyId(std::move(value)); return *this;} /** * <p> If you provide a AWS KMS key ID, Amazon SageMaker uses it to encrypt data at * rest on the ML storage volume that is attached to your notebook instance. </p> */ inline CreateNotebookInstanceRequest& WithKmsKeyId(const char* value) { SetKmsKeyId(value); return *this;} /** * <p>A list of tags to associate with the notebook instance. You can add tags * later by using the <code>CreateTags</code> API.</p> */ inline const Aws::Vector<Tag>& GetTags() const{ return m_tags; } /** * <p>A list of tags to associate with the notebook instance. You can add tags * later by using the <code>CreateTags</code> API.</p> */ inline void SetTags(const Aws::Vector<Tag>& value) { m_tagsHasBeenSet = true; m_tags = value; } /** * <p>A list of tags to associate with the notebook instance. You can add tags * later by using the <code>CreateTags</code> API.</p> */ inline void SetTags(Aws::Vector<Tag>&& value) { m_tagsHasBeenSet = true; m_tags = std::move(value); } /** * <p>A list of tags to associate with the notebook instance. You can add tags * later by using the <code>CreateTags</code> API.</p> */ inline CreateNotebookInstanceRequest& WithTags(const Aws::Vector<Tag>& value) { SetTags(value); return *this;} /** * <p>A list of tags to associate with the notebook instance. You can add tags * later by using the <code>CreateTags</code> API.</p> */ inline CreateNotebookInstanceRequest& WithTags(Aws::Vector<Tag>&& value) { SetTags(std::move(value)); return *this;} /** * <p>A list of tags to associate with the notebook instance. You can add tags * later by using the <code>CreateTags</code> API.</p> */ inline CreateNotebookInstanceRequest& AddTags(const Tag& value) { m_tagsHasBeenSet = true; m_tags.push_back(value); return *this; } /** * <p>A list of tags to associate with the notebook instance. You can add tags * later by using the <code>CreateTags</code> API.</p> */ inline CreateNotebookInstanceRequest& AddTags(Tag&& value) { m_tagsHasBeenSet = true; m_tags.push_back(std::move(value)); return *this; } /** * <p>The name of a lifecycle configuration to associate with the notebook * instance. For information about lifestyle configurations, see <a * href="http://docs.aws.amazon.com/sagemaker/latest/dg/notebook-lifecycle-config.html">Step * 2.1: (Optional) Customize a Notebook Instance</a>.</p> */ inline const Aws::String& GetLifecycleConfigName() const{ return m_lifecycleConfigName; } /** * <p>The name of a lifecycle configuration to associate with the notebook * instance. For information about lifestyle configurations, see <a * href="http://docs.aws.amazon.com/sagemaker/latest/dg/notebook-lifecycle-config.html">Step * 2.1: (Optional) Customize a Notebook Instance</a>.</p> */ inline void SetLifecycleConfigName(const Aws::String& value) { m_lifecycleConfigNameHasBeenSet = true; m_lifecycleConfigName = value; } /** * <p>The name of a lifecycle configuration to associate with the notebook * instance. For information about lifestyle configurations, see <a * href="http://docs.aws.amazon.com/sagemaker/latest/dg/notebook-lifecycle-config.html">Step * 2.1: (Optional) Customize a Notebook Instance</a>.</p> */ inline void SetLifecycleConfigName(Aws::String&& value) { m_lifecycleConfigNameHasBeenSet = true; m_lifecycleConfigName = std::move(value); } /** * <p>The name of a lifecycle configuration to associate with the notebook * instance. For information about lifestyle configurations, see <a * href="http://docs.aws.amazon.com/sagemaker/latest/dg/notebook-lifecycle-config.html">Step * 2.1: (Optional) Customize a Notebook Instance</a>.</p> */ inline void SetLifecycleConfigName(const char* value) { m_lifecycleConfigNameHasBeenSet = true; m_lifecycleConfigName.assign(value); } /** * <p>The name of a lifecycle configuration to associate with the notebook * instance. For information about lifestyle configurations, see <a * href="http://docs.aws.amazon.com/sagemaker/latest/dg/notebook-lifecycle-config.html">Step * 2.1: (Optional) Customize a Notebook Instance</a>.</p> */ inline CreateNotebookInstanceRequest& WithLifecycleConfigName(const Aws::String& value) { SetLifecycleConfigName(value); return *this;} /** * <p>The name of a lifecycle configuration to associate with the notebook * instance. For information about lifestyle configurations, see <a * href="http://docs.aws.amazon.com/sagemaker/latest/dg/notebook-lifecycle-config.html">Step * 2.1: (Optional) Customize a Notebook Instance</a>.</p> */ inline CreateNotebookInstanceRequest& WithLifecycleConfigName(Aws::String&& value) { SetLifecycleConfigName(std::move(value)); return *this;} /** * <p>The name of a lifecycle configuration to associate with the notebook * instance. For information about lifestyle configurations, see <a * href="http://docs.aws.amazon.com/sagemaker/latest/dg/notebook-lifecycle-config.html">Step * 2.1: (Optional) Customize a Notebook Instance</a>.</p> */ inline CreateNotebookInstanceRequest& WithLifecycleConfigName(const char* value) { SetLifecycleConfigName(value); return *this;} /** * <p>Sets whether Amazon SageMaker provides internet access to the notebook * instance. If you set this to <code>Disabled</code> this notebook instance will * be able to access resources only in your VPC, and will not be able to connect to * Amazon SageMaker training and endpoint services unless your configure a NAT * Gateway in your VPC.</p> <p>For more information, see <a * href="http://docs.aws.amazon.com/sagemaker/latest/dg/appendix-additional-considerations.html#appendix-notebook-and-internet-access">Notebook * Instances Are Internet-Enabled by Default</a>. You can set the value of this * parameter to <code>Disabled</code> only if you set a value for the * <code>SubnetId</code> parameter.</p> */ inline const DirectInternetAccess& GetDirectInternetAccess() const{ return m_directInternetAccess; } /** * <p>Sets whether Amazon SageMaker provides internet access to the notebook * instance. If you set this to <code>Disabled</code> this notebook instance will * be able to access resources only in your VPC, and will not be able to connect to * Amazon SageMaker training and endpoint services unless your configure a NAT * Gateway in your VPC.</p> <p>For more information, see <a * href="http://docs.aws.amazon.com/sagemaker/latest/dg/appendix-additional-considerations.html#appendix-notebook-and-internet-access">Notebook * Instances Are Internet-Enabled by Default</a>. You can set the value of this * parameter to <code>Disabled</code> only if you set a value for the * <code>SubnetId</code> parameter.</p> */ inline void SetDirectInternetAccess(const DirectInternetAccess& value) { m_directInternetAccessHasBeenSet = true; m_directInternetAccess = value; } /** * <p>Sets whether Amazon SageMaker provides internet access to the notebook * instance. If you set this to <code>Disabled</code> this notebook instance will * be able to access resources only in your VPC, and will not be able to connect to * Amazon SageMaker training and endpoint services unless your configure a NAT * Gateway in your VPC.</p> <p>For more information, see <a * href="http://docs.aws.amazon.com/sagemaker/latest/dg/appendix-additional-considerations.html#appendix-notebook-and-internet-access">Notebook * Instances Are Internet-Enabled by Default</a>. You can set the value of this * parameter to <code>Disabled</code> only if you set a value for the * <code>SubnetId</code> parameter.</p> */ inline void SetDirectInternetAccess(DirectInternetAccess&& value) { m_directInternetAccessHasBeenSet = true; m_directInternetAccess = std::move(value); } /** * <p>Sets whether Amazon SageMaker provides internet access to the notebook * instance. If you set this to <code>Disabled</code> this notebook instance will * be able to access resources only in your VPC, and will not be able to connect to * Amazon SageMaker training and endpoint services unless your configure a NAT * Gateway in your VPC.</p> <p>For more information, see <a * href="http://docs.aws.amazon.com/sagemaker/latest/dg/appendix-additional-considerations.html#appendix-notebook-and-internet-access">Notebook * Instances Are Internet-Enabled by Default</a>. You can set the value of this * parameter to <code>Disabled</code> only if you set a value for the * <code>SubnetId</code> parameter.</p> */ inline CreateNotebookInstanceRequest& WithDirectInternetAccess(const DirectInternetAccess& value) { SetDirectInternetAccess(value); return *this;} /** * <p>Sets whether Amazon SageMaker provides internet access to the notebook * instance. If you set this to <code>Disabled</code> this notebook instance will * be able to access resources only in your VPC, and will not be able to connect to * Amazon SageMaker training and endpoint services unless your configure a NAT * Gateway in your VPC.</p> <p>For more information, see <a * href="http://docs.aws.amazon.com/sagemaker/latest/dg/appendix-additional-considerations.html#appendix-notebook-and-internet-access">Notebook * Instances Are Internet-Enabled by Default</a>. You can set the value of this * parameter to <code>Disabled</code> only if you set a value for the * <code>SubnetId</code> parameter.</p> */ inline CreateNotebookInstanceRequest& WithDirectInternetAccess(DirectInternetAccess&& value) { SetDirectInternetAccess(std::move(value)); return *this;} /** * <p>The size, in GB, of the ML storage volume to attach to the notebook * instance.</p> */ inline int GetVolumeSizeInGB() const{ return m_volumeSizeInGB; } /** * <p>The size, in GB, of the ML storage volume to attach to the notebook * instance.</p> */ inline void SetVolumeSizeInGB(int value) { m_volumeSizeInGBHasBeenSet = true; m_volumeSizeInGB = value; } /** * <p>The size, in GB, of the ML storage volume to attach to the notebook * instance.</p> */ inline CreateNotebookInstanceRequest& WithVolumeSizeInGB(int value) { SetVolumeSizeInGB(value); return *this;} private: Aws::String m_notebookInstanceName; bool m_notebookInstanceNameHasBeenSet; InstanceType m_instanceType; bool m_instanceTypeHasBeenSet; Aws::String m_subnetId; bool m_subnetIdHasBeenSet; Aws::Vector<Aws::String> m_securityGroupIds; bool m_securityGroupIdsHasBeenSet; Aws::String m_roleArn; bool m_roleArnHasBeenSet; Aws::String m_kmsKeyId; bool m_kmsKeyIdHasBeenSet; Aws::Vector<Tag> m_tags; bool m_tagsHasBeenSet; Aws::String m_lifecycleConfigName; bool m_lifecycleConfigNameHasBeenSet; DirectInternetAccess m_directInternetAccess; bool m_directInternetAccessHasBeenSet; int m_volumeSizeInGB; bool m_volumeSizeInGBHasBeenSet; }; } // namespace Model } // namespace SageMaker } // namespace Aws
{ "content_hash": "995e43779cdbd8e95ec5e5d7e7b9318b", "timestamp": "", "source": "github", "line_count": 553, "max_line_length": 185, "avg_line_length": 48.96925858951175, "alnum_prop": 0.697562776957164, "repo_name": "JoyIfBam5/aws-sdk-cpp", "id": "b4876738de024c8ec2fb434c5bb4190d1432a263", "size": "27653", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-cpp-sdk-sagemaker/include/aws/sagemaker/model/CreateNotebookInstanceRequest.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "11868" }, { "name": "C++", "bytes": "167818064" }, { "name": "CMake", "bytes": "591577" }, { "name": "HTML", "bytes": "4471" }, { "name": "Java", "bytes": "271801" }, { "name": "Python", "bytes": "85650" }, { "name": "Shell", "bytes": "5277" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Globalization; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.Core.Pipeline; using Azure.ResourceManager; using Azure.ResourceManager.Communication.Models; using Azure.ResourceManager.Resources; namespace Azure.ResourceManager.Communication { /// <summary> /// A Class representing an EmailServiceResource along with the instance operations that can be performed on it. /// If you have a <see cref="ResourceIdentifier" /> you can construct an <see cref="EmailServiceResource" /> /// from an instance of <see cref="ArmClient" /> using the GetEmailServiceResource method. /// Otherwise you can get one from its parent resource <see cref="ResourceGroupResource" /> using the GetEmailServiceResource method. /// </summary> public partial class EmailServiceResource : ArmResource { /// <summary> Generate the resource identifier of a <see cref="EmailServiceResource"/> instance. </summary> public static ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string emailServiceName) { var resourceId = $"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Communication/emailServices/{emailServiceName}"; return new ResourceIdentifier(resourceId); } private readonly ClientDiagnostics _emailServiceResourceEmailServicesClientDiagnostics; private readonly EmailServicesRestOperations _emailServiceResourceEmailServicesRestClient; private readonly EmailServiceResourceData _data; /// <summary> Initializes a new instance of the <see cref="EmailServiceResource"/> class for mocking. </summary> protected EmailServiceResource() { } /// <summary> Initializes a new instance of the <see cref = "EmailServiceResource"/> class. </summary> /// <param name="client"> The client parameters to use in these operations. </param> /// <param name="data"> The resource that is the target of operations. </param> internal EmailServiceResource(ArmClient client, EmailServiceResourceData data) : this(client, data.Id) { HasData = true; _data = data; } /// <summary> Initializes a new instance of the <see cref="EmailServiceResource"/> class. </summary> /// <param name="client"> The client parameters to use in these operations. </param> /// <param name="id"> The identifier of the resource that is the target of operations. </param> internal EmailServiceResource(ArmClient client, ResourceIdentifier id) : base(client, id) { _emailServiceResourceEmailServicesClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Communication", ResourceType.Namespace, Diagnostics); TryGetApiVersion(ResourceType, out string emailServiceResourceEmailServicesApiVersion); _emailServiceResourceEmailServicesRestClient = new EmailServicesRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, emailServiceResourceEmailServicesApiVersion); #if DEBUG ValidateResourceId(Id); #endif } /// <summary> Gets the resource type for the operations. </summary> public static readonly ResourceType ResourceType = "Microsoft.Communication/emailServices"; /// <summary> Gets whether or not the current instance has data. </summary> public virtual bool HasData { get; } /// <summary> Gets the data representing this Feature. </summary> /// <exception cref="InvalidOperationException"> Throws if there is no data loaded in the current instance. </exception> public virtual EmailServiceResourceData Data { get { if (!HasData) throw new InvalidOperationException("The current instance does not have data, you must call Get first."); return _data; } } internal static void ValidateResourceId(ResourceIdentifier id) { if (id.ResourceType != ResourceType) throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id)); } /// <summary> Gets a collection of CommunicationDomainResources in the EmailServiceResource. </summary> /// <returns> An object representing collection of CommunicationDomainResources and their operations over a CommunicationDomainResource. </returns> public virtual CommunicationDomainResourceCollection GetCommunicationDomainResources() { return GetCachedClient(Client => new CommunicationDomainResourceCollection(Client, Id)); } /// <summary> /// Get the Domains resource and its properties. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Communication/emailServices/{emailServiceName}/domains/{domainName} /// Operation Id: Domains_Get /// </summary> /// <param name="domainName"> The name of the Domains resource. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentException"> <paramref name="domainName"/> is an empty string, and was expected to be non-empty. </exception> /// <exception cref="ArgumentNullException"> <paramref name="domainName"/> is null. </exception> [ForwardsClientCalls] public virtual async Task<Response<CommunicationDomainResource>> GetCommunicationDomainResourceAsync(string domainName, CancellationToken cancellationToken = default) { return await GetCommunicationDomainResources().GetAsync(domainName, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get the Domains resource and its properties. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Communication/emailServices/{emailServiceName}/domains/{domainName} /// Operation Id: Domains_Get /// </summary> /// <param name="domainName"> The name of the Domains resource. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentException"> <paramref name="domainName"/> is an empty string, and was expected to be non-empty. </exception> /// <exception cref="ArgumentNullException"> <paramref name="domainName"/> is null. </exception> [ForwardsClientCalls] public virtual Response<CommunicationDomainResource> GetCommunicationDomainResource(string domainName, CancellationToken cancellationToken = default) { return GetCommunicationDomainResources().Get(domainName, cancellationToken); } /// <summary> /// Get the EmailService and its properties. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Communication/emailServices/{emailServiceName} /// Operation Id: EmailServices_Get /// </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual async Task<Response<EmailServiceResource>> GetAsync(CancellationToken cancellationToken = default) { using var scope = _emailServiceResourceEmailServicesClientDiagnostics.CreateScope("EmailServiceResource.Get"); scope.Start(); try { var response = await _emailServiceResourceEmailServicesRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false); if (response.Value == null) throw new RequestFailedException(response.GetRawResponse()); return Response.FromValue(new EmailServiceResource(Client, response.Value), response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Get the EmailService and its properties. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Communication/emailServices/{emailServiceName} /// Operation Id: EmailServices_Get /// </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual Response<EmailServiceResource> Get(CancellationToken cancellationToken = default) { using var scope = _emailServiceResourceEmailServicesClientDiagnostics.CreateScope("EmailServiceResource.Get"); scope.Start(); try { var response = _emailServiceResourceEmailServicesRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken); if (response.Value == null) throw new RequestFailedException(response.GetRawResponse()); return Response.FromValue(new EmailServiceResource(Client, response.Value), response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Operation to delete a EmailService. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Communication/emailServices/{emailServiceName} /// Operation Id: EmailServices_Delete /// </summary> /// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual async Task<ArmOperation> DeleteAsync(WaitUntil waitUntil, CancellationToken cancellationToken = default) { using var scope = _emailServiceResourceEmailServicesClientDiagnostics.CreateScope("EmailServiceResource.Delete"); scope.Start(); try { var response = await _emailServiceResourceEmailServicesRestClient.DeleteAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false); var operation = new CommunicationArmOperation(_emailServiceResourceEmailServicesClientDiagnostics, Pipeline, _emailServiceResourceEmailServicesRestClient.CreateDeleteRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name).Request, response, OperationFinalStateVia.Location); if (waitUntil == WaitUntil.Completed) await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false); return operation; } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Operation to delete a EmailService. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Communication/emailServices/{emailServiceName} /// Operation Id: EmailServices_Delete /// </summary> /// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual ArmOperation Delete(WaitUntil waitUntil, CancellationToken cancellationToken = default) { using var scope = _emailServiceResourceEmailServicesClientDiagnostics.CreateScope("EmailServiceResource.Delete"); scope.Start(); try { var response = _emailServiceResourceEmailServicesRestClient.Delete(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken); var operation = new CommunicationArmOperation(_emailServiceResourceEmailServicesClientDiagnostics, Pipeline, _emailServiceResourceEmailServicesRestClient.CreateDeleteRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name).Request, response, OperationFinalStateVia.Location); if (waitUntil == WaitUntil.Completed) operation.WaitForCompletionResponse(cancellationToken); return operation; } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Operation to update an existing EmailService. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Communication/emailServices/{emailServiceName} /// Operation Id: EmailServices_Update /// </summary> /// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param> /// <param name="patch"> Parameters for the update operation. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="patch"/> is null. </exception> public virtual async Task<ArmOperation<EmailServiceResource>> UpdateAsync(WaitUntil waitUntil, EmailServiceResourcePatch patch, CancellationToken cancellationToken = default) { Argument.AssertNotNull(patch, nameof(patch)); using var scope = _emailServiceResourceEmailServicesClientDiagnostics.CreateScope("EmailServiceResource.Update"); scope.Start(); try { var response = await _emailServiceResourceEmailServicesRestClient.UpdateAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, patch, cancellationToken).ConfigureAwait(false); var operation = new CommunicationArmOperation<EmailServiceResource>(new EmailServiceResourceOperationSource(Client), _emailServiceResourceEmailServicesClientDiagnostics, Pipeline, _emailServiceResourceEmailServicesRestClient.CreateUpdateRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, patch).Request, response, OperationFinalStateVia.AzureAsyncOperation); if (waitUntil == WaitUntil.Completed) await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); return operation; } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Operation to update an existing EmailService. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Communication/emailServices/{emailServiceName} /// Operation Id: EmailServices_Update /// </summary> /// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param> /// <param name="patch"> Parameters for the update operation. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="patch"/> is null. </exception> public virtual ArmOperation<EmailServiceResource> Update(WaitUntil waitUntil, EmailServiceResourcePatch patch, CancellationToken cancellationToken = default) { Argument.AssertNotNull(patch, nameof(patch)); using var scope = _emailServiceResourceEmailServicesClientDiagnostics.CreateScope("EmailServiceResource.Update"); scope.Start(); try { var response = _emailServiceResourceEmailServicesRestClient.Update(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, patch, cancellationToken); var operation = new CommunicationArmOperation<EmailServiceResource>(new EmailServiceResourceOperationSource(Client), _emailServiceResourceEmailServicesClientDiagnostics, Pipeline, _emailServiceResourceEmailServicesRestClient.CreateUpdateRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, patch).Request, response, OperationFinalStateVia.AzureAsyncOperation); if (waitUntil == WaitUntil.Completed) operation.WaitForCompletion(cancellationToken); return operation; } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Add a tag to the current resource. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Communication/emailServices/{emailServiceName} /// Operation Id: EmailServices_Get /// </summary> /// <param name="key"> The key for the tag. </param> /// <param name="value"> The value for the tag. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="key"/> or <paramref name="value"/> is null. </exception> public virtual async Task<Response<EmailServiceResource>> AddTagAsync(string key, string value, CancellationToken cancellationToken = default) { Argument.AssertNotNull(key, nameof(key)); Argument.AssertNotNull(value, nameof(value)); using var scope = _emailServiceResourceEmailServicesClientDiagnostics.CreateScope("EmailServiceResource.AddTag"); scope.Start(); try { if (await CanUseTagResourceAsync(cancellationToken: cancellationToken).ConfigureAwait(false)) { var originalTags = await GetTagResource().GetAsync(cancellationToken).ConfigureAwait(false); originalTags.Value.Data.TagValues[key] = value; await GetTagResource().CreateOrUpdateAsync(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken).ConfigureAwait(false); var originalResponse = await _emailServiceResourceEmailServicesRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false); return Response.FromValue(new EmailServiceResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); } else { var current = (await GetAsync(cancellationToken: cancellationToken).ConfigureAwait(false)).Value.Data; var patch = new EmailServiceResourcePatch(); foreach (var tag in current.Tags) { patch.Tags.Add(tag); } patch.Tags[key] = value; var result = await UpdateAsync(WaitUntil.Completed, patch, cancellationToken: cancellationToken).ConfigureAwait(false); return Response.FromValue(result.Value, result.GetRawResponse()); } } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Add a tag to the current resource. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Communication/emailServices/{emailServiceName} /// Operation Id: EmailServices_Get /// </summary> /// <param name="key"> The key for the tag. </param> /// <param name="value"> The value for the tag. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="key"/> or <paramref name="value"/> is null. </exception> public virtual Response<EmailServiceResource> AddTag(string key, string value, CancellationToken cancellationToken = default) { Argument.AssertNotNull(key, nameof(key)); Argument.AssertNotNull(value, nameof(value)); using var scope = _emailServiceResourceEmailServicesClientDiagnostics.CreateScope("EmailServiceResource.AddTag"); scope.Start(); try { if (CanUseTagResource(cancellationToken: cancellationToken)) { var originalTags = GetTagResource().Get(cancellationToken); originalTags.Value.Data.TagValues[key] = value; GetTagResource().CreateOrUpdate(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken); var originalResponse = _emailServiceResourceEmailServicesRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken); return Response.FromValue(new EmailServiceResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); } else { var current = Get(cancellationToken: cancellationToken).Value.Data; var patch = new EmailServiceResourcePatch(); foreach (var tag in current.Tags) { patch.Tags.Add(tag); } patch.Tags[key] = value; var result = Update(WaitUntil.Completed, patch, cancellationToken: cancellationToken); return Response.FromValue(result.Value, result.GetRawResponse()); } } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Replace the tags on the resource with the given set. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Communication/emailServices/{emailServiceName} /// Operation Id: EmailServices_Get /// </summary> /// <param name="tags"> The set of tags to use as replacement. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="tags"/> is null. </exception> public virtual async Task<Response<EmailServiceResource>> SetTagsAsync(IDictionary<string, string> tags, CancellationToken cancellationToken = default) { Argument.AssertNotNull(tags, nameof(tags)); using var scope = _emailServiceResourceEmailServicesClientDiagnostics.CreateScope("EmailServiceResource.SetTags"); scope.Start(); try { if (await CanUseTagResourceAsync(cancellationToken: cancellationToken).ConfigureAwait(false)) { await GetTagResource().DeleteAsync(WaitUntil.Completed, cancellationToken: cancellationToken).ConfigureAwait(false); var originalTags = await GetTagResource().GetAsync(cancellationToken).ConfigureAwait(false); originalTags.Value.Data.TagValues.ReplaceWith(tags); await GetTagResource().CreateOrUpdateAsync(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken).ConfigureAwait(false); var originalResponse = await _emailServiceResourceEmailServicesRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false); return Response.FromValue(new EmailServiceResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); } else { var current = (await GetAsync(cancellationToken: cancellationToken).ConfigureAwait(false)).Value.Data; var patch = new EmailServiceResourcePatch(); patch.Tags.ReplaceWith(tags); var result = await UpdateAsync(WaitUntil.Completed, patch, cancellationToken: cancellationToken).ConfigureAwait(false); return Response.FromValue(result.Value, result.GetRawResponse()); } } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Replace the tags on the resource with the given set. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Communication/emailServices/{emailServiceName} /// Operation Id: EmailServices_Get /// </summary> /// <param name="tags"> The set of tags to use as replacement. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="tags"/> is null. </exception> public virtual Response<EmailServiceResource> SetTags(IDictionary<string, string> tags, CancellationToken cancellationToken = default) { Argument.AssertNotNull(tags, nameof(tags)); using var scope = _emailServiceResourceEmailServicesClientDiagnostics.CreateScope("EmailServiceResource.SetTags"); scope.Start(); try { if (CanUseTagResource(cancellationToken: cancellationToken)) { GetTagResource().Delete(WaitUntil.Completed, cancellationToken: cancellationToken); var originalTags = GetTagResource().Get(cancellationToken); originalTags.Value.Data.TagValues.ReplaceWith(tags); GetTagResource().CreateOrUpdate(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken); var originalResponse = _emailServiceResourceEmailServicesRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken); return Response.FromValue(new EmailServiceResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); } else { var current = Get(cancellationToken: cancellationToken).Value.Data; var patch = new EmailServiceResourcePatch(); patch.Tags.ReplaceWith(tags); var result = Update(WaitUntil.Completed, patch, cancellationToken: cancellationToken); return Response.FromValue(result.Value, result.GetRawResponse()); } } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Removes a tag by key from the resource. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Communication/emailServices/{emailServiceName} /// Operation Id: EmailServices_Get /// </summary> /// <param name="key"> The key for the tag. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="key"/> is null. </exception> public virtual async Task<Response<EmailServiceResource>> RemoveTagAsync(string key, CancellationToken cancellationToken = default) { Argument.AssertNotNull(key, nameof(key)); using var scope = _emailServiceResourceEmailServicesClientDiagnostics.CreateScope("EmailServiceResource.RemoveTag"); scope.Start(); try { if (await CanUseTagResourceAsync(cancellationToken: cancellationToken).ConfigureAwait(false)) { var originalTags = await GetTagResource().GetAsync(cancellationToken).ConfigureAwait(false); originalTags.Value.Data.TagValues.Remove(key); await GetTagResource().CreateOrUpdateAsync(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken).ConfigureAwait(false); var originalResponse = await _emailServiceResourceEmailServicesRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false); return Response.FromValue(new EmailServiceResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); } else { var current = (await GetAsync(cancellationToken: cancellationToken).ConfigureAwait(false)).Value.Data; var patch = new EmailServiceResourcePatch(); foreach (var tag in current.Tags) { patch.Tags.Add(tag); } patch.Tags.Remove(key); var result = await UpdateAsync(WaitUntil.Completed, patch, cancellationToken: cancellationToken).ConfigureAwait(false); return Response.FromValue(result.Value, result.GetRawResponse()); } } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Removes a tag by key from the resource. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Communication/emailServices/{emailServiceName} /// Operation Id: EmailServices_Get /// </summary> /// <param name="key"> The key for the tag. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="key"/> is null. </exception> public virtual Response<EmailServiceResource> RemoveTag(string key, CancellationToken cancellationToken = default) { Argument.AssertNotNull(key, nameof(key)); using var scope = _emailServiceResourceEmailServicesClientDiagnostics.CreateScope("EmailServiceResource.RemoveTag"); scope.Start(); try { if (CanUseTagResource(cancellationToken: cancellationToken)) { var originalTags = GetTagResource().Get(cancellationToken); originalTags.Value.Data.TagValues.Remove(key); GetTagResource().CreateOrUpdate(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken); var originalResponse = _emailServiceResourceEmailServicesRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken); return Response.FromValue(new EmailServiceResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); } else { var current = Get(cancellationToken: cancellationToken).Value.Data; var patch = new EmailServiceResourcePatch(); foreach (var tag in current.Tags) { patch.Tags.Add(tag); } patch.Tags.Remove(key); var result = Update(WaitUntil.Completed, patch, cancellationToken: cancellationToken); return Response.FromValue(result.Value, result.GetRawResponse()); } } catch (Exception e) { scope.Failed(e); throw; } } } }
{ "content_hash": "dd8a8ec24e530fc0c7a55ddb3bd81cb1", "timestamp": "", "source": "github", "line_count": 544, "max_line_length": 488, "avg_line_length": 61.1875, "alnum_prop": 0.6543892327104488, "repo_name": "Azure/azure-sdk-for-net", "id": "c9a3c302a0d7fffe40ddb96a5d2541b7d78debc2", "size": "33424", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "sdk/communication/Azure.ResourceManager.Communication/src/Generated/EmailServiceResource.cs", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.5.0_09) on Wed Aug 01 14:02:17 EEST 2007 --> <TITLE> datechooser.beans.editor.border.types (DateChooser javadoc) </TITLE> <META NAME="keywords" CONTENT="datechooser.beans.editor.border.types package"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { parent.document.title="datechooser.beans.editor.border.types (DateChooser javadoc)"; } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../datechooser/beans/editor/border/package-summary.html"><B>PREV PACKAGE</B></A>&nbsp; &nbsp;<A HREF="../../../../../datechooser/beans/editor/cell/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?datechooser/beans/editor/border/types/package-summary.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <H2> Package datechooser.beans.editor.border.types </H2> Visual editors for all border types. <P> <B>See:</B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<A HREF="#package_description"><B>Description</B></A> <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Class Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../datechooser/beans/editor/border/types/AbstractBevelBorderEditor.html" title="class in datechooser.beans.editor.border.types">AbstractBevelBorderEditor</A></B></TD> <TD>Editor for bevel borders.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../datechooser/beans/editor/border/types/AbstractBorderEditor.html" title="class in datechooser.beans.editor.border.types">AbstractBorderEditor</A></B></TD> <TD>Abstract editor panel for some border type.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../datechooser/beans/editor/border/types/BevelBorderEditor.html" title="class in datechooser.beans.editor.border.types">BevelBorderEditor</A></B></TD> <TD>Editor for bevel borders.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../datechooser/beans/editor/border/types/CompoundBorderEditor.html" title="class in datechooser.beans.editor.border.types">CompoundBorderEditor</A></B></TD> <TD>Editor for compound borders.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../datechooser/beans/editor/border/types/DefaultBorderEditor.html" title="class in datechooser.beans.editor.border.types">DefaultBorderEditor</A></B></TD> <TD>Default border editing.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../datechooser/beans/editor/border/types/EmptyBorderEditor.html" title="class in datechooser.beans.editor.border.types">EmptyBorderEditor</A></B></TD> <TD>Editor for empty borders.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../datechooser/beans/editor/border/types/EtchedBorderEditor.html" title="class in datechooser.beans.editor.border.types">EtchedBorderEditor</A></B></TD> <TD>Editor for etched borders.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../datechooser/beans/editor/border/types/LineBorderEditor.html" title="class in datechooser.beans.editor.border.types">LineBorderEditor</A></B></TD> <TD>Editor for line borders.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../datechooser/beans/editor/border/types/MatteBorderEditor.html" title="class in datechooser.beans.editor.border.types">MatteBorderEditor</A></B></TD> <TD>Editor for matte borders.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../datechooser/beans/editor/border/types/NoBorderEditor.html" title="class in datechooser.beans.editor.border.types">NoBorderEditor</A></B></TD> <TD>Lets set no border.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../datechooser/beans/editor/border/types/SoftBevelBorderEditor.html" title="class in datechooser.beans.editor.border.types">SoftBevelBorderEditor</A></B></TD> <TD>Editor for soft bevel borders.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../datechooser/beans/editor/border/types/TitledBorderEditor.html" title="class in datechooser.beans.editor.border.types">TitledBorderEditor</A></B></TD> <TD>Editor for titled borders.</TD> </TR> </TABLE> &nbsp; <P> <A NAME="package_description"><!-- --></A><H2> Package datechooser.beans.editor.border.types Description </H2> <P> Visual editors for all border types.<br> Визуальные редакторы для всех типов границ. <P> <P> <DL> <DT><B>Author:</B></DT> <DD>Androsov Vadim ([email protected])</DD> </DL> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../datechooser/beans/editor/border/package-summary.html"><B>PREV PACKAGE</B></A>&nbsp; &nbsp;<A HREF="../../../../../datechooser/beans/editor/cell/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?datechooser/beans/editor/border/types/package-summary.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
{ "content_hash": "a34aa743c0caef70f8c7542e019de4a2", "timestamp": "", "source": "github", "line_count": 216, "max_line_length": 206, "avg_line_length": 47.31018518518518, "alnum_prop": 0.6380272042274195, "repo_name": "AndresJMM/Proyecto", "id": "8acb0af7a9aaab0c73d82824ddf5282c068e0f8d", "size": "10256", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Proyecto/librerias/jdatechooser_bin_doc_1_1_1/javadoc/datechooser/beans/editor/border/types/package-summary.html", "mode": "33261", "license": "apache-2.0", "language": [], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in Spl. pl. 2:1053. 1753 #### Original name null ### Remarks null
{ "content_hash": "95e16fef168d3fa1c6593724979a6d15", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 11.615384615384615, "alnum_prop": 0.6821192052980133, "repo_name": "mdoering/backbone", "id": "7bad558b815c58aa7a32d1c1d557ba50585623c3", "size": "200", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Chenopodiaceae/Atriplex/Atriplex portulacoides/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
using Microsoft.Practices.EnterpriseLibrary.SemanticLogging; using System; using System.Collections.Generic; using System.Diagnostics.Tracing; using System.Linq; using System.Reactive.Linq; using System.Text; using System.Threading.Tasks; namespace OneCog.Spark.Sparkles { public interface IMonitor : IObservable<EventEntry> { } internal class Monitor : IMonitor { private readonly ObservableEventListener _sparkListener; private readonly ObservableEventListener _elasticSearchListener; private readonly IObservable<EventEntry> _observable; public Monitor() { _sparkListener = new ObservableEventListener(); _sparkListener.EnableEvents((EventSource)Instrumentation.SparkCore, EventLevel.Warning); _elasticSearchListener = new ObservableEventListener(); _elasticSearchListener.EnableEvents((EventSource)Instrumentation.ElasticSearch, EventLevel.Warning); _observable = Observable.Merge(_sparkListener, _elasticSearchListener).Publish().RefCount(); } public IDisposable Subscribe(IObserver<EventEntry> observer) { return _observable.Subscribe(observer); } } }
{ "content_hash": "5b2e1ab339bf6597bbb076cca959abc5", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 112, "avg_line_length": 31.641025641025642, "alnum_prop": 0.7155591572123177, "repo_name": "ibebbs/OneCog.Spark.Sparkles", "id": "b5cc92411d2dc3d87d4c06052b53cbac55832b5b", "size": "1236", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/OneCog.Spark.Sparkles/Monitor.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "61027" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item> <shape android:shape="rectangle"> <solid android:color="#CABBBBBB"/> <corners android:radius="2dp" /> </shape> </item> <item android:left="1dp" android:right="1dp" android:top="1dp" android:bottom="1dp"> <shape android:shape="rectangle"> <solid android:color="@android:color/white"/> <corners android:radius="1dp" /> </shape> </item> </layer-list>
{ "content_hash": "17afe72e4a4ed314c1e6a06ac49a5cc7", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 71, "avg_line_length": 29.7, "alnum_prop": 0.5538720538720538, "repo_name": "Xyresic/Kaku", "id": "32076dd46b55c9773d63ab5de94b8726a1473192", "size": "594", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/src/main/res/drawable/bg_solid_border_corners_0_white_black_round.xml", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Java", "bytes": "177148" }, { "name": "Kotlin", "bytes": "214054" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "4d8c1ec9c1724aa6a5ae2b505478bee5", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "173d7e76971e407f0d1faa68e76bf37d48249b9c", "size": "195", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Habenaria/Habenaria intermedia/ Syn. Ochyrorchis intermedia/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
using Nucleus.Base; using Nucleus.Logs; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Nucleus.Game { /// <summary> /// Base class for simple effects /// </summary> public abstract class BasicEffect : Unique, IEffect { public abstract bool Apply(IActionLog log, EffectContext context); } }
{ "content_hash": "55120756295e8e6194f41a08f92d6cc6", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 74, "avg_line_length": 22.38888888888889, "alnum_prop": 0.707196029776675, "repo_name": "pnjeffries/Nucleus", "id": "48ffecddd4a27428c81ce51904e77b9017aafb24", "size": "405", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Nucleus/Nucleus.Game/Effects/BasicEffect.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "4478271" } ], "symlink_target": "" }