text
stringlengths
2
100k
meta
dict
import React from 'react'; import JwtDetail from '../component/JwtDetail'; import { parseJwt } from '../utils'; import '../../css/dev-tools-jwt-detail-panel.less'; export default class DevToolsJwtDetailPanel extends React.Component { onClose() { this.props.onClose(); } render() { let type = null; let data = this.props.data; let jwt = parseJwt(data.value); switch (data.source) { case 'cookie': type = "Cookie"; break; case 'request': let capitalizedType = data.type[0].toUpperCase() + data.type.substring(1); type = capitalizedType + " header"; break; case 'storage': switch (data.type) { case 'session': type = "Session storage"; break; case 'local': type = "Local storage"; break; } break; } return ( <div id="dev-tools-jwt-detail-panel"> <div className="sub-menu"> <i className="fa fa-times close-button" aria-hidden="true" onClick={this.onClose.bind(this)}></i> <div className="item"> {data.name} </div> </div> <div className="content"> <JwtDetail jwt={jwt} showRaw={true} /> </div> </div> ); } }
{ "pile_set_name": "Github" }
# dev.loklak.org This repository aggregates separated rendered HTML pages from various Loklak projects. Please **do not** submit issues or pull requests to this repository. Due to the fact it's automated and only contains rendered HTML pages. Aggregation is achieved with `git subtree` which is used over submodules for stability reasons.
{ "pile_set_name": "Github" }
<?php namespace Hamcrest\Type; /* Copyright (c) 2010 hamcrest.org */ use Hamcrest\Core\IsTypeOf; /** * Tests whether the value is a scalar (boolean, integer, double, or string). */ class IsScalar extends IsTypeOf { public function __construct() { parent::__construct('scalar'); } public function matches($item) { return is_scalar($item); } /** * Is the value a scalar (boolean, integer, double, or string)? * * @factory */ public static function scalarValue() { return new self; } }
{ "pile_set_name": "Github" }
/* * Copyright 2018 Rundeck, Inc. (http://rundeck.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.rundeck.util import spock.lang.Specification import spock.lang.Unroll import java.util.concurrent.TimeUnit import static org.rundeck.util.Sizes.parseFileSize /** * @author greg * @since 2/23/17 */ class SizesTest extends Specification { @Unroll("parse #string expect #val") def "file size"() { expect: parseFileSize(string) == val where: string | val "1" | 1L "1k" | 1024L "1K" | 1024L "1Kb" | 1024L "1KB" | 1024L "1kb" | 1024L "500KB" | 1024L * 500 "1m" | 1024 * 1024L "100M" | 1024 * 1024L * 100 "1024mb" | 1024 * 1024L * 1024L "1g" | 1024 * 1024L * 1024L "1t" | 1024 * 1024L * 1024L * 1024L } @Unroll("parse #string expect #val") def "file size invalid"() { expect: parseFileSize(string) == val where: string | val "1z" | null "1H" | null "1abcd" | null "asdf2" | null } def "evaluate timeout duration"() { expect: result == Sizes.parseTimeDuration(value) where: value | result "1s" | 1L "1m" | 60 "1h" | 3600 "1d" | 24 * 3600 "1w" | 7 * 24 * 3600 "1y" | 365 * 24 * 3600 } def "evaluate timeout duration units"() { expect: Sizes.parseTimeDuration(value, unit) == result where: value | unit | result "1s" | TimeUnit.SECONDS | 1L "2s" | TimeUnit.SECONDS | 2L "2000s" | TimeUnit.SECONDS | 2000L "1m" | TimeUnit.MINUTES | 1 "2m" | TimeUnit.MINUTES | 2 "2000m" | TimeUnit.MINUTES | 2000 "1h" | TimeUnit.HOURS | 1 "2h" | TimeUnit.HOURS | 2 "2000h" | TimeUnit.HOURS | 2000 "1d" | TimeUnit.DAYS | 1 "2d" | TimeUnit.DAYS | 2 "2000d" | TimeUnit.DAYS | 2000 "1w" | TimeUnit.DAYS | 7 "2w" | TimeUnit.DAYS | 14 "2000w" | TimeUnit.DAYS | 14000 "1y" | TimeUnit.SECONDS | 365 * 24 * 3600 "1y" | TimeUnit.DAYS | 365 "2y" | TimeUnit.DAYS | 2 * 365 "2000y" | TimeUnit.DAYS | 2000 * 365 } def "evaluate timeout duration multiple unit"() { expect: result == Sizes.parseTimeDuration(value) where: value | result "1d1h1m1s" | 24 * 3600 + 3600 + 60 + 1L "1d1h1m2s" | 24 * 3600 + 3600 + 60 + 2 "1d1h17m1s" | 24 * 3600 + 3600 + (17 * 60) + 1 "1d9h1m1s" | 24 * 3600 + (9 * 3600) + (1 * 60) + 1 "3d1h1m1s" | (3 * 24 * 3600) + (1 * 3600) + (1 * 60) + 1 } def "evaluate timeout duration ignored text"() { expect: result == Sizes.parseTimeDuration(value) where: value | result "1d 1h 1m 1s" | 24 * 3600 + 3600 + 60 + 1L "1d 1h 1m 2s" | 24 * 3600 + 3600 + 60 + 2 "1d 1h 17m 1s" | 24 * 3600 + 3600 + (17 * 60) + 1 "1d 9h 1m 1s" | 24 * 3600 + (9 * 3600) + (1 * 60) + 1 "3d 1h 1m 1s" | (3 * 24 * 3600) + (1 * 3600) + (1 * 60) + 1 "3d 12h #usual wait time" | (3 * 24 * 3600) + (12 * 3600) + (0 * 60) + 0 } def "evaluate timeout duration default seconds"() { expect: result == Sizes.parseTimeDuration(value) where: value | result "0" | 0L "123" | 123 "10000" | 10000 "5858929" | 5858929 } def "evaluate timeout duration invalid"() { expect: result == Sizes.parseTimeDuration(value) where: value | result "asdf" | 0L "123z" | 0 } }
{ "pile_set_name": "Github" }
/************************************************************* * * MathJax/jax/output/HTML-CSS/fonts/STIX/General/Bold/Cyrillic.js * * Copyright (c) 2009-2018 The MathJax Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ MathJax.Hub.Insert( MathJax.OutputJax['HTML-CSS'].FONTDATA.FONTS['STIXGeneral-bold'], { 0x401: [916,0,667,16,641], // CYRILLIC CAPITAL LETTER IO 0x402: [676,97,856,40,809], // CYRILLIC CAPITAL LETTER DJE 0x403: [963,0,632,20,600], // CYRILLIC CAPITAL LETTER GJE 0x404: [691,19,685,37,638], // CYRILLIC CAPITAL LETTER UKRAINIAN IE 0x405: [692,19,556,35,513], // CYRILLIC CAPITAL LETTER DZE 0x406: [676,0,389,20,370], // CYRILLIC CAPITAL LETTER BYELORUSSIAN-UKRAINIAN I 0x407: [916,0,389,20,370], // CYRILLIC CAPITAL LETTER YI 0x408: [676,96,500,3,478], // CYRILLIC CAPITAL LETTER JE 0x409: [676,18,1005,10,958], // CYRILLIC CAPITAL LETTER LJE 0x40A: [676,0,1054,21,1007], // CYRILLIC CAPITAL LETTER NJE 0x40B: [676,0,883,40,868], // CYRILLIC CAPITAL LETTER TSHE 0x40C: [923,0,759,21,741], // CYRILLIC CAPITAL LETTER KJE 0x40E: [926,22,722,15,699], // CYRILLIC CAPITAL LETTER SHORT U 0x40F: [676,176,770,21,753], // CYRILLIC CAPITAL LETTER DZHE 0x410: [690,0,722,9,689], // CYRILLIC CAPITAL LETTER A 0x411: [676,0,667,16,619], // CYRILLIC CAPITAL LETTER BE 0x412: [676,0,667,16,619], // CYRILLIC CAPITAL LETTER VE 0x413: [676,0,632,20,600], // CYRILLIC CAPITAL LETTER GHE 0x414: [676,176,715,24,691], // CYRILLIC CAPITAL LETTER DE 0x415: [676,0,667,16,641], // CYRILLIC CAPITAL LETTER IE 0x416: [684,0,1130,32,1091], // CYRILLIC CAPITAL LETTER ZHE 0x417: [691,19,570,22,531], // CYRILLIC CAPITAL LETTER ZE 0x418: [676,0,778,21,759], // CYRILLIC CAPITAL LETTER I 0x419: [926,0,778,21,759], // CYRILLIC CAPITAL LETTER SHORT I 0x41A: [684,0,759,21,741], // CYRILLIC CAPITAL LETTER KA 0x41B: [676,18,738,10,719], // CYRILLIC CAPITAL LETTER EL 0x41C: [676,0,944,14,921], // CYRILLIC CAPITAL LETTER EM 0x41D: [676,0,778,21,759], // CYRILLIC CAPITAL LETTER EN 0x41E: [691,19,778,35,743], // CYRILLIC CAPITAL LETTER O 0x41F: [676,0,762,13,751], // CYRILLIC CAPITAL LETTER PE 0x420: [676,0,611,16,600], // CYRILLIC CAPITAL LETTER ER 0x421: [691,19,709,36,674], // CYRILLIC CAPITAL LETTER ES 0x422: [676,0,667,31,636], // CYRILLIC CAPITAL LETTER TE 0x423: [676,22,722,15,699], // CYRILLIC CAPITAL LETTER U 0x424: [676,0,850,25,825], // CYRILLIC CAPITAL LETTER EF 0x425: [676,0,722,16,699], // CYRILLIC CAPITAL LETTER HA 0x426: [676,176,770,21,753], // CYRILLIC CAPITAL LETTER TSE 0x427: [676,0,732,7,710], // CYRILLIC CAPITAL LETTER CHE 0x428: [676,0,1020,21,1001], // CYRILLIC CAPITAL LETTER SHA 0x429: [676,176,1020,21,1001], // CYRILLIC CAPITAL LETTER SHCHA 0x42A: [676,0,805,41,757], // CYRILLIC CAPITAL LETTER HARD SIGN 0x42B: [676,0,1004,16,985], // CYRILLIC CAPITAL LETTER YERU 0x42C: [676,0,672,19,624], // CYRILLIC CAPITAL LETTER SOFT SIGN 0x42D: [691,19,685,37,648], // CYRILLIC CAPITAL LETTER E 0x42E: [691,19,955,21,920], // CYRILLIC CAPITAL LETTER YU 0x42F: [676,0,736,12,687], // CYRILLIC CAPITAL LETTER YA 0x430: [473,14,517,42,505], // CYRILLIC SMALL LETTER A 0x431: [691,14,500,25,476], // CYRILLIC SMALL LETTER BE 0x432: [461,0,492,21,475], // CYRILLIC SMALL LETTER VE 0x433: [461,0,451,21,434], // CYRILLIC SMALL LETTER GHE 0x434: [461,143,541,19,524], // CYRILLIC SMALL LETTER DE 0x435: [473,14,444,25,427], // CYRILLIC SMALL LETTER IE 0x436: [467,0,762,14,748], // CYRILLIC SMALL LETTER ZHE 0x437: [473,17,446,25,420], // CYRILLIC SMALL LETTER ZE 0x438: [461,0,556,21,543], // CYRILLIC SMALL LETTER I 0x439: [691,0,556,21,543], // CYRILLIC SMALL LETTER SHORT I 0x43A: [467,0,556,22,543], // CYRILLIC SMALL LETTER KA 0x43B: [461,11,546,11,529], // CYRILLIC SMALL LETTER EL 0x43C: [461,0,657,20,640], // CYRILLIC SMALL LETTER EM 0x43D: [461,0,560,21,543], // CYRILLIC SMALL LETTER EN 0x43E: [473,14,500,25,476], // CYRILLIC SMALL LETTER O 0x43F: [461,0,556,21,543], // CYRILLIC SMALL LETTER PE 0x440: [473,205,556,19,524], // CYRILLIC SMALL LETTER ER 0x441: [473,14,444,25,430], // CYRILLIC SMALL LETTER ES 0x442: [461,0,509,18,493], // CYRILLIC SMALL LETTER TE 0x443: [461,205,520,16,502], // CYRILLIC SMALL LETTER U 0x444: [676,205,726,31,693], // CYRILLIC SMALL LETTER EF 0x445: [461,0,500,12,484], // CYRILLIC SMALL LETTER HA 0x446: [461,143,556,21,543], // CYRILLIC SMALL LETTER TSE 0x447: [461,0,559,20,542], // CYRILLIC SMALL LETTER CHE 0x448: [461,0,841,21,824], // CYRILLIC SMALL LETTER SHA 0x449: [461,143,841,21,824], // CYRILLIC SMALL LETTER SHCHA 0x44A: [461,0,607,15,592], // CYRILLIC SMALL LETTER HARD SIGN 0x44B: [461,0,759,22,741], // CYRILLIC SMALL LETTER YERU 0x44C: [461,0,498,21,483], // CYRILLIC SMALL LETTER SOFT SIGN 0x44D: [473,14,453,24,429], // CYRILLIC SMALL LETTER E 0x44E: [473,14,785,21,761], // CYRILLIC SMALL LETTER YU 0x44F: [461,0,526,11,509], // CYRILLIC SMALL LETTER YA 0x451: [666,14,444,25,427], // CYRILLIC SMALL LETTER IO 0x452: [676,205,556,15,485], // CYRILLIC SMALL LETTER DJE 0x453: [713,0,451,21,434], // CYRILLIC SMALL LETTER GJE 0x454: [473,14,453,24,429], // CYRILLIC SMALL LETTER UKRAINIAN IE 0x455: [473,14,389,25,361], // CYRILLIC SMALL LETTER DZE 0x456: [691,0,278,15,256], // CYRILLIC SMALL LETTER BYELORUSSIAN-UKRAINIAN I 0x457: [666,0,278,-30,309], // CYRILLIC SMALL LETTER YI 0x458: [691,203,333,-57,263], // CYRILLIC SMALL LETTER JE 0x459: [461,11,760,11,745], // CYRILLIC SMALL LETTER LJE 0x45A: [461,0,775,21,760], // CYRILLIC SMALL LETTER NJE 0x45B: [676,0,556,15,534], // CYRILLIC SMALL LETTER TSHE 0x45C: [713,0,556,22,543], // CYRILLIC SMALL LETTER KJE 0x45E: [691,205,500,16,502], // CYRILLIC SMALL LETTER SHORT U 0x45F: [461,143,556,21,543], // CYRILLIC SMALL LETTER DZHE 0x462: [676,0,793,31,745], // CYRILLIC CAPITAL LETTER YAT 0x463: [676,0,602,15,587], // CYRILLIC SMALL LETTER YAT 0x46A: [676,0,1123,30,1088], // CYRILLIC CAPITAL LETTER BIG YUS 0x46B: [461,0,762,14,748], // CYRILLIC SMALL LETTER BIG YUS 0x472: [691,19,778,35,743], // CYRILLIC CAPITAL LETTER FITA 0x473: [473,14,500,25,476], // CYRILLIC SMALL LETTER FITA 0x474: [691,18,793,16,778], // CYRILLIC CAPITAL LETTER IZHITSA 0x475: [470,14,559,21,550], // CYRILLIC SMALL LETTER IZHITSA 0x490: [833,0,626,14,594], // CYRILLIC CAPITAL LETTER GHE WITH UPTURN 0x491: [602,0,451,21,434] // CYRILLIC SMALL LETTER GHE WITH UPTURN } ); MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].fontDir + "/General/Bold/Cyrillic.js");
{ "pile_set_name": "Github" }
/** * \file pk.h * * \brief Public Key abstraction layer * * Copyright (C) 2006-2015, ARM Limited, 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 * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file is part of mbed TLS (https://tls.mbed.org) */ #ifndef MBEDTLS_PK_H #define MBEDTLS_PK_H #if !defined(MBEDTLS_CONFIG_FILE) #include "config.h" #else #include MBEDTLS_CONFIG_FILE #endif #include "md.h" #if defined(MBEDTLS_RSA_C) #include "rsa.h" #endif #if defined(MBEDTLS_ECP_C) #include "ecp.h" #endif #if defined(MBEDTLS_ECDSA_C) #include "ecdsa.h" #endif #if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \ !defined(inline) && !defined(__cplusplus) #define inline __inline #endif #define MBEDTLS_ERR_PK_ALLOC_FAILED -0x3F80 /**< Memory allocation failed. */ #define MBEDTLS_ERR_PK_TYPE_MISMATCH -0x3F00 /**< Type mismatch, eg attempt to encrypt with an ECDSA key */ #define MBEDTLS_ERR_PK_BAD_INPUT_DATA -0x3E80 /**< Bad input parameters to function. */ #define MBEDTLS_ERR_PK_FILE_IO_ERROR -0x3E00 /**< Read/write of file failed. */ #define MBEDTLS_ERR_PK_KEY_INVALID_VERSION -0x3D80 /**< Unsupported key version */ #define MBEDTLS_ERR_PK_KEY_INVALID_FORMAT -0x3D00 /**< Invalid key tag or value. */ #define MBEDTLS_ERR_PK_UNKNOWN_PK_ALG -0x3C80 /**< Key algorithm is unsupported (only RSA and EC are supported). */ #define MBEDTLS_ERR_PK_PASSWORD_REQUIRED -0x3C00 /**< Private key password can't be empty. */ #define MBEDTLS_ERR_PK_PASSWORD_MISMATCH -0x3B80 /**< Given private key password does not allow for correct decryption. */ #define MBEDTLS_ERR_PK_INVALID_PUBKEY -0x3B00 /**< The pubkey tag or value is invalid (only RSA and EC are supported). */ #define MBEDTLS_ERR_PK_INVALID_ALG -0x3A80 /**< The algorithm tag or value is invalid. */ #define MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE -0x3A00 /**< Elliptic curve is unsupported (only NIST curves are supported). */ #define MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE -0x3980 /**< Unavailable feature, e.g. RSA disabled for RSA key. */ #define MBEDTLS_ERR_PK_SIG_LEN_MISMATCH -0x3900 /**< The signature is valid but its length is less than expected. */ #ifdef __cplusplus extern "C" { #endif /** * \brief Public key types */ typedef enum { MBEDTLS_PK_NONE=0, MBEDTLS_PK_RSA, MBEDTLS_PK_ECKEY, MBEDTLS_PK_ECKEY_DH, MBEDTLS_PK_ECDSA, MBEDTLS_PK_RSA_ALT, MBEDTLS_PK_RSASSA_PSS, } mbedtls_pk_type_t; /** * \brief Options for RSASSA-PSS signature verification. * See \c mbedtls_rsa_rsassa_pss_verify_ext() */ typedef struct { mbedtls_md_type_t mgf1_hash_id; int expected_salt_len; } mbedtls_pk_rsassa_pss_options; /** * \brief Types for interfacing with the debug module */ typedef enum { MBEDTLS_PK_DEBUG_NONE = 0, MBEDTLS_PK_DEBUG_MPI, MBEDTLS_PK_DEBUG_ECP, } mbedtls_pk_debug_type; /** * \brief Item to send to the debug module */ typedef struct { mbedtls_pk_debug_type type; const char *name; void *value; } mbedtls_pk_debug_item; /** Maximum number of item send for debugging, plus 1 */ #define MBEDTLS_PK_DEBUG_MAX_ITEMS 3 /** * \brief Public key information and operations */ typedef struct mbedtls_pk_info_t mbedtls_pk_info_t; /** * \brief Public key container */ typedef struct { const mbedtls_pk_info_t * pk_info; /**< Public key informations */ void * pk_ctx; /**< Underlying public key context */ } mbedtls_pk_context; #if defined(MBEDTLS_RSA_C) /** * Quick access to an RSA context inside a PK context. * * \warning You must make sure the PK context actually holds an RSA context * before using this function! */ static inline mbedtls_rsa_context *mbedtls_pk_rsa( const mbedtls_pk_context pk ) { return( (mbedtls_rsa_context *) (pk).pk_ctx ); } #endif /* MBEDTLS_RSA_C */ #if defined(MBEDTLS_ECP_C) /** * Quick access to an EC context inside a PK context. * * \warning You must make sure the PK context actually holds an EC context * before using this function! */ static inline mbedtls_ecp_keypair *mbedtls_pk_ec( const mbedtls_pk_context pk ) { return( (mbedtls_ecp_keypair *) (pk).pk_ctx ); } #endif /* MBEDTLS_ECP_C */ #if defined(MBEDTLS_PK_RSA_ALT_SUPPORT) /** * \brief Types for RSA-alt abstraction */ typedef int (*mbedtls_pk_rsa_alt_decrypt_func)( void *ctx, int mode, size_t *olen, const unsigned char *input, unsigned char *output, size_t output_max_len ); typedef int (*mbedtls_pk_rsa_alt_sign_func)( void *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, mbedtls_md_type_t md_alg, unsigned int hashlen, const unsigned char *hash, unsigned char *sig ); typedef size_t (*mbedtls_pk_rsa_alt_key_len_func)( void *ctx ); #endif /* MBEDTLS_PK_RSA_ALT_SUPPORT */ /** * \brief Return information associated with the given PK type * * \param pk_type PK type to search for. * * \return The PK info associated with the type or NULL if not found. */ const mbedtls_pk_info_t *mbedtls_pk_info_from_type( mbedtls_pk_type_t pk_type ); /** * \brief Initialize a mbedtls_pk_context (as NONE) */ void mbedtls_pk_init( mbedtls_pk_context *ctx ); /** * \brief Free a mbedtls_pk_context */ void mbedtls_pk_free( mbedtls_pk_context *ctx ); /** * \brief Initialize a PK context with the information given * and allocates the type-specific PK subcontext. * * \param ctx Context to initialize. Must be empty (type NONE). * \param info Information to use * * \return 0 on success, * MBEDTLS_ERR_PK_BAD_INPUT_DATA on invalid input, * MBEDTLS_ERR_PK_ALLOC_FAILED on allocation failure. * * \note For contexts holding an RSA-alt key, use * \c mbedtls_pk_setup_rsa_alt() instead. */ int mbedtls_pk_setup( mbedtls_pk_context *ctx, const mbedtls_pk_info_t *info ); #if defined(MBEDTLS_PK_RSA_ALT_SUPPORT) /** * \brief Initialize an RSA-alt context * * \param ctx Context to initialize. Must be empty (type NONE). * \param key RSA key pointer * \param decrypt_func Decryption function * \param sign_func Signing function * \param key_len_func Function returning key length in bytes * * \return 0 on success, or MBEDTLS_ERR_PK_BAD_INPUT_DATA if the * context wasn't already initialized as RSA_ALT. * * \note This function replaces \c mbedtls_pk_setup() for RSA-alt. */ int mbedtls_pk_setup_rsa_alt( mbedtls_pk_context *ctx, void * key, mbedtls_pk_rsa_alt_decrypt_func decrypt_func, mbedtls_pk_rsa_alt_sign_func sign_func, mbedtls_pk_rsa_alt_key_len_func key_len_func ); #endif /* MBEDTLS_PK_RSA_ALT_SUPPORT */ /** * \brief Get the size in bits of the underlying key * * \param ctx Context to use * * \return Key size in bits, or 0 on error */ size_t mbedtls_pk_get_bitlen( const mbedtls_pk_context *ctx ); /** * \brief Get the length in bytes of the underlying key * \param ctx Context to use * * \return Key length in bytes, or 0 on error */ static inline size_t mbedtls_pk_get_len( const mbedtls_pk_context *ctx ) { return( ( mbedtls_pk_get_bitlen( ctx ) + 7 ) / 8 ); } /** * \brief Tell if a context can do the operation given by type * * \param ctx Context to test * \param type Target type * * \return 0 if context can't do the operations, * 1 otherwise. */ int mbedtls_pk_can_do( const mbedtls_pk_context *ctx, mbedtls_pk_type_t type ); /** * \brief Verify signature (including padding if relevant). * * \param ctx PK context to use * \param md_alg Hash algorithm used (see notes) * \param hash Hash of the message to sign * \param hash_len Hash length or 0 (see notes) * \param sig Signature to verify * \param sig_len Signature length * * \return 0 on success (signature is valid), * MBEDTLS_ERR_PK_SIG_LEN_MISMATCH if the signature is * valid but its actual length is less than sig_len, * or a specific error code. * * \note For RSA keys, the default padding type is PKCS#1 v1.5. * Use \c mbedtls_pk_verify_ext( MBEDTLS_PK_RSASSA_PSS, ... ) * to verify RSASSA_PSS signatures. * * \note If hash_len is 0, then the length associated with md_alg * is used instead, or an error returned if it is invalid. * * \note md_alg may be MBEDTLS_MD_NONE, only if hash_len != 0 */ int mbedtls_pk_verify( mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg, const unsigned char *hash, size_t hash_len, const unsigned char *sig, size_t sig_len ); /** * \brief Verify signature, with options. * (Includes verification of the padding depending on type.) * * \param type Signature type (inc. possible padding type) to verify * \param options Pointer to type-specific options, or NULL * \param ctx PK context to use * \param md_alg Hash algorithm used (see notes) * \param hash Hash of the message to sign * \param hash_len Hash length or 0 (see notes) * \param sig Signature to verify * \param sig_len Signature length * * \return 0 on success (signature is valid), * MBEDTLS_ERR_PK_TYPE_MISMATCH if the PK context can't be * used for this type of signatures, * MBEDTLS_ERR_PK_SIG_LEN_MISMATCH if the signature is * valid but its actual length is less than sig_len, * or a specific error code. * * \note If hash_len is 0, then the length associated with md_alg * is used instead, or an error returned if it is invalid. * * \note md_alg may be MBEDTLS_MD_NONE, only if hash_len != 0 * * \note If type is MBEDTLS_PK_RSASSA_PSS, then options must point * to a mbedtls_pk_rsassa_pss_options structure, * otherwise it must be NULL. */ int mbedtls_pk_verify_ext( mbedtls_pk_type_t type, const void *options, mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg, const unsigned char *hash, size_t hash_len, const unsigned char *sig, size_t sig_len ); /** * \brief Make signature, including padding if relevant. * * \param ctx PK context to use - must hold a private key * \param md_alg Hash algorithm used (see notes) * \param hash Hash of the message to sign * \param hash_len Hash length or 0 (see notes) * \param sig Place to write the signature * \param sig_len Number of bytes written * \param f_rng RNG function * \param p_rng RNG parameter * * \return 0 on success, or a specific error code. * * \note For RSA keys, the default padding type is PKCS#1 v1.5. * There is no interface in the PK module to make RSASSA-PSS * signatures yet. * * \note If hash_len is 0, then the length associated with md_alg * is used instead, or an error returned if it is invalid. * * \note For RSA, md_alg may be MBEDTLS_MD_NONE if hash_len != 0. * For ECDSA, md_alg may never be MBEDTLS_MD_NONE. */ int mbedtls_pk_sign( mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg, const unsigned char *hash, size_t hash_len, unsigned char *sig, size_t *sig_len, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); /** * \brief Decrypt message (including padding if relevant). * * \param ctx PK context to use - must hold a private key * \param input Input to decrypt * \param ilen Input size * \param output Decrypted output * \param olen Decrypted message length * \param osize Size of the output buffer * \param f_rng RNG function * \param p_rng RNG parameter * * \note For RSA keys, the default padding type is PKCS#1 v1.5. * * \return 0 on success, or a specific error code. */ int mbedtls_pk_decrypt( mbedtls_pk_context *ctx, const unsigned char *input, size_t ilen, unsigned char *output, size_t *olen, size_t osize, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); /** * \brief Encrypt message (including padding if relevant). * * \param ctx PK context to use * \param input Message to encrypt * \param ilen Message size * \param output Encrypted output * \param olen Encrypted output length * \param osize Size of the output buffer * \param f_rng RNG function * \param p_rng RNG parameter * * \note For RSA keys, the default padding type is PKCS#1 v1.5. * * \return 0 on success, or a specific error code. */ int mbedtls_pk_encrypt( mbedtls_pk_context *ctx, const unsigned char *input, size_t ilen, unsigned char *output, size_t *olen, size_t osize, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); /** * \brief Check if a public-private pair of keys matches. * * \param pub Context holding a public key. * \param prv Context holding a private (and public) key. * * \return 0 on success or MBEDTLS_ERR_PK_BAD_INPUT_DATA */ int mbedtls_pk_check_pair( const mbedtls_pk_context *pub, const mbedtls_pk_context *prv ); /** * \brief Export debug information * * \param ctx Context to use * \param items Place to write debug items * * \return 0 on success or MBEDTLS_ERR_PK_BAD_INPUT_DATA */ int mbedtls_pk_debug( const mbedtls_pk_context *ctx, mbedtls_pk_debug_item *items ); /** * \brief Access the type name * * \param ctx Context to use * * \return Type name on success, or "invalid PK" */ const char * mbedtls_pk_get_name( const mbedtls_pk_context *ctx ); /** * \brief Get the key type * * \param ctx Context to use * * \return Type on success, or MBEDTLS_PK_NONE */ mbedtls_pk_type_t mbedtls_pk_get_type( const mbedtls_pk_context *ctx ); #if defined(MBEDTLS_PK_PARSE_C) /** \ingroup pk_module */ /** * \brief Parse a private key in PEM or DER format * * \param ctx key to be initialized * \param key input buffer * \param keylen size of the buffer * (including the terminating null byte for PEM data) * \param pwd password for decryption (optional) * \param pwdlen size of the password * * \note On entry, ctx must be empty, either freshly initialised * with mbedtls_pk_init() or reset with mbedtls_pk_free(). If you need a * specific key type, check the result with mbedtls_pk_can_do(). * * \note The key is also checked for correctness. * * \return 0 if successful, or a specific PK or PEM error code */ int mbedtls_pk_parse_key( mbedtls_pk_context *ctx, const unsigned char *key, size_t keylen, const unsigned char *pwd, size_t pwdlen ); /** \ingroup pk_module */ /** * \brief Parse a public key in PEM or DER format * * \param ctx key to be initialized * \param key input buffer * \param keylen size of the buffer * (including the terminating null byte for PEM data) * * \note On entry, ctx must be empty, either freshly initialised * with mbedtls_pk_init() or reset with mbedtls_pk_free(). If you need a * specific key type, check the result with mbedtls_pk_can_do(). * * \note The key is also checked for correctness. * * \return 0 if successful, or a specific PK or PEM error code */ int mbedtls_pk_parse_public_key( mbedtls_pk_context *ctx, const unsigned char *key, size_t keylen ); #if defined(MBEDTLS_FS_IO) /** \ingroup pk_module */ /** * \brief Load and parse a private key * * \param ctx key to be initialized * \param path filename to read the private key from * \param password password to decrypt the file (can be NULL) * * \note On entry, ctx must be empty, either freshly initialised * with mbedtls_pk_init() or reset with mbedtls_pk_free(). If you need a * specific key type, check the result with mbedtls_pk_can_do(). * * \note The key is also checked for correctness. * * \return 0 if successful, or a specific PK or PEM error code */ int mbedtls_pk_parse_keyfile( mbedtls_pk_context *ctx, const char *path, const char *password ); /** \ingroup pk_module */ /** * \brief Load and parse a public key * * \param ctx key to be initialized * \param path filename to read the public key from * * \note On entry, ctx must be empty, either freshly initialised * with mbedtls_pk_init() or reset with mbedtls_pk_free(). If * you need a specific key type, check the result with * mbedtls_pk_can_do(). * * \note The key is also checked for correctness. * * \return 0 if successful, or a specific PK or PEM error code */ int mbedtls_pk_parse_public_keyfile( mbedtls_pk_context *ctx, const char *path ); #endif /* MBEDTLS_FS_IO */ #endif /* MBEDTLS_PK_PARSE_C */ #if defined(MBEDTLS_PK_WRITE_C) /** * \brief Write a private key to a PKCS#1 or SEC1 DER structure * Note: data is written at the end of the buffer! Use the * return value to determine where you should start * using the buffer * * \param ctx private to write away * \param buf buffer to write to * \param size size of the buffer * * \return length of data written if successful, or a specific * error code */ int mbedtls_pk_write_key_der( mbedtls_pk_context *ctx, unsigned char *buf, size_t size ); /** * \brief Write a public key to a SubjectPublicKeyInfo DER structure * Note: data is written at the end of the buffer! Use the * return value to determine where you should start * using the buffer * * \param ctx public key to write away * \param buf buffer to write to * \param size size of the buffer * * \return length of data written if successful, or a specific * error code */ int mbedtls_pk_write_pubkey_der( mbedtls_pk_context *ctx, unsigned char *buf, size_t size ); #if defined(MBEDTLS_PEM_WRITE_C) /** * \brief Write a public key to a PEM string * * \param ctx public key to write away * \param buf buffer to write to * \param size size of the buffer * * \return 0 if successful, or a specific error code */ int mbedtls_pk_write_pubkey_pem( mbedtls_pk_context *ctx, unsigned char *buf, size_t size ); /** * \brief Write a private key to a PKCS#1 or SEC1 PEM string * * \param ctx private to write away * \param buf buffer to write to * \param size size of the buffer * * \return 0 if successful, or a specific error code */ int mbedtls_pk_write_key_pem( mbedtls_pk_context *ctx, unsigned char *buf, size_t size ); #endif /* MBEDTLS_PEM_WRITE_C */ #endif /* MBEDTLS_PK_WRITE_C */ /* * WARNING: Low-level functions. You probably do not want to use these unless * you are certain you do ;) */ #if defined(MBEDTLS_PK_PARSE_C) /** * \brief Parse a SubjectPublicKeyInfo DER structure * * \param p the position in the ASN.1 data * \param end end of the buffer * \param pk the key to fill * * \return 0 if successful, or a specific PK error code */ int mbedtls_pk_parse_subpubkey( unsigned char **p, const unsigned char *end, mbedtls_pk_context *pk ); #endif /* MBEDTLS_PK_PARSE_C */ #if defined(MBEDTLS_PK_WRITE_C) /** * \brief Write a subjectPublicKey to ASN.1 data * Note: function works backwards in data buffer * * \param p reference to current position pointer * \param start start of the buffer (for bounds-checking) * \param key public key to write away * * \return the length written or a negative error code */ int mbedtls_pk_write_pubkey( unsigned char **p, unsigned char *start, const mbedtls_pk_context *key ); #endif /* MBEDTLS_PK_WRITE_C */ /* * Internal module functions. You probably do not want to use these unless you * know you do. */ #if defined(MBEDTLS_FS_IO) int mbedtls_pk_load_file( const char *path, unsigned char **buf, size_t *n ); #endif #ifdef __cplusplus } #endif #endif /* MBEDTLS_PK_H */
{ "pile_set_name": "Github" }
/* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * TodoStore */ var AppDispatcher = require('../dispatcher/AppDispatcher'); var EventEmitter = require('events').EventEmitter; var TodoConstants = require('../constants/TodoConstants'); var assign = require('object-assign'); var RemoteDev = require('remotedev'); var CHANGE_EVENT = 'change'; var _todos = {}; /** * Create a TODO item. * @param {string} text The content of the TODO */ function create(text) { // Hand waving here -- not showing how this interacts with XHR or persistent // server-side storage. // Using the current timestamp + random number in place of a real id. var id = (+new Date() + Math.floor(Math.random() * 999999)).toString(36); _todos[id] = { id: id, complete: false, text: text }; } /** * Update a TODO item. * @param {string} id * @param {object} updates An object literal containing only the data to be * updated. */ function update(id, updates) { _todos[id] = assign({}, _todos[id], updates); } /** * Update all of the TODO items with the same object. * @param {object} updates An object literal containing only the data to be * updated. */ function updateAll(updates) { for (var id in _todos) { update(id, updates); } } /** * Delete a TODO item. * @param {string} id */ function destroy(id) { delete _todos[id]; } /** * Delete all the completed TODO items. */ function destroyCompleted() { for (var id in _todos) { if (_todos[id].complete) { destroy(id); } } } var TodoStore = assign({}, EventEmitter.prototype, { /** * Tests whether all the remaining TODO items are marked as completed. * @return {boolean} */ areAllComplete: function() { for (var id in _todos) { if (!_todos[id].complete) { return false; } } return true; }, /** * Get the entire collection of TODOs. * @return {object} */ getAll: function() { return _todos; }, emitChange: function() { this.emit(CHANGE_EVENT); }, /** * @param {function} callback */ addChangeListener: function(callback) { this.on(CHANGE_EVENT, callback); }, /** * @param {function} callback */ removeChangeListener: function(callback) { this.removeListener(CHANGE_EVENT, callback); } }); // Initial state is {} RemoteDev.init({}, { name: 'Facebook Flux' }); // Subscribe to RemoteDev RemoteDev.subscribe(state => { _todos = state; TodoStore.emitChange(); }); // Register callback to handle all updates AppDispatcher.register(function(action) { var text; switch(action.actionType) { case TodoConstants.TODO_CREATE: text = action.text.trim(); if (text !== '') { create(text); TodoStore.emitChange(); } break; case TodoConstants.TODO_TOGGLE_COMPLETE_ALL: if (TodoStore.areAllComplete()) { updateAll({complete: false}); } else { updateAll({complete: true}); } TodoStore.emitChange(); break; case TodoConstants.TODO_UNDO_COMPLETE: update(action.id, {complete: false}); TodoStore.emitChange(); break; case TodoConstants.TODO_COMPLETE: update(action.id, {complete: true}); TodoStore.emitChange(); break; case TodoConstants.TODO_UPDATE_TEXT: text = action.text.trim(); if (text !== '') { update(action.id, {text: text}); TodoStore.emitChange(); } break; case TodoConstants.TODO_DESTROY: destroy(action.id); TodoStore.emitChange(); break; case TodoConstants.TODO_DESTROY_COMPLETED: destroyCompleted(); TodoStore.emitChange(); break; default: // no op } // Send to the remote monitor RemoteDev.send(action, _todos); }); module.exports = TodoStore;
{ "pile_set_name": "Github" }
/* voc 2.1.0 [2019/11/01]. Bootstrapping compiler for address size 8, alignment 8. xrtspaSF */ #define SHORTINT INT8 #define INTEGER INT16 #define LONGINT INT32 #define SET UINT32 #include "SYSTEM.h" #include "Out.h" #include "Strings.h" export CHAR VT100_CSI[5]; static CHAR VT100_tmpstr[32]; export void VT100_CHA (INT16 n); export void VT100_CNL (INT16 n); export void VT100_CPL (INT16 n); export void VT100_CUB (INT16 n); export void VT100_CUD (INT16 n); export void VT100_CUF (INT16 n); export void VT100_CUP (INT16 n, INT16 m); export void VT100_CUU (INT16 n); export void VT100_DECTCEMh (void); export void VT100_DECTCEMl (void); export void VT100_DSR (INT16 n); export void VT100_ED (INT16 n); export void VT100_EL (INT16 n); static void VT100_EscSeq (INT16 n, CHAR *letter, ADDRESS letter__len); static void VT100_EscSeq0 (CHAR *letter, ADDRESS letter__len); static void VT100_EscSeq2 (INT16 n, INT16 m, CHAR *letter, ADDRESS letter__len); static void VT100_EscSeqSwapped (INT16 n, CHAR *letter, ADDRESS letter__len); export void VT100_HVP (INT16 n, INT16 m); export void VT100_IntToStr (INT32 int_, CHAR *str, ADDRESS str__len); export void VT100_RCP (void); static void VT100_Reverse0 (CHAR *str, ADDRESS str__len, INT16 start, INT16 end); export void VT100_SCP (void); export void VT100_SD (INT16 n); export void VT100_SGR (INT16 n); export void VT100_SGR2 (INT16 n, INT16 m); export void VT100_SU (INT16 n); export void VT100_SetAttr (CHAR *attr, ADDRESS attr__len); static void VT100_Reverse0 (CHAR *str, ADDRESS str__len, INT16 start, INT16 end) { CHAR h; while (start < end) { h = str[__X(start, str__len)]; str[__X(start, str__len)] = str[__X(end, str__len)]; str[__X(end, str__len)] = h; start += 1; end -= 1; } } void VT100_IntToStr (INT32 int_, CHAR *str, ADDRESS str__len) { CHAR b[21]; INT16 s, e; INT8 maxLength; maxLength = 11; if (int_ == (-2147483647-1)) { __MOVE("-2147483648", b, 12); e = 11; } else { if (int_ < 0) { b[0] = '-'; int_ = -int_; s = 1; } else { s = 0; } e = s; do { b[__X(e, 21)] = __CHR((int)__MOD(int_, 10) + 48); int_ = __DIV(int_, 10); e += 1; } while (!(int_ == 0)); b[__X(e, 21)] = 0x00; VT100_Reverse0((void*)b, 21, s, e - 1); } __COPY(b, str, str__len); } static void VT100_EscSeq0 (CHAR *letter, ADDRESS letter__len) { CHAR cmd[9]; __DUP(letter, letter__len, CHAR); __COPY(VT100_CSI, cmd, 9); Strings_Append(letter, letter__len, (void*)cmd, 9); Out_String(cmd, 9); __DEL(letter); } static void VT100_EscSeq (INT16 n, CHAR *letter, ADDRESS letter__len) { CHAR nstr[2]; CHAR cmd[7]; __DUP(letter, letter__len, CHAR); VT100_IntToStr(n, (void*)nstr, 2); __COPY(VT100_CSI, cmd, 7); Strings_Append(nstr, 2, (void*)cmd, 7); Strings_Append(letter, letter__len, (void*)cmd, 7); Out_String(cmd, 7); __DEL(letter); } static void VT100_EscSeqSwapped (INT16 n, CHAR *letter, ADDRESS letter__len) { CHAR nstr[2]; CHAR cmd[7]; __DUP(letter, letter__len, CHAR); VT100_IntToStr(n, (void*)nstr, 2); __COPY(VT100_CSI, cmd, 7); Strings_Append(letter, letter__len, (void*)cmd, 7); Strings_Append(nstr, 2, (void*)cmd, 7); Out_String(cmd, 7); __DEL(letter); } static void VT100_EscSeq2 (INT16 n, INT16 m, CHAR *letter, ADDRESS letter__len) { CHAR nstr[5], mstr[5]; CHAR cmd[12]; __DUP(letter, letter__len, CHAR); VT100_IntToStr(n, (void*)nstr, 5); VT100_IntToStr(m, (void*)mstr, 5); __COPY(VT100_CSI, cmd, 12); Strings_Append(nstr, 5, (void*)cmd, 12); Strings_Append((CHAR*)";", 2, (void*)cmd, 12); Strings_Append(mstr, 5, (void*)cmd, 12); Strings_Append(letter, letter__len, (void*)cmd, 12); Out_String(cmd, 12); __DEL(letter); } void VT100_CUU (INT16 n) { VT100_EscSeq(n, (CHAR*)"A", 2); } void VT100_CUD (INT16 n) { VT100_EscSeq(n, (CHAR*)"B", 2); } void VT100_CUF (INT16 n) { VT100_EscSeq(n, (CHAR*)"C", 2); } void VT100_CUB (INT16 n) { VT100_EscSeq(n, (CHAR*)"D", 2); } void VT100_CNL (INT16 n) { VT100_EscSeq(n, (CHAR*)"E", 2); } void VT100_CPL (INT16 n) { VT100_EscSeq(n, (CHAR*)"F", 2); } void VT100_CHA (INT16 n) { VT100_EscSeq(n, (CHAR*)"G", 2); } void VT100_CUP (INT16 n, INT16 m) { VT100_EscSeq2(n, m, (CHAR*)"H", 2); } void VT100_ED (INT16 n) { VT100_EscSeq(n, (CHAR*)"J", 2); } void VT100_EL (INT16 n) { VT100_EscSeq(n, (CHAR*)"K", 2); } void VT100_SU (INT16 n) { VT100_EscSeq(n, (CHAR*)"S", 2); } void VT100_SD (INT16 n) { VT100_EscSeq(n, (CHAR*)"T", 2); } void VT100_HVP (INT16 n, INT16 m) { VT100_EscSeq2(n, m, (CHAR*)"f", 2); } void VT100_SGR (INT16 n) { VT100_EscSeq(n, (CHAR*)"m", 2); } void VT100_SGR2 (INT16 n, INT16 m) { VT100_EscSeq2(n, m, (CHAR*)"m", 2); } void VT100_DSR (INT16 n) { VT100_EscSeq(6, (CHAR*)"n", 2); } void VT100_SCP (void) { VT100_EscSeq0((CHAR*)"s", 2); } void VT100_RCP (void) { VT100_EscSeq0((CHAR*)"u", 2); } void VT100_DECTCEMl (void) { VT100_EscSeq0((CHAR*)"\?25l", 5); } void VT100_DECTCEMh (void) { VT100_EscSeq0((CHAR*)"\?25h", 5); } void VT100_SetAttr (CHAR *attr, ADDRESS attr__len) { CHAR tmpstr[16]; __DUP(attr, attr__len, CHAR); __COPY(VT100_CSI, tmpstr, 16); Strings_Append(attr, attr__len, (void*)tmpstr, 16); Out_String(tmpstr, 16); __DEL(attr); } export void *VT100__init(void) { __DEFMOD; __MODULE_IMPORT(Out); __MODULE_IMPORT(Strings); __REGMOD("VT100", 0); __REGCMD("DECTCEMh", VT100_DECTCEMh); __REGCMD("DECTCEMl", VT100_DECTCEMl); __REGCMD("RCP", VT100_RCP); __REGCMD("SCP", VT100_SCP); /* BEGIN */ __COPY("\033", VT100_CSI, 5); Strings_Append((CHAR*)"[", 2, (void*)VT100_CSI, 5); __ENDMOD; }
{ "pile_set_name": "Github" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>CSS Test: Background with (attachment color image repeat position)</title> <link rel="author" title="Microsoft" href="http://www.microsoft.com/" /> <link rel="help" href="http://www.w3.org/TR/CSS21/colors.html#propdef-background" /> <link rel="help" href="http://www.w3.org/TR/CSS21/colors.html#background-properties" /> <meta name="flags" content="image interact" /> <meta name="assert" content="Background with (attachment color image repeat position) sets the background to the color specified, tiling the image across the x-axis at the bottom of the element." /> <style type="text/css"> #div1 { height: 200px; overflow: scroll; width: 200px; } div div { background: scroll green url("support/cat.png") repeat-x bottom; height: 400px; width: 400px; } </style> </head> <body> <p>Test passes if there is a green box below, and when the box is scrolled down, there is a line of cat images at the bottom of the box.</p> <div id="div1"> <div></div> </div> </body> </html>
{ "pile_set_name": "Github" }
package ch.cyberduck.core.worker; /* * Copyright (c) 2002-2017 iterate GmbH. All rights reserved. * https://cyberduck.io/ * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ import ch.cyberduck.core.AlphanumericRandomStringService; import ch.cyberduck.core.DisabledConnectionCallback; import ch.cyberduck.core.DisabledLoginCallback; import ch.cyberduck.core.DisabledProgressListener; import ch.cyberduck.core.Host; import ch.cyberduck.core.Local; import ch.cyberduck.core.NullFilter; import ch.cyberduck.core.Path; import ch.cyberduck.core.TestProtocol; import ch.cyberduck.core.VersionId; import ch.cyberduck.core.features.Delete; import ch.cyberduck.core.googlestorage.AbstractGoogleStorageTest; import ch.cyberduck.core.googlestorage.GoogleStorageDeleteFeature; import ch.cyberduck.core.googlestorage.GoogleStorageWriteFeature; import ch.cyberduck.core.io.DisabledStreamListener; import ch.cyberduck.core.io.SHA256ChecksumCompute; import ch.cyberduck.core.io.StatusOutputStream; import ch.cyberduck.core.io.StreamCopier; import ch.cyberduck.core.local.TemporaryFileServiceFactory; import ch.cyberduck.core.notification.DisabledNotificationService; import ch.cyberduck.core.transfer.DisabledTransferErrorCallback; import ch.cyberduck.core.transfer.DisabledTransferPrompt; import ch.cyberduck.core.transfer.DownloadTransfer; import ch.cyberduck.core.transfer.Transfer; import ch.cyberduck.core.transfer.TransferAction; import ch.cyberduck.core.transfer.TransferItem; import ch.cyberduck.core.transfer.TransferOptions; import ch.cyberduck.core.transfer.TransferSpeedometer; import ch.cyberduck.core.transfer.TransferStatus; import ch.cyberduck.test.IntegrationTest; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.RandomUtils; import org.junit.Test; import org.junit.experimental.categories.Category; import java.io.ByteArrayInputStream; import java.util.Collections; import java.util.EnumSet; import static org.junit.Assert.*; @Category(IntegrationTest.class) public class SingleTransferWorkerTest extends AbstractGoogleStorageTest { @Test public void testDownload() throws Exception { final Path home = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.volume)); final Path test = new Path(home, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); final Local localFile = TemporaryFileServiceFactory.get().create(test); { final byte[] content = RandomUtils.nextBytes(39864); final TransferStatus writeStatus = new TransferStatus().length(content.length).withChecksum(new SHA256ChecksumCompute().compute(new ByteArrayInputStream(content), new TransferStatus())); final StatusOutputStream out = new GoogleStorageWriteFeature(session).write(test, writeStatus, new DisabledConnectionCallback()); assertNotNull(out); new StreamCopier(writeStatus, writeStatus).withLimit((long) content.length).transfer(new ByteArrayInputStream(content), out); out.close(); } final byte[] content = RandomUtils.nextBytes(39864); final TransferStatus writeStatus = new TransferStatus().length(content.length).withChecksum(new SHA256ChecksumCompute().compute(new ByteArrayInputStream(content), new TransferStatus())); final StatusOutputStream<VersionId> out = new GoogleStorageWriteFeature(session).write(test, writeStatus, new DisabledConnectionCallback()); assertNotNull(out); new StreamCopier(writeStatus, writeStatus).withLimit((long) content.length).transfer(new ByteArrayInputStream(content), out); out.close(); final String versionId = String.valueOf(out.getStatus().id); assertNotNull(versionId); final Transfer t = new DownloadTransfer(new Host(new TestProtocol()), Collections.singletonList(new TransferItem(test, localFile)), new NullFilter<>()); assertTrue(new SingleTransferWorker(session, session, t, new TransferOptions(), new TransferSpeedometer(t), new DisabledTransferPrompt() { @Override public TransferAction prompt(final TransferItem file) { return TransferAction.overwrite; } }, new DisabledTransferErrorCallback(), new DisabledProgressListener(), new DisabledStreamListener(), new DisabledLoginCallback(), new DisabledNotificationService()) { }.run(session)); assertArrayEquals(content, IOUtils.toByteArray(localFile.getInputStream())); new GoogleStorageDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback()); localFile.delete(); } }
{ "pile_set_name": "Github" }
<div class="article-meta"> <a ui-sref="app.profile.main({ username:$ctrl.article.author.username })"> <img ng-src="{{$ctrl.article.author.image}}" /> </a> <div class="info"> <a class="author" ui-sref="app.profile.main({ username:$ctrl.article.author.username })" ng-bind="$ctrl.article.author.username"> </a> <span class="date" ng-bind="$ctrl.article.createdAt | date: 'longDate' "> </span> </div> <ng-transclude></ng-transclude> </div>
{ "pile_set_name": "Github" }
{ "name": "jansenfelipe/cpf-gratis", "description": "Com esse pacote você poderá consultar, gratuitamente, CPFs diretamente no site da receita.", "keywords": ["laravel", "cpf", "php"], "license": "MIT", "authors": [ { "name": "Jansen Felipe", "email": "[email protected]" } ], "require": { "php": ">=5.4.0", "fabpot/goutte": "2.0.*@dev", "jansenfelipe/utils": "^2.0@dev" }, "autoload": { "psr-4": { "JansenFelipe\\CpfGratis\\": "src/" } }, "require-dev": { "phpunit/phpunit": "~4.0" }, "extra": { "branch-alias": { "dev-master": "3.0-dev" } }, "suggest": { "jansenfelipe/cnpj-gratis": "Permite consulta de CNPJ no site da receita", "jansenfelipe/cep-gratis": "Permite consulta de CEP no site dos Correios" }, "minimum-stability": "dev" }
{ "pile_set_name": "Github" }
/* Definitions of some C99 math library functions, for those platforms that don't implement these functions already. */ #include "Python.h" #include <float.h> #include "_math.h" /* The following copyright notice applies to the original implementations of acosh, asinh and atanh. */ /* * ==================================================== * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunPro, a Sun Microsystems, Inc. business. * Permission to use, copy, modify, and distribute this * software is freely granted, provided that this notice * is preserved. * ==================================================== */ static const double ln2 = 6.93147180559945286227E-01; static const double two_pow_m28 = 3.7252902984619141E-09; /* 2**-28 */ static const double two_pow_p28 = 268435456.0; /* 2**28 */ static const double zero = 0.0; /* acosh(x) * Method : * Based on * acosh(x) = log [ x + sqrt(x*x-1) ] * we have * acosh(x) := log(x)+ln2, if x is large; else * acosh(x) := log(2x-1/(sqrt(x*x-1)+x)) if x>2; else * acosh(x) := log1p(t+sqrt(2.0*t+t*t)); where t=x-1. * * Special cases: * acosh(x) is NaN with signal if x<1. * acosh(NaN) is NaN without signal. */ double _Py_acosh(double x) { if (Py_IS_NAN(x)) { return x+x; } if (x < 1.) { /* x < 1; return a signaling NaN */ errno = EDOM; #ifdef Py_NAN return Py_NAN; #else return (x-x)/(x-x); #endif } else if (x >= two_pow_p28) { /* x > 2**28 */ if (Py_IS_INFINITY(x)) { return x+x; } else { return log(x)+ln2; /* acosh(huge)=log(2x) */ } } else if (x == 1.) { return 0.0; /* acosh(1) = 0 */ } else if (x > 2.) { /* 2 < x < 2**28 */ double t = x*x; return log(2.0*x - 1.0 / (x + sqrt(t - 1.0))); } else { /* 1 < x <= 2 */ double t = x - 1.0; return m_log1p(t + sqrt(2.0*t + t*t)); } } /* asinh(x) * Method : * Based on * asinh(x) = sign(x) * log [ |x| + sqrt(x*x+1) ] * we have * asinh(x) := x if 1+x*x=1, * := sign(x)*(log(x)+ln2)) for large |x|, else * := sign(x)*log(2|x|+1/(|x|+sqrt(x*x+1))) if|x|>2, else * := sign(x)*log1p(|x| + x^2/(1 + sqrt(1+x^2))) */ double _Py_asinh(double x) { double w; double absx = fabs(x); if (Py_IS_NAN(x) || Py_IS_INFINITY(x)) { return x+x; } if (absx < two_pow_m28) { /* |x| < 2**-28 */ return x; /* return x inexact except 0 */ } if (absx > two_pow_p28) { /* |x| > 2**28 */ w = log(absx)+ln2; } else if (absx > 2.0) { /* 2 < |x| < 2**28 */ w = log(2.0*absx + 1.0 / (sqrt(x*x + 1.0) + absx)); } else { /* 2**-28 <= |x| < 2= */ double t = x*x; w = m_log1p(absx + t / (1.0 + sqrt(1.0 + t))); } return copysign(w, x); } /* atanh(x) * Method : * 1.Reduced x to positive by atanh(-x) = -atanh(x) * 2.For x>=0.5 * 1 2x x * atanh(x) = --- * log(1 + -------) = 0.5 * log1p(2 * -------) * 2 1 - x 1 - x * * For x<0.5 * atanh(x) = 0.5*log1p(2x+2x*x/(1-x)) * * Special cases: * atanh(x) is NaN if |x| >= 1 with signal; * atanh(NaN) is that NaN with no signal; * */ double _Py_atanh(double x) { double absx; double t; if (Py_IS_NAN(x)) { return x+x; } absx = fabs(x); if (absx >= 1.) { /* |x| >= 1 */ errno = EDOM; #ifdef Py_NAN return Py_NAN; #else return x/zero; #endif } if (absx < two_pow_m28) { /* |x| < 2**-28 */ return x; } if (absx < 0.5) { /* |x| < 0.5 */ t = absx+absx; t = 0.5 * m_log1p(t + t*absx / (1.0 - absx)); } else { /* 0.5 <= |x| <= 1.0 */ t = 0.5 * m_log1p((absx + absx) / (1.0 - absx)); } return copysign(t, x); } /* Mathematically, expm1(x) = exp(x) - 1. The expm1 function is designed to avoid the significant loss of precision that arises from direct evaluation of the expression exp(x) - 1, for x near 0. */ double _Py_expm1(double x) { /* For abs(x) >= log(2), it's safe to evaluate exp(x) - 1 directly; this also works fine for infinities and nans. For smaller x, we can use a method due to Kahan that achieves close to full accuracy. */ if (fabs(x) < 0.7) { double u; u = exp(x); if (u == 1.0) return x; else return (u - 1.0) * x / log(u); } else return exp(x) - 1.0; } /* log1p(x) = log(1+x). The log1p function is designed to avoid the significant loss of precision that arises from direct evaluation when x is small. */ #ifdef HAVE_LOG1P double _Py_log1p(double x) { /* Some platforms supply a log1p function but don't respect the sign of zero: log1p(-0.0) gives 0.0 instead of the correct result of -0.0. To save fiddling with configure tests and platform checks, we handle the special case of zero input directly on all platforms. */ if (x == 0.0) { return x; } else { return log1p(x); } } #else double _Py_log1p(double x) { /* For x small, we use the following approach. Let y be the nearest float to 1+x, then 1+x = y * (1 - (y-1-x)/y) so log(1+x) = log(y) + log(1-(y-1-x)/y). Since (y-1-x)/y is tiny, the second term is well approximated by (y-1-x)/y. If abs(x) >= DBL_EPSILON/2 or the rounding-mode is some form of round-to-nearest then y-1-x will be exactly representable, and is computed exactly by (y-1)-x. If abs(x) < DBL_EPSILON/2 and the rounding mode is not known to be round-to-nearest then this method is slightly dangerous: 1+x could be rounded up to 1+DBL_EPSILON instead of down to 1, and in that case y-1-x will not be exactly representable any more and the result can be off by many ulps. But this is easily fixed: for a floating-point number |x| < DBL_EPSILON/2., the closest floating-point number to log(1+x) is exactly x. */ double y; if (fabs(x) < DBL_EPSILON/2.) { return x; } else if (-0.5 <= x && x <= 1.) { /* WARNING: it's possible than an overeager compiler will incorrectly optimize the following two lines to the equivalent of "return log(1.+x)". If this happens, then results from log1p will be inaccurate for small x. */ y = 1.+x; return log(y)-((y-1.)-x)/y; } else { /* NaNs and infinities should end up here */ return log(1.+x); } } #endif /* ifdef HAVE_LOG1P */
{ "pile_set_name": "Github" }
/* * Copyright (C) 2016 Konstantin Tokavev <[email protected]> * Copyright (C) 2016 Yusuke Suzuki <[email protected]> * Copyright (C) 2011 Igalia S.L. * Copyright (C) 2010 Apple Inc. All rights reserved. * Portions Copyright (c) 2010 Motorola Mobility, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include <wtf/WorkQueue.h> #include <wtf/WallTime.h> #include <wtf/text/WTFString.h> #include <wtf/threads/BinarySemaphore.h> void WorkQueue::platformInitialize(const char* name, Type, QOS) { BinarySemaphore semaphore; Thread::create(name, [&] { m_runLoop = &RunLoop::current(); semaphore.signal(); m_runLoop->run(); })->detach(); semaphore.wait(); } void WorkQueue::platformInvalidate() { if (m_runLoop) { Ref<RunLoop> protector(*m_runLoop); protector->stop(); protector->dispatch([] { RunLoop::current().stop(); }); } } void WorkQueue::dispatch(Function<void()>&& function) { RefPtr<WorkQueue> protect(this); m_runLoop->dispatch([protect, function = WTFMove(function)] { function(); }); } void WorkQueue::dispatchAfter(Seconds delay, Function<void()>&& function) { RefPtr<WorkQueue> protect(this); m_runLoop->dispatchAfter(delay, [protect, function = WTFMove(function)] { function(); }); }
{ "pile_set_name": "Github" }
import { UseCaseError } from "../../../../shared/core/UseCaseError"; import { Result } from "../../../../shared/core/Result"; export namespace RefreshAccessTokenErrors { export class RefreshTokenNotFound extends Result<UseCaseError> { constructor () { super(false, { message: `Refresh token doesn't exist` } as UseCaseError) } } export class UserNotFoundOrDeletedError extends Result<UseCaseError> { constructor () { super(false, { message: `User not found or doesn't exist anymore.` } as UseCaseError) } } }
{ "pile_set_name": "Github" }
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for tensorflow.ops.tf.Assign*.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python.framework import dtypes from tensorflow.python.ops import array_ops from tensorflow.python.ops import state_ops from tensorflow.python.ops import variables from tensorflow.python.platform import test class AssignOpTest(test.TestCase): def _initAssignFetch(self, x, y, use_gpu=False): """Initialize a param to init and update it with y.""" super(AssignOpTest, self).setUp() with self.test_session(use_gpu=use_gpu): p = variables.Variable(x) assign = state_ops.assign(p, y) p.initializer.run() new_value = assign.eval() return p.eval(), new_value def _initAssignAddFetch(self, x, y, use_gpu=False): """Initialize a param to init, and compute param += y.""" with self.test_session(use_gpu=use_gpu): p = variables.Variable(x) add = state_ops.assign_add(p, y) p.initializer.run() new_value = add.eval() return p.eval(), new_value def _initAssignSubFetch(self, x, y, use_gpu=False): """Initialize a param to init, and compute param -= y.""" with self.test_session(use_gpu=use_gpu): p = variables.Variable(x) sub = state_ops.assign_sub(p, y) p.initializer.run() new_value = sub.eval() return p.eval(), new_value def _testTypes(self, vals): for dtype in [np.float32, np.float64, np.int32, np.int64]: x = np.zeros(vals.shape).astype(dtype) y = vals.astype(dtype) var_value, op_value = self._initAssignFetch(x, y, use_gpu=False) self.assertAllEqual(y, var_value) self.assertAllEqual(y, op_value) var_value, op_value = self._initAssignAddFetch(x, y, use_gpu=False) self.assertAllEqual(x + y, var_value) self.assertAllEqual(x + y, op_value) var_value, op_value = self._initAssignSubFetch(x, y, use_gpu=False) self.assertAllEqual(x - y, var_value) self.assertAllEqual(x - y, op_value) if test.is_built_with_cuda() and dtype in [np.float32, np.float64]: var_value, op_value = self._initAssignFetch(x, y, use_gpu=True) self.assertAllEqual(y, var_value) self.assertAllEqual(y, op_value) var_value, op_value = self._initAssignAddFetch(x, y, use_gpu=True) self.assertAllEqual(x + y, var_value) self.assertAllEqual(x + y, op_value) var_value, op_value = self._initAssignSubFetch(x, y, use_gpu=False) self.assertAllEqual(x - y, var_value) self.assertAllEqual(x - y, op_value) def testBasic(self): self._testTypes(np.arange(0, 20).reshape([4, 5])) def testAssignNonStrictShapeChecking(self): with self.test_session(): data = array_ops.fill([1024, 1024], 0) p = variables.Variable([1]) a = state_ops.assign(p, data, validate_shape=False) a.op.run() self.assertAllEqual(p.eval(), data.eval()) # Assign to yet another shape data2 = array_ops.fill([10, 10], 1) a2 = state_ops.assign(p, data2, validate_shape=False) a2.op.run() self.assertAllEqual(p.eval(), data2.eval()) def testInitRequiredAssignAdd(self): with self.test_session(): p = variables.Variable(array_ops.fill([1024, 1024], 1), dtypes.int32) a = state_ops.assign_add(p, array_ops.fill([1024, 1024], 0)) with self.assertRaisesOpError("use uninitialized"): a.op.run() def testInitRequiredAssignSub(self): with self.test_session(): p = variables.Variable(array_ops.fill([1024, 1024], 1), dtypes.int32) a = state_ops.assign_sub(p, array_ops.fill([1024, 1024], 0)) with self.assertRaisesOpError("use uninitialized"): a.op.run() if __name__ == "__main__": test.main()
{ "pile_set_name": "Github" }
/* Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package serializer import ( "encoding/json" "fmt" "log" "os" "reflect" "strings" "testing" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/conversion" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/util/diff" "github.com/ghodss/yaml" "github.com/google/gofuzz" flag "github.com/spf13/pflag" ) var fuzzIters = flag.Int("fuzz-iters", 50, "How many fuzzing iterations to do.") type testMetaFactory struct{} func (testMetaFactory) Interpret(data []byte) (*schema.GroupVersionKind, error) { findKind := struct { APIVersion string `json:"myVersionKey,omitempty"` ObjectKind string `json:"myKindKey,omitempty"` }{} // yaml is a superset of json, so we use it to decode here. That way, // we understand both. if err := yaml.Unmarshal(data, &findKind); err != nil { return nil, fmt.Errorf("couldn't get version/kind: %v", err) } gv, err := schema.ParseGroupVersion(findKind.APIVersion) if err != nil { return nil, err } return &schema.GroupVersionKind{Group: gv.Group, Version: gv.Version, Kind: findKind.ObjectKind}, nil } // Test a weird version/kind embedding format. type MyWeirdCustomEmbeddedVersionKindField struct { ID string `json:"ID,omitempty"` APIVersion string `json:"myVersionKey,omitempty"` ObjectKind string `json:"myKindKey,omitempty"` Z string `json:"Z,omitempty"` Y uint64 `json:"Y,omitempty"` } type TestType1 struct { MyWeirdCustomEmbeddedVersionKindField `json:",inline"` A string `json:"A,omitempty"` B int `json:"B,omitempty"` C int8 `json:"C,omitempty"` D int16 `json:"D,omitempty"` E int32 `json:"E,omitempty"` F int64 `json:"F,omitempty"` G uint `json:"G,omitempty"` H uint8 `json:"H,omitempty"` I uint16 `json:"I,omitempty"` J uint32 `json:"J,omitempty"` K uint64 `json:"K,omitempty"` L bool `json:"L,omitempty"` M map[string]int `json:"M,omitempty"` N map[string]TestType2 `json:"N,omitempty"` O *TestType2 `json:"O,omitempty"` P []TestType2 `json:"Q,omitempty"` } type TestType2 struct { A string `json:"A,omitempty"` B int `json:"B,omitempty"` } type ExternalTestType2 struct { A string `json:"A,omitempty"` B int `json:"B,omitempty"` } type ExternalTestType1 struct { MyWeirdCustomEmbeddedVersionKindField `json:",inline"` A string `json:"A,omitempty"` B int `json:"B,omitempty"` C int8 `json:"C,omitempty"` D int16 `json:"D,omitempty"` E int32 `json:"E,omitempty"` F int64 `json:"F,omitempty"` G uint `json:"G,omitempty"` H uint8 `json:"H,omitempty"` I uint16 `json:"I,omitempty"` J uint32 `json:"J,omitempty"` K uint64 `json:"K,omitempty"` L bool `json:"L,omitempty"` M map[string]int `json:"M,omitempty"` N map[string]ExternalTestType2 `json:"N,omitempty"` O *ExternalTestType2 `json:"O,omitempty"` P []ExternalTestType2 `json:"Q,omitempty"` } type ExternalInternalSame struct { MyWeirdCustomEmbeddedVersionKindField `json:",inline"` A TestType2 `json:"A,omitempty"` } // TestObjectFuzzer can randomly populate all the above objects. var TestObjectFuzzer = fuzz.New().NilChance(.5).NumElements(1, 100).Funcs( func(j *MyWeirdCustomEmbeddedVersionKindField, c fuzz.Continue) { c.FuzzNoCustom(j) j.APIVersion = "" j.ObjectKind = "" }, ) func (obj *MyWeirdCustomEmbeddedVersionKindField) GetObjectKind() schema.ObjectKind { return obj } func (obj *MyWeirdCustomEmbeddedVersionKindField) SetGroupVersionKind(gvk schema.GroupVersionKind) { obj.APIVersion, obj.ObjectKind = gvk.ToAPIVersionAndKind() } func (obj *MyWeirdCustomEmbeddedVersionKindField) GroupVersionKind() schema.GroupVersionKind { return schema.FromAPIVersionAndKind(obj.APIVersion, obj.ObjectKind) } func (obj *ExternalInternalSame) GetObjectKind() schema.ObjectKind { return &obj.MyWeirdCustomEmbeddedVersionKindField } func (obj *TestType1) GetObjectKind() schema.ObjectKind { return &obj.MyWeirdCustomEmbeddedVersionKindField } func (obj *ExternalTestType1) GetObjectKind() schema.ObjectKind { return &obj.MyWeirdCustomEmbeddedVersionKindField } func (obj *TestType2) GetObjectKind() schema.ObjectKind { return schema.EmptyObjectKind } func (obj *ExternalTestType2) GetObjectKind() schema.ObjectKind { return schema.EmptyObjectKind } // Returns a new Scheme set up with the test objects. func GetTestScheme() (*runtime.Scheme, runtime.Codec) { internalGV := schema.GroupVersion{Version: runtime.APIVersionInternal} externalGV := schema.GroupVersion{Version: "v1"} externalGV2 := schema.GroupVersion{Version: "v2"} s := runtime.NewScheme() // Ordinarily, we wouldn't add TestType2, but because this is a test and // both types are from the same package, we need to get it into the system // so that converter will match it with ExternalType2. s.AddKnownTypes(internalGV, &TestType1{}, &TestType2{}, &ExternalInternalSame{}) s.AddKnownTypes(externalGV, &ExternalInternalSame{}) s.AddKnownTypeWithName(externalGV.WithKind("TestType1"), &ExternalTestType1{}) s.AddKnownTypeWithName(externalGV.WithKind("TestType2"), &ExternalTestType2{}) s.AddKnownTypeWithName(internalGV.WithKind("TestType3"), &TestType1{}) s.AddKnownTypeWithName(externalGV.WithKind("TestType3"), &ExternalTestType1{}) s.AddKnownTypeWithName(externalGV2.WithKind("TestType1"), &ExternalTestType1{}) s.AddUnversionedTypes(externalGV, &metav1.Status{}) cf := newCodecFactory(s, newSerializersForScheme(s, testMetaFactory{})) codec := cf.LegacyCodec(schema.GroupVersion{Version: "v1"}) return s, codec } var semantic = conversion.EqualitiesOrDie( func(a, b MyWeirdCustomEmbeddedVersionKindField) bool { a.APIVersion, a.ObjectKind = "", "" b.APIVersion, b.ObjectKind = "", "" return a == b }, ) func runTest(t *testing.T, source interface{}) { name := reflect.TypeOf(source).Elem().Name() TestObjectFuzzer.Fuzz(source) _, codec := GetTestScheme() data, err := runtime.Encode(codec, source.(runtime.Object)) if err != nil { t.Errorf("%v: %v (%#v)", name, err, source) return } obj2, err := runtime.Decode(codec, data) if err != nil { t.Errorf("%v: %v (%v)", name, err, string(data)) return } if !semantic.DeepEqual(source, obj2) { t.Errorf("1: %v: diff: %v", name, diff.ObjectGoPrintSideBySide(source, obj2)) return } obj3 := reflect.New(reflect.TypeOf(source).Elem()).Interface() if err := runtime.DecodeInto(codec, data, obj3.(runtime.Object)); err != nil { t.Errorf("2: %v: %v", name, err) return } if !semantic.DeepEqual(source, obj3) { t.Errorf("3: %v: diff: %v", name, diff.ObjectDiff(source, obj3)) return } } func TestTypes(t *testing.T) { table := []interface{}{ &TestType1{}, &ExternalInternalSame{}, } for _, item := range table { // Try a few times, since runTest uses random values. for i := 0; i < *fuzzIters; i++ { runTest(t, item) } } } func TestVersionedEncoding(t *testing.T) { s, _ := GetTestScheme() cf := newCodecFactory(s, newSerializersForScheme(s, testMetaFactory{})) info, _ := runtime.SerializerInfoForMediaType(cf.SupportedMediaTypes(), runtime.ContentTypeJSON) encoder := info.Serializer codec := cf.CodecForVersions(encoder, nil, schema.GroupVersion{Version: "v2"}, nil) out, err := runtime.Encode(codec, &TestType1{}) if err != nil { t.Fatal(err) } if string(out) != `{"myVersionKey":"v2","myKindKey":"TestType1"}`+"\n" { t.Fatal(string(out)) } codec = cf.CodecForVersions(encoder, nil, schema.GroupVersion{Version: "v3"}, nil) _, err = runtime.Encode(codec, &TestType1{}) if err == nil { t.Fatal(err) } // unversioned encode with no versions is written directly to wire codec = cf.CodecForVersions(encoder, nil, runtime.InternalGroupVersioner, nil) out, err = runtime.Encode(codec, &TestType1{}) if err != nil { t.Fatal(err) } if string(out) != `{}`+"\n" { t.Fatal(string(out)) } } func TestMultipleNames(t *testing.T) { _, codec := GetTestScheme() obj, _, err := codec.Decode([]byte(`{"myKindKey":"TestType3","myVersionKey":"v1","A":"value"}`), nil, nil) if err != nil { t.Fatalf("unexpected error: %v", err) } internal := obj.(*TestType1) if internal.A != "value" { t.Fatalf("unexpected decoded object: %#v", internal) } out, err := runtime.Encode(codec, internal) if err != nil { t.Fatalf("unexpected error: %v", err) } if !strings.Contains(string(out), `"myKindKey":"TestType1"`) { t.Errorf("unexpected encoded output: %s", string(out)) } } func TestConvertTypesWhenDefaultNamesMatch(t *testing.T) { internalGV := schema.GroupVersion{Version: runtime.APIVersionInternal} externalGV := schema.GroupVersion{Version: "v1"} s := runtime.NewScheme() // create two names internally, with TestType1 being preferred s.AddKnownTypeWithName(internalGV.WithKind("TestType1"), &TestType1{}) s.AddKnownTypeWithName(internalGV.WithKind("OtherType1"), &TestType1{}) // create two names externally, with TestType1 being preferred s.AddKnownTypeWithName(externalGV.WithKind("TestType1"), &ExternalTestType1{}) s.AddKnownTypeWithName(externalGV.WithKind("OtherType1"), &ExternalTestType1{}) ext := &ExternalTestType1{} ext.APIVersion = "v1" ext.ObjectKind = "OtherType1" ext.A = "test" data, err := json.Marshal(ext) if err != nil { t.Fatalf("unexpected error: %v", err) } expect := &TestType1{A: "test"} codec := newCodecFactory(s, newSerializersForScheme(s, testMetaFactory{})).LegacyCodec(schema.GroupVersion{Version: "v1"}) obj, err := runtime.Decode(codec, data) if err != nil { t.Fatalf("unexpected error: %v", err) } if !semantic.DeepEqual(expect, obj) { t.Errorf("unexpected object: %#v", obj) } into := &TestType1{} if err := runtime.DecodeInto(codec, data, into); err != nil { t.Fatalf("unexpected error: %v", err) } if !semantic.DeepEqual(expect, into) { t.Errorf("unexpected object: %#v", obj) } } func TestEncode_Ptr(t *testing.T) { _, codec := GetTestScheme() tt := &TestType1{A: "I am a pointer object"} data, err := runtime.Encode(codec, tt) obj2, err2 := runtime.Decode(codec, data) if err != nil || err2 != nil { t.Fatalf("Failure: '%v' '%v'\n%s", err, err2, data) } if _, ok := obj2.(*TestType1); !ok { t.Fatalf("Got wrong type") } if !semantic.DeepEqual(obj2, tt) { t.Errorf("Expected:\n %#v,\n Got:\n %#v", tt, obj2) } } func TestBadJSONRejection(t *testing.T) { log.SetOutput(os.Stderr) _, codec := GetTestScheme() badJSONs := [][]byte{ []byte(`{"myVersionKey":"v1"}`), // Missing kind []byte(`{"myVersionKey":"v1","myKindKey":"bar"}`), // Unknown kind []byte(`{"myVersionKey":"bar","myKindKey":"TestType1"}`), // Unknown version []byte(`{"myKindKey":"TestType1"}`), // Missing version } for _, b := range badJSONs { if _, err := runtime.Decode(codec, b); err == nil { t.Errorf("Did not reject bad json: %s", string(b)) } } badJSONKindMismatch := []byte(`{"myVersionKey":"v1","myKindKey":"ExternalInternalSame"}`) if err := runtime.DecodeInto(codec, badJSONKindMismatch, &TestType1{}); err == nil { t.Errorf("Kind is set but doesn't match the object type: %s", badJSONKindMismatch) } if err := runtime.DecodeInto(codec, []byte(``), &TestType1{}); err != nil { t.Errorf("Should allow empty decode: %v", err) } if _, _, err := codec.Decode([]byte(``), &schema.GroupVersionKind{Kind: "ExternalInternalSame"}, nil); err == nil { t.Errorf("Did not give error for empty data with only kind default") } if _, _, err := codec.Decode([]byte(`{"myVersionKey":"v1"}`), &schema.GroupVersionKind{Kind: "ExternalInternalSame"}, nil); err != nil { t.Errorf("Gave error for version and kind default") } if _, _, err := codec.Decode([]byte(`{"myKindKey":"ExternalInternalSame"}`), &schema.GroupVersionKind{Version: "v1"}, nil); err != nil { t.Errorf("Gave error for version and kind default") } if _, _, err := codec.Decode([]byte(``), &schema.GroupVersionKind{Kind: "ExternalInternalSame", Version: "v1"}, nil); err != nil { t.Errorf("Gave error for version and kind defaulted: %v", err) } if _, err := runtime.Decode(codec, []byte(``)); err == nil { t.Errorf("Did not give error for empty data") } } // Returns a new Scheme set up with the test objects needed by TestDirectCodec. func GetDirectCodecTestScheme() *runtime.Scheme { internalGV := schema.GroupVersion{Version: runtime.APIVersionInternal} externalGV := schema.GroupVersion{Version: "v1"} s := runtime.NewScheme() // Ordinarily, we wouldn't add TestType2, but because this is a test and // both types are from the same package, we need to get it into the system // so that converter will match it with ExternalType2. s.AddKnownTypes(internalGV, &TestType1{}) s.AddKnownTypes(externalGV, &ExternalTestType1{}) s.AddUnversionedTypes(externalGV, &metav1.Status{}) return s } func TestDirectCodec(t *testing.T) { s := GetDirectCodecTestScheme() cf := newCodecFactory(s, newSerializersForScheme(s, testMetaFactory{})) info, _ := runtime.SerializerInfoForMediaType(cf.SupportedMediaTypes(), runtime.ContentTypeJSON) serializer := info.Serializer df := DirectCodecFactory{cf} ignoredGV, err := schema.ParseGroupVersion("ignored group/ignored version") if err != nil { t.Fatal(err) } directEncoder := df.EncoderForVersion(serializer, ignoredGV) directDecoder := df.DecoderToVersion(serializer, ignoredGV) out, err := runtime.Encode(directEncoder, &ExternalTestType1{}) if err != nil { t.Fatal(err) } if string(out) != `{"myVersionKey":"v1","myKindKey":"ExternalTestType1"}`+"\n" { t.Fatal(string(out)) } a, _, err := directDecoder.Decode(out, nil, nil) e := &ExternalTestType1{ MyWeirdCustomEmbeddedVersionKindField: MyWeirdCustomEmbeddedVersionKindField{ APIVersion: "v1", ObjectKind: "ExternalTestType1", }, } if !semantic.DeepEqual(e, a) { t.Fatalf("expect %v, got %v", e, a) } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!-- This is a code snippets export file generated by the Code Snippets WordPress plugin. --> <!-- https://wordpress.org/plugins/code-snippets --> <!-- To import these snippets a WordPress site follow these steps: --> <!-- 1. Log in to that site as an administrator. --> <!-- 2. Install the Code Snippets plugin using the directions provided at the above link. --> <!-- 3. Go to 'Tools: Import' in the WordPress admin panel. --> <!-- 4. Click on the "Code Snippets" importer in the list --> <!-- 5. Upload this file using the form provided on that page. --> <!-- 6. Code Snippets will then import all of the snippets and associated information contained in this file into your site. --> <!-- 7. You will then have to visit the 'Snippets: All Snippets' admin menu and activate desired snippets. --> <!-- generator="Code Snippets/2.8.6" created="2017-09-06 18:38" --> <snippets> <snippet scope="2"> <name>Change title of WooCommerce thank you page</name> <desc></desc> <tags>woocommerce, thank, you, page, title, change</tags> <code>add_filter( 'the_title', 'woo_title_order_received', 10, 2 );&#13; function woo_title_order_received( $title, $id ) {&#13; if ( function_exists( 'is_order_received_page' ) &amp;&amp; &#13; is_order_received_page() &amp;&amp; get_the_ID() === $id ) {&#13; $title = "Thank you for your order! :)";&#13; }&#13; return $title;&#13; }</code> </snippet> </snippets>
{ "pile_set_name": "Github" }
platform=xilinx_u200_xdma_201830_2 debug=1
{ "pile_set_name": "Github" }
defmodule Core.Repo.Migrations.OrderBelongsToAddress do use Ecto.Migration def change do alter table(:snitch_orders) do add :billing_address_id, references("snitch_addresses") add :shipping_address_id, references("snitch_addresses") end end end
{ "pile_set_name": "Github" }
// // Carousel // -------------------------------------------------- // Wrapper for the slide container and indicators .carousel { position: relative; } .carousel-inner { position: relative; overflow: hidden; width: 100%; > .item { display: none; position: relative; .transition(.6s ease-in-out left); // Account for jankitude on images > img, > a > img { &:extend(.img-responsive); line-height: 1; } // WebKit CSS3 transforms for supported devices @media all and (transform-3d), (-webkit-transform-3d) { .transition-transform(~'0.6s ease-in-out'); .backface-visibility(~'hidden'); .perspective(1000px); &.next, &.active.right { .translate3d(100%, 0, 0); left: 0; } &.prev, &.active.left { .translate3d(-100%, 0, 0); left: 0; } &.next.left, &.prev.right, &.active { .translate3d(0, 0, 0); left: 0; } } } > .active, > .next, > .prev { display: block; } > .active { left: 0; } > .next, > .prev { position: absolute; top: 0; width: 100%; } > .next { left: 100%; } > .prev { left: -100%; } > .next.left, > .prev.right { left: 0; } > .active.left { left: -100%; } > .active.right { left: 100%; } } // Left/right controls for nav // --------------------------- .carousel-control { position: absolute; top: 0; left: 0; bottom: 0; width: @carousel-control-width; .opacity(@carousel-control-opacity); font-size: @carousel-control-font-size; color: @carousel-control-color; text-align: center; text-shadow: @carousel-text-shadow; background-color: rgba(0, 0, 0, 0); // Fix IE9 click-thru bug // We can't have this transition here because WebKit cancels the carousel // animation if you trip this while in the middle of another animation. // Set gradients for backgrounds &.left { #gradient > .horizontal(@start-color: rgba(0,0,0,.5); @end-color: rgba(0,0,0,.0001)); } &.right { left: auto; right: 0; #gradient > .horizontal(@start-color: rgba(0,0,0,.0001); @end-color: rgba(0,0,0,.5)); } // Hover/focus state &:hover, &:focus { outline: 0; color: @carousel-control-color; text-decoration: none; .opacity(.9); } // Toggles .icon-prev, .icon-next, .glyphicon-chevron-left, .glyphicon-chevron-right { position: absolute; top: 50%; margin-top: -10px; z-index: 5; display: inline-block; } .icon-prev, .glyphicon-chevron-left { left: 50%; margin-left: -10px; } .icon-next, .glyphicon-chevron-right { right: 50%; margin-right: -10px; } .icon-prev, .icon-next { width: 20px; height: 20px; line-height: 1; font-family: serif; } .icon-prev { &:before { content: '\2039';// SINGLE LEFT-POINTING ANGLE QUOTATION MARK (U+2039) } } .icon-next { &:before { content: '\203a';// SINGLE RIGHT-POINTING ANGLE QUOTATION MARK (U+203A) } } } // Optional indicator pips // // Add an unordered list with the following class and add a list item for each // slide your carousel holds. .carousel-indicators { position: absolute; bottom: 10px; left: 50%; z-index: 15; width: 60%; margin-left: -30%; padding-left: 0; list-style: none; text-align: center; li { display: inline-block; width: 10px; height: 10px; margin: 1px; text-indent: -999px; border: 1px solid @carousel-indicator-border-color; border-radius: 10px; cursor: pointer; // IE8-9 hack for event handling // // Internet Explorer 8-9 does not support clicks on elements without a set // `background-color`. We cannot use `filter` since that's not viewed as a // background color by the browser. Thus, a hack is needed. // See https://developer.mozilla.org/en-US/docs/Web/Events/click#Internet_Explorer // // For IE8, we set solid black as it doesn't support `rgba()`. For IE9, we // set alpha transparency for the best results possible. background-color: #000 \9; // IE8 background-color: rgba(0,0,0,0); // IE9 } .active { margin: 0; width: 12px; height: 12px; background-color: @carousel-indicator-active-bg; } } // Optional captions // ----------------------------- // Hidden by default for smaller viewports .carousel-caption { position: absolute; left: 15%; right: 15%; bottom: 20px; z-index: 10; padding-top: 20px; padding-bottom: 20px; color: @carousel-caption-color; text-align: center; text-shadow: @carousel-text-shadow; & .btn { text-shadow: none; // No shadow for button elements in carousel-caption } } // Scale up controls for tablets and up @media screen and (min-width: @screen-sm-min) { // Scale up the controls a smidge .carousel-control { .glyphicon-chevron-left, .glyphicon-chevron-right, .icon-prev, .icon-next { width: (@carousel-control-font-size * 1.5); height: (@carousel-control-font-size * 1.5); margin-top: (@carousel-control-font-size / -2); font-size: (@carousel-control-font-size * 1.5); } .glyphicon-chevron-left, .icon-prev { margin-left: (@carousel-control-font-size / -2); } .glyphicon-chevron-right, .icon-next { margin-right: (@carousel-control-font-size / -2); } } // Show and left align the captions .carousel-caption { left: 20%; right: 20%; padding-bottom: 30px; } // Move up the indicators .carousel-indicators { bottom: 20px; } }
{ "pile_set_name": "Github" }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Enum: DateTimeStyles.cs ** ** ** Purpose: Contains valid formats for DateTime recognized by ** the DateTime class' parsing code. ** ** ===========================================================*/ namespace System.Globalization { [Serializable] [Flags] [System.Runtime.InteropServices.ComVisible(true)] public enum DateTimeStyles { // Bit flag indicating that leading whitespace is allowed. Character values // 0x0009, 0x000A, 0x000B, 0x000C, 0x000D, and 0x0020 are considered to be // whitespace. None = 0x00000000, AllowLeadingWhite = 0x00000001, AllowTrailingWhite = 0x00000002, //Bitflag indicating trailing whitespace is allowed. AllowInnerWhite = 0x00000004, AllowWhiteSpaces = AllowLeadingWhite | AllowInnerWhite | AllowTrailingWhite, // When parsing a date/time string, if all year/month/day are missing, set the default date // to 0001/1/1, instead of the current year/month/day. NoCurrentDateDefault = 0x00000008, // When parsing a date/time string, if a timezone specifier ("GMT","Z","+xxxx", "-xxxx" exists), we will // ajdust the parsed time based to GMT. AdjustToUniversal = 0x00000010, AssumeLocal = 0x00000020, AssumeUniversal = 0x00000040, // Attempt to preserve whether the input is unspecified, local or UTC RoundtripKind = 0x00000080, } }
{ "pile_set_name": "Github" }
{ "signextend_Overflow_dj42": { "env": { "currentCoinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", "currentDifficulty": "0x020000", "currentGasLimit": "0x7fffffffffffffff", "currentNumber": "1", "currentTimestamp": "1000", "previousHash": "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6" }, "exec": { "address": "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", "caller": "cd1722f2947def4cf144679da39c4c32bdc35681", "data": "", "gas": "1000000", "gasPrice": "12", "origin": "cd1722f2947def4cf144679da39c4c32bdc35681", "value": "11" }, "expect": { "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6": { "storage": {} } }, "pre": { "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6": { "balance": "1000000000000000000", "code": "(asm 0x05 JUMP JUMPDEST STOP JUMPDEST 0x8000 DUP1 0x010000000000000001 SIGNEXTEND 0x8001 GT 0x03 JUMPI 0xbadf000d 0x11 SSTORE)", "nonce": "0", "storage": {} } } } }
{ "pile_set_name": "Github" }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Les informations générales relatives à un assembly dépendent de // l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations // associées à un assembly. [assembly: AssemblyTitle("Wexflow.Tasks.FileContentMatch")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Wexflow.Tasks.FileContentMatch")] [assembly: AssemblyCopyright("Copyright © 2019")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly // aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de // COM, affectez la valeur true à l'attribut ComVisible sur ce type. [assembly: ComVisible(false)] // Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM [assembly: Guid("f151425b-cb47-4ef6-adb7-d8c2d9ae0479")] // Les informations de version pour un assembly se composent des quatre valeurs suivantes : // // Version principale // Version secondaire // Numéro de build // Révision // // Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut // en utilisant '*', comme indiqué ci-dessous : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("5.8.0.0")] [assembly: AssemblyFileVersion("5.8.0.0")]
{ "pile_set_name": "Github" }
package io.improbable.keanu.algorithms.mcmc.proposal; import com.google.common.collect.ImmutableSet; import io.improbable.keanu.algorithms.Variable; import java.util.List; import java.util.Set; public final class FullVariableSelector implements MHStepVariableSelector { static final FullVariableSelector INSTANCE = new FullVariableSelector(); private FullVariableSelector() { } @Override public Set<Variable> select(List<? extends Variable> latentVariables, int sampleNumber) { return ImmutableSet.copyOf(latentVariables); } }
{ "pile_set_name": "Github" }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import InternalClassPackage.*; import com.adobe.test.Assert; // var SECTION = "Definitions"; // provide a document reference (ie, ECMA section) // var VERSION = "AS 3.0"; // Version of JavaScript or ECMA // var TITLE = "Override public function in internal class extending internal class"; // Provide ECMA section title or a description var BUGNUMBER = ""; var CLASSDEFN = new IntExtInternalOverRidePublic(); var d:Date = new Date(0); Assert.expectEq( "CLASSDEFN.orSet", false, CLASSDEFN.orSet ); Assert.expectEq( "CLASSDEFN.orGet", false, CLASSDEFN.orGet ); Assert.expectEq( "CLASSDEFN.setGetDate(d).getFullYear()", d.getFullYear(), CLASSDEFN.setGetDate(d).getFullYear()); Assert.expectEq( "CLASSDEFN.orSet", true, CLASSDEFN.orSet ); Assert.expectEq( "CLASSDEFN.orGet", true, CLASSDEFN.orGet ); // This function is for executing the test case and then // displaying the result on to the console or the LOG file.
{ "pile_set_name": "Github" }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\OptionsResolver\Exception; /** * Thrown when two lazy options have a cyclic dependency. * * @author Bernhard Schussek <[email protected]> */ class OptionDefinitionException extends \LogicException implements ExceptionInterface { }
{ "pile_set_name": "Github" }
#pragma once #include <Basic/Ptr.h> #include <functional> #include <map> #include <tuple> namespace Ubpa { class Op; class OpQueue; class EventMngr { public: enum ENUM_EVENT_TYPE { KB_PRESS, KB_RELEASE, MOUSE_MOVE, MOUSE_PRESS, MOUSE_RELEASE, MOUSE_WHEEL, }; public: static EventMngr& GetInstance() { static EventMngr instance; return instance; } void Reg(size_t event, Ptr<Op> op); void Reg(size_t event, ENUM_EVENT_TYPE eventType, Ptr<Op> op); template<typename T> void Reg(size_t event, Ptr<T> target, Ptr<Op> op) { return Reg(event, target.get(), op); } void Reg(size_t event, void* target, Ptr<Op> op); template<typename T> void Reg(size_t event, Ptr<T> target, ENUM_EVENT_TYPE eventType, Ptr<Op> op) { return Reg(event, target.get(), eventType, op); } void Reg(size_t event, void* target, ENUM_EVENT_TYPE eventType, Ptr<Op> op); void Response(size_t event); void Response(size_t event, ENUM_EVENT_TYPE eventType); template<typename T> void Response(size_t event, Ptr<T> target) { return Response(event, target.get()); } void Response(size_t event, void* target); template<typename T> void Response(size_t event, Ptr<T> target, ENUM_EVENT_TYPE eventType) { return Response(event, target.get(), eventType); } void Response(size_t event, void* target, ENUM_EVENT_TYPE eventType); protected: EventMngr() = default; ~EventMngr() = default; private: std::map<size_t, Ptr<OpQueue> > directory; std::map<std::tuple<size_t, void*>, Ptr<OpQueue> > directory20; std::map<std::tuple<size_t, ENUM_EVENT_TYPE>, Ptr<OpQueue> > directory21; std::map<std::tuple<size_t, void*, ENUM_EVENT_TYPE>, Ptr<OpQueue> > directory3; }; }
{ "pile_set_name": "Github" }
{ "images" : [ { "idiom" : "universal", "scale" : "1x" }, { "idiom" : "universal", "scale" : "2x" }, { "idiom" : "universal", "filename" : "[email protected]", "scale" : "3x" } ], "info" : { "version" : 1, "author" : "xcode" } }
{ "pile_set_name": "Github" }
import styled from 'styled-components'; export const Wrapper = styled.nav` margin: 1em 0; text-align: center; ul { display: flex; justify-content: center; align-items: center; width: 100%; } li { display: flex; padding: 0 .4em; } `;
{ "pile_set_name": "Github" }
# Copyright 2017 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Docker file for building gRPC Raspbian binaries FROM quay.io/grpc/raspbian_armv6 # Place any extra build instructions between these commands # Recommend modifying upstream docker image (quay.io/grpc/raspbian_armv6) # for build steps because running them under QEMU is very slow # (https://github.com/kpayson64/armv7hf-debian-qemu) # RUN [ "cross-build-start" ] # RUN [ "cross-build-end" ]
{ "pile_set_name": "Github" }
Peter Jarvis, who announced he would be stepping down as chief executive of leisure and brewing group Whitbread Plc in the summer, paid tribute to his successor David Thomas as an inspired retailer. "He is a retailer. He has been in retail all his life. I am not a retailer. I devised the retail strategy. I was a marketer, I was in ads until I was fourty. But David knows the retail business like the back of his hand." Whitbread is now embarking on a period of organic growth driven by its retail brands which Thomas is best suited to orchestrate, said Jarvis.
{ "pile_set_name": "Github" }
/* Generated by Font Squirrel (https://www.fontsquirrel.com) on February 26, 2017 */ @font-face { font-family: 'print_char_21medium'; src: url('../fonts/printchar21-webfont.woff2') format('woff2'), url('../fonts/printchar21-webfont.woff') format('woff'); font-weight: normal; font-style: normal; }
{ "pile_set_name": "Github" }
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file 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. */ import { RequestHandlerChain } from '../handler/RequestHandlerChain'; /** * An interface providing a mapping of handler input to {@link RequestHandlerChain}. */ export interface RequestMapper<Input, Output> { getRequestHandlerChain(input: Input): Promise<RequestHandlerChain<Input, Output>> | RequestHandlerChain<Input, Output>; }
{ "pile_set_name": "Github" }
/* * Gumstix Platforms * * Copyright (c) 2007 by Thorsten Zitterell <[email protected]> * * Code based on spitz platform by Andrzej Zaborowski <[email protected]> * * This code is licensed under the GNU GPL v2. */ /* * Example usage: * * connex: * ======= * create image: * # dd of=flash bs=1k count=16k if=/dev/zero * # dd of=flash bs=1k conv=notrunc if=u-boot.bin * # dd of=flash bs=1k conv=notrunc seek=256 if=rootfs.arm_nofpu.jffs2 * start it: * # qemu-system-arm -M connex -pflash flash -monitor null -nographic * * verdex: * ======= * create image: * # dd of=flash bs=1k count=32k if=/dev/zero * # dd of=flash bs=1k conv=notrunc if=u-boot.bin * # dd of=flash bs=1k conv=notrunc seek=256 if=rootfs.arm_nofpu.jffs2 * # dd of=flash bs=1k conv=notrunc seek=31744 if=uImage * start it: * # qemu-system-arm -M verdex -pflash flash -monitor null -nographic -m 289 */ #include "hw.h" #include "pxa.h" #include "net.h" #include "flash.h" #include "devices.h" #include "boards.h" #include "blockdev.h" #include "exec-memory.h" static const int sector_len = 128 * 1024; static void connex_init(ram_addr_t ram_size, const char *boot_device, const char *kernel_filename, const char *kernel_cmdline, const char *initrd_filename, const char *cpu_model) { PXA2xxState *cpu; DriveInfo *dinfo; int be; MemoryRegion *address_space_mem = get_system_memory(); uint32_t connex_rom = 0x01000000; uint32_t connex_ram = 0x04000000; cpu = pxa255_init(address_space_mem, connex_ram); dinfo = drive_get(IF_PFLASH, 0, 0); if (!dinfo) { fprintf(stderr, "A flash image must be given with the " "'pflash' parameter\n"); exit(1); } #ifdef TARGET_WORDS_BIGENDIAN be = 1; #else be = 0; #endif if (!pflash_cfi01_register(0x00000000, NULL, "connext.rom", connex_rom, dinfo->bdrv, sector_len, connex_rom / sector_len, 2, 0, 0, 0, 0, be)) { fprintf(stderr, "qemu: Error registering flash memory.\n"); exit(1); } /* Interrupt line of NIC is connected to GPIO line 36 */ smc91c111_init(&nd_table[0], 0x04000300, qdev_get_gpio_in(cpu->gpio, 36)); } static void verdex_init(ram_addr_t ram_size, const char *boot_device, const char *kernel_filename, const char *kernel_cmdline, const char *initrd_filename, const char *cpu_model) { PXA2xxState *cpu; DriveInfo *dinfo; int be; MemoryRegion *address_space_mem = get_system_memory(); uint32_t verdex_rom = 0x02000000; uint32_t verdex_ram = 0x10000000; cpu = pxa270_init(address_space_mem, verdex_ram, cpu_model ?: "pxa270-c0"); dinfo = drive_get(IF_PFLASH, 0, 0); if (!dinfo) { fprintf(stderr, "A flash image must be given with the " "'pflash' parameter\n"); exit(1); } #ifdef TARGET_WORDS_BIGENDIAN be = 1; #else be = 0; #endif if (!pflash_cfi01_register(0x00000000, NULL, "verdex.rom", verdex_rom, dinfo->bdrv, sector_len, verdex_rom / sector_len, 2, 0, 0, 0, 0, be)) { fprintf(stderr, "qemu: Error registering flash memory.\n"); exit(1); } /* Interrupt line of NIC is connected to GPIO line 99 */ smc91c111_init(&nd_table[0], 0x04000300, qdev_get_gpio_in(cpu->gpio, 99)); } static QEMUMachine connex_machine = { .name = "connex", .desc = "Gumstix Connex (PXA255)", .init = connex_init, }; static QEMUMachine verdex_machine = { .name = "verdex", .desc = "Gumstix Verdex (PXA270)", .init = verdex_init, }; static void gumstix_machine_init(void) { qemu_register_machine(&connex_machine); qemu_register_machine(&verdex_machine); } machine_init(gumstix_machine_init);
{ "pile_set_name": "Github" }
package com.shuyu.github.kotlin.common.gsyimageloader.gsygiideloader import com.bumptech.glide.load.Key import java.security.MessageDigest /** * Glide原图缓存Key * Created by guoshuyu on 2018/1/22. */ class GSYGlideCacheKey constructor(private val id: String, private val signature: Key) : Key { override fun equals(o: Any?): Boolean { if (this === o) { return true } if (o == null || javaClass != o.javaClass) { return false } val that = o as GSYGlideCacheKey? return id == that!!.id && signature == that.signature } override fun hashCode(): Int { var result = id.hashCode() result = 31 * result + signature.hashCode() return result } override fun updateDiskCacheKey(messageDigest: MessageDigest) { messageDigest.update(id.toByteArray(charset(Key.STRING_CHARSET_NAME))) signature.updateDiskCacheKey(messageDigest) } }
{ "pile_set_name": "Github" }
{ "pile_set_name": "Github" }
// gerber-plotter render snapshot tests 'use strict' const snapshot = require('snap-shot-it') const {getBoards} = require('@tracespace/fixtures') const getResults = require('./get-results') const SUITES = [...getBoards.sync().filter(b => !b.skipSnapshot)] describe(`gerber-plotter :: integration`, function() { this.timeout(15000) SUITES.forEach(suite => describe(suite.name, function() { const specs = suite.specs || suite.layers let suiteResults before(function(done) { if (process.env.INTEGRATION !== '1') return this.skip() getResults(suite, (error, results) => { if (error) return done(error) suiteResults = results done() }) }) specs.forEach((spec, i) => it(`renders ${spec.name}`, function() { snapshot(suiteResults.specs[i].render) }) ) }) ) })
{ "pile_set_name": "Github" }
<?php /** * Contains the ConcordDefault convention class. * * @copyright Copyright (c) 2017 Attila Fulop * @author Attila Fulop * @license MIT * @since 2017-04-14 * */ namespace Konekt\Concord\Conventions; use Illuminate\Support\Str; use Konekt\Concord\Contracts\Convention; /** * Concord's default conventions */ class ConcordDefault extends BaseConvention implements Convention { /** * @inheritdoc */ public function modulesFolder(): string { return 'Modules'; } /** * @inheritDoc */ public function modelsFolder(): string { return 'Models'; } /** * @inheritDoc */ public function contractsFolder(): string { return 'Contracts'; } /** * @inheritDoc */ public function controllersFolder(): string { return 'Http/Controllers'; } /** * @inheritDoc */ public function requestsFolder(): string { return 'Http/Requests'; } /** * @inheritDoc */ public function resourcesFolder(): string { return 'Http/Resources'; } /** * @inheritDoc */ public function contractForRequest(string $requestClass): string { return sprintf( '%s\\Contracts\\Requests\\%s', $this->oneLevelUp($this->oneLevelUp($this->getNamespace($requestClass))), class_basename($requestClass) ); } /** * @inheritDoc */ public function contractForModel(string $modelClass): string { return sprintf( '%s\\Contracts\\%s', $this->oneLevelUp($this->getNamespace($modelClass)), class_basename($modelClass) ); } /** * @inheritDoc */ public function modelForRepository(string $repositoryClass): string { return Str::replaceLast('Repository', '', $repositoryClass); } /** * @inheritDoc */ public function modelForProxy(string $proxyClass): string { return Str::replaceLast('Proxy', '', $proxyClass); } /** * @inheritDoc */ public function repositoryForModel(string $modelClass): string { return $modelClass . 'Repository'; } /** * @inheritDoc */ public function proxyForModel(string $modelClass): string { return $modelClass . 'Proxy'; } /** * @inheritDoc */ public function manifestFile(): string { return 'resources/manifest.php'; } /** * @inheritDoc */ public function configFolder(): string { return 'resources/config'; } /** * @inheritDoc */ public function migrationsFolder(): string { return 'resources/database/migrations'; } /** * @inheritDoc */ public function viewsFolder(): string { return 'resources/views'; } /** * @inheritDoc */ public function routesFolder(): string { return 'resources/routes'; } /** * @inheritDoc */ public function providersFolder(): string { return 'Providers'; } /** * @inheritDoc */ public function enumsFolder(): string { return 'Models'; } /** * @inheritDoc */ public function contractForEnum(string $enumClass): string { // Enums are in the same folder as models, so we use the existing method return $this->contractForModel($enumClass); } /** * @inheritDoc */ public function proxyForEnum(string $enumClass): string { // Identical with model proxies return $this->proxyForModel($enumClass); } /** * @inheritDoc */ public function enumForProxy(string $proxyClass): string { // Identical with model proxies return $this->modelForProxy($proxyClass); } /** * @inheritdoc */ public function proxyForEnumContract(string $enumContract) { return $this->proxyForEnum( $this->defaultEnumClassForContract($enumContract) ); } /** * @inheritdoc */ public function proxyForModelContract(string $modelContract): string { return $this->proxyForModel( $this->defaultModelClassForContract($modelContract) ); } /** * Returns the convention's default enum class for an enum contract * * @param $enumContract * * @return string */ protected function defaultEnumClassForContract($enumContract) { return $this->oneLevelUp($this->getNamespace($enumContract)) . '\\' . $this->enumsFolder() . '\\' . class_basename($enumContract); } /** * Returns the convention's default model class for a model contract * * @param $modelContract * * @return string */ protected function defaultModelClassForContract($modelContract) { return $this->oneLevelUp($this->getNamespace($modelContract)) . '\\' . $this->modelsFolder() . '\\' . class_basename($modelContract); } }
{ "pile_set_name": "Github" }
/* * Copyright (C) 2013 Reimar Döffinger <[email protected]> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * @ingroup lavu_hash_generic * Generic hashing API */ #ifndef AVUTIL_HASH_H #define AVUTIL_HASH_H #include <stdint.h> #include "version.h" /** * @defgroup lavu_hash Hash Functions * @ingroup lavu_crypto * Hash functions useful in multimedia. * * Hash functions are widely used in multimedia, from error checking and * concealment to internal regression testing. libavutil has efficient * implementations of a variety of hash functions that may be useful for * FFmpeg and other multimedia applications. * * @{ * * @defgroup lavu_hash_generic Generic Hashing API * An abstraction layer for all hash functions supported by libavutil. * * If your application needs to support a wide range of different hash * functions, then the Generic Hashing API is for you. It provides a generic, * reusable API for @ref lavu_hash "all hash functions" implemented in libavutil. * If you just need to use one particular hash function, use the @ref lavu_hash * "individual hash" directly. * * @section Sample Code * * A basic template for using the Generic Hashing API follows: * * @code * struct AVHashContext *ctx = NULL; * const char *hash_name = NULL; * uint8_t *output_buf = NULL; * * // Select from a string returned by av_hash_names() * hash_name = ...; * * // Allocate a hash context * ret = av_hash_alloc(&ctx, hash_name); * if (ret < 0) * return ret; * * // Initialize the hash context * av_hash_init(ctx); * * // Update the hash context with data * while (data_left) { * av_hash_update(ctx, data, size); * } * * // Now we have no more data, so it is time to finalize the hash and get the * // output. But we need to first allocate an output buffer. Note that you can * // use any memory allocation function, including malloc(), not just * // av_malloc(). * output_buf = av_malloc(av_hash_get_size(ctx)); * if (!output_buf) * return AVERROR(ENOMEM); * * // Finalize the hash context. * // You can use any of the av_hash_final*() functions provided, for other * // output formats. If you do so, be sure to adjust the memory allocation * // above. See the function documentation below for the exact amount of extra * // memory needed. * av_hash_final(ctx, output_buffer); * * // Free the context * av_hash_freep(&ctx); * @endcode * * @section Hash Function-Specific Information * If the CRC32 hash is selected, the #AV_CRC_32_IEEE polynomial will be * used. * * If the Murmur3 hash is selected, the default seed will be used. See @ref * lavu_murmur3_seedinfo "Murmur3" for more information. * * @{ */ /** * @example ffhash.c * This example is a simple command line application that takes one or more * arguments. It demonstrates a typical use of the hashing API with allocation, * initialization, updating, and finalizing. */ struct AVHashContext; /** * Allocate a hash context for the algorithm specified by name. * * @return >= 0 for success, a negative error code for failure * * @note The context is not initialized after a call to this function; you must * call av_hash_init() to do so. */ int av_hash_alloc(struct AVHashContext **ctx, const char *name); /** * Get the names of available hash algorithms. * * This function can be used to enumerate the algorithms. * * @param[in] i Index of the hash algorithm, starting from 0 * @return Pointer to a static string or `NULL` if `i` is out of range */ const char *av_hash_names(int i); /** * Get the name of the algorithm corresponding to the given hash context. */ const char *av_hash_get_name(const struct AVHashContext *ctx); /** * Maximum value that av_hash_get_size() will currently return. * * You can use this if you absolutely want or need to use static allocation for * the output buffer and are fine with not supporting hashes newly added to * libavutil without recompilation. * * @warning * Adding new hashes with larger sizes, and increasing the macro while doing * so, will not be considered an ABI change. To prevent your code from * overflowing a buffer, either dynamically allocate the output buffer with * av_hash_get_size(), or limit your use of the Hashing API to hashes that are * already in FFmpeg during the time of compilation. */ #define AV_HASH_MAX_SIZE 64 /** * Get the size of the resulting hash value in bytes. * * The maximum value this function will currently return is available as macro * #AV_HASH_MAX_SIZE. * * @param[in] ctx Hash context * @return Size of the hash value in bytes */ int av_hash_get_size(const struct AVHashContext *ctx); /** * Initialize or reset a hash context. * * @param[in,out] ctx Hash context */ void av_hash_init(struct AVHashContext *ctx); /** * Update a hash context with additional data. * * @param[in,out] ctx Hash context * @param[in] src Data to be added to the hash context * @param[in] len Size of the additional data */ #if FF_API_CRYPTO_SIZE_T void av_hash_update(struct AVHashContext *ctx, const uint8_t *src, int len); #else void av_hash_update(struct AVHashContext *ctx, const uint8_t *src, size_t len); #endif /** * Finalize a hash context and compute the actual hash value. * * The minimum size of `dst` buffer is given by av_hash_get_size() or * #AV_HASH_MAX_SIZE. The use of the latter macro is discouraged. * * It is not safe to update or finalize a hash context again, if it has already * been finalized. * * @param[in,out] ctx Hash context * @param[out] dst Where the final hash value will be stored * * @see av_hash_final_bin() provides an alternative API */ void av_hash_final(struct AVHashContext *ctx, uint8_t *dst); /** * Finalize a hash context and store the actual hash value in a buffer. * * It is not safe to update or finalize a hash context again, if it has already * been finalized. * * If `size` is smaller than the hash size (given by av_hash_get_size()), the * hash is truncated; if size is larger, the buffer is padded with 0. * * @param[in,out] ctx Hash context * @param[out] dst Where the final hash value will be stored * @param[in] size Number of bytes to write to `dst` */ void av_hash_final_bin(struct AVHashContext *ctx, uint8_t *dst, int size); /** * Finalize a hash context and store the hexadecimal representation of the * actual hash value as a string. * * It is not safe to update or finalize a hash context again, if it has already * been finalized. * * The string is always 0-terminated. * * If `size` is smaller than `2 * hash_size + 1`, where `hash_size` is the * value returned by av_hash_get_size(), the string will be truncated. * * @param[in,out] ctx Hash context * @param[out] dst Where the string will be stored * @param[in] size Maximum number of bytes to write to `dst` */ void av_hash_final_hex(struct AVHashContext *ctx, uint8_t *dst, int size); /** * Finalize a hash context and store the Base64 representation of the * actual hash value as a string. * * It is not safe to update or finalize a hash context again, if it has already * been finalized. * * The string is always 0-terminated. * * If `size` is smaller than AV_BASE64_SIZE(hash_size), where `hash_size` is * the value returned by av_hash_get_size(), the string will be truncated. * * @param[in,out] ctx Hash context * @param[out] dst Where the final hash value will be stored * @param[in] size Maximum number of bytes to write to `dst` */ void av_hash_final_b64(struct AVHashContext *ctx, uint8_t *dst, int size); /** * Free hash context and set hash context pointer to `NULL`. * * @param[in,out] ctx Pointer to hash context */ void av_hash_freep(struct AVHashContext **ctx); /** * @} * @} */ #endif /* AVUTIL_HASH_H */
{ "pile_set_name": "Github" }
export MakeInc_cmd=${SRCROOT}/makedefs/MakeInc.cmd export MakeInc_def=${SRCROOT}/makedefs/MakeInc.def export MakeInc_rule=${SRCROOT}/makedefs/MakeInc.rule export MakeInc_dir=${SRCROOT}/makedefs/MakeInc.dir include $(MakeInc_cmd) include $(MakeInc_def) INSTINC_SUBDIRS = \ audit EXPINC_SUBDIRS = \ audit include $(MakeInc_rule) include $(MakeInc_dir)
{ "pile_set_name": "Github" }
package biweekly.io.scribe.property; import java.util.EnumSet; import java.util.Set; import biweekly.ICalVersion; import biweekly.property.PercentComplete; /* Copyright (c) 2013-2018, Michael Angstadt All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * Marshals {@link PercentComplete} properties. * @author Michael Angstadt */ public class PercentCompleteScribe extends IntegerPropertyScribe<PercentComplete> { public PercentCompleteScribe() { super(PercentComplete.class, "PERCENT-COMPLETE"); } @Override protected PercentComplete newInstance(Integer value) { return new PercentComplete(value); } @Override public Set<ICalVersion> getSupportedVersions() { return EnumSet.of(ICalVersion.V2_0_DEPRECATED, ICalVersion.V2_0); } }
{ "pile_set_name": "Github" }
import { api } from '../barrels/api'; import { BqView } from './bq-view'; export interface ItemGenBqViews { bq_views: BqView[]; filters_fractions: { [s: string]: api.Fraction[]; }; }
{ "pile_set_name": "Github" }
// Copyright 2020 The Defold Foundation // Licensed under the Defold License version 1.0 (the "License"); you may not use // this file except in compliance with the License. // // You may obtain a copy of the License, together with FAQs at // https://www.defold.com/license // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. #ifndef DMSDK_SSLSOCKET_H #define DMSDK_SSLSOCKET_H #include <stdint.h> // Cannot forward declate enums #include <dmsdk/dlib/socket.h> /*# SDK Secure socket API documentation * [file:<dmsdk/dlib/sslsocket.h>] * * Secure socket functions. * * @document * @name SSLSocket * @namespace dmSSLSocket */ namespace dmSSLSocket { /*# result enumeration * * Result enumeration. * * @enum * @name dmSSLSocket::Result * @member dmSSLSocket::RESULT_OK (0) * @member dmSSLSocket::RESULT_SSL_INIT_FAILED (-2000) * @member dmSSLSocket::RESULT_HANDSHAKE_FAILED (-2001) * @member dmSSLSocket::RESULT_WOULDBLOCK (-2002) * @member dmSSLSocket::RESULT_CONNREFUSED (-2003) * */ enum Result { RESULT_OK = 0, RESULT_SSL_INIT_FAILED = -2000, RESULT_HANDSHAKE_FAILED = -2001, RESULT_WOULDBLOCK = -2002, RESULT_CONNREFUSED = -2003, }; /*# Socket type definition * @typedef * @name Socket */ typedef struct SSLSocket* Socket; const Socket INVALID_SOCKET_HANDLE = 0; /*# create a secure socket * Create a new secure socket * @name dmSSLSocket::New * @param socket [type:dmSocket::Socket] The socket to wrap * @param host [type:const char*] The name of the host (e.g. "httpbin.org") * @param timeout [type:uint64_t] The timeout for the handshake procedure. (microseconds) * @param sslsocket [type:dmSSLSocket::Socket*] Pointer to a secure socket * @return RESULT_OK on succcess * @examples * ```cpp * dmSSLSocket::Result result; * dmSSLSocket::Socket sslsocket; * result = dmSSLSocket::New(socket, "httpbin.org", 500*1000, &sslsocket); * if (dmSSLSocket::RESULT_OK == result) * { * // ... * } else { * // ... * } * ``` */ Result New(dmSocket::Socket socket, const char* host, uint64_t timeout, Socket* sslsocket); /*# delete a secure socket * Delete a secure socket. Does not close the underlying socket * @name dmSSLSocket::Delete * @param socket [type:dmSSLSocket::Socket] Secure socket to close * @return RESULT_OK on success * @examples * ```cpp * dmSSLSocket::Delete(sslsocket); * ``` */ Result Delete(Socket socket); /*# send a message on a secure socket * Send a message on a secure socket * @name dmSSLSocket::Send * @param socket [type:dmSSLSocket::Socket] SSL socket to send a message on * @param buffer Buffer to send * @param length Length of buffer to send * @param sent_bytes Number of bytes sent (result) * @return RESULT_OK on success */ dmSocket::Result Send(Socket socket, const void* buffer, int length, int* sent_bytes); /*# receive data on a secure socket * Receive data on a secure socket * @name dmSSLSocket::Receive * @param socket [type:dmSSLSocket::Socket] Socket to receive data on * @param buffer Buffer to receive to * @param length Receive buffer length * @param received_bytes Number of received bytes (result) * @return RESULT_OK on success */ dmSocket::Result Receive(Socket socket, void* buffer, int length, int* received_bytes); /*# * Set socket receive timeout * @note Timeout resolution might be in milliseconds, e.g. windows. Use values * larger than or equal to 1000 * @name dmSocket::SetReceiveTimeout * @param socket [type:dmSocket::Socket] socket * @param timeout [type:uint64_t] timeout in microseconds * @return RESULT_OK on success */ dmSocket::Result SetReceiveTimeout(Socket socket, uint64_t timeout); } #endif // DMSDK_SSLSOCKET_H
{ "pile_set_name": "Github" }
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * This file is part of PhotoScrollerNetwork -- An iOS project that smoothly and efficiently * renders large images in progressively smaller ones for display in a CATiledLayer backed view. * Images can either be local, or more interestingly, downloaded from the internet. * Images can be rendered by an iOS CGImageSource, libjpeg-turbo, or incrmentally by * libjpeg (the turbo version) - the latter gives the best speed. * * Parts taken with minor changes from Apple's PhotoScroller sample code, the * ConcurrentOp from my ConcurrentOperations github sample code, and TiledImageBuilder * was completely original source code developed by me. * * Copyright 2012-2019 David Hoerl All Rights Reserved. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #import "ViewController.h" #import "PhotoViewController.h" //#import "ConcurrentOp.h" #import "TiledImageBuilder.h" #import "TilingView.h" @interface ViewController () - (IBAction)segmentChanged:(id)sender; - (IBAction)stepperStepped:(id)sender; //- (IBAction)makeImage:(id)sender; // in progress @end @implementation ViewController { IBOutlet UIButton *runButton; IBOutlet UISegmentedControl *technology; IBOutlet UISwitch *useInternet; IBOutlet UISwitch *justOneImage; IBOutlet UILabel *orientationValue; IBOutlet UIImageView *imageView; IBOutlet UILabel *fileName; } - (IBAction)sliderAction:(id)sender { float num = (float)[(UISlider *)sender value]; long val = lrintf(num); if(!sender || !val) { fileName.text = @"large_leaves_70mp"; // Space4 large_leaves_70mp } else { fileName.text = [NSString stringWithFormat:@"Space%ld", val+3]; } } - (IBAction)segmentChanged:(id)sender { #if 0 if(technology.selectedSegmentIndex == 2) { useInternet.on = YES; useInternet.enabled = NO; } else { useInternet.enabled = YES; } #endif } - (IBAction)stepperStepped:(id)sender { UIStepper *stepper = (UIStepper *)sender; orientationValue.text = [NSString stringWithFormat:@"%ld", lrint(stepper.value)]; } #if 0 // does not work #warning FIX ME SOMEDAY - (IBAction)makeImage:(id)sender { NSString *path = [[NSBundle mainBundle] pathForResource:@"Shed" ofType:@"jpg"]; assert(path); // 320 just shows we don't need to size it to what our desired size is TiledImageBuilder *tb = [[TiledImageBuilder alloc] initWithImagePath:path withDecode:cgimageDecoder size:CGSizeMake(320, 320) orientation:1]; assert(tb); TilingView *tv = [[TilingView alloc] initWithImageBuilder:tb]; assert(tv); tv.frame = CGRectMake(0, 0, imageView.bounds.size.width, imageView.bounds.size.height); UIImage *image = [tv image]; assert(image); imageView.image = image; } #endif - (IBAction)button:(id)sender { PhotoViewController *pvc = [[PhotoViewController alloc] initWithNibName:@"PhotoViewController" bundle:nil]; pvc.isWebTest = useInternet.on; #ifdef LIBJPEG pvc.decoder = useInternet.on ? libjpegIncremental : libjpegTurboDecoder; #else pvc.decoder = cgimageDecoder; #endif pvc.justDoOneImage = justOneImage.on; pvc.orientation = [orientationValue.text integerValue]; pvc.singleName = fileName.text; assert(fileName.text); UIBarButtonItem *temporaryBarButtonItem = [UIBarButtonItem new]; [temporaryBarButtonItem setTitle:@"Back"]; self.navigationItem.backBarButtonItem = temporaryBarButtonItem; [self.navigationController pushViewController:pvc animated:YES]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; NSLog(@"Yikes! ViewController didReceiveMemoryWarning!"); } #pragma mark - View lifecycle - (void)viewDidLoad { [super viewDidLoad]; #if defined(LIBJPEG) technology.hidden = NO; #else technology.hidden = YES; #endif self.navigationItem.title = @"PhotoScrollerNetwork"; [self sliderAction:nil]; } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; self.navigationItem.backBarButtonItem = nil; } - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; } - (void)viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; } @end
{ "pile_set_name": "Github" }
# Makefile.in generated by automake 1.11.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, # 2003, 2004, 2005, 2006, 2007, 2008, 2009 Free Software Foundation, # Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ target_triplet = @target@ epcuda_PROGRAMS = Sort$(EXEEXT) subdir = src/cuda/level1/sort/epmpi DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = am__installdirs = "$(DESTDIR)$(epcudadir)" PROGRAMS = $(epcuda_PROGRAMS) am_Sort_OBJECTS = main.$(OBJEXT) Sort_OBJECTS = $(am_Sort_OBJECTS) am__DEPENDENCIES_1 = Sort_DEPENDENCIES = Sort.o sort_kernel.o $(am__DEPENDENCIES_1) DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir)/config depcomp = $(SHELL) $(top_srcdir)/build-aux/depcomp am__depfiles_maybe = depfiles am__mv = mv -f CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) CXXLINK = $(CXXLD) $(AM_CXXFLAGS) $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) \ -o $@ SOURCES = $(Sort_SOURCES) DIST_SOURCES = $(Sort_SOURCES) ETAGS = etags CTAGS = ctags DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) # How to find source files VPATH = $(srcdir)/..:$(srcdir)/../../../common:$(srcdir)/../../../../common ACLOCAL = @ACLOCAL@ ALLOCA = @ALLOCA@ AMTAR = @AMTAR@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ BIBTEX = @BIBTEX@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPPFLAGS = @CPPFLAGS@ CUDA_CPPFLAGS = @CUDA_CPPFLAGS@ CUDA_INCDIR = @CUDA_INCDIR@ # Which compiler to use to build and link CXX = ${MPICXX} CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ GREP = @GREP@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LATEXMK = @LATEXMK@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MKDIR_P = @MKDIR_P@ MPICXX = @MPICXX@ MPI_SUBDIRS = @MPI_SUBDIRS@ NVCC = @NVCC@ NVCXXFLAGS = @NVCXXFLAGS@ OBJEXT = @OBJEXT@ OPENCL_LIBS = @OPENCL_LIBS@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PDFLATEX = @PDFLATEX@ PERL = @PERL@ RANLIB = @RANLIB@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ USE_CUDA = @USE_CUDA@ USE_MPI = @USE_MPI@ VERSION = @VERSION@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target = @target@ target_alias = @target_alias@ target_cpu = @target_cpu@ target_os = @target_os@ target_vendor = @target_vendor@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ CXXLD = ${MPICXX} AM_LDFLAGS = $(CUDA_LDFLAGS) AM_CPPFLAGS = $(CUDA_INC) $(MPI_CPPFLAGS) -I$(top_srcdir)/src/mpi/common # What is the destination for programs built from this directory? epcudadir = $(bindir)/EP/CUDA # How to build those programs? Sort_SOURCES = main.cpp Sort_LDADD = Sort.o sort_kernel.o $(CUDA_LIBS) $(LIBS) all: all-am .SUFFIXES: .SUFFIXES: .cpp .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/cuda/level1/sort/epmpi/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/cuda/level1/sort/epmpi/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): install-epcudaPROGRAMS: $(epcuda_PROGRAMS) @$(NORMAL_INSTALL) test -z "$(epcudadir)" || $(MKDIR_P) "$(DESTDIR)$(epcudadir)" @list='$(epcuda_PROGRAMS)'; test -n "$(epcudadir)" || list=; \ for p in $$list; do echo "$$p $$p"; done | \ sed 's/$(EXEEXT)$$//' | \ while read p p1; do if test -f $$p; \ then echo "$$p"; echo "$$p"; else :; fi; \ done | \ sed -e 'p;s,.*/,,;n;h' -e 's|.*|.|' \ -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \ sed 'N;N;N;s,\n, ,g' | \ $(AWK) 'BEGIN { files["."] = ""; dirs["."] = 1 } \ { d=$$3; if (dirs[d] != 1) { print "d", d; dirs[d] = 1 } \ if ($$2 == $$4) files[d] = files[d] " " $$1; \ else { print "f", $$3 "/" $$4, $$1; } } \ END { for (d in files) print "f", d, files[d] }' | \ while read type dir files; do \ if test "$$dir" = .; then dir=; else dir=/$$dir; fi; \ test -z "$$files" || { \ echo " $(INSTALL_PROGRAM_ENV) $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(epcudadir)$$dir'"; \ $(INSTALL_PROGRAM_ENV) $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(epcudadir)$$dir" || exit $$?; \ } \ ; done uninstall-epcudaPROGRAMS: @$(NORMAL_UNINSTALL) @list='$(epcuda_PROGRAMS)'; test -n "$(epcudadir)" || list=; \ files=`for p in $$list; do echo "$$p"; done | \ sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \ -e 's/$$/$(EXEEXT)/' `; \ test -n "$$list" || exit 0; \ echo " ( cd '$(DESTDIR)$(epcudadir)' && rm -f" $$files ")"; \ cd "$(DESTDIR)$(epcudadir)" && rm -f $$files clean-epcudaPROGRAMS: -test -z "$(epcuda_PROGRAMS)" || rm -f $(epcuda_PROGRAMS) Sort$(EXEEXT): $(Sort_OBJECTS) $(Sort_DEPENDENCIES) @rm -f Sort$(EXEEXT) $(CXXLINK) $(Sort_OBJECTS) $(Sort_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/main.Po@am__quote@ .cpp.o: @am__fastdepCXX_TRUE@ $(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXXCOMPILE) -c -o $@ $< .cpp.obj: @am__fastdepCXX_TRUE@ $(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ mkid -fID $$unique tags: TAGS TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) set x; \ here=`pwd`; \ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: CTAGS CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile $(PROGRAMS) installdirs: for dir in "$(DESTDIR)$(epcudadir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ `test -z '$(STRIP)' || \ echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-epcudaPROGRAMS clean-generic mostlyclean-am distclean: distclean-am -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-epcudaPROGRAMS install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-epcudaPROGRAMS .MAKE: install-am install-strip .PHONY: CTAGS GTAGS all all-am check check-am clean \ clean-epcudaPROGRAMS clean-generic ctags distclean \ distclean-compile distclean-generic distclean-tags distdir dvi \ dvi-am html html-am info info-am install install-am \ install-data install-data-am install-dvi install-dvi-am \ install-epcudaPROGRAMS install-exec install-exec-am \ install-html install-html-am install-info install-info-am \ install-man install-pdf install-pdf-am install-ps \ install-ps-am install-strip installcheck installcheck-am \ installdirs maintainer-clean maintainer-clean-generic \ mostlyclean mostlyclean-compile mostlyclean-generic pdf pdf-am \ ps ps-am tags uninstall uninstall-am uninstall-epcudaPROGRAMS include $(top_builddir)/config/config.mk include $(top_builddir)/config/targets.mk # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT:
{ "pile_set_name": "Github" }
Issue2790-b.agda:1,1-42 Cannot set OPTIONS pragma --cubical and --with-K with safe flag.
{ "pile_set_name": "Github" }
import bpy bpy.context.camera.sensor_width = 30.0 bpy.context.camera.sensor_height = 15.0 bpy.context.camera.sensor_fit = 'HORIZONTAL'
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <Package xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10" xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest" xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10" IgnorableNamespaces="uap mp"> <Identity Name="10805zumoTestUser.AppCenter-Contoso.Forms.Puppet.U" Publisher="CN=B2D1C358-6AF8-4416-BF73-129CC1F3C152" Version="3.4.3.0" /> <mp:PhoneIdentity PhoneProductId="55497ed8-b2ac-4485-ba79-e2b65bb720ed" PhonePublisherId="00000000-0000-0000-0000-000000000000" /> <Properties> <DisplayName>AppCenter-Contoso.Forms.Puppet.UWP</DisplayName> <PublisherDisplayName>Azure Mobile Team</PublisherDisplayName> <Logo>Assets\StoreLogo.png</Logo> </Properties> <Dependencies> <TargetDeviceFamily Name="Windows.Universal" MinVersion="10.0.0.0" MaxVersionTested="10.0.0.0" /> </Dependencies> <Resources> <Resource Language="x-generate" /> </Resources> <Applications> <Application Id="App" Executable="$targetnametoken$.exe" EntryPoint="Contoso.Forms.Puppet.UWP.App"> <uap:VisualElements DisplayName="AppCenter Puppet UWP" Square150x150Logo="Assets\Square150x150Logo.png" Square44x44Logo="Assets\Square44x44Logo.png" Description="Contoso.Forms.Puppet.UWP" BackgroundColor="white"> <uap:DefaultTile Wide310x150Logo="Assets\Wide310x150Logo.png"> </uap:DefaultTile> <uap:SplashScreen Image="Assets\SplashScreen.png" BackgroundColor="white" /> </uap:VisualElements> </Application> </Applications> <Capabilities> <Capability Name="internetClient" /> <Capability Name="privateNetworkClientServer" /> <uap:Capability Name="picturesLibrary"/> <DeviceCapability Name="location" /> </Capabilities> </Package>
{ "pile_set_name": "Github" }
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24" android:tint="?attr/colorControlNormal"> <path android:fillColor="@android:color/white" android:pathData="M14,9l-1,-2H7V5.72C7.6,5.38 8,4.74 8,4c0,-1.1 -0.9,-2 -2,-2S4,2.9 4,4c0,0.74 0.4,1.38 1,1.72V21h2v-4h5l1,2h7V9H14zM18,17h-4l-1,-2H7V9h5l1,2h5V17z"/> </vector>
{ "pile_set_name": "Github" }
var async = require('async'); var jsObfuscate = require('../jsObfuscate'); module.exports = function(grunt) { grunt.registerMultiTask( 'jsObfuscate', 'Obfuscate JavaScript files via javascriptobfuscator.com.', function() { var options = this.options(); var cc = options.concurrency; cc = /^[0-9]+$/.test(cc) && (cc > 0 && cc < 100) ? cc : 2; var queue = async.queue(function(task, callback) { var content = task.src.map(function(src) { return grunt.file.read(src).replace(/^\#\!.*/, ''); }).join('\n;\n'); jsObfuscate(content, options). then(function(obfuscated) { grunt.file.write(task.dest, obfuscated); }). then(callback). catch(callback); }, cc); queue.drain = this.async(); var files = this.files; for (var i = 0; i < files.length; i++) { queue.push(files[i], (function(current) { return function(err) { if (err) { var src = current.src.join(', '); console.error(('Fatal error occurred when processing ' + src + ':').red); grunt.fail.fatal(err); } grunt.log.ok('Obfuscated: ' + current.dest.cyan); }; })(files[i])); } }); };
{ "pile_set_name": "Github" }
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package event import ( "context" "golang.org/x/tools/internal/event/core" "golang.org/x/tools/internal/event/keys" "golang.org/x/tools/internal/event/label" ) // Exporter is a function that handles events. // It may return a modified context and event. type Exporter func(context.Context, core.Event, label.Map) context.Context // SetExporter sets the global exporter function that handles all events. // The exporter is called synchronously from the event call site, so it should // return quickly so as not to hold up user code. func SetExporter(e Exporter) { core.SetExporter(core.Exporter(e)) } // Log takes a message and a label list and combines them into a single event // before delivering them to the exporter. func Log(ctx context.Context, message string, labels ...label.Label) { core.Export(ctx, core.MakeEvent([3]label.Label{ keys.Msg.Of(message), }, labels)) } // IsLog returns true if the event was built by the Log function. // It is intended to be used in exporters to identify the semantics of the // event when deciding what to do with it. func IsLog(ev core.Event) bool { return ev.Label(0).Key() == keys.Msg } // Error takes a message and a label list and combines them into a single event // before delivering them to the exporter. It captures the error in the // delivered event. func Error(ctx context.Context, message string, err error, labels ...label.Label) { core.Export(ctx, core.MakeEvent([3]label.Label{ keys.Msg.Of(message), keys.Err.Of(err), }, labels)) } // IsError returns true if the event was built by the Error function. // It is intended to be used in exporters to identify the semantics of the // event when deciding what to do with it. func IsError(ev core.Event) bool { return ev.Label(0).Key() == keys.Msg && ev.Label(1).Key() == keys.Err } // Metric sends a label event to the exporter with the supplied labels. func Metric(ctx context.Context, labels ...label.Label) { core.Export(ctx, core.MakeEvent([3]label.Label{ keys.Metric.New(), }, labels)) } // IsMetric returns true if the event was built by the Metric function. // It is intended to be used in exporters to identify the semantics of the // event when deciding what to do with it. func IsMetric(ev core.Event) bool { return ev.Label(0).Key() == keys.Metric } // Label sends a label event to the exporter with the supplied labels. func Label(ctx context.Context, labels ...label.Label) context.Context { return core.Export(ctx, core.MakeEvent([3]label.Label{ keys.Label.New(), }, labels)) } // IsLabel returns true if the event was built by the Label function. // It is intended to be used in exporters to identify the semantics of the // event when deciding what to do with it. func IsLabel(ev core.Event) bool { return ev.Label(0).Key() == keys.Label } // Start sends a span start event with the supplied label list to the exporter. // It also returns a function that will end the span, which should normally be // deferred. func Start(ctx context.Context, name string, labels ...label.Label) (context.Context, func()) { return core.ExportPair(ctx, core.MakeEvent([3]label.Label{ keys.Start.Of(name), }, labels), core.MakeEvent([3]label.Label{ keys.End.New(), }, nil)) } // IsStart returns true if the event was built by the Start function. // It is intended to be used in exporters to identify the semantics of the // event when deciding what to do with it. func IsStart(ev core.Event) bool { return ev.Label(0).Key() == keys.Start } // IsEnd returns true if the event was built by the End function. // It is intended to be used in exporters to identify the semantics of the // event when deciding what to do with it. func IsEnd(ev core.Event) bool { return ev.Label(0).Key() == keys.End } // Detach returns a context without an associated span. // This allows the creation of spans that are not children of the current span. func Detach(ctx context.Context) context.Context { return core.Export(ctx, core.MakeEvent([3]label.Label{ keys.Detach.New(), }, nil)) } // IsDetach returns true if the event was built by the Detach function. // It is intended to be used in exporters to identify the semantics of the // event when deciding what to do with it. func IsDetach(ev core.Event) bool { return ev.Label(0).Key() == keys.Detach }
{ "pile_set_name": "Github" }
# swoole_client->sock 类型为int。sock属性是此socket的文件描述符。在PHP代码中可以使用 ```php $sock = fopen("php://fd/".$swoole_client->sock); ``` __注意:$client->sock属性值,仅在$client->connect后才能取到。在未连接服务器之前,此属性的值为null。__ 将swoole_client的socket转换成一个stream socket。可以调用fread/fwrite/fclose等函数进程操作。 > swoole_server中的$fd不能用此方法转换,因为$fd只是一个数字,$fd文件描述符属于主进程 $swoole_client->sock可以转换成int作为数组的key.
{ "pile_set_name": "Github" }
defaults: &defaults host: '127.0.0.1' autocreate_indexes: false allow_dynamic_fields: true include_root_in_json: false parameterize_keys: true persist_in_safe_mode: false raise_not_found_error: true reconnect_time: 3 development: <<: *defaults database: quora_development development_mongohq: <<: *defaults #uri: mongodb://<user>:<password>@flame.mongohq.com:27070/quora #use demo mongohq database for fast run uri: mongodb://root:[email protected]:27070/quora test: <<: *defaults database: quora_test # set these environment variables on your prod server production: <<: *defaults host: '127.0.0.1' database: quora
{ "pile_set_name": "Github" }
// SPDX-License-Identifier: GPL-2.0+ /* * (C) Copyright 2000-2003 * Wolfgang Denk, DENX Software Engineering, [email protected]. * * Copyright (C) 2004-2007 Freescale Semiconductor, Inc. * TsiChung Liew ([email protected]) */ #include <common.h> #include <flash.h> #include <init.h> #include <irq_func.h> #include <asm/immap.h> #ifndef CONFIG_SYS_FLASH_CFI typedef unsigned short FLASH_PORT_WIDTH; typedef volatile unsigned short FLASH_PORT_WIDTHV; #define FPW FLASH_PORT_WIDTH #define FPWV FLASH_PORT_WIDTHV #define FLASH_CYCLE1 0x5555 #define FLASH_CYCLE2 0x2aaa #define SYNC __asm__("nop") /*----------------------------------------------------------------------- * Functions */ ulong flash_get_size(FPWV * addr, flash_info_t * info); int flash_get_offsets(ulong base, flash_info_t * info); int write_word(flash_info_t * info, FPWV * dest, u16 data); static inline void spin_wheel(void); flash_info_t flash_info[CONFIG_SYS_MAX_FLASH_BANKS]; ulong flash_init(void) { ulong size = 0; ulong fbase = 0; fbase = (ulong) CONFIG_SYS_FLASH_BASE; flash_get_size((FPWV *) fbase, &flash_info[0]); flash_get_offsets((ulong) fbase, &flash_info[0]); fbase += flash_info[0].size; size += flash_info[0].size; /* Protect monitor and environment sectors */ flash_protect(FLAG_PROTECT_SET, CONFIG_SYS_MONITOR_BASE, CONFIG_SYS_MONITOR_BASE + monitor_flash_len - 1, &flash_info[0]); return size; } int flash_get_offsets(ulong base, flash_info_t * info) { int i; if ((info->flash_id & FLASH_VENDMASK) == FLASH_MAN_SST) { info->start[0] = base; info->protect[0] = 0; for (i = 1; i < CONFIG_SYS_SST_SECT; i++) { info->start[i] = info->start[i - 1] + CONFIG_SYS_SST_SECTSZ; info->protect[i] = 0; } } return ERR_OK; } void flash_print_info(flash_info_t * info) { int i; switch (info->flash_id & FLASH_VENDMASK) { case FLASH_MAN_SST: printf("SST "); break; default: printf("Unknown Vendor "); break; } switch (info->flash_id & FLASH_TYPEMASK) { case FLASH_SST6401B: printf("SST39VF6401B\n"); break; default: printf("Unknown Chip Type\n"); return; } if (info->size > 0x100000) { int remainder; printf(" Size: %ld", info->size >> 20); remainder = (info->size % 0x100000); if (remainder) { remainder >>= 10; remainder = (int)((float) (((float)remainder / (float)1024) * 10000)); printf(".%d ", remainder); } printf("MB in %d Sectors\n", info->sector_count); } else printf(" Size: %ld KB in %d Sectors\n", info->size >> 10, info->sector_count); printf(" Sector Start Addresses:"); for (i = 0; i < info->sector_count; ++i) { if ((i % 5) == 0) printf("\n "); printf(" %08lX%s", info->start[i], info->protect[i] ? " (RO)" : " "); } printf("\n"); } /* * The following code cannot be run from FLASH! */ ulong flash_get_size(FPWV * addr, flash_info_t * info) { u16 value; addr[FLASH_CYCLE1] = (FPWV) 0x00AA00AA; /* for Atmel, Intel ignores this */ addr[FLASH_CYCLE2] = (FPWV) 0x00550055; /* for Atmel, Intel ignores this */ addr[FLASH_CYCLE1] = (FPWV) 0x00900090; /* selects Intel or Atmel */ switch (addr[0] & 0xffff) { case (u8) SST_MANUFACT: info->flash_id = FLASH_MAN_SST; value = addr[1]; break; default: printf("Unknown Flash\n"); info->flash_id = FLASH_UNKNOWN; info->sector_count = 0; info->size = 0; *addr = (FPW) 0x00F000F0; return (0); /* no or unknown flash */ } switch (value) { case (u16) SST_ID_xF6401B: info->flash_id += FLASH_SST6401B; break; default: info->flash_id = FLASH_UNKNOWN; break; } info->sector_count = 0; info->size = 0; info->sector_count = CONFIG_SYS_SST_SECT; info->size = CONFIG_SYS_SST_SECT * CONFIG_SYS_SST_SECTSZ; /* reset ID mode */ *addr = (FPWV) 0x00F000F0; if (info->sector_count > CONFIG_SYS_MAX_FLASH_SECT) { printf("** ERROR: sector count %d > max (%d) **\n", info->sector_count, CONFIG_SYS_MAX_FLASH_SECT); info->sector_count = CONFIG_SYS_MAX_FLASH_SECT; } return (info->size); } int flash_erase(flash_info_t * info, int s_first, int s_last) { FPWV *addr; int flag, prot, sect, count; ulong type, start; int rcode = 0, flashtype = 0; if ((s_first < 0) || (s_first > s_last)) { if (info->flash_id == FLASH_UNKNOWN) printf("- missing\n"); else printf("- no sectors to erase\n"); return 1; } type = (info->flash_id & FLASH_VENDMASK); switch (type) { case FLASH_MAN_SST: flashtype = 1; break; default: type = (info->flash_id & FLASH_VENDMASK); printf("Can't erase unknown flash type %08lx - aborted\n", info->flash_id); return 1; } prot = 0; for (sect = s_first; sect <= s_last; ++sect) { if (info->protect[sect]) { prot++; } } if (prot) printf("- Warning: %d protected sectors will not be erased!\n", prot); else printf("\n"); flag = disable_interrupts(); start = get_timer(0); if ((s_last - s_first) == (CONFIG_SYS_SST_SECT - 1)) { if (prot == 0) { addr = (FPWV *) info->start[0]; addr[FLASH_CYCLE1] = 0x00AA; /* unlock */ addr[FLASH_CYCLE2] = 0x0055; /* unlock */ addr[FLASH_CYCLE1] = 0x0080; /* erase mode */ addr[FLASH_CYCLE1] = 0x00AA; /* unlock */ addr[FLASH_CYCLE2] = 0x0055; /* unlock */ *addr = 0x0030; /* erase chip */ count = 0; start = get_timer(0); while ((*addr & 0x0080) != 0x0080) { if (count++ > 0x10000) { spin_wheel(); count = 0; } if (get_timer(start) > CONFIG_SYS_FLASH_ERASE_TOUT) { printf("Timeout\n"); *addr = 0x00F0; /* reset to read mode */ return 1; } } *addr = 0x00F0; /* reset to read mode */ printf("\b. done\n"); if (flag) enable_interrupts(); return 0; } else if (prot == CONFIG_SYS_SST_SECT) { return 1; } } /* Start erase on unprotected sectors */ for (sect = s_first; sect <= s_last; sect++) { if (info->protect[sect] == 0) { /* not protected */ addr = (FPWV *) (info->start[sect]); printf("."); /* arm simple, non interrupt dependent timer */ start = get_timer(0); switch (flashtype) { case 1: { FPWV *base; /* first address in bank */ flag = disable_interrupts(); base = (FPWV *) (CONFIG_SYS_FLASH_BASE); /* First sector */ base[FLASH_CYCLE1] = 0x00AA; /* unlock */ base[FLASH_CYCLE2] = 0x0055; /* unlock */ base[FLASH_CYCLE1] = 0x0080; /* erase mode */ base[FLASH_CYCLE1] = 0x00AA; /* unlock */ base[FLASH_CYCLE2] = 0x0055; /* unlock */ *addr = 0x0050; /* erase sector */ if (flag) enable_interrupts(); while ((*addr & 0x0080) != 0x0080) { if (get_timer(start) > CONFIG_SYS_FLASH_ERASE_TOUT) { printf("Timeout\n"); *addr = 0x00F0; /* reset to read mode */ rcode = 1; break; } } *addr = 0x00F0; /* reset to read mode */ break; } } /* switch (flashtype) */ } } printf(" done\n"); if (flag) enable_interrupts(); return rcode; } int write_buff(flash_info_t * info, uchar * src, ulong addr, ulong cnt) { ulong wp, count; u16 data; int rc; if (info->flash_id == FLASH_UNKNOWN) return 4; /* get lower word aligned address */ wp = addr; /* handle unaligned start bytes */ if (wp & 1) { data = *((FPWV *) wp); data = (data << 8) | *src; if ((rc = write_word(info, (FPWV *) wp, data)) != 0) return (rc); wp++; cnt -= 1; src++; } while (cnt >= 2) { /* * handle word aligned part */ count = 0; data = *((FPWV *) src); if ((rc = write_word(info, (FPWV *) wp, data)) != 0) return (rc); wp += 2; src += 2; cnt -= 2; if (count++ > 0x800) { spin_wheel(); count = 0; } } /* handle word aligned part */ if (cnt) { /* handle word aligned part */ count = 0; data = *((FPWV *) wp); data = (data & 0x00FF) | (*src << 8); if ((rc = write_word(info, (FPWV *) wp, data)) != 0) return (rc); wp++; src++; cnt -= 1; if (count++ > 0x800) { spin_wheel(); count = 0; } } if (cnt == 0) return ERR_OK; return ERR_OK; } /*----------------------------------------------------------------------- * Write a word to Flash * A word is 16 bits, whichever the bus width of the flash bank * (not an individual chip) is. * * returns: * 0 - OK * 1 - write timeout * 2 - Flash not erased */ int write_word(flash_info_t * info, FPWV * dest, u16 data) { ulong start; int flag; int res = 0; /* result, assume success */ FPWV *base; /* first address in flash bank */ /* Check if Flash is (sufficiently) erased */ if ((*dest & (u8) data) != (u8) data) { return (2); } base = (FPWV *) (CONFIG_SYS_FLASH_BASE); /* Disable interrupts which might cause a timeout here */ flag = disable_interrupts(); base[FLASH_CYCLE1] = (u8) 0x00AA00AA; /* unlock */ base[FLASH_CYCLE2] = (u8) 0x00550055; /* unlock */ base[FLASH_CYCLE1] = (u8) 0x00A000A0; /* selects program mode */ *dest = data; /* start programming the data */ /* re-enable interrupts if necessary */ if (flag) enable_interrupts(); start = get_timer(0); /* data polling for D7 */ while (res == 0 && (*dest & (u8) 0x00800080) != (data & (u8) 0x00800080)) { if (get_timer(start) > CONFIG_SYS_FLASH_WRITE_TOUT) { *dest = (u8) 0x00F000F0; /* reset bank */ res = 1; } } *dest++ = (u8) 0x00F000F0; /* reset bank */ return (res); } static inline void spin_wheel(void) { static int p = 0; static char w[] = "\\/-"; printf("\010%c", w[p]); (++p == 3) ? (p = 0) : 0; } #endif
{ "pile_set_name": "Github" }
{ "definitions": { "definition_1": { "class": "Full\\Qualified\\Class1", "public": true, "synthetic": false, "lazy": true, "shared": true, "abstract": true, "autowire": false, "autoconfigure": false, "arguments": [ { "type": "service", "id": "definition2" }, "%parameter%", { "class": "inline_service", "public": false, "synthetic": false, "lazy": false, "shared": true, "abstract": false, "autowire": false, "autoconfigure": false, "arguments": [ "arg1", "arg2" ], "file": null, "tags": [] }, [ "foo", { "type": "service", "id": "definition2" }, { "class": "inline_service", "public": false, "synthetic": false, "lazy": false, "shared": true, "abstract": false, "autowire": false, "autoconfigure": false, "arguments": [], "file": null, "tags": [] } ], [ { "type": "service", "id": "definition_1" }, { "type": "service", "id": "definition_2" } ] ], "file": null, "factory_class": "Full\\Qualified\\FactoryClass", "factory_method": "get", "tags": [] } }, "aliases": { "alias_1": { "service": "service_1", "public": true } }, "services": { "service_container": "Symfony\\Component\\DependencyInjection\\ContainerBuilder" } }
{ "pile_set_name": "Github" }
[gd_resource type="AtlasTexture" load_steps=2 format=2] [ext_resource path="res://addons/Rakugo/emojis/atlas/72x72-1.png" type="Texture" id=1] [resource] flags = 7 atlas = ExtResource( 1 ) region = Rect2( 1945, 127, 34, 72 ) margin = Rect2( 19, 0, 38, 0 )
{ "pile_set_name": "Github" }
#include "ClosestNotMeRayResultCallback.h" ClosestNotMeRayResultCallback::ClosestNotMeRayResultCallback (btCollisionObject* me) : ClosestRayResultCallback(btVector3(0.0, 0.0, 0.0), btVector3(0.0, 0.0, 0.0)) { m_me = me; } btScalar ClosestNotMeRayResultCallback::addSingleResult(btCollisionWorld::LocalRayResult& rayResult,bool normalInWorldSpace) { if (rayResult.m_collisionObject == m_me) return 1.0; return ClosestNotMeRayResultCallback::ClosestRayResultCallback::addSingleResult (rayResult, normalInWorldSpace); }
{ "pile_set_name": "Github" }
LAMMPS (6 Oct 2016) # 3d Lennard-Jones melt variable x index 1 variable y index 1 variable z index 1 variable xx equal 20*$x variable xx equal 20*2 variable yy equal 20*$y variable yy equal 20*2 variable zz equal 20*$z variable zz equal 20*1 units lj atom_style atomic lattice fcc 0.8442 Lattice spacing in x,y,z = 1.6796 1.6796 1.6796 region box block 0 ${xx} 0 ${yy} 0 ${zz} region box block 0 40 0 ${yy} 0 ${zz} region box block 0 40 0 40 0 ${zz} region box block 0 40 0 40 0 20 create_box 1 box Created orthogonal box = (0 0 0) to (67.1838 67.1838 33.5919) 2 by 2 by 1 MPI processor grid create_atoms 1 box Created 128000 atoms mass 1 1.0 velocity all create 1.44 87287 loop geom pair_style lj/cut 2.5 pair_coeff 1 1 1.0 1.0 2.5 neighbor 0.3 bin neigh_modify delay 0 every 20 check no fix 1 all nve run 100 Neighbor list info ... 1 neighbor list requests update every 20 steps, delay 0 steps, check no max neighbors/atom: 2000, page size: 100000 master list distance cutoff = 2.8 ghost atom cutoff = 2.8 binsize = 1.4 -> bins = 48 48 24 Memory usage per processor = 8.13678 Mbytes Step Temp E_pair E_mol TotEng Press 0 1.44 -6.7733681 0 -4.6133849 -5.0196788 100 0.75841891 -5.759957 0 -4.6223375 0.20008866 Loop time of 2.55762 on 4 procs for 100 steps with 128000 atoms Performance: 16890.677 tau/day, 39.099 timesteps/s 99.8% CPU use with 4 MPI tasks x no OpenMP threads MPI task timing breakdown: Section | min time | avg time | max time |%varavg| %total --------------------------------------------------------------- Pair | 2.0583 | 2.0988 | 2.1594 | 2.6 | 82.06 Neigh | 0.24411 | 0.24838 | 0.25585 | 0.9 | 9.71 Comm | 0.066397 | 0.13872 | 0.1863 | 11.9 | 5.42 Output | 0.00012994 | 0.00021023 | 0.00025702 | 0.3 | 0.01 Modify | 0.055533 | 0.058343 | 0.061791 | 1.2 | 2.28 Other | | 0.0132 | | | 0.52 Nlocal: 32000 ave 32060 max 31939 min Histogram: 1 0 1 0 0 0 0 1 0 1 Nghost: 19630.8 ave 19681 max 19562 min Histogram: 1 0 0 0 1 0 0 0 1 1 Neighs: 1.20195e+06 ave 1.20354e+06 max 1.19931e+06 min Histogram: 1 0 0 0 0 0 0 2 0 1 Total # of neighbors = 4807797 Ave neighs/atom = 37.5609 Neighbor list builds = 5 Dangerous builds not checked Total wall time: 0:00:02
{ "pile_set_name": "Github" }
@ticket-BB-15876 @fixture-OroFlatRateShippingBundle:FlatRateIntegration.yml @fixture-OroPaymentTermBundle:PaymentTermIntegration.yml @fixture-OroPromotionBundle:promotions.yml @fixture-OroPromotionBundle:shopping_list.yml Feature: Promotions on checkout from quote In order to check that promotions can't be used for Quotes As a Buyer I need to not see enter coupon section and discount subtotal at checkout Scenario: Logged in as buyer and manager on different window sessions Given sessions active: | Admin | first_session | | Buyer | second_session | Scenario: Prepare quote and check that discounts are not applied on checkout Given I proceed as the Admin And I login as administrator And I disable inventory management And I go to Sales / Quotes When I click "Create Quote" And I fill "Quote Form" with: | Customer | Company A | | Customer User | Amanda Cole | | PO Number | PO42 | | LineItemProduct | SKU2 | And I type "10" in "LineItemPrice" And I save and close form And agree that shipping cost may have changed Then I should see "Quote has been saved" flash message When click "Send to Customer" And click "Send" And I proceed as the Buyer And I signed in as [email protected] on the store frontend And follow "Account" And click "Quotes" And click view "PO42" in grid And click "Accept and Submit to Order" And I click "Submit" Then I should not see "Discount" Scenario: Check that there is no coupon form on checkout Then I should not see "I have a Coupon Code" Scenario: Check that discounts does not applied on submitted order When I select "Fifth avenue, 10115 Berlin, Germany" on the "Billing Information" checkout step and press Continue And I select "Fifth avenue, 10115 Berlin, Germany" on the "Shipping Information" checkout step and press Continue And I check "Flat Rate" on the "Shipping Method" checkout step and press Continue And I click "Continue" And I click "Submit Order" Then I see the "Thank You" page with "Thank You For Your Purchase!" title When I follow "click here to review" And I should be on Order Frontend View page Then I should not see "Discount"
{ "pile_set_name": "Github" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.13"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>Fling Engine: Fling::BaseEditor Class Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectlogo"><img alt="Logo" src="profile_64x64.png"/></td> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">Fling Engine &#160;<span id="projectnumber">0.00.1</span> </div> <div id="projectbrief">Fling Engine is a game engine written in Vulkan</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.13 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); </script> <div id="main-nav"></div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="namespaceFling.html">Fling</a></li><li class="navelem"><a class="el" href="classFling_1_1BaseEditor.html">BaseEditor</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="#pub-methods">Public Member Functions</a> &#124; <a href="#pro-methods">Protected Member Functions</a> &#124; <a href="#pro-attribs">Protected Attributes</a> &#124; <a href="#friends">Friends</a> </div> <div class="headertitle"> <div class="title">Fling::BaseEditor Class Reference</div> </div> </div><!--header--> <div class="contents"> <p>The <a class="el" href="classFling_1_1BaseEditor.html" title="The BaseEditor of the Fling Engine. ">BaseEditor</a> of the <a class="el" href="namespaceFling.html">Fling</a> <a class="el" href="classFling_1_1Engine.html" title="Core engine class of Fling. ">Engine</a>. <a href="classFling_1_1BaseEditor.html#details">More...</a></p> <p><code>#include &lt;<a class="el" href="BaseEditor_8h_source.html">BaseEditor.h</a>&gt;</code></p> <p>Inherited by <a class="el" href="classSandbox_1_1SandboxEditor.html">Sandbox::SandboxEditor</a>.</p> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a> Public Member Functions</h2></td></tr> <tr class="memitem:a386fd81f582014039a0bf0d35890459b"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classFling_1_1BaseEditor.html#a386fd81f582014039a0bf0d35890459b">BaseEditor</a> ()=default</td></tr> <tr class="separator:a386fd81f582014039a0bf0d35890459b"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:aae6a6ed30cf4d3177ce89364a19e1027"><td class="memItemLeft" align="right" valign="top">virtual&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classFling_1_1BaseEditor.html#aae6a6ed30cf4d3177ce89364a19e1027">~BaseEditor</a> ()=default</td></tr> <tr class="separator:aae6a6ed30cf4d3177ce89364a19e1027"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a950e56ad9dc11863857729b98ca1bf86"><td class="memItemLeft" align="right" valign="top">virtual void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classFling_1_1BaseEditor.html#a950e56ad9dc11863857729b98ca1bf86">RegisterComponents</a> (entt::registry &amp;t_Reg)</td></tr> <tr class="memdesc:a950e56ad9dc11863857729b98ca1bf86"><td class="mdescLeft">&#160;</td><td class="mdescRight">Register. <a href="#a950e56ad9dc11863857729b98ca1bf86">More...</a><br /></td></tr> <tr class="separator:a950e56ad9dc11863857729b98ca1bf86"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:afa91ead40386b4c7d72a45352db33b00"><td class="memItemLeft" align="right" valign="top">virtual void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classFling_1_1BaseEditor.html#afa91ead40386b4c7d72a45352db33b00">Draw</a> (entt::registry &amp;t_Reg, float DeltaTime)</td></tr> <tr class="memdesc:afa91ead40386b4c7d72a45352db33b00"><td class="mdescLeft">&#160;</td><td class="mdescRight">Draws the editor via IMGUI. <a href="#afa91ead40386b4c7d72a45352db33b00">More...</a><br /></td></tr> <tr class="separator:afa91ead40386b4c7d72a45352db33b00"><td class="memSeparator" colspan="2">&#160;</td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pro-methods"></a> Protected Member Functions</h2></td></tr> <tr class="memitem:ac8f3ff6f9b54e9495592100e4927e94c"><td class="memItemLeft" align="right" valign="top">virtual void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classFling_1_1BaseEditor.html#ac8f3ff6f9b54e9495592100e4927e94c">OnLoadLevel</a> (std::string t_FileName)</td></tr> <tr class="separator:ac8f3ff6f9b54e9495592100e4927e94c"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:afdb484d7a59faede7e79e53a3853a14e"><td class="memItemLeft" align="right" valign="top">virtual void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classFling_1_1BaseEditor.html#afdb484d7a59faede7e79e53a3853a14e">OnSaveLevel</a> (std::string t_FileName)</td></tr> <tr class="separator:afdb484d7a59faede7e79e53a3853a14e"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:af5c8c98c1c2ab8f8165fff4958d97d14"><td class="memItemLeft" align="right" valign="top">virtual void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classFling_1_1BaseEditor.html#af5c8c98c1c2ab8f8165fff4958d97d14">DrawFileMenu</a> ()</td></tr> <tr class="separator:af5c8c98c1c2ab8f8165fff4958d97d14"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a83f9df868e350ceb7181aa586ec314a6"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classFling_1_1BaseEditor.html#a83f9df868e350ceb7181aa586ec314a6">DrawGpuInfo</a> ()</td></tr> <tr class="separator:a83f9df868e350ceb7181aa586ec314a6"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a37948d246446ac4b38343a8a9f21530f"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classFling_1_1BaseEditor.html#a37948d246446ac4b38343a8a9f21530f">DrawWorldOutline</a> (entt::registry &amp;t_Reg)</td></tr> <tr class="separator:a37948d246446ac4b38343a8a9f21530f"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ab1bcdc50632a005616676d40614a64da"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classFling_1_1BaseEditor.html#ab1bcdc50632a005616676d40614a64da">DrawWindowOptions</a> ()</td></tr> <tr class="separator:ab1bcdc50632a005616676d40614a64da"><td class="memSeparator" colspan="2">&#160;</td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pro-attribs"></a> Protected Attributes</h2></td></tr> <tr class="memitem:a2e00581003ad6c22a727ade27e47282e"><td class="memItemLeft" align="right" valign="top">std::array&lt; float, 400 &gt;&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classFling_1_1BaseEditor.html#a2e00581003ad6c22a727ade27e47282e">fpsGraph</a> {}</td></tr> <tr class="separator:a2e00581003ad6c22a727ade27e47282e"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:aed26e1ef54b532f86121c99eec87afff"><td class="memItemLeft" align="right" valign="top">float&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classFling_1_1BaseEditor.html#aed26e1ef54b532f86121c99eec87afff">m_FrameTimeMin</a> = 9999.0f</td></tr> <tr class="separator:aed26e1ef54b532f86121c99eec87afff"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ac9d80680687b120ef14b9bc78a4527d3"><td class="memItemLeft" align="right" valign="top">float&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classFling_1_1BaseEditor.html#ac9d80680687b120ef14b9bc78a4527d3">m_FrameTimeMax</a> = 0.0f</td></tr> <tr class="separator:ac9d80680687b120ef14b9bc78a4527d3"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a828b856ae37ae00eb126eb2bb73d39b6"><td class="memItemLeft" align="right" valign="top">bool&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classFling_1_1BaseEditor.html#a828b856ae37ae00eb126eb2bb73d39b6">m_DisplayGPUInfo</a> = false</td></tr> <tr class="separator:a828b856ae37ae00eb126eb2bb73d39b6"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:afc415be133682bf92aa19f053c58fae5"><td class="memItemLeft" align="right" valign="top">bool&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classFling_1_1BaseEditor.html#afc415be133682bf92aa19f053c58fae5">m_DisplayComponentEditor</a> = true</td></tr> <tr class="separator:afc415be133682bf92aa19f053c58fae5"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:af69a0547e740def4c0e0e3b8d58e3237"><td class="memItemLeft" align="right" valign="top">bool&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classFling_1_1BaseEditor.html#af69a0547e740def4c0e0e3b8d58e3237">m_DisplayWorldOutline</a> = true</td></tr> <tr class="separator:af69a0547e740def4c0e0e3b8d58e3237"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a0c7881fa0e14e920db0907546580ff78"><td class="memItemLeft" align="right" valign="top">bool&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classFling_1_1BaseEditor.html#a0c7881fa0e14e920db0907546580ff78">m_DisplayWindowOptions</a> = false</td></tr> <tr class="separator:a0c7881fa0e14e920db0907546580ff78"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:afd018fd9516d25c9956aca1f4d42a458"><td class="memItemLeft" align="right" valign="top">entt::entity&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classFling_1_1BaseEditor.html#afd018fd9516d25c9956aca1f4d42a458">m_CompEditorEntityType</a> = entt::null</td></tr> <tr class="memdesc:afd018fd9516d25c9956aca1f4d42a458"><td class="mdescLeft">&#160;</td><td class="mdescRight">Component editor so that we can draw our component window. <a href="#afd018fd9516d25c9956aca1f4d42a458">More...</a><br /></td></tr> <tr class="separator:afd018fd9516d25c9956aca1f4d42a458"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a2c2efe6a0b3ae8689df0dd1d41769e25"><td class="memItemLeft" align="right" valign="top">MM::ImGuiEntityEditor&lt; entt::registry &gt;&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classFling_1_1BaseEditor.html#a2c2efe6a0b3ae8689df0dd1d41769e25">m_ComponentEditor</a></td></tr> <tr class="separator:a2c2efe6a0b3ae8689df0dd1d41769e25"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a96cdd473667776a43a98993f433556e0"><td class="memItemLeft" align="right" valign="top">class <a class="el" href="classFling_1_1World.html">World</a> *&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classFling_1_1BaseEditor.html#a96cdd473667776a43a98993f433556e0">m_OwningWorld</a> = nullptr</td></tr> <tr class="separator:a96cdd473667776a43a98993f433556e0"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a6634784a9f816286bbe2f942692df0c3"><td class="memItemLeft" align="right" valign="top">class <a class="el" href="classFling_1_1Game.html">Game</a> *&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classFling_1_1BaseEditor.html#a6634784a9f816286bbe2f942692df0c3">m_Game</a> = nullptr</td></tr> <tr class="separator:a6634784a9f816286bbe2f942692df0c3"><td class="memSeparator" colspan="2">&#160;</td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="friends"></a> Friends</h2></td></tr> <tr class="memitem:a3e1914489e4bed4f9f23cdeab34a43dc"><td class="memItemLeft" align="right" valign="top">class&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classFling_1_1BaseEditor.html#a3e1914489e4bed4f9f23cdeab34a43dc">Engine</a></td></tr> <tr class="separator:a3e1914489e4bed4f9f23cdeab34a43dc"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2> <div class="textblock"><p>The <a class="el" href="classFling_1_1BaseEditor.html" title="The BaseEditor of the Fling Engine. ">BaseEditor</a> of the <a class="el" href="namespaceFling.html">Fling</a> <a class="el" href="classFling_1_1Engine.html" title="Core engine class of Fling. ">Engine</a>. </p> <p>Draw and add any game specifc Editor UI tools here </p> </div><h2 class="groupheader">Constructor &amp; Destructor Documentation</h2> <a id="a386fd81f582014039a0bf0d35890459b"></a> <h2 class="memtitle"><span class="permalink"><a href="#a386fd81f582014039a0bf0d35890459b">&#9670;&nbsp;</a></span>BaseEditor()</h2> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">Fling::BaseEditor::BaseEditor </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">default</span></span> </td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="aae6a6ed30cf4d3177ce89364a19e1027"></a> <h2 class="memtitle"><span class="permalink"><a href="#aae6a6ed30cf4d3177ce89364a19e1027">&#9670;&nbsp;</a></span>~BaseEditor()</h2> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">virtual Fling::BaseEditor::~BaseEditor </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">virtual</span><span class="mlabel">default</span></span> </td> </tr> </table> </div><div class="memdoc"> </div> </div> <h2 class="groupheader">Member Function Documentation</h2> <a id="afa91ead40386b4c7d72a45352db33b00"></a> <h2 class="memtitle"><span class="permalink"><a href="#afa91ead40386b4c7d72a45352db33b00">&#9670;&nbsp;</a></span>Draw()</h2> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">virtual void Fling::BaseEditor::Draw </td> <td>(</td> <td class="paramtype">entt::registry &amp;&#160;</td> <td class="paramname"><em>t_Reg</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">float&#160;</td> <td class="paramname"><em>DeltaTime</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">virtual</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Draws the editor via IMGUI. </p> <p>Does NOT need to do any addition renderering pipeline things </p> <p>Reimplemented in <a class="el" href="classSandbox_1_1SandboxEditor.html#a277e81815282a25d4b54036fa6765f59">Sandbox::SandboxEditor</a>.</p> </div> </div> <a id="af5c8c98c1c2ab8f8165fff4958d97d14"></a> <h2 class="memtitle"><span class="permalink"><a href="#af5c8c98c1c2ab8f8165fff4958d97d14">&#9670;&nbsp;</a></span>DrawFileMenu()</h2> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">virtual void Fling::BaseEditor::DrawFileMenu </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">protected</span><span class="mlabel">virtual</span></span> </td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="a83f9df868e350ceb7181aa586ec314a6"></a> <h2 class="memtitle"><span class="permalink"><a href="#a83f9df868e350ceb7181aa586ec314a6">&#9670;&nbsp;</a></span>DrawGpuInfo()</h2> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">void Fling::BaseEditor::DrawGpuInfo </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">protected</span></span> </td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ab1bcdc50632a005616676d40614a64da"></a> <h2 class="memtitle"><span class="permalink"><a href="#ab1bcdc50632a005616676d40614a64da">&#9670;&nbsp;</a></span>DrawWindowOptions()</h2> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">void Fling::BaseEditor::DrawWindowOptions </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">protected</span></span> </td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="a37948d246446ac4b38343a8a9f21530f"></a> <h2 class="memtitle"><span class="permalink"><a href="#a37948d246446ac4b38343a8a9f21530f">&#9670;&nbsp;</a></span>DrawWorldOutline()</h2> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">void Fling::BaseEditor::DrawWorldOutline </td> <td>(</td> <td class="paramtype">entt::registry &amp;&#160;</td> <td class="paramname"><em>t_Reg</em></td><td>)</td> <td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">protected</span></span> </td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ac8f3ff6f9b54e9495592100e4927e94c"></a> <h2 class="memtitle"><span class="permalink"><a href="#ac8f3ff6f9b54e9495592100e4927e94c">&#9670;&nbsp;</a></span>OnLoadLevel()</h2> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">virtual void Fling::BaseEditor::OnLoadLevel </td> <td>(</td> <td class="paramtype">std::string&#160;</td> <td class="paramname"><em>t_FileName</em></td><td>)</td> <td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">protected</span><span class="mlabel">virtual</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Reimplemented in <a class="el" href="classSandbox_1_1SandboxEditor.html#a743ac83315d17f6d0cbf2f088356bf23">Sandbox::SandboxEditor</a>.</p> </div> </div> <a id="afdb484d7a59faede7e79e53a3853a14e"></a> <h2 class="memtitle"><span class="permalink"><a href="#afdb484d7a59faede7e79e53a3853a14e">&#9670;&nbsp;</a></span>OnSaveLevel()</h2> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">virtual void Fling::BaseEditor::OnSaveLevel </td> <td>(</td> <td class="paramtype">std::string&#160;</td> <td class="paramname"><em>t_FileName</em></td><td>)</td> <td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">protected</span><span class="mlabel">virtual</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Reimplemented in <a class="el" href="classSandbox_1_1SandboxEditor.html#a1eed58dcc1b0892e1ae191985b19e41d">Sandbox::SandboxEditor</a>.</p> </div> </div> <a id="a950e56ad9dc11863857729b98ca1bf86"></a> <h2 class="memtitle"><span class="permalink"><a href="#a950e56ad9dc11863857729b98ca1bf86">&#9670;&nbsp;</a></span>RegisterComponents()</h2> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">virtual void Fling::BaseEditor::RegisterComponents </td> <td>(</td> <td class="paramtype">entt::registry &amp;&#160;</td> <td class="paramname"><em>t_Reg</em></td><td>)</td> <td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">virtual</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Register. </p> </div> </div> <h2 class="groupheader">Friends And Related Function Documentation</h2> <a id="a3e1914489e4bed4f9f23cdeab34a43dc"></a> <h2 class="memtitle"><span class="permalink"><a href="#a3e1914489e4bed4f9f23cdeab34a43dc">&#9670;&nbsp;</a></span>Engine</h2> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">friend class <a class="el" href="classFling_1_1Engine.html">Engine</a></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">friend</span></span> </td> </tr> </table> </div><div class="memdoc"> </div> </div> <h2 class="groupheader">Field Documentation</h2> <a id="a2e00581003ad6c22a727ade27e47282e"></a> <h2 class="memtitle"><span class="permalink"><a href="#a2e00581003ad6c22a727ade27e47282e">&#9670;&nbsp;</a></span>fpsGraph</h2> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">std::array&lt;float, 400&gt; Fling::BaseEditor::fpsGraph {}</td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">protected</span></span> </td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="afd018fd9516d25c9956aca1f4d42a458"></a> <h2 class="memtitle"><span class="permalink"><a href="#afd018fd9516d25c9956aca1f4d42a458">&#9670;&nbsp;</a></span>m_CompEditorEntityType</h2> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">entt::entity Fling::BaseEditor::m_CompEditorEntityType = entt::null</td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">protected</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Component editor so that we can draw our component window. </p> </div> </div> <a id="a2c2efe6a0b3ae8689df0dd1d41769e25"></a> <h2 class="memtitle"><span class="permalink"><a href="#a2c2efe6a0b3ae8689df0dd1d41769e25">&#9670;&nbsp;</a></span>m_ComponentEditor</h2> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">MM::ImGuiEntityEditor&lt;entt::registry&gt; Fling::BaseEditor::m_ComponentEditor</td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">protected</span></span> </td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="afc415be133682bf92aa19f053c58fae5"></a> <h2 class="memtitle"><span class="permalink"><a href="#afc415be133682bf92aa19f053c58fae5">&#9670;&nbsp;</a></span>m_DisplayComponentEditor</h2> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">bool Fling::BaseEditor::m_DisplayComponentEditor = true</td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">protected</span></span> </td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="a828b856ae37ae00eb126eb2bb73d39b6"></a> <h2 class="memtitle"><span class="permalink"><a href="#a828b856ae37ae00eb126eb2bb73d39b6">&#9670;&nbsp;</a></span>m_DisplayGPUInfo</h2> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">bool Fling::BaseEditor::m_DisplayGPUInfo = false</td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">protected</span></span> </td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="a0c7881fa0e14e920db0907546580ff78"></a> <h2 class="memtitle"><span class="permalink"><a href="#a0c7881fa0e14e920db0907546580ff78">&#9670;&nbsp;</a></span>m_DisplayWindowOptions</h2> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">bool Fling::BaseEditor::m_DisplayWindowOptions = false</td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">protected</span></span> </td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="af69a0547e740def4c0e0e3b8d58e3237"></a> <h2 class="memtitle"><span class="permalink"><a href="#af69a0547e740def4c0e0e3b8d58e3237">&#9670;&nbsp;</a></span>m_DisplayWorldOutline</h2> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">bool Fling::BaseEditor::m_DisplayWorldOutline = true</td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">protected</span></span> </td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ac9d80680687b120ef14b9bc78a4527d3"></a> <h2 class="memtitle"><span class="permalink"><a href="#ac9d80680687b120ef14b9bc78a4527d3">&#9670;&nbsp;</a></span>m_FrameTimeMax</h2> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">float Fling::BaseEditor::m_FrameTimeMax = 0.0f</td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">protected</span></span> </td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="aed26e1ef54b532f86121c99eec87afff"></a> <h2 class="memtitle"><span class="permalink"><a href="#aed26e1ef54b532f86121c99eec87afff">&#9670;&nbsp;</a></span>m_FrameTimeMin</h2> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">float Fling::BaseEditor::m_FrameTimeMin = 9999.0f</td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">protected</span></span> </td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="a6634784a9f816286bbe2f942692df0c3"></a> <h2 class="memtitle"><span class="permalink"><a href="#a6634784a9f816286bbe2f942692df0c3">&#9670;&nbsp;</a></span>m_Game</h2> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">class <a class="el" href="classFling_1_1Game.html">Game</a>* Fling::BaseEditor::m_Game = nullptr</td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">protected</span></span> </td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="a96cdd473667776a43a98993f433556e0"></a> <h2 class="memtitle"><span class="permalink"><a href="#a96cdd473667776a43a98993f433556e0">&#9670;&nbsp;</a></span>m_OwningWorld</h2> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">class <a class="el" href="classFling_1_1World.html">World</a>* Fling::BaseEditor::m_OwningWorld = nullptr</td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">protected</span></span> </td> </tr> </table> </div><div class="memdoc"> </div> </div> <hr/>The documentation for this class was generated from the following file:<ul> <li>FlingEngine/Editor/inc/<a class="el" href="BaseEditor_8h_source.html">BaseEditor.h</a></li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.13 </small></address> </body> </html>
{ "pile_set_name": "Github" }
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2015-2016 Gael Guennebaud <[email protected]> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. // workaround issue between gcc >= 4.7 and cuda 5.5 #if (defined __GNUC__) && (__GNUC__>4 || __GNUC_MINOR__>=7) #undef _GLIBCXX_ATOMIC_BUILTINS #undef _GLIBCXX_USE_INT128 #endif #define EIGEN_TEST_NO_LONGDOUBLE #define EIGEN_TEST_NO_COMPLEX #define EIGEN_TEST_FUNC cuda_basic #define EIGEN_DEFAULT_DENSE_INDEX_TYPE int #include <math_constants.h> #include <cuda.h> #if defined __CUDACC_VER__ && __CUDACC_VER__ >= 70500 #include <cuda_fp16.h> #endif #include "main.h" #include "cuda_common.h" // Check that dense modules can be properly parsed by nvcc #include <Eigen/Dense> // struct Foo{ // EIGEN_DEVICE_FUNC // void operator()(int i, const float* mats, float* vecs) const { // using namespace Eigen; // // Matrix3f M(data); // // Vector3f x(data+9); // // Map<Vector3f>(data+9) = M.inverse() * x; // Matrix3f M(mats+i/16); // Vector3f x(vecs+i*3); // // using std::min; // // using std::sqrt; // Map<Vector3f>(vecs+i*3) << x.minCoeff(), 1, 2;// / x.dot(x);//(M.inverse() * x) / x.x(); // //x = x*2 + x.y() * x + x * x.maxCoeff() - x / x.sum(); // } // }; template<typename T> struct coeff_wise { EIGEN_DEVICE_FUNC void operator()(int i, const typename T::Scalar* in, typename T::Scalar* out) const { using namespace Eigen; T x1(in+i); T x2(in+i+1); T x3(in+i+2); Map<T> res(out+i*T::MaxSizeAtCompileTime); res.array() += (in[0] * x1 + x2).array() * x3.array(); } }; template<typename T> struct replicate { EIGEN_DEVICE_FUNC void operator()(int i, const typename T::Scalar* in, typename T::Scalar* out) const { using namespace Eigen; T x1(in+i); int step = x1.size() * 4; int stride = 3 * step; typedef Map<Array<typename T::Scalar,Dynamic,Dynamic> > MapType; MapType(out+i*stride+0*step, x1.rows()*2, x1.cols()*2) = x1.replicate(2,2); MapType(out+i*stride+1*step, x1.rows()*3, x1.cols()) = in[i] * x1.colwise().replicate(3); MapType(out+i*stride+2*step, x1.rows(), x1.cols()*3) = in[i] * x1.rowwise().replicate(3); } }; template<typename T> struct redux { EIGEN_DEVICE_FUNC void operator()(int i, const typename T::Scalar* in, typename T::Scalar* out) const { using namespace Eigen; int N = 10; T x1(in+i); out[i*N+0] = x1.minCoeff(); out[i*N+1] = x1.maxCoeff(); out[i*N+2] = x1.sum(); out[i*N+3] = x1.prod(); out[i*N+4] = x1.matrix().squaredNorm(); out[i*N+5] = x1.matrix().norm(); out[i*N+6] = x1.colwise().sum().maxCoeff(); out[i*N+7] = x1.rowwise().maxCoeff().sum(); out[i*N+8] = x1.matrix().colwise().squaredNorm().sum(); } }; template<typename T1, typename T2> struct prod_test { EIGEN_DEVICE_FUNC void operator()(int i, const typename T1::Scalar* in, typename T1::Scalar* out) const { using namespace Eigen; typedef Matrix<typename T1::Scalar, T1::RowsAtCompileTime, T2::ColsAtCompileTime> T3; T1 x1(in+i); T2 x2(in+i+1); Map<T3> res(out+i*T3::MaxSizeAtCompileTime); res += in[i] * x1 * x2; } }; template<typename T1, typename T2> struct diagonal { EIGEN_DEVICE_FUNC void operator()(int i, const typename T1::Scalar* in, typename T1::Scalar* out) const { using namespace Eigen; T1 x1(in+i); Map<T2> res(out+i*T2::MaxSizeAtCompileTime); res += x1.diagonal(); } }; template<typename T> struct eigenvalues { EIGEN_DEVICE_FUNC void operator()(int i, const typename T::Scalar* in, typename T::Scalar* out) const { using namespace Eigen; typedef Matrix<typename T::Scalar, T::RowsAtCompileTime, 1> Vec; T M(in+i); Map<Vec> res(out+i*Vec::MaxSizeAtCompileTime); T A = M*M.adjoint(); SelfAdjointEigenSolver<T> eig; eig.computeDirect(M); res = eig.eigenvalues(); } }; void test_cuda_basic() { ei_test_init_cuda(); int nthreads = 100; Eigen::VectorXf in, out; #ifndef __CUDA_ARCH__ int data_size = nthreads * 512; in.setRandom(data_size); out.setRandom(data_size); #endif CALL_SUBTEST( run_and_compare_to_cuda(coeff_wise<Vector3f>(), nthreads, in, out) ); CALL_SUBTEST( run_and_compare_to_cuda(coeff_wise<Array44f>(), nthreads, in, out) ); CALL_SUBTEST( run_and_compare_to_cuda(replicate<Array4f>(), nthreads, in, out) ); CALL_SUBTEST( run_and_compare_to_cuda(replicate<Array33f>(), nthreads, in, out) ); CALL_SUBTEST( run_and_compare_to_cuda(redux<Array4f>(), nthreads, in, out) ); CALL_SUBTEST( run_and_compare_to_cuda(redux<Matrix3f>(), nthreads, in, out) ); CALL_SUBTEST( run_and_compare_to_cuda(prod_test<Matrix3f,Matrix3f>(), nthreads, in, out) ); CALL_SUBTEST( run_and_compare_to_cuda(prod_test<Matrix4f,Vector4f>(), nthreads, in, out) ); CALL_SUBTEST( run_and_compare_to_cuda(diagonal<Matrix3f,Vector3f>(), nthreads, in, out) ); CALL_SUBTEST( run_and_compare_to_cuda(diagonal<Matrix4f,Vector4f>(), nthreads, in, out) ); CALL_SUBTEST( run_and_compare_to_cuda(eigenvalues<Matrix3f>(), nthreads, in, out) ); CALL_SUBTEST( run_and_compare_to_cuda(eigenvalues<Matrix2f>(), nthreads, in, out) ); }
{ "pile_set_name": "Github" }
/* Copyright 2018 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Code generated by client-gen. DO NOT EDIT. package v1 import ( v1 "k8s.io/api/core/v1" meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" scheme "k8s.io/client-go/kubernetes/scheme" rest "k8s.io/client-go/rest" ) // PersistentVolumesGetter has a method to return a PersistentVolumeInterface. // A group's client should implement this interface. type PersistentVolumesGetter interface { PersistentVolumes() PersistentVolumeInterface } // PersistentVolumeInterface has methods to work with PersistentVolume resources. type PersistentVolumeInterface interface { Create(*v1.PersistentVolume) (*v1.PersistentVolume, error) Update(*v1.PersistentVolume) (*v1.PersistentVolume, error) UpdateStatus(*v1.PersistentVolume) (*v1.PersistentVolume, error) Delete(name string, options *meta_v1.DeleteOptions) error DeleteCollection(options *meta_v1.DeleteOptions, listOptions meta_v1.ListOptions) error Get(name string, options meta_v1.GetOptions) (*v1.PersistentVolume, error) List(opts meta_v1.ListOptions) (*v1.PersistentVolumeList, error) Watch(opts meta_v1.ListOptions) (watch.Interface, error) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.PersistentVolume, err error) PersistentVolumeExpansion } // persistentVolumes implements PersistentVolumeInterface type persistentVolumes struct { client rest.Interface } // newPersistentVolumes returns a PersistentVolumes func newPersistentVolumes(c *CoreV1Client) *persistentVolumes { return &persistentVolumes{ client: c.RESTClient(), } } // Get takes name of the persistentVolume, and returns the corresponding persistentVolume object, and an error if there is any. func (c *persistentVolumes) Get(name string, options meta_v1.GetOptions) (result *v1.PersistentVolume, err error) { result = &v1.PersistentVolume{} err = c.client.Get(). Resource("persistentvolumes"). Name(name). VersionedParams(&options, scheme.ParameterCodec). Do(). Into(result) return } // List takes label and field selectors, and returns the list of PersistentVolumes that match those selectors. func (c *persistentVolumes) List(opts meta_v1.ListOptions) (result *v1.PersistentVolumeList, err error) { result = &v1.PersistentVolumeList{} err = c.client.Get(). Resource("persistentvolumes"). VersionedParams(&opts, scheme.ParameterCodec). Do(). Into(result) return } // Watch returns a watch.Interface that watches the requested persistentVolumes. func (c *persistentVolumes) Watch(opts meta_v1.ListOptions) (watch.Interface, error) { opts.Watch = true return c.client.Get(). Resource("persistentvolumes"). VersionedParams(&opts, scheme.ParameterCodec). Watch() } // Create takes the representation of a persistentVolume and creates it. Returns the server's representation of the persistentVolume, and an error, if there is any. func (c *persistentVolumes) Create(persistentVolume *v1.PersistentVolume) (result *v1.PersistentVolume, err error) { result = &v1.PersistentVolume{} err = c.client.Post(). Resource("persistentvolumes"). Body(persistentVolume). Do(). Into(result) return } // Update takes the representation of a persistentVolume and updates it. Returns the server's representation of the persistentVolume, and an error, if there is any. func (c *persistentVolumes) Update(persistentVolume *v1.PersistentVolume) (result *v1.PersistentVolume, err error) { result = &v1.PersistentVolume{} err = c.client.Put(). Resource("persistentvolumes"). Name(persistentVolume.Name). Body(persistentVolume). Do(). Into(result) return } // UpdateStatus was generated because the type contains a Status member. // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). func (c *persistentVolumes) UpdateStatus(persistentVolume *v1.PersistentVolume) (result *v1.PersistentVolume, err error) { result = &v1.PersistentVolume{} err = c.client.Put(). Resource("persistentvolumes"). Name(persistentVolume.Name). SubResource("status"). Body(persistentVolume). Do(). Into(result) return } // Delete takes name of the persistentVolume and deletes it. Returns an error if one occurs. func (c *persistentVolumes) Delete(name string, options *meta_v1.DeleteOptions) error { return c.client.Delete(). Resource("persistentvolumes"). Name(name). Body(options). Do(). Error() } // DeleteCollection deletes a collection of objects. func (c *persistentVolumes) DeleteCollection(options *meta_v1.DeleteOptions, listOptions meta_v1.ListOptions) error { return c.client.Delete(). Resource("persistentvolumes"). VersionedParams(&listOptions, scheme.ParameterCodec). Body(options). Do(). Error() } // Patch applies the patch and returns the patched persistentVolume. func (c *persistentVolumes) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.PersistentVolume, err error) { result = &v1.PersistentVolume{} err = c.client.Patch(pt). Resource("persistentvolumes"). SubResource(subresources...). Name(name). Body(data). Do(). Into(result) return }
{ "pile_set_name": "Github" }
-------------------------------------------------------------------------------- Caret offset: 29 -------------------------------------------------------------------------------- # Live templates test sample given (<selection>$expr<caret></selection>) { } { say 'hi'; } { say 'hi'; } continue {} say 'hi' ; my $var = 1 + 2; if($a){} unless($a){} if($a){} else{} if($a){} elsif($b){} if($a){} elsif($b){} if($a){} else{} while($a){} until($a){} for($a){} foreach($a){} for($a =1;$a < 1; $++){} foreach($a =1;$a < 1; $++){} while($a){}continue{} until($a){}continue{} for($a){}continue{} foreach($a){}continue{} given($a){ } given($a){ when($b){} } given($a){ when($b){} when($b){} } given($a){ when($b){} default{} }-------------------------------------------------------------------------------- Caret offset: 46 -------------------------------------------------------------------------------- # Live templates test sample { say 'hi'; given (<selection>$expr<caret></selection>) { } } { say 'hi'; } continue {} say 'hi' ; my $var = 1 + 2; if($a){} unless($a){} if($a){} else{} if($a){} elsif($b){} if($a){} elsif($b){} if($a){} else{} while($a){} until($a){} for($a){} foreach($a){} for($a =1;$a < 1; $++){} foreach($a =1;$a < 1; $++){} while($a){}continue{} until($a){}continue{} for($a){}continue{} foreach($a){}continue{} given($a){ } given($a){ when($b){} } given($a){ when($b){} when($b){} } given($a){ when($b){} default{} }-------------------------------------------------------------------------------- Caret offset: 49 -------------------------------------------------------------------------------- # Live templates test sample { say 'hi'; } given (<selection>$expr<caret></selection>) { } { say 'hi'; } continue {} say 'hi' ; my $var = 1 + 2; if($a){} unless($a){} if($a){} else{} if($a){} elsif($b){} if($a){} elsif($b){} if($a){} else{} while($a){} until($a){} for($a){} foreach($a){} for($a =1;$a < 1; $++){} foreach($a =1;$a < 1; $++){} while($a){}continue{} until($a){}continue{} for($a){}continue{} foreach($a){}continue{} given($a){ } given($a){ when($b){} } given($a){ when($b){} when($b){} } given($a){ when($b){} default{} }-------------------------------------------------------------------------------- Caret offset: 67 -------------------------------------------------------------------------------- # Live templates test sample { say 'hi'; } { say 'hi'; given (<selection>$expr<caret></selection>) { } } continue {} say 'hi' ; my $var = 1 + 2; if($a){} unless($a){} if($a){} else{} if($a){} elsif($b){} if($a){} elsif($b){} if($a){} else{} while($a){} until($a){} for($a){} foreach($a){} for($a =1;$a < 1; $++){} foreach($a =1;$a < 1; $++){} while($a){}continue{} until($a){}continue{} for($a){}continue{} foreach($a){}continue{} given($a){ } given($a){ when($b){} } given($a){ when($b){} when($b){} } given($a){ when($b){} default{} }-------------------------------------------------------------------------------- Caret offset: 82 -------------------------------------------------------------------------------- # Live templates test sample { say 'hi'; } { say 'hi'; } continue {} given (<selection>$expr<caret></selection>) { } say 'hi' ; my $var = 1 + 2; if($a){} unless($a){} if($a){} else{} if($a){} elsif($b){} if($a){} elsif($b){} if($a){} else{} while($a){} until($a){} for($a){} foreach($a){} for($a =1;$a < 1; $++){} foreach($a =1;$a < 1; $++){} while($a){}continue{} until($a){}continue{} for($a){}continue{} foreach($a){}continue{} given($a){ } given($a){ when($b){} } given($a){ when($b){} when($b){} } given($a){ when($b){} default{} }-------------------------------------------------------------------------------- Caret offset: 93 -------------------------------------------------------------------------------- # Live templates test sample { say 'hi'; } { say 'hi'; } continue {} say 'hi' given(<selection>$expr<caret></selection>) { }; my $var = 1 + 2; if($a){} unless($a){} if($a){} else{} if($a){} elsif($b){} if($a){} elsif($b){} if($a){} else{} while($a){} until($a){} for($a){} foreach($a){} for($a =1;$a < 1; $++){} foreach($a =1;$a < 1; $++){} while($a){}continue{} until($a){}continue{} for($a){}continue{} foreach($a){}continue{} given($a){ } given($a){ when($b){} } given($a){ when($b){} when($b){} } given($a){ when($b){} default{} }-------------------------------------------------------------------------------- Caret offset: 123 -------------------------------------------------------------------------------- # Live templates test sample { say 'hi'; } { say 'hi'; } continue {} say 'hi' ; my $var = 1 + 2; if($a){} given (<selection>$expr<caret></selection>) { } unless($a){} if($a){} else{} if($a){} elsif($b){} if($a){} elsif($b){} if($a){} else{} while($a){} until($a){} for($a){} foreach($a){} for($a =1;$a < 1; $++){} foreach($a =1;$a < 1; $++){} while($a){}continue{} until($a){}continue{} for($a){}continue{} foreach($a){}continue{} given($a){ } given($a){ when($b){} } given($a){ when($b){} when($b){} } given($a){ when($b){} default{} }-------------------------------------------------------------------------------- Caret offset: 138 -------------------------------------------------------------------------------- # Live templates test sample { say 'hi'; } { say 'hi'; } continue {} say 'hi' ; my $var = 1 + 2; if($a){} unless($a){} given (<selection>$expr<caret></selection>) { } if($a){} else{} if($a){} elsif($b){} if($a){} elsif($b){} if($a){} else{} while($a){} until($a){} for($a){} foreach($a){} for($a =1;$a < 1; $++){} foreach($a =1;$a < 1; $++){} while($a){}continue{} until($a){}continue{} for($a){}continue{} foreach($a){}continue{} given($a){ } given($a){ when($b){} } given($a){ when($b){} when($b){} } given($a){ when($b){} default{} }-------------------------------------------------------------------------------- Caret offset: 156 -------------------------------------------------------------------------------- # Live templates test sample { say 'hi'; } { say 'hi'; } continue {} say 'hi' ; my $var = 1 + 2; if($a){} unless($a){} if($a){} else{} given (<selection>$expr<caret></selection>) { } if($a){} elsif($b){} if($a){} elsif($b){} if($a){} else{} while($a){} until($a){} for($a){} foreach($a){} for($a =1;$a < 1; $++){} foreach($a =1;$a < 1; $++){} while($a){}continue{} until($a){}continue{} for($a){}continue{} foreach($a){}continue{} given($a){ } given($a){ when($b){} } given($a){ when($b){} when($b){} } given($a){ when($b){} default{} }-------------------------------------------------------------------------------- Caret offset: 179 -------------------------------------------------------------------------------- # Live templates test sample { say 'hi'; } { say 'hi'; } continue {} say 'hi' ; my $var = 1 + 2; if($a){} unless($a){} if($a){} else{} if($a){} elsif($b){} given (<selection>$expr<caret></selection>) { } if($a){} elsif($b){} if($a){} else{} while($a){} until($a){} for($a){} foreach($a){} for($a =1;$a < 1; $++){} foreach($a =1;$a < 1; $++){} while($a){}continue{} until($a){}continue{} for($a){}continue{} foreach($a){}continue{} given($a){ } given($a){ when($b){} } given($a){ when($b){} when($b){} } given($a){ when($b){} default{} }-------------------------------------------------------------------------------- Caret offset: 190 -------------------------------------------------------------------------------- # Live templates test sample { say 'hi'; } { say 'hi'; } continue {} say 'hi' ; my $var = 1 + 2; if($a){} unless($a){} if($a){} else{} if($a){} elsif($b){} if($a){} given (<selection>$expr<caret></selection>) { } elsif($b){} if($a){} else{} while($a){} until($a){} for($a){} foreach($a){} for($a =1;$a < 1; $++){} foreach($a =1;$a < 1; $++){} while($a){}continue{} until($a){}continue{} for($a){}continue{} foreach($a){}continue{} given($a){ } given($a){ when($b){} } given($a){ when($b){} when($b){} } given($a){ when($b){} default{} }-------------------------------------------------------------------------------- Caret offset: 213 -------------------------------------------------------------------------------- # Live templates test sample { say 'hi'; } { say 'hi'; } continue {} say 'hi' ; my $var = 1 + 2; if($a){} unless($a){} if($a){} else{} if($a){} elsif($b){} if($a){} elsif($b){} if($a){} given (<selection>$expr<caret></selection>) { } else{} while($a){} until($a){} for($a){} foreach($a){} for($a =1;$a < 1; $++){} foreach($a =1;$a < 1; $++){} while($a){}continue{} until($a){}continue{} for($a){}continue{} foreach($a){}continue{} given($a){ } given($a){ when($b){} } given($a){ when($b){} when($b){} } given($a){ when($b){} default{} }-------------------------------------------------------------------------------- Caret offset: 234 -------------------------------------------------------------------------------- # Live templates test sample { say 'hi'; } { say 'hi'; } continue {} say 'hi' ; my $var = 1 + 2; if($a){} unless($a){} if($a){} else{} if($a){} elsif($b){} if($a){} elsif($b){} if($a){} else{} while($a){} given (<selection>$expr<caret></selection>) { } until($a){} for($a){} foreach($a){} for($a =1;$a < 1; $++){} foreach($a =1;$a < 1; $++){} while($a){}continue{} until($a){}continue{} for($a){}continue{} foreach($a){}continue{} given($a){ } given($a){ when($b){} } given($a){ when($b){} when($b){} } given($a){ when($b){} default{} }-------------------------------------------------------------------------------- Caret offset: 248 -------------------------------------------------------------------------------- # Live templates test sample { say 'hi'; } { say 'hi'; } continue {} say 'hi' ; my $var = 1 + 2; if($a){} unless($a){} if($a){} else{} if($a){} elsif($b){} if($a){} elsif($b){} if($a){} else{} while($a){} until($a){} given (<selection>$expr<caret></selection>) { } for($a){} foreach($a){} for($a =1;$a < 1; $++){} foreach($a =1;$a < 1; $++){} while($a){}continue{} until($a){}continue{} for($a){}continue{} foreach($a){}continue{} given($a){ } given($a){ when($b){} } given($a){ when($b){} when($b){} } given($a){ when($b){} default{} }-------------------------------------------------------------------------------- Caret offset: 260 -------------------------------------------------------------------------------- # Live templates test sample { say 'hi'; } { say 'hi'; } continue {} say 'hi' ; my $var = 1 + 2; if($a){} unless($a){} if($a){} else{} if($a){} elsif($b){} if($a){} elsif($b){} if($a){} else{} while($a){} until($a){} for($a){} given (<selection>$expr<caret></selection>) { } foreach($a){} for($a =1;$a < 1; $++){} foreach($a =1;$a < 1; $++){} while($a){}continue{} until($a){}continue{} for($a){}continue{} foreach($a){}continue{} given($a){ } given($a){ when($b){} } given($a){ when($b){} when($b){} } given($a){ when($b){} default{} }-------------------------------------------------------------------------------- Caret offset: 276 -------------------------------------------------------------------------------- # Live templates test sample { say 'hi'; } { say 'hi'; } continue {} say 'hi' ; my $var = 1 + 2; if($a){} unless($a){} if($a){} else{} if($a){} elsif($b){} if($a){} elsif($b){} if($a){} else{} while($a){} until($a){} for($a){} foreach($a){} given (<selection>$expr<caret></selection>) { } for($a =1;$a < 1; $++){} foreach($a =1;$a < 1; $++){} while($a){}continue{} until($a){}continue{} for($a){}continue{} foreach($a){}continue{} given($a){ } given($a){ when($b){} } given($a){ when($b){} when($b){} } given($a){ when($b){} default{} }-------------------------------------------------------------------------------- Caret offset: 303 -------------------------------------------------------------------------------- # Live templates test sample { say 'hi'; } { say 'hi'; } continue {} say 'hi' ; my $var = 1 + 2; if($a){} unless($a){} if($a){} else{} if($a){} elsif($b){} if($a){} elsif($b){} if($a){} else{} while($a){} until($a){} for($a){} foreach($a){} for($a =1;$a < 1; $++){} given (<selection>$expr<caret></selection>) { } foreach($a =1;$a < 1; $++){} while($a){}continue{} until($a){}continue{} for($a){}continue{} foreach($a){}continue{} given($a){ } given($a){ when($b){} } given($a){ when($b){} when($b){} } given($a){ when($b){} default{} }-------------------------------------------------------------------------------- Caret offset: 334 -------------------------------------------------------------------------------- # Live templates test sample { say 'hi'; } { say 'hi'; } continue {} say 'hi' ; my $var = 1 + 2; if($a){} unless($a){} if($a){} else{} if($a){} elsif($b){} if($a){} elsif($b){} if($a){} else{} while($a){} until($a){} for($a){} foreach($a){} for($a =1;$a < 1; $++){} foreach($a =1;$a < 1; $++){} given (<selection>$expr<caret></selection>) { } while($a){}continue{} until($a){}continue{} for($a){}continue{} foreach($a){}continue{} given($a){ } given($a){ when($b){} } given($a){ when($b){} when($b){} } given($a){ when($b){} default{} }-------------------------------------------------------------------------------- Caret offset: 358 -------------------------------------------------------------------------------- # Live templates test sample { say 'hi'; } { say 'hi'; } continue {} say 'hi' ; my $var = 1 + 2; if($a){} unless($a){} if($a){} else{} if($a){} elsif($b){} if($a){} elsif($b){} if($a){} else{} while($a){} until($a){} for($a){} foreach($a){} for($a =1;$a < 1; $++){} foreach($a =1;$a < 1; $++){} while($a){}continue{} given (<selection>$expr<caret></selection>) { } until($a){}continue{} for($a){}continue{} foreach($a){}continue{} given($a){ } given($a){ when($b){} } given($a){ when($b){} when($b){} } given($a){ when($b){} default{} }-------------------------------------------------------------------------------- Caret offset: 382 -------------------------------------------------------------------------------- # Live templates test sample { say 'hi'; } { say 'hi'; } continue {} say 'hi' ; my $var = 1 + 2; if($a){} unless($a){} if($a){} else{} if($a){} elsif($b){} if($a){} elsif($b){} if($a){} else{} while($a){} until($a){} for($a){} foreach($a){} for($a =1;$a < 1; $++){} foreach($a =1;$a < 1; $++){} while($a){}continue{} until($a){}continue{} given (<selection>$expr<caret></selection>) { } for($a){}continue{} foreach($a){}continue{} given($a){ } given($a){ when($b){} } given($a){ when($b){} when($b){} } given($a){ when($b){} default{} }-------------------------------------------------------------------------------- Caret offset: 404 -------------------------------------------------------------------------------- # Live templates test sample { say 'hi'; } { say 'hi'; } continue {} say 'hi' ; my $var = 1 + 2; if($a){} unless($a){} if($a){} else{} if($a){} elsif($b){} if($a){} elsif($b){} if($a){} else{} while($a){} until($a){} for($a){} foreach($a){} for($a =1;$a < 1; $++){} foreach($a =1;$a < 1; $++){} while($a){}continue{} until($a){}continue{} for($a){}continue{} given (<selection>$expr<caret></selection>) { } foreach($a){}continue{} given($a){ } given($a){ when($b){} } given($a){ when($b){} when($b){} } given($a){ when($b){} default{} }-------------------------------------------------------------------------------- Caret offset: 430 -------------------------------------------------------------------------------- # Live templates test sample { say 'hi'; } { say 'hi'; } continue {} say 'hi' ; my $var = 1 + 2; if($a){} unless($a){} if($a){} else{} if($a){} elsif($b){} if($a){} elsif($b){} if($a){} else{} while($a){} until($a){} for($a){} foreach($a){} for($a =1;$a < 1; $++){} foreach($a =1;$a < 1; $++){} while($a){}continue{} until($a){}continue{} for($a){}continue{} foreach($a){}continue{} given (<selection>$expr<caret></selection>) { } given($a){ } given($a){ when($b){} } given($a){ when($b){} when($b){} } given($a){ when($b){} default{} }-------------------------------------------------------------------------------- Caret offset: 445 -------------------------------------------------------------------------------- # Live templates test sample { say 'hi'; } { say 'hi'; } continue {} say 'hi' ; my $var = 1 + 2; if($a){} unless($a){} if($a){} else{} if($a){} elsif($b){} if($a){} elsif($b){} if($a){} else{} while($a){} until($a){} for($a){} foreach($a){} for($a =1;$a < 1; $++){} foreach($a =1;$a < 1; $++){} while($a){}continue{} until($a){}continue{} for($a){}continue{} foreach($a){}continue{} given($a){ given (<selection>$expr<caret></selection>) { } } given($a){ when($b){} } given($a){ when($b){} when($b){} } given($a){ when($b){} default{} }-------------------------------------------------------------------------------- Caret offset: 475 -------------------------------------------------------------------------------- # Live templates test sample { say 'hi'; } { say 'hi'; } continue {} say 'hi' ; my $var = 1 + 2; if($a){} unless($a){} if($a){} else{} if($a){} elsif($b){} if($a){} elsif($b){} if($a){} else{} while($a){} until($a){} for($a){} foreach($a){} for($a =1;$a < 1; $++){} foreach($a =1;$a < 1; $++){} while($a){}continue{} until($a){}continue{} for($a){}continue{} foreach($a){}continue{} given($a){ } given($a){ when($b){} given (<selection>$expr<caret></selection>) { } } given($a){ when($b){} when($b){} } given($a){ when($b){} default{} }-------------------------------------------------------------------------------- Caret offset: 505 -------------------------------------------------------------------------------- # Live templates test sample { say 'hi'; } { say 'hi'; } continue {} say 'hi' ; my $var = 1 + 2; if($a){} unless($a){} if($a){} else{} if($a){} elsif($b){} if($a){} elsif($b){} if($a){} else{} while($a){} until($a){} for($a){} foreach($a){} for($a =1;$a < 1; $++){} foreach($a =1;$a < 1; $++){} while($a){}continue{} until($a){}continue{} for($a){}continue{} foreach($a){}continue{} given($a){ } given($a){ when($b){} } given($a){ when($b){} given (<selection>$expr<caret></selection>) { } when($b){} } given($a){ when($b){} default{} }-------------------------------------------------------------------------------- Caret offset: 548 -------------------------------------------------------------------------------- # Live templates test sample { say 'hi'; } { say 'hi'; } continue {} say 'hi' ; my $var = 1 + 2; if($a){} unless($a){} if($a){} else{} if($a){} elsif($b){} if($a){} elsif($b){} if($a){} else{} while($a){} until($a){} for($a){} foreach($a){} for($a =1;$a < 1; $++){} foreach($a =1;$a < 1; $++){} while($a){}continue{} until($a){}continue{} for($a){}continue{} foreach($a){}continue{} given($a){ } given($a){ when($b){} } given($a){ when($b){} when($b){} } given($a){ when($b){} given (<selection>$expr<caret></selection>) { } default{} }
{ "pile_set_name": "Github" }
/* * Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package sun.nio.cs; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetEncoder; import java.nio.charset.CoderResult; import java.nio.charset.CodingErrorAction; /* Legal UTF-8 Byte Sequences * * # Code Points Bits Bit/Byte pattern * 1 7 0xxxxxxx * U+0000..U+007F 00..7F * * 2 11 110xxxxx 10xxxxxx * U+0080..U+07FF C2..DF 80..BF * * 3 16 1110xxxx 10xxxxxx 10xxxxxx * U+0800..U+0FFF E0 A0..BF 80..BF * U+1000..U+FFFF E1..EF 80..BF 80..BF * * 4 21 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx * U+10000..U+3FFFF F0 90..BF 80..BF 80..BF * U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF * U+100000..U10FFFF F4 80..8F 80..BF 80..BF * */ public final class UTF_8 extends Unicode { public static final UTF_8 INSTANCE = new UTF_8(); public UTF_8() { super("UTF-8", StandardCharsets.aliases_UTF_8()); } public String historicalName() { return "UTF8"; } public CharsetDecoder newDecoder() { return new Decoder(this); } public CharsetEncoder newEncoder() { return new Encoder(this); } static final void updatePositions(Buffer src, int sp, Buffer dst, int dp) { src.position(sp - src.arrayOffset()); dst.position(dp - dst.arrayOffset()); } private static class Decoder extends CharsetDecoder { private Decoder(Charset cs) { super(cs, 1.0f, 1.0f); } private static boolean isNotContinuation(int b) { return (b & 0xc0) != 0x80; } // [E0] [A0..BF] [80..BF] // [E1..EF] [80..BF] [80..BF] private static boolean isMalformed3(int b1, int b2, int b3) { return (b1 == (byte)0xe0 && (b2 & 0xe0) == 0x80) || (b2 & 0xc0) != 0x80 || (b3 & 0xc0) != 0x80; } // only used when there is only one byte left in src buffer private static boolean isMalformed3_2(int b1, int b2) { return (b1 == (byte)0xe0 && (b2 & 0xe0) == 0x80) || (b2 & 0xc0) != 0x80; } // [F0] [90..BF] [80..BF] [80..BF] // [F1..F3] [80..BF] [80..BF] [80..BF] // [F4] [80..8F] [80..BF] [80..BF] // only check 80-be range here, the [0xf0,0x80...] and [0xf4,0x90-...] // will be checked by Character.isSupplementaryCodePoint(uc) private static boolean isMalformed4(int b2, int b3, int b4) { return (b2 & 0xc0) != 0x80 || (b3 & 0xc0) != 0x80 || (b4 & 0xc0) != 0x80; } // only used when there is less than 4 bytes left in src buffer. // both b1 and b2 should be "& 0xff" before passed in. private static boolean isMalformed4_2(int b1, int b2) { return (b1 == 0xf0 && (b2 < 0x90 || b2 > 0xbf)) || (b1 == 0xf4 && (b2 & 0xf0) != 0x80) || (b2 & 0xc0) != 0x80; } // tests if b1 and b2 are malformed as the first 2 bytes of a // legal`4-byte utf-8 byte sequence. // only used when there is less than 4 bytes left in src buffer, // after isMalformed4_2 has been invoked. private static boolean isMalformed4_3(int b3) { return (b3 & 0xc0) != 0x80; } private static CoderResult lookupN(ByteBuffer src, int n) { for (int i = 1; i < n; i++) { if (isNotContinuation(src.get())) return CoderResult.malformedForLength(i); } return CoderResult.malformedForLength(n); } private static CoderResult malformedN(ByteBuffer src, int nb) { switch (nb) { case 1: case 2: // always 1 return CoderResult.malformedForLength(1); case 3: int b1 = src.get(); int b2 = src.get(); // no need to lookup b3 return CoderResult.malformedForLength( ((b1 == (byte)0xe0 && (b2 & 0xe0) == 0x80) || isNotContinuation(b2)) ? 1 : 2); case 4: // we don't care the speed here b1 = src.get() & 0xff; b2 = src.get() & 0xff; if (b1 > 0xf4 || (b1 == 0xf0 && (b2 < 0x90 || b2 > 0xbf)) || (b1 == 0xf4 && (b2 & 0xf0) != 0x80) || isNotContinuation(b2)) return CoderResult.malformedForLength(1); if (isNotContinuation(src.get())) return CoderResult.malformedForLength(2); return CoderResult.malformedForLength(3); default: assert false; return null; } } private static CoderResult malformed(ByteBuffer src, int sp, CharBuffer dst, int dp, int nb) { src.position(sp - src.arrayOffset()); CoderResult cr = malformedN(src, nb); updatePositions(src, sp, dst, dp); return cr; } private static CoderResult malformed(ByteBuffer src, int mark, int nb) { src.position(mark); CoderResult cr = malformedN(src, nb); src.position(mark); return cr; } private static CoderResult malformedForLength(ByteBuffer src, int sp, CharBuffer dst, int dp, int malformedNB) { updatePositions(src, sp, dst, dp); return CoderResult.malformedForLength(malformedNB); } private static CoderResult malformedForLength(ByteBuffer src, int mark, int malformedNB) { src.position(mark); return CoderResult.malformedForLength(malformedNB); } private static CoderResult xflow(Buffer src, int sp, int sl, Buffer dst, int dp, int nb) { updatePositions(src, sp, dst, dp); return (nb == 0 || sl - sp < nb) ? CoderResult.UNDERFLOW : CoderResult.OVERFLOW; } private static CoderResult xflow(Buffer src, int mark, int nb) { src.position(mark); return (nb == 0 || src.remaining() < nb) ? CoderResult.UNDERFLOW : CoderResult.OVERFLOW; } private CoderResult decodeArrayLoop(ByteBuffer src, CharBuffer dst) { // This method is optimized for ASCII input. byte[] sa = src.array(); int sp = src.arrayOffset() + src.position(); int sl = src.arrayOffset() + src.limit(); char[] da = dst.array(); int dp = dst.arrayOffset() + dst.position(); int dl = dst.arrayOffset() + dst.limit(); int dlASCII = dp + Math.min(sl - sp, dl - dp); // ASCII only loop while (dp < dlASCII && sa[sp] >= 0) da[dp++] = (char) sa[sp++]; while (sp < sl) { int b1 = sa[sp]; if (b1 >= 0) { // 1 byte, 7 bits: 0xxxxxxx if (dp >= dl) return xflow(src, sp, sl, dst, dp, 1); da[dp++] = (char) b1; sp++; } else if ((b1 >> 5) == -2 && (b1 & 0x1e) != 0) { // 2 bytes, 11 bits: 110xxxxx 10xxxxxx // [C2..DF] [80..BF] if (sl - sp < 2 || dp >= dl) return xflow(src, sp, sl, dst, dp, 2); int b2 = sa[sp + 1]; // Now we check the first byte of 2-byte sequence as // if ((b1 >> 5) == -2 && (b1 & 0x1e) != 0) // no longer need to check b1 against c1 & c0 for // malformed as we did in previous version // (b1 & 0x1e) == 0x0 || (b2 & 0xc0) != 0x80; // only need to check the second byte b2. if (isNotContinuation(b2)) return malformedForLength(src, sp, dst, dp, 1); da[dp++] = (char) (((b1 << 6) ^ b2) ^ (((byte) 0xC0 << 6) ^ ((byte) 0x80 << 0))); sp += 2; } else if ((b1 >> 4) == -2) { // 3 bytes, 16 bits: 1110xxxx 10xxxxxx 10xxxxxx int srcRemaining = sl - sp; if (srcRemaining < 3 || dp >= dl) { if (srcRemaining > 1 && isMalformed3_2(b1, sa[sp + 1])) return malformedForLength(src, sp, dst, dp, 1); return xflow(src, sp, sl, dst, dp, 3); } int b2 = sa[sp + 1]; int b3 = sa[sp + 2]; if (isMalformed3(b1, b2, b3)) return malformed(src, sp, dst, dp, 3); char c = (char) ((b1 << 12) ^ (b2 << 6) ^ (b3 ^ (((byte) 0xE0 << 12) ^ ((byte) 0x80 << 6) ^ ((byte) 0x80 << 0)))); if (Character.isSurrogate(c)) return malformedForLength(src, sp, dst, dp, 3); da[dp++] = c; sp += 3; } else if ((b1 >> 3) == -2) { // 4 bytes, 21 bits: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx int srcRemaining = sl - sp; if (srcRemaining < 4 || dl - dp < 2) { b1 &= 0xff; if (b1 > 0xf4 || srcRemaining > 1 && isMalformed4_2(b1, sa[sp + 1] & 0xff)) return malformedForLength(src, sp, dst, dp, 1); if (srcRemaining > 2 && isMalformed4_3(sa[sp + 2])) return malformedForLength(src, sp, dst, dp, 2); return xflow(src, sp, sl, dst, dp, 4); } int b2 = sa[sp + 1]; int b3 = sa[sp + 2]; int b4 = sa[sp + 3]; int uc = ((b1 << 18) ^ (b2 << 12) ^ (b3 << 6) ^ (b4 ^ (((byte) 0xF0 << 18) ^ ((byte) 0x80 << 12) ^ ((byte) 0x80 << 6) ^ ((byte) 0x80 << 0)))); if (isMalformed4(b2, b3, b4) || // shortest form check !Character.isSupplementaryCodePoint(uc)) { return malformed(src, sp, dst, dp, 4); } da[dp++] = Character.highSurrogate(uc); da[dp++] = Character.lowSurrogate(uc); sp += 4; } else return malformed(src, sp, dst, dp, 1); } return xflow(src, sp, sl, dst, dp, 0); } private CoderResult decodeBufferLoop(ByteBuffer src, CharBuffer dst) { int mark = src.position(); int limit = src.limit(); while (mark < limit) { int b1 = src.get(); if (b1 >= 0) { // 1 byte, 7 bits: 0xxxxxxx if (dst.remaining() < 1) return xflow(src, mark, 1); // overflow dst.put((char) b1); mark++; } else if ((b1 >> 5) == -2 && (b1 & 0x1e) != 0) { // 2 bytes, 11 bits: 110xxxxx 10xxxxxx if (limit - mark < 2|| dst.remaining() < 1) return xflow(src, mark, 2); int b2 = src.get(); if (isNotContinuation(b2)) return malformedForLength(src, mark, 1); dst.put((char) (((b1 << 6) ^ b2) ^ (((byte) 0xC0 << 6) ^ ((byte) 0x80 << 0)))); mark += 2; } else if ((b1 >> 4) == -2) { // 3 bytes, 16 bits: 1110xxxx 10xxxxxx 10xxxxxx int srcRemaining = limit - mark; if (srcRemaining < 3 || dst.remaining() < 1) { if (srcRemaining > 1 && isMalformed3_2(b1, src.get())) return malformedForLength(src, mark, 1); return xflow(src, mark, 3); } int b2 = src.get(); int b3 = src.get(); if (isMalformed3(b1, b2, b3)) return malformed(src, mark, 3); char c = (char) ((b1 << 12) ^ (b2 << 6) ^ (b3 ^ (((byte) 0xE0 << 12) ^ ((byte) 0x80 << 6) ^ ((byte) 0x80 << 0)))); if (Character.isSurrogate(c)) return malformedForLength(src, mark, 3); dst.put(c); mark += 3; } else if ((b1 >> 3) == -2) { // 4 bytes, 21 bits: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx int srcRemaining = limit - mark; if (srcRemaining < 4 || dst.remaining() < 2) { b1 &= 0xff; if (b1 > 0xf4 || srcRemaining > 1 && isMalformed4_2(b1, src.get() & 0xff)) return malformedForLength(src, mark, 1); if (srcRemaining > 2 && isMalformed4_3(src.get())) return malformedForLength(src, mark, 2); return xflow(src, mark, 4); } int b2 = src.get(); int b3 = src.get(); int b4 = src.get(); int uc = ((b1 << 18) ^ (b2 << 12) ^ (b3 << 6) ^ (b4 ^ (((byte) 0xF0 << 18) ^ ((byte) 0x80 << 12) ^ ((byte) 0x80 << 6) ^ ((byte) 0x80 << 0)))); if (isMalformed4(b2, b3, b4) || // shortest form check !Character.isSupplementaryCodePoint(uc)) { return malformed(src, mark, 4); } dst.put(Character.highSurrogate(uc)); dst.put(Character.lowSurrogate(uc)); mark += 4; } else { return malformed(src, mark, 1); } } return xflow(src, mark, 0); } protected CoderResult decodeLoop(ByteBuffer src, CharBuffer dst) { if (src.hasArray() && dst.hasArray()) return decodeArrayLoop(src, dst); else return decodeBufferLoop(src, dst); } private static ByteBuffer getByteBuffer(ByteBuffer bb, byte[] ba, int sp) { if (bb == null) bb = ByteBuffer.wrap(ba); bb.position(sp); return bb; } } private static final class Encoder extends CharsetEncoder { private Encoder(Charset cs) { super(cs, 1.1f, 3.0f); } public boolean canEncode(char c) { return !Character.isSurrogate(c); } public boolean isLegalReplacement(byte[] repl) { return ((repl.length == 1 && repl[0] >= 0) || super.isLegalReplacement(repl)); } private static CoderResult overflow(CharBuffer src, int sp, ByteBuffer dst, int dp) { updatePositions(src, sp, dst, dp); return CoderResult.OVERFLOW; } private static CoderResult overflow(CharBuffer src, int mark) { src.position(mark); return CoderResult.OVERFLOW; } private Surrogate.Parser sgp; private CoderResult encodeArrayLoop(CharBuffer src, ByteBuffer dst) { char[] sa = src.array(); int sp = src.arrayOffset() + src.position(); int sl = src.arrayOffset() + src.limit(); byte[] da = dst.array(); int dp = dst.arrayOffset() + dst.position(); int dl = dst.arrayOffset() + dst.limit(); int dlASCII = dp + Math.min(sl - sp, dl - dp); // ASCII only loop while (dp < dlASCII && sa[sp] < '\u0080') da[dp++] = (byte) sa[sp++]; while (sp < sl) { char c = sa[sp]; if (c < 0x80) { // Have at most seven bits if (dp >= dl) return overflow(src, sp, dst, dp); da[dp++] = (byte)c; } else if (c < 0x800) { // 2 bytes, 11 bits if (dl - dp < 2) return overflow(src, sp, dst, dp); da[dp++] = (byte)(0xc0 | (c >> 6)); da[dp++] = (byte)(0x80 | (c & 0x3f)); } else if (Character.isSurrogate(c)) { // Have a surrogate pair if (sgp == null) sgp = new Surrogate.Parser(); int uc = sgp.parse(c, sa, sp, sl); if (uc < 0) { updatePositions(src, sp, dst, dp); return sgp.error(); } if (dl - dp < 4) return overflow(src, sp, dst, dp); da[dp++] = (byte)(0xf0 | ((uc >> 18))); da[dp++] = (byte)(0x80 | ((uc >> 12) & 0x3f)); da[dp++] = (byte)(0x80 | ((uc >> 6) & 0x3f)); da[dp++] = (byte)(0x80 | (uc & 0x3f)); sp++; // 2 chars } else { // 3 bytes, 16 bits if (dl - dp < 3) return overflow(src, sp, dst, dp); da[dp++] = (byte)(0xe0 | ((c >> 12))); da[dp++] = (byte)(0x80 | ((c >> 6) & 0x3f)); da[dp++] = (byte)(0x80 | (c & 0x3f)); } sp++; } updatePositions(src, sp, dst, dp); return CoderResult.UNDERFLOW; } private CoderResult encodeBufferLoop(CharBuffer src, ByteBuffer dst) { int mark = src.position(); while (src.hasRemaining()) { char c = src.get(); if (c < 0x80) { // Have at most seven bits if (!dst.hasRemaining()) return overflow(src, mark); dst.put((byte)c); } else if (c < 0x800) { // 2 bytes, 11 bits if (dst.remaining() < 2) return overflow(src, mark); dst.put((byte)(0xc0 | (c >> 6))); dst.put((byte)(0x80 | (c & 0x3f))); } else if (Character.isSurrogate(c)) { // Have a surrogate pair if (sgp == null) sgp = new Surrogate.Parser(); int uc = sgp.parse(c, src); if (uc < 0) { src.position(mark); return sgp.error(); } if (dst.remaining() < 4) return overflow(src, mark); dst.put((byte)(0xf0 | ((uc >> 18)))); dst.put((byte)(0x80 | ((uc >> 12) & 0x3f))); dst.put((byte)(0x80 | ((uc >> 6) & 0x3f))); dst.put((byte)(0x80 | (uc & 0x3f))); mark++; // 2 chars } else { // 3 bytes, 16 bits if (dst.remaining() < 3) return overflow(src, mark); dst.put((byte)(0xe0 | ((c >> 12)))); dst.put((byte)(0x80 | ((c >> 6) & 0x3f))); dst.put((byte)(0x80 | (c & 0x3f))); } mark++; } src.position(mark); return CoderResult.UNDERFLOW; } protected final CoderResult encodeLoop(CharBuffer src, ByteBuffer dst) { if (src.hasArray() && dst.hasArray()) return encodeArrayLoop(src, dst); else return encodeBufferLoop(src, dst); } } }
{ "pile_set_name": "Github" }
# Tree 树形控件 用来展示多层级数据结构, 可展开折叠, 选中, 模糊搜索, 支持作用域插槽。 ## 代码演示 ### 基本使用 :::demo ```html <template> <n-Tree :data="treeList" :default-expand-all="true" /> </template> <script> export default { data () { return { treeList: [ { "id": 1007, "name": "山东省", "children": [{ "id": 1103, "name": "济南市", "children": [{ "id": 2544, "name": "济南市无影山西路店" }, { "id": 2545, "name": "济南市堤口路店" }] }, { "id": 1105, "name": "沂市", "children": [{ "id": 2561, "name": "沂市东岳庙店" }] }] } ], } } } </script> ``` ::: ### 常用的属性和方法 :::demo ```html <template> <div> <n-button @click="setKeys">通过key选中河南和河北</n-button> <n-button @click="getKeys">获取所有选中项的keys</n-button> <n-button @click="getNodes">获取所有选中项的nodes</n-button> <n-button @click="resetChecked">清空所有选中状态</n-button> <n-button @click="getNodes">通过key获取河北省节点</n-button> <hr /> <n-tree ref="tree" node-key="id" :data="treeList" :show-checkbox="true" :default-checked-keys="[1103]" :default-expanded-keys="[1103, 1105]" @node-click="handleClick" ></n-tree> </div> </template> <script> export default { data() { return { treeList: [ { "id": 1000, "name": "河南省", "children": [{ "id": 1009, "name": "新乡市", "children": [{ "id": 1119, "name": "新乡市宏力大道店" }, { "id": 1120, "name": "新乡市胜利北街店" }, { "id": 1121, "name": "新乡市首比街店" }] }, { "id": 1016, "name": "巩义市", "children": [{ "id": 1254, "name": "巩义市新兴路店" }] }] }, { "id": 1001, "name": "河北省", "children": [] }, { "id": 1007, "name": "山东省", "children": [{ "id": 1103, "name": "济南市", "children": [{ "id": 2544, "name": "济南市无影山西路店" }, { "id": 2545, "name": "济南市堤口路店" }] }, { "id": 1105, "name": "沂市", "children": [{ "id": 2561, "name": "沂市东岳庙店" }] }] }, { "id": 1008, "name": "甘肃省", "children": [{ "id": 1111, "name": "兰州市", "children": [{ "id": 2649, "name": "兰州市金港城店" }, { "id": 2651, "name": "兰州市秦安路店" }] }] } ], } }, methods: { setKeys () { this.$refs.tree.setCheckedByKeys([1000, 1001], true) }, getKeys () { const keys = this.$refs.tree.getCheckedKeys() console.log(keys) }, getNodes () { const nodes = this.$refs.tree.getCheckedNodes() console.log(nodes) }, resetChecked () { this.$refs.tree.resetChecked() }, getNode () { const node = this.$refs.tree.getNode(1001) console.log(node) }, handleClick (e, node) { console.log(node) } } } </script> ``` ::: ### 模糊搜索功能 :::demo ```html <template> <div> <n-input v-model="input" size="sm" type="text" /> <n-tree node-key="id" :data="treeList" :search="input" :default-expand-all="true" ></n-tree> </div> </template> <script> export default { data() { return { input: '济南无影山', treeList: [ { "id": 1000, "name": "河南省", "children": [{ "id": 1009, "name": "新乡市", "children": [{ "id": 1119, "name": "新乡市宏力大道店" }, { "id": 1120, "name": "新乡市胜利北街店" }, { "id": 1121, "name": "新乡市首比街店" }] }, { "id": 1016, "name": "巩义市", "children": [{ "id": 1254, "name": "巩义市新兴路店" }] }] }, { "id": 1001, "name": "河北省", "children": [] }, { "id": 1007, "name": "山东省", "children": [{ "id": 1103, "name": "济南市", "children": [{ "id": 2544, "name": "济南市无影山西路店" }, { "id": 2545, "name": "济南市堤口路店" }] }, { "id": 1105, "name": "沂市", "children": [{ "id": 2561, "name": "沂市东岳庙店" }] }] }, { "id": 1008, "name": "甘肃省", "children": [{ "id": 1111, "name": "兰州市", "children": [{ "id": 2649, "name": "兰州市金港城店" }, { "id": 2651, "name": "兰州市秦安路店" }] }] } ], } } } </script> ``` ::: ### 作用域插槽 :::demo ```html <template> <div> <div style="overflow: hidden"> <n-button @click="handleAppendRoot()" style="float: right"> 添加根节点 </n-button> </div> <n-tree ref="tree" node-key="id" :data="treeList" :default-expand-all="true" :deepCopy="false" > <template slot-scope="node"> <div style="margin: 5px"> <span>{{node.name}}</span> <n-button @click.native.stop="handleRemove(node)" style="float: right" >删除</n-button> <n-button @click.native.stop="handleAppend(node)" style="float: right;margin-right: 10px" >添加</n-button> </div> </template> </n-tree> </div> </template> <script> export default { data() { return { treeList: [ { "id": 1007, "name": "山东省", "children": [{ "id": 1103, "name": "济南市", "children": [{ "id": 2544, "name": "济南市无影山西路店" }, { "id": 2545, "name": "济南市堤口路店" }] }, { "id": 1105, "name": "沂市", "children": [{ "id": 2561, "name": "沂市东岳庙店" }] }] } ], } }, methods: { handleRemove (data) { // 删除节点 this.$refs.tree.remove(data.id) }, handleAppend (data) { // 添加子节点 this.$refs.tree.append(data.id, { id: Date.now(), name: '新节点' }) }, handleAppendRoot () { // 添加根节点 this.$refs.tree.append(null, { id: Date.now(), name: '新节点' }) } } } </script> ``` ::: ## 属性 | 参数 | 说明 | 类型 | 默认值 | | :--- | :--- | :--- | :--- | | data | 源数据 | Array | 必填项 | node-key | 节点的唯一标识 | String | 'id' | theme-color | 主题色 | String | '#409eff' | search | 模糊搜索的关键词 | String | '' | hide-misses | 是否隐藏模糊搜索不匹配的节点 | Boolean | true | expand-misses | 是否展开模糊搜索不匹配的节点 | Boolean | false | search-debounce | 模糊搜索防抖 (毫秒) | Number | 500 | empty-text | 内容为空时展示的文本 | String | '' | show-checkbox | 是否显示checkbox | Boolean | false | default-expand-all | 是否默认展开所有节点 | Boolean | false | expand-on-click-node | 点击节点时是否展开或折叠 | Boolean | true | check-on-click-node | 点击节点时是否选中节点 | Boolean | false | default-expanded-keys | 默认展开节点的keys | Array | [] | default-checked-keys | 默认选中节点的keys | Array | [] | filter-node | 过滤显示的节点 (父节点全选时会选中隐藏的节点) | Function | - | props | 配置选项,请看下表 | Object | ## 配置项 | 参数 | 说明 | 类型 | :-- | :-- | :-- | name | 节点名称 | String | children | 节点的子集 | String | disabled | 该节点是否禁用 | String ## 事件 | 事件名 | 说明 | 参数 | :--- | :--- | :--- | node-click | 节点被点击时触发 | 参数1: 事件参数event, 参数2: 当前node节点 | node-checked | 节点的选中状态改变时触发 | 参数1: 事件参数event, 参数2: 当前node节点 | node-expand | 节点展开或折叠时触发 | 参数1: 事件参数event, 参数2: 当前node节点 ## 方法 | 方法名 | 说明 | 参数 | 参数类型 | 返回值 | :--- | :--- | :--- | :--- | :--- | getNodeByKey | 通过key获取对应节点 | 参数1: 唯一标识key | String / Number | 成功返回对应的节点, 失败返回null | resetChecked | 取消所有节点的选中状态 | - | - | - | setCheckedByKeys| 通过keys批量设置节点的选中状态 | 参数1: 唯一标识keys, 参数2: 状态 | 参数1: Array, 参数2: Boolean | - | getCheckedKeys | 获取选中节点的keys | 参数1: 指定表示(默认为nodeKey) | String | 所有选中节点的唯一标识keys | getCheckedNodes | 获取选中的节点nodes | - | - | 所有选中的节点nodes | remove | 通过key删除一个节点 | 参数1: 唯一标识key或当前节点 | String / Number | 成功返回true, 失败返回false | append | 通过key添加一个子节点 | 参数1: 唯一标识key或当前节点, 参数2: node节点 | String / Number | 成功返回true, 失败返回false | insertBefore | 通过key在前添加一个兄弟节点 | 参数1: 唯一标识key或当前节点, 参数2: node节点 | String / Number | 成功返回true, 失败返回false | insertAfter | 通过key在后添加一个兄弟节点 | 参数1: 唯一标识key或当前节点, 参数2: node节点 | String / Number | 成功返回true, 失败返回false | getTotalOfNodes | 获取所有满足条件的节点数量 | - | Function | 所有满足条件的节点数量
{ "pile_set_name": "Github" }
//----------------------------------------------------------------------- // <copyright file="MockOpenIdExtension.cs" company="Outercurve Foundation"> // Copyright (c) Outercurve Foundation. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace DotNetOpenAuth.Test.Mocks { using System; using System.Collections.Generic; using System.Linq; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId.Extensions; using DotNetOpenAuth.OpenId.Messages; internal class MockOpenIdExtension : IOpenIdMessageExtension { internal const string MockTypeUri = "http://mockextension"; internal static readonly StandardOpenIdExtensionFactory.CreateDelegate Factory = (typeUri, data, baseMessage, isProviderRole) => { if (typeUri == MockTypeUri) { return new MockOpenIdExtension(); } return null; }; private IDictionary<string, string> extraData = new Dictionary<string, string>(); internal MockOpenIdExtension() { } /// <summary> /// Initializes a new instance of the <see cref="MockOpenIdExtension"/> class. /// </summary> /// <param name="partValue">The value of the 'Part' parameter.</param> /// <param name="extraValue">The value of the 'data' parameter.</param> internal MockOpenIdExtension(string partValue, string extraValue) { this.Part = partValue; this.Data = extraValue; } #region IOpenIdMessageExtension Members public string TypeUri { get { return MockTypeUri; } } public IEnumerable<string> AdditionalSupportedTypeUris { get { return Enumerable.Empty<string>(); } } /// <summary> /// Gets or sets a value indicating whether this extension was /// signed by the OpenID Provider. /// </summary> /// <value> /// <c>true</c> if this instance is signed by the provider; otherwise, <c>false</c>. /// </value> public bool IsSignedByRemoteParty { get; set; } #endregion #region IMessage Properties public Version Version { get { return new Version(1, 0); } } public IDictionary<string, string> ExtraData { get { return this.extraData; } } #endregion [MessagePart] internal string Part { get; set; } internal string Data { get { string data; this.extraData.TryGetValue("data", out data); return data; } set { this.extraData["data"] = value; } } public override bool Equals(object obj) { MockOpenIdExtension other = obj as MockOpenIdExtension; if (other == null) { return false; } return this.Part.EqualsNullSafe(other.Part) && this.Data.EqualsNullSafe(other.Data); } public override int GetHashCode() { return 1; // mock doesn't need a good hash code algorithm } #region IMessage methods public void EnsureValidMessage() { } #endregion } }
{ "pile_set_name": "Github" }
Recovery (Urgent): * Not clear what the pipeline for errors should be * Find better names for the many modules * If necessary, tune performance * What is the licensing situation? Error messages (Medium-term): * Agree on a strategy with other people: what should messages look like? What should they do: describe the context? suggest common corrections? Point people to grammar documentation? * To learn what correct files look like we can probably data-mine public reason repositories. * To learn what incorrect files look like, we need some way to collect common errors!!!! Completion (Long-term): * Introduce merlin.location when there is ambiguity between concrete and abstract locations
{ "pile_set_name": "Github" }
Still in development, but if you are interested into looking around, start with swigtypemaps.swg which is the head file. Also read the docs for %fragments in fragments.swg and follow the definitions in one of the supported languages: python, perl, ruby, tcl /* ----------------------------------------------------------------------------- * Internal typemap specializations * ----------------------------------------------------------------------------- */ carrays.swg Implement the carrays.i library cdata.swg Implement the cdata.i library cmalloc.swg Implement the cmalloc.i library cpointer.swg Implement the cpointer.i library cstring.swg Implement the cstring.i library typemaps for char * cwstring.swg Implement the cstring.i library typemaps for wchar_t * exception.swg Implement the exception.i library implicit.swg Allow the use of implicit C++ constructors string.swg Typemaps for char * string wstring.swg Typemaps for wchar_t * string std_string.swg Typemaps for std::string std_wstring.swg Typemaps for std::wstring swigtype.swg Typemaps for the SWIGTYPE type void.swg Typemaps for the 'void' type enumint.swg Typemaps for enums treated as 'int' swigobject.swg Typemaps for the SWIG_Object as in PyObject, Tcl_Obj, etc. misctypes.swg Typemaps for miscellaneos types (size_t, ptrdiff_t, etc) ptrtypes.swg Typemaps for types with a 'ptr' behavior valtypes.swg Typemaps for 'by value' types inoutlist.swg IN/OUTPUT/INOUT typemaps, where the OUTPUT values are returned in a list primtypes.swg Common macros to manage primitive types (short,int,double,etc) cstrings.swg Common macros to implemented the cstring/cwstring libraries std_strings.swg Common macros to implemented the std::string/std::wstring typemaps strings.swg Common macros and typemaps for string and wstring (char *, wchar_t *) swigmacros.swg Basic macros fragments.swg Macros for fragment manipulations typemaps.swg The old typemaps.i library, not needed anymore
{ "pile_set_name": "Github" }
// license:BSD-3-Clause // copyright-holders:AJR /*************************************************************************** This is the base for several NEC 78K family disassemblers. These have more or less incompatible instruction decodings, so this file mostly contains common helpers. ***************************************************************************/ #include "emu.h" #include "upd78kd.h" upd78k_family_disassembler::upd78k_family_disassembler(const char *const sfr_names[], const char *const sfrp_names[]) : util::disasm_interface() , m_sfr_names(sfr_names) , m_sfrp_names(sfrp_names) { } u32 upd78k_family_disassembler::opcode_alignment() const { return 1; } void upd78k_family_disassembler::format_imm8(std::ostream &stream, u8 d) { if (d < 0xa0) util::stream_format(stream, "#%02XH", d); else util::stream_format(stream, "#0%02XH", d); } void upd78k_family_disassembler::format_imm16(std::ostream &stream, u16 d) { if (d < 0xa000) util::stream_format(stream, "#%04XH", d); else util::stream_format(stream, "#0%04XH", d); } void upd78k_family_disassembler::format_ix_disp8(std::ostream &stream, const char *r, u8 d) { if (d < 0xa0) util::stream_format(stream, "[%s+%02XH]", r, d); else util::stream_format(stream, "[%s+0%02XH]", r, d); } void upd78k_family_disassembler::format_ix_disp16(std::ostream &stream, const char *r, u16 d) { if (d > 0xff00) // assume these are effectively small negative offsets { stream << "-"; d = 0x10000 - d; } if (d < 0x000a) util::stream_format(stream, "%d[%s]", d, r); else { if (d < 0x0010 || d >= (d < 0x0100 ? 0x00a0 : d < 0x1000 ? 0x0a00 : 0xa000)) stream << "0"; util::stream_format(stream, "%XH[%s]", d, r); } } void upd78k_family_disassembler::format_ix_base16(std::ostream &stream, const char *r, u16 d) { if (d >= 0xa000) stream << "0"; util::stream_format(stream, "%04XH[%s]", d, r); } void upd78k_family_disassembler::format_abs16(std::ostream &stream, u16 addr) { if (addr < 0xa000) util::stream_format(stream, "!%04XH", addr); else util::stream_format(stream, "!0%04XH", addr); } void upd78k_family_disassembler::format_jdisp8(std::ostream &stream, offs_t pc, u8 disp) { u16 addr = pc + s8(disp); if (addr < 0xa000) util::stream_format(stream, "$%04XH", addr); else util::stream_format(stream, "$0%04XH", addr); } void upd78k_family_disassembler::format_sfr(std::ostream &stream, u8 addr) { if (m_sfr_names[addr] != nullptr) stream << m_sfr_names[addr]; else util::stream_format(stream, "0%04XH", 0xff00 + addr); } void upd78k_family_disassembler::format_saddr(std::ostream &stream, u8 addr) { if (addr < 0x20) format_sfr(stream, addr); else util::stream_format(stream, "0%04XH", 0xfe00 + addr); } void upd78k_family_disassembler::format_sfrp(std::ostream &stream, u8 addr) { if (!BIT(addr, 0) && m_sfrp_names[addr >> 1] != nullptr) stream << m_sfrp_names[addr >> 1]; else util::stream_format(stream, "0%04XH", 0xff00 + addr); } void upd78k_family_disassembler::format_count(std::ostream &stream, u8 n) { if (n < 0x0a) util::stream_format(stream, "%d", n); else { if (n >= 0x0a) stream << "0"; util::stream_format(stream, "%02XH", n); } } void upd78k_family_disassembler::format_saddrp(std::ostream &stream, u8 addr) { if (addr < 0x20) format_sfrp(stream, addr); else util::stream_format(stream, "0%04XH", 0xfe00 + addr); } offs_t upd78k_family_disassembler::dasm_illegal(std::ostream &stream, u8 op) { if (op < 0xa0) util::stream_format(stream, "%-8s%02XH", "DB", op); else util::stream_format(stream, "%-8s0%02XH", "DB", op); return 1 | SUPPORTED; } offs_t upd78k_family_disassembler::dasm_illegal2(std::ostream &stream, u8 op1, u8 op2) { if (op2 < 0xa0) util::stream_format(stream, "%-8s%02XH,%02XH", "DB", op1, op2); else util::stream_format(stream, "%-8s%02XH,0%02XH", "DB", op1, op2); return 2 | SUPPORTED; } offs_t upd78k_family_disassembler::dasm_illegal3(std::ostream &stream, u8 op1, u8 op2, u8 op3) { if (op3 < 0xa0) util::stream_format(stream, "%-8s%02XH,%02XH,%02XH", "DB", op1, op2, op3); else util::stream_format(stream, "%-8s%02XH,%02XH,0%02XH", "DB", op1, op2, op3); return 3 | SUPPORTED; } // For families with 4 banks of 8 registers and only one PSW byte upd78k_8reg_disassembler::upd78k_8reg_disassembler(const char *const sfr_names[], const char *const sfrp_names[]) : upd78k_family_disassembler(sfr_names, sfrp_names) { } const char *const upd78k_8reg_disassembler::s_r_names[8] = { "X", "A", "C", "B", "E", "D", "L", "H" }; const char *const upd78k_8reg_disassembler::s_rp_names[4] = { "AX", "BC", "DE", "HL" }; const char *const upd78k_8reg_disassembler::s_psw_bits[8] = { "CY", "ISP", "PSW.2", "RBS0", "AC", "RBS1", "Z", "IE" };
{ "pile_set_name": "Github" }
/*! ***************************************************************************** Copyright (c) Microsoft Corporation. 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 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ /// <reference no-default-lib="true"/> /// <reference lib="es2020" /> /// <reference lib="dom" /> /// <reference lib="webworker.importscripts" /> /// <reference lib="scripthost" /> /// <reference lib="dom.iterable" />
{ "pile_set_name": "Github" }
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. package app import ( "context" "crypto/ecdsa" "crypto/tls" "fmt" "hash/maphash" "net" "net/http" "net/url" "os" "os/exec" "path" "strings" "sync" "sync/atomic" "syscall" "time" "github.com/getsentry/sentry-go" sentryhttp "github.com/getsentry/sentry-go/http" "github.com/gorilla/mux" "github.com/pkg/errors" "github.com/rs/cors" "golang.org/x/crypto/acme/autocert" "github.com/mattermost/mattermost-server/v5/audit" "github.com/mattermost/mattermost-server/v5/config" "github.com/mattermost/mattermost-server/v5/einterfaces" "github.com/mattermost/mattermost-server/v5/jobs" "github.com/mattermost/mattermost-server/v5/mlog" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/plugin" "github.com/mattermost/mattermost-server/v5/services/cache" "github.com/mattermost/mattermost-server/v5/services/filesstore" "github.com/mattermost/mattermost-server/v5/services/httpservice" "github.com/mattermost/mattermost-server/v5/services/imageproxy" "github.com/mattermost/mattermost-server/v5/services/mailservice" "github.com/mattermost/mattermost-server/v5/services/searchengine" "github.com/mattermost/mattermost-server/v5/services/searchengine/bleveengine" "github.com/mattermost/mattermost-server/v5/services/telemetry" "github.com/mattermost/mattermost-server/v5/services/timezones" "github.com/mattermost/mattermost-server/v5/services/tracing" "github.com/mattermost/mattermost-server/v5/services/upgrader" "github.com/mattermost/mattermost-server/v5/store" "github.com/mattermost/mattermost-server/v5/store/localcachelayer" "github.com/mattermost/mattermost-server/v5/store/retrylayer" "github.com/mattermost/mattermost-server/v5/store/searchlayer" "github.com/mattermost/mattermost-server/v5/store/sqlstore" "github.com/mattermost/mattermost-server/v5/store/timerlayer" "github.com/mattermost/mattermost-server/v5/utils" ) var MaxNotificationsPerChannelDefault int64 = 1000000 // declaring this as var to allow overriding in tests var SENTRY_DSN = "placeholder_sentry_dsn" type Server struct { sqlStore *sqlstore.SqlSupplier Store store.Store WebSocketRouter *WebSocketRouter AppInitializedOnce sync.Once // RootRouter is the starting point for all HTTP requests to the server. RootRouter *mux.Router // LocalRouter is the starting point for all the local UNIX socket // requests to the server LocalRouter *mux.Router // Router is the starting point for all web, api4 and ws requests to the server. It differs // from RootRouter only if the SiteURL contains a /subpath. Router *mux.Router Server *http.Server ListenAddr *net.TCPAddr RateLimiter *RateLimiter Busy *Busy localModeServer *http.Server didFinishListen chan struct{} goroutineCount int32 goroutineExitSignal chan struct{} PluginsEnvironment *plugin.Environment PluginConfigListenerId string PluginsLock sync.RWMutex EmailService *EmailService hubs []*Hub hashSeed maphash.Seed PushNotificationsHub PushNotificationsHub pushNotificationClient *http.Client // TODO: move this to it's own package runjobs bool Jobs *jobs.JobServer clusterLeaderListeners sync.Map licenseValue atomic.Value clientLicenseValue atomic.Value licenseListeners map[string]func(*model.License, *model.License) timezones *timezones.Timezones newStore func() store.Store htmlTemplateWatcher *utils.HTMLTemplateWatcher sessionCache cache.Cache seenPendingPostIdsCache cache.Cache statusCache cache.Cache configListenerId string licenseListenerId string logListenerId string clusterLeaderListenerId string searchConfigListenerId string searchLicenseListenerId string loggerLicenseListenerId string configStore config.Store asymmetricSigningKey *ecdsa.PrivateKey postActionCookieSecret []byte advancedLogListenerCleanup func() pluginCommands []*PluginCommand pluginCommandsLock sync.RWMutex clientConfig atomic.Value clientConfigHash atomic.Value limitedClientConfig atomic.Value telemetryService *telemetry.TelemetryService phase2PermissionsMigrationComplete bool HTTPService httpservice.HTTPService ImageProxy *imageproxy.ImageProxy Audit *audit.Audit Log *mlog.Logger NotificationsLog *mlog.Logger joinCluster bool startMetrics bool startSearchEngine bool SearchEngine *searchengine.Broker AccountMigration einterfaces.AccountMigrationInterface Cluster einterfaces.ClusterInterface Compliance einterfaces.ComplianceInterface DataRetention einterfaces.DataRetentionInterface Ldap einterfaces.LdapInterface MessageExport einterfaces.MessageExportInterface Cloud einterfaces.CloudInterface Metrics einterfaces.MetricsInterface Notification einterfaces.NotificationInterface Saml einterfaces.SamlInterface CacheProvider cache.Provider tracer *tracing.Tracer // These are used to prevent concurrent upload requests // for a given upload session which could cause inconsistencies // and data corruption. uploadLockMapMut sync.Mutex uploadLockMap map[string]bool } func NewServer(options ...Option) (*Server, error) { rootRouter := mux.NewRouter() localRouter := mux.NewRouter() s := &Server{ goroutineExitSignal: make(chan struct{}, 1), RootRouter: rootRouter, LocalRouter: localRouter, licenseListeners: map[string]func(*model.License, *model.License){}, hashSeed: maphash.MakeSeed(), uploadLockMap: map[string]bool{}, } for _, option := range options { if err := option(s); err != nil { return nil, errors.Wrap(err, "failed to apply option") } } if s.configStore == nil { configStore, err := config.NewFileStore("config.json", true) if err != nil { return nil, errors.Wrap(err, "failed to load config") } s.configStore = configStore } if err := s.initLogging(); err != nil { mlog.Error(err.Error()) } // This is called after initLogging() to avoid a race condition. mlog.Info("Server is initializing...") // It is important to initialize the hub only after the global logger is set // to avoid race conditions while logging from inside the hub. fakeApp := New(ServerConnector(s)) fakeApp.HubStart() if *s.Config().LogSettings.EnableDiagnostics && *s.Config().LogSettings.EnableSentry { if strings.Contains(SENTRY_DSN, "placeholder") { mlog.Warn("Sentry reporting is enabled, but SENTRY_DSN is not set. Disabling reporting.") } else { if err := sentry.Init(sentry.ClientOptions{ Dsn: SENTRY_DSN, Release: model.BuildHash, AttachStacktrace: true, }); err != nil { mlog.Warn("Sentry could not be initiated, probably bad DSN?", mlog.Err(err)) } } } if *s.Config().ServiceSettings.EnableOpenTracing { tracer, err := tracing.New() if err != nil { return nil, err } s.tracer = tracer } s.HTTPService = httpservice.MakeHTTPService(s) s.pushNotificationClient = s.HTTPService.MakeClient(true) s.ImageProxy = imageproxy.MakeImageProxy(s, s.HTTPService, s.Log) if err := utils.TranslationsPreInit(); err != nil { return nil, errors.Wrapf(err, "unable to load Mattermost translation files") } searchEngine := searchengine.NewBroker(s.Config(), s.Jobs) bleveEngine := bleveengine.NewBleveEngine(s.Config(), s.Jobs) if err := bleveEngine.Start(); err != nil { return nil, err } searchEngine.RegisterBleveEngine(bleveEngine) s.SearchEngine = searchEngine // at the moment we only have this implementation // in the future the cache provider will be built based on the loaded config s.CacheProvider = cache.NewProvider() if err := s.CacheProvider.Connect(); err != nil { return nil, errors.Wrapf(err, "Unable to connect to cache provider") } s.sessionCache = s.CacheProvider.NewCache(&cache.CacheOptions{ Size: model.SESSION_CACHE_SIZE, }) s.seenPendingPostIdsCache = s.CacheProvider.NewCache(&cache.CacheOptions{ Size: PENDING_POST_IDS_CACHE_SIZE, }) s.statusCache = s.CacheProvider.NewCache(&cache.CacheOptions{ Size: model.STATUS_CACHE_SIZE, }) s.createPushNotificationsHub() if err := utils.InitTranslations(s.Config().LocalizationSettings); err != nil { return nil, errors.Wrapf(err, "unable to load Mattermost translation files") } s.configListenerId = s.AddConfigListener(func(_, _ *model.Config) { s.configOrLicenseListener() message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_CONFIG_CHANGED, "", "", "", nil) message.Add("config", s.ClientConfigWithComputed()) s.Go(func() { s.Publish(message) }) }) s.licenseListenerId = s.AddLicenseListener(func(oldLicense, newLicense *model.License) { s.configOrLicenseListener() message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_LICENSE_CHANGED, "", "", "", nil) message.Add("license", s.GetSanitizedClientLicense()) s.Go(func() { s.Publish(message) }) }) s.initEnterprise() if s.newStore == nil { s.newStore = func() store.Store { s.sqlStore = sqlstore.NewSqlSupplier(s.Config().SqlSettings, s.Metrics) searchStore := searchlayer.NewSearchLayer( localcachelayer.NewLocalCacheLayer( retrylayer.New(s.sqlStore), s.Metrics, s.Cluster, s.CacheProvider, ), s.SearchEngine, s.Config(), ) s.AddConfigListener(func(prevCfg, cfg *model.Config) { searchStore.UpdateConfig(cfg) }) s.sqlStore.UpdateLicense(s.License()) s.AddLicenseListener(func(oldLicense, newLicense *model.License) { s.sqlStore.UpdateLicense(newLicense) }) return timerlayer.New( searchStore, s.Metrics, ) } } if htmlTemplateWatcher, err := utils.NewHTMLTemplateWatcher("templates"); err != nil { mlog.Error("Failed to parse server templates", mlog.Err(err)) } else { s.htmlTemplateWatcher = htmlTemplateWatcher } s.Store = s.newStore() s.telemetryService = telemetry.New(s, s.Store, s.SearchEngine, s.Log) emailService, err := NewEmailService(s) if err != nil { return nil, errors.Wrapf(err, "unable to initialize email service") } s.EmailService = emailService if model.BuildEnterpriseReady == "true" { s.LoadLicense() } s.initJobs() if s.joinCluster && s.Cluster != nil { s.Cluster.StartInterNodeCommunication() } if err = s.ensureAsymmetricSigningKey(); err != nil { return nil, errors.Wrapf(err, "unable to ensure asymmetric signing key") } if err = s.ensurePostActionCookieSecret(); err != nil { return nil, errors.Wrapf(err, "unable to ensure PostAction cookie secret") } if err = s.ensureInstallationDate(); err != nil { return nil, errors.Wrapf(err, "unable to ensure installation date") } if err = s.ensureFirstServerRunTimestamp(); err != nil { return nil, errors.Wrapf(err, "unable to ensure first run timestamp") } s.regenerateClientConfig() s.clusterLeaderListenerId = s.AddClusterLeaderChangedListener(func() { mlog.Info("Cluster leader changed. Determining if job schedulers should be running:", mlog.Bool("isLeader", s.IsLeader())) if s.Jobs != nil && s.Jobs.Schedulers != nil { s.Jobs.Schedulers.HandleClusterLeaderChange(s.IsLeader()) } }) subpath, err := utils.GetSubpathFromConfig(s.Config()) if err != nil { return nil, errors.Wrap(err, "failed to parse SiteURL subpath") } s.Router = s.RootRouter.PathPrefix(subpath).Subrouter() // FakeApp: remove this when we have the ServePluginRequest and ServePluginPublicRequest migrated in the server pluginsRoute := s.Router.PathPrefix("/plugins/{plugin_id:[A-Za-z0-9\\_\\-\\.]+}").Subrouter() pluginsRoute.HandleFunc("", fakeApp.ServePluginRequest) pluginsRoute.HandleFunc("/public/{public_file:.*}", fakeApp.ServePluginPublicRequest) pluginsRoute.HandleFunc("/{anything:.*}", fakeApp.ServePluginRequest) // If configured with a subpath, redirect 404s at the root back into the subpath. if subpath != "/" { s.RootRouter.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { r.URL.Path = path.Join(subpath, r.URL.Path) http.Redirect(w, r, r.URL.String(), http.StatusFound) }) } s.WebSocketRouter = &WebSocketRouter{ server: s, handlers: make(map[string]webSocketHandler), } s.WebSocketRouter.app = fakeApp if appErr := mailservice.TestConnection(s.Config()); appErr != nil { mlog.Error("Mail server connection test is failed: " + appErr.Message) } if _, err = url.ParseRequestURI(*s.Config().ServiceSettings.SiteURL); err != nil { mlog.Error("SiteURL must be set. Some features will operate incorrectly if the SiteURL is not set. See documentation for details: http://about.mattermost.com/default-site-url") } backend, appErr := s.FileBackend() if appErr == nil { appErr = backend.TestConnection() } if appErr != nil { mlog.Error("Problem with file storage settings", mlog.Err(appErr)) } model.AppErrorInit(utils.T) s.timezones = timezones.New() // Start email batching because it's not like the other jobs s.AddConfigListener(func(_, _ *model.Config) { s.EmailService.InitEmailBatching() }) // Start plugin health check job pluginsEnvironment := s.PluginsEnvironment if pluginsEnvironment != nil { pluginsEnvironment.InitPluginHealthCheckJob(*s.Config().PluginSettings.Enable && *s.Config().PluginSettings.EnableHealthCheck) } s.AddConfigListener(func(_, c *model.Config) { pluginsEnvironment := s.PluginsEnvironment if pluginsEnvironment != nil { pluginsEnvironment.InitPluginHealthCheckJob(*s.Config().PluginSettings.Enable && *c.PluginSettings.EnableHealthCheck) } }) logCurrentVersion := fmt.Sprintf("Current version is %v (%v/%v/%v/%v)", model.CurrentVersion, model.BuildNumber, model.BuildDate, model.BuildHash, model.BuildHashEnterprise) mlog.Info( logCurrentVersion, mlog.String("current_version", model.CurrentVersion), mlog.String("build_number", model.BuildNumber), mlog.String("build_date", model.BuildDate), mlog.String("build_hash", model.BuildHash), mlog.String("build_hash_enterprise", model.BuildHashEnterprise), ) if model.BuildEnterpriseReady == "true" { mlog.Info("Enterprise Build", mlog.Bool("enterprise_build", true)) } else { mlog.Info("Team Edition Build", mlog.Bool("enterprise_build", false)) } pwd, _ := os.Getwd() mlog.Info("Printing current working", mlog.String("directory", pwd)) mlog.Info("Loaded config", mlog.String("source", s.configStore.String())) s.checkPushNotificationServerUrl() license := s.License() if license == nil { s.UpdateConfig(func(cfg *model.Config) { cfg.TeamSettings.MaxNotificationsPerChannel = &MaxNotificationsPerChannelDefault }) } s.ReloadConfig() allowAdvancedLogging := license != nil && *license.Features.AdvancedLogging if s.Audit == nil { s.Audit = &audit.Audit{} s.Audit.Init(audit.DefMaxQueueSize) if err = s.configureAudit(s.Audit, allowAdvancedLogging); err != nil { mlog.Error("Error configuring audit", mlog.Err(err)) } } s.removeUnlicensedLogTargets(license) s.enableLoggingMetrics() s.loggerLicenseListenerId = s.AddLicenseListener(func(oldLicense, newLicense *model.License) { s.removeUnlicensedLogTargets(newLicense) s.enableLoggingMetrics() }) // Enable developer settings if this is a "dev" build if model.BuildNumber == "dev" { s.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableDeveloper = true }) } if err = s.Store.Status().ResetAll(); err != nil { mlog.Error("Error to reset the server status.", mlog.Err(err)) } if s.startMetrics && s.Metrics != nil { s.Metrics.StartServer() } s.SearchEngine.UpdateConfig(s.Config()) searchConfigListenerId, searchLicenseListenerId := s.StartSearchEngine() s.searchConfigListenerId = searchConfigListenerId s.searchLicenseListenerId = searchLicenseListenerId // if enabled - perform initial product notices fetch if *s.Config().AnnouncementSettings.AdminNoticesEnabled || *s.Config().AnnouncementSettings.UserNoticesEnabled { go fakeApp.UpdateProductNotices() } return s, nil } func (s *Server) RunJobs() { if s.runjobs { s.Go(func() { runSecurityJob(s) }) s.Go(func() { firstRun, err := s.getFirstServerRunTimestamp() if err != nil { mlog.Warn("Fetching time of first server run failed. Setting to 'now'.") s.ensureFirstServerRunTimestamp() firstRun = utils.MillisFromTime(time.Now()) } s.telemetryService.RunTelemetryJob(firstRun) }) s.Go(func() { runSessionCleanupJob(s) }) s.Go(func() { runTokenCleanupJob(s) }) s.Go(func() { runCommandWebhookCleanupJob(s) }) if complianceI := s.Compliance; complianceI != nil { complianceI.StartComplianceDailyJob() } if *s.Config().JobSettings.RunJobs && s.Jobs != nil { s.Jobs.StartWorkers() } if *s.Config().JobSettings.RunScheduler && s.Jobs != nil { s.Jobs.StartSchedulers() } } } // Global app options that should be applied to apps created by this server func (s *Server) AppOptions() []AppOption { return []AppOption{ ServerConnector(s), } } // initLogging initializes and configures the logger. This may be called more than once. func (s *Server) initLogging() error { if s.Log == nil { s.Log = mlog.NewLogger(utils.MloggerConfigFromLoggerConfig(&s.Config().LogSettings, utils.GetLogFileLocation)) } if s.NotificationsLog == nil { notificationLogSettings := utils.GetLogSettingsFromNotificationsLogSettings(&s.Config().NotificationLogSettings) s.NotificationsLog = mlog.NewLogger(utils.MloggerConfigFromLoggerConfig(notificationLogSettings, utils.GetNotificationsLogFileLocation)). WithCallerSkip(1).With(mlog.String("logSource", "notifications")) } // Redirect default golang logger to this logger mlog.RedirectStdLog(s.Log) // Use this app logger as the global logger (eventually remove all instances of global logging) mlog.InitGlobalLogger(s.Log) if s.logListenerId != "" { s.RemoveConfigListener(s.logListenerId) } s.logListenerId = s.AddConfigListener(func(_, after *model.Config) { s.Log.ChangeLevels(utils.MloggerConfigFromLoggerConfig(&after.LogSettings, utils.GetLogFileLocation)) notificationLogSettings := utils.GetLogSettingsFromNotificationsLogSettings(&after.NotificationLogSettings) s.NotificationsLog.ChangeLevels(utils.MloggerConfigFromLoggerConfig(notificationLogSettings, utils.GetNotificationsLogFileLocation)) }) // Configure advanced logging. // Advanced logging is E20 only, however logging must be initialized before the license // file is loaded. If no valid E20 license exists then advanced logging will be // shutdown once license is loaded/checked. if *s.Config().LogSettings.AdvancedLoggingConfig != "" { dsn := *s.Config().LogSettings.AdvancedLoggingConfig isJson := config.IsJsonMap(dsn) // If this is a file based config we need the full path so it can be watched. if !isJson { if fs, ok := s.configStore.(*config.FileStore); ok { dsn = fs.GetFilePath(dsn) } } cfg, err := config.NewLogConfigSrc(dsn, isJson, s.configStore) if err != nil { return fmt.Errorf("invalid advanced logging config, %w", err) } if err := mlog.ConfigAdvancedLogging(cfg.Get()); err != nil { return fmt.Errorf("error configuring advanced logging, %w", err) } if !isJson { mlog.Info("Loaded advanced logging config", mlog.String("source", dsn)) } listenerId := cfg.AddListener(func(_, newCfg mlog.LogTargetCfg) { if err := mlog.ConfigAdvancedLogging(newCfg); err != nil { mlog.Error("Error re-configuring advanced logging", mlog.Err(err)) } else { mlog.Info("Re-configured advanced logging") } }) // In case initLogging is called more than once. if s.advancedLogListenerCleanup != nil { s.advancedLogListenerCleanup() } s.advancedLogListenerCleanup = func() { cfg.RemoveListener(listenerId) } } return nil } func (s *Server) removeUnlicensedLogTargets(license *model.License) { if license != nil && *license.Features.AdvancedLogging { // advanced logging enabled via license; no need to remove any targets return } timeoutCtx, cancelCtx := context.WithTimeout(context.Background(), time.Second*10) defer cancelCtx() mlog.RemoveTargets(timeoutCtx, func(ti mlog.TargetInfo) bool { return ti.Type != "*target.Writer" && ti.Type != "*target.File" }) } func (s *Server) enableLoggingMetrics() { if s.Metrics == nil { return } if err := mlog.EnableMetrics(s.Metrics.GetLoggerMetricsCollector()); err != nil { mlog.Error("Failed to enable advanced logging metrics", mlog.Err(err)) } else { mlog.Debug("Advanced logging metrics enabled") } } const TIME_TO_WAIT_FOR_CONNECTIONS_TO_CLOSE_ON_SERVER_SHUTDOWN = time.Second func (s *Server) StopHTTPServer() { if s.Server != nil { ctx, cancel := context.WithTimeout(context.Background(), TIME_TO_WAIT_FOR_CONNECTIONS_TO_CLOSE_ON_SERVER_SHUTDOWN) defer cancel() didShutdown := false for s.didFinishListen != nil && !didShutdown { if err := s.Server.Shutdown(ctx); err != nil { mlog.Warn("Unable to shutdown server", mlog.Err(err)) } timer := time.NewTimer(time.Millisecond * 50) select { case <-s.didFinishListen: didShutdown = true case <-timer.C: } timer.Stop() } s.Server.Close() s.Server = nil } } func (s *Server) Shutdown() error { mlog.Info("Stopping Server...") defer sentry.Flush(2 * time.Second) s.HubStop() s.ShutDownPlugins() s.RemoveLicenseListener(s.licenseListenerId) s.RemoveLicenseListener(s.loggerLicenseListenerId) s.RemoveClusterLeaderChangedListener(s.clusterLeaderListenerId) if s.tracer != nil { if err := s.tracer.Close(); err != nil { mlog.Error("Unable to cleanly shutdown opentracing client", mlog.Err(err)) } } err := s.telemetryService.Shutdown() if err != nil { mlog.Error("Unable to cleanly shutdown telemetry client", mlog.Err(err)) } s.StopHTTPServer() s.stopLocalModeServer() // Push notification hub needs to be shutdown after HTTP server // to prevent stray requests from generating a push notification after it's shut down. s.StopPushNotificationsHubWorkers() s.WaitForGoroutines() if s.htmlTemplateWatcher != nil { s.htmlTemplateWatcher.Close() } if s.advancedLogListenerCleanup != nil { s.advancedLogListenerCleanup() s.advancedLogListenerCleanup = nil } s.RemoveConfigListener(s.configListenerId) s.RemoveConfigListener(s.logListenerId) s.stopSearchEngine() s.Audit.Shutdown() s.configStore.Close() if s.Cluster != nil { s.Cluster.StopInterNodeCommunication() } if s.Metrics != nil { s.Metrics.StopServer() } // This must be done after the cluster is stopped. if s.Jobs != nil && s.runjobs { s.Jobs.StopWorkers() s.Jobs.StopSchedulers() } if s.Store != nil { s.Store.Close() } if s.CacheProvider != nil { if err = s.CacheProvider.Close(); err != nil { mlog.Error("Unable to cleanly shutdown cache", mlog.Err(err)) } } timeoutCtx, timeoutCancel := context.WithTimeout(context.Background(), time.Second*15) defer timeoutCancel() if err := mlog.Flush(timeoutCtx); err != nil { mlog.Error("Error flushing logs", mlog.Err(err)) } mlog.Info("Server stopped") // this should just write the "server stopped" record, the rest are already flushed. timeoutCtx2, timeoutCancel2 := context.WithTimeout(context.Background(), time.Second*5) defer timeoutCancel2() _ = mlog.ShutdownAdvancedLogging(timeoutCtx2) return nil } func (s *Server) Restart() error { percentage, err := s.UpgradeToE0Status() if err != nil || percentage != 100 { return errors.Wrap(err, "unable to restart because the system has not been upgraded") } s.Shutdown() argv0, err := exec.LookPath(os.Args[0]) if err != nil { return err } if _, err = os.Stat(argv0); err != nil { return err } mlog.Info("Restarting server") return syscall.Exec(argv0, os.Args, os.Environ()) } func (s *Server) isUpgradedFromTE() bool { val, err := s.Store.System().GetByName(model.SYSTEM_UPGRADED_FROM_TE_ID) if err != nil { return false } return val.Value == "true" } func (s *Server) CanIUpgradeToE0() error { return upgrader.CanIUpgradeToE0() } func (s *Server) UpgradeToE0() error { if err := upgrader.UpgradeToE0(); err != nil { return err } upgradedFromTE := &model.System{Name: model.SYSTEM_UPGRADED_FROM_TE_ID, Value: "true"} s.Store.System().Save(upgradedFromTE) return nil } func (s *Server) UpgradeToE0Status() (int64, error) { return upgrader.UpgradeToE0Status() } // Go creates a goroutine, but maintains a record of it to ensure that execution completes before // the server is shutdown. func (s *Server) Go(f func()) { atomic.AddInt32(&s.goroutineCount, 1) go func() { f() atomic.AddInt32(&s.goroutineCount, -1) select { case s.goroutineExitSignal <- struct{}{}: default: } }() } // WaitForGoroutines blocks until all goroutines created by App.Go exit. func (s *Server) WaitForGoroutines() { for atomic.LoadInt32(&s.goroutineCount) != 0 { <-s.goroutineExitSignal } } var corsAllowedMethods = []string{ "POST", "GET", "OPTIONS", "PUT", "PATCH", "DELETE", } // golang.org/x/crypto/acme/autocert/autocert.go func handleHTTPRedirect(w http.ResponseWriter, r *http.Request) { if r.Method != "GET" && r.Method != "HEAD" { http.Error(w, "Use HTTPS", http.StatusBadRequest) return } target := "https://" + stripPort(r.Host) + r.URL.RequestURI() http.Redirect(w, r, target, http.StatusFound) } // golang.org/x/crypto/acme/autocert/autocert.go func stripPort(hostport string) string { host, _, err := net.SplitHostPort(hostport) if err != nil { return hostport } return net.JoinHostPort(host, "443") } func (s *Server) Start() error { mlog.Info("Starting Server...") var handler http.Handler = s.RootRouter if *s.Config().LogSettings.EnableDiagnostics && *s.Config().LogSettings.EnableSentry && !strings.Contains(SENTRY_DSN, "placeholder") { sentryHandler := sentryhttp.New(sentryhttp.Options{ Repanic: true, }) handler = sentryHandler.Handle(handler) } if allowedOrigins := *s.Config().ServiceSettings.AllowCorsFrom; allowedOrigins != "" { exposedCorsHeaders := *s.Config().ServiceSettings.CorsExposedHeaders allowCredentials := *s.Config().ServiceSettings.CorsAllowCredentials debug := *s.Config().ServiceSettings.CorsDebug corsWrapper := cors.New(cors.Options{ AllowedOrigins: strings.Fields(allowedOrigins), AllowedMethods: corsAllowedMethods, AllowedHeaders: []string{"*"}, ExposedHeaders: strings.Fields(exposedCorsHeaders), MaxAge: 86400, AllowCredentials: allowCredentials, Debug: debug, }) // If we have debugging of CORS turned on then forward messages to logs if debug { corsWrapper.Log = s.Log.StdLog(mlog.String("source", "cors")) } handler = corsWrapper.Handler(handler) } if *s.Config().RateLimitSettings.Enable { mlog.Info("RateLimiter is enabled") rateLimiter, err := NewRateLimiter(&s.Config().RateLimitSettings, s.Config().ServiceSettings.TrustedProxyIPHeader) if err != nil { return err } s.RateLimiter = rateLimiter handler = rateLimiter.RateLimitHandler(handler) } s.Busy = NewBusy(s.Cluster) // Creating a logger for logging errors from http.Server at error level errStdLog, err := s.Log.StdLogAt(mlog.LevelError, mlog.String("source", "httpserver")) if err != nil { return err } s.Server = &http.Server{ Handler: handler, ReadTimeout: time.Duration(*s.Config().ServiceSettings.ReadTimeout) * time.Second, WriteTimeout: time.Duration(*s.Config().ServiceSettings.WriteTimeout) * time.Second, IdleTimeout: time.Duration(*s.Config().ServiceSettings.IdleTimeout) * time.Second, ErrorLog: errStdLog, } addr := *s.Config().ServiceSettings.ListenAddress if addr == "" { if *s.Config().ServiceSettings.ConnectionSecurity == model.CONN_SECURITY_TLS { addr = ":https" } else { addr = ":http" } } listener, err := net.Listen("tcp", addr) if err != nil { errors.Wrapf(err, utils.T("api.server.start_server.starting.critical"), err) return err } s.ListenAddr = listener.Addr().(*net.TCPAddr) logListeningPort := fmt.Sprintf("Server is listening on %v", listener.Addr().String()) mlog.Info(logListeningPort, mlog.String("address", listener.Addr().String())) m := &autocert.Manager{ Cache: autocert.DirCache(*s.Config().ServiceSettings.LetsEncryptCertificateCacheFile), Prompt: autocert.AcceptTOS, } if *s.Config().ServiceSettings.Forward80To443 { if host, port, err := net.SplitHostPort(addr); err != nil { mlog.Error("Unable to setup forwarding", mlog.Err(err)) } else if port != "443" { return fmt.Errorf(utils.T("api.server.start_server.forward80to443.enabled_but_listening_on_wrong_port"), port) } else { httpListenAddress := net.JoinHostPort(host, "http") if *s.Config().ServiceSettings.UseLetsEncrypt { server := &http.Server{ Addr: httpListenAddress, Handler: m.HTTPHandler(nil), ErrorLog: s.Log.StdLog(mlog.String("source", "le_forwarder_server")), } go server.ListenAndServe() } else { go func() { redirectListener, err := net.Listen("tcp", httpListenAddress) if err != nil { mlog.Error("Unable to setup forwarding", mlog.Err(err)) return } defer redirectListener.Close() server := &http.Server{ Handler: http.HandlerFunc(handleHTTPRedirect), ErrorLog: s.Log.StdLog(mlog.String("source", "forwarder_server")), } server.Serve(redirectListener) }() } } } else if *s.Config().ServiceSettings.UseLetsEncrypt { return errors.New(utils.T("api.server.start_server.forward80to443.disabled_while_using_lets_encrypt")) } s.didFinishListen = make(chan struct{}) go func() { var err error if *s.Config().ServiceSettings.ConnectionSecurity == model.CONN_SECURITY_TLS { tlsConfig := &tls.Config{ PreferServerCipherSuites: true, CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256}, } switch *s.Config().ServiceSettings.TLSMinVer { case "1.0": tlsConfig.MinVersion = tls.VersionTLS10 case "1.1": tlsConfig.MinVersion = tls.VersionTLS11 default: tlsConfig.MinVersion = tls.VersionTLS12 } defaultCiphers := []uint16{ tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, tls.TLS_RSA_WITH_AES_128_GCM_SHA256, tls.TLS_RSA_WITH_AES_256_GCM_SHA384, } if len(s.Config().ServiceSettings.TLSOverwriteCiphers) == 0 { tlsConfig.CipherSuites = defaultCiphers } else { var cipherSuites []uint16 for _, cipher := range s.Config().ServiceSettings.TLSOverwriteCiphers { value, ok := model.ServerTLSSupportedCiphers[cipher] if !ok { mlog.Warn("Unsupported cipher passed", mlog.String("cipher", cipher)) continue } cipherSuites = append(cipherSuites, value) } if len(cipherSuites) == 0 { mlog.Warn("No supported ciphers passed, fallback to default cipher suite") cipherSuites = defaultCiphers } tlsConfig.CipherSuites = cipherSuites } certFile := "" keyFile := "" if *s.Config().ServiceSettings.UseLetsEncrypt { tlsConfig.GetCertificate = m.GetCertificate tlsConfig.NextProtos = append(tlsConfig.NextProtos, "h2") } else { certFile = *s.Config().ServiceSettings.TLSCertFile keyFile = *s.Config().ServiceSettings.TLSKeyFile } s.Server.TLSConfig = tlsConfig err = s.Server.ServeTLS(listener, certFile, keyFile) } else { err = s.Server.Serve(listener) } if err != nil && err != http.ErrServerClosed { mlog.Critical("Error starting server", mlog.Err(err)) time.Sleep(time.Second) } close(s.didFinishListen) }() if *s.Config().ServiceSettings.EnableLocalMode { if err := s.startLocalModeServer(); err != nil { mlog.Critical(err.Error()) } } return nil } func (s *Server) startLocalModeServer() error { s.localModeServer = &http.Server{ Handler: s.LocalRouter, } socket := *s.configStore.Get().ServiceSettings.LocalModeSocketLocation unixListener, err := net.Listen("unix", socket) if err != nil { return errors.Wrapf(err, utils.T("api.server.start_server.starting.critical"), err) } if err = os.Chmod(socket, 0600); err != nil { return errors.Wrapf(err, utils.T("api.server.start_server.starting.critical"), err) } go func() { err = s.localModeServer.Serve(unixListener) if err != nil && err != http.ErrServerClosed { mlog.Critical("Error starting unix socket server", mlog.Err(err)) } }() return nil } func (s *Server) stopLocalModeServer() { if s.localModeServer != nil { s.localModeServer.Close() } } func (a *App) OriginChecker() func(*http.Request) bool { if allowed := *a.Config().ServiceSettings.AllowCorsFrom; allowed != "" { if allowed != "*" { siteURL, err := url.Parse(*a.Config().ServiceSettings.SiteURL) if err == nil { siteURL.Path = "" allowed += " " + siteURL.String() } } return utils.OriginChecker(allowed) } return nil } func (s *Server) checkPushNotificationServerUrl() { notificationServer := *s.Config().EmailSettings.PushNotificationServer if strings.HasPrefix(notificationServer, "http://") { mlog.Warn("Your push notification server is configured with HTTP. For improved security, update to HTTPS in your configuration.") } } func runSecurityJob(s *Server) { doSecurity(s) model.CreateRecurringTask("Security", func() { doSecurity(s) }, time.Hour*4) } func runTokenCleanupJob(s *Server) { doTokenCleanup(s) model.CreateRecurringTask("Token Cleanup", func() { doTokenCleanup(s) }, time.Hour*1) } func runCommandWebhookCleanupJob(s *Server) { doCommandWebhookCleanup(s) model.CreateRecurringTask("Command Hook Cleanup", func() { doCommandWebhookCleanup(s) }, time.Hour*1) } func runSessionCleanupJob(s *Server) { doSessionCleanup(s) model.CreateRecurringTask("Session Cleanup", func() { doSessionCleanup(s) }, time.Hour*24) } func runLicenseExpirationCheckJob(a *App) { doLicenseExpirationCheck(a) model.CreateRecurringTask("License Expiration Check", func() { doLicenseExpirationCheck(a) }, time.Hour*24) } func runCheckWarnMetricStatusJob(a *App) { doCheckWarnMetricStatus(a) model.CreateRecurringTask("Check Warn Metric Status Job", func() { doCheckWarnMetricStatus(a) }, time.Hour*model.WARN_METRIC_JOB_INTERVAL) } func doSecurity(s *Server) { s.DoSecurityUpdateCheck() } func doTokenCleanup(s *Server) { s.Store.Token().Cleanup() } func doCommandWebhookCleanup(s *Server) { s.Store.CommandWebhook().Cleanup() } const ( SESSIONS_CLEANUP_BATCH_SIZE = 1000 ) func doSessionCleanup(s *Server) { s.Store.Session().Cleanup(model.GetMillis(), SESSIONS_CLEANUP_BATCH_SIZE) } func doCheckWarnMetricStatus(a *App) { license := a.Srv().License() if license != nil { mlog.Debug("License is present, skip") return } // Get the system fields values from store systemDataList, nErr := a.Srv().Store.System().Get() if nErr != nil { mlog.Error("No system properties obtained", mlog.Err(nErr)) return } warnMetricStatusFromStore := make(map[string]string) for key, value := range systemDataList { if strings.HasPrefix(key, model.WARN_METRIC_STATUS_STORE_PREFIX) { if _, ok := model.WarnMetricsTable[key]; ok { warnMetricStatusFromStore[key] = value if value == model.WARN_METRIC_STATUS_ACK { // If any warn metric has already been acked, we return mlog.Debug("Warn metrics have been acked, skip") return } } } } lastWarnMetricRunTimestamp, err := a.Srv().getLastWarnMetricTimestamp() if err != nil { mlog.Debug("Cannot obtain last advisory run timestamp", mlog.Err(err)) } else { currentTime := utils.MillisFromTime(time.Now()) // If the admin advisory has already been shown in the last 7 days if (currentTime-lastWarnMetricRunTimestamp)/(model.WARN_METRIC_JOB_WAIT_TIME) < 1 { mlog.Debug("No advisories should be shown during the wait interval time") return } } numberOfActiveUsers, err0 := a.Srv().Store.User().Count(model.UserCountOptions{}) if err0 != nil { mlog.Error("Error attempting to get active registered users.", mlog.Err(err0)) } teamCount, err1 := a.Srv().Store.Team().AnalyticsTeamCount(false) if err1 != nil { mlog.Error("Error attempting to get number of teams.", mlog.Err(err1)) } openChannelCount, err2 := a.Srv().Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN) if err2 != nil { mlog.Error("Error attempting to get number of public channels.", mlog.Err(err2)) } // If an account is created with a different email domain // Search for an entry that has an email account different from the current domain // Get domain account from site url localDomainAccount := utils.GetHostnameFromSiteURL(*a.Srv().Config().ServiceSettings.SiteURL) isDiffEmailAccount, err3 := a.Srv().Store.User().AnalyticsGetExternalUsers(localDomainAccount) if err3 != nil { mlog.Error("Error attempting to get number of private channels.", mlog.Err(err3)) } warnMetrics := []model.WarnMetric{} if numberOfActiveUsers < model.WARN_METRIC_NUMBER_OF_ACTIVE_USERS_25 { return } else if teamCount >= model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_TEAMS_5].Limit && warnMetricStatusFromStore[model.SYSTEM_WARN_METRIC_NUMBER_OF_TEAMS_5] != model.WARN_METRIC_STATUS_RUNONCE { warnMetrics = append(warnMetrics, model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_TEAMS_5]) } else if *a.Config().ServiceSettings.EnableMultifactorAuthentication && warnMetricStatusFromStore[model.SYSTEM_WARN_METRIC_MFA] != model.WARN_METRIC_STATUS_RUNONCE { warnMetrics = append(warnMetrics, model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_MFA]) } else if isDiffEmailAccount && warnMetricStatusFromStore[model.SYSTEM_WARN_METRIC_EMAIL_DOMAIN] != model.WARN_METRIC_STATUS_RUNONCE { warnMetrics = append(warnMetrics, model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_EMAIL_DOMAIN]) } else if openChannelCount >= model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_CHANNELS_50].Limit && warnMetricStatusFromStore[model.SYSTEM_WARN_METRIC_NUMBER_OF_CHANNELS_50] != model.WARN_METRIC_STATUS_RUNONCE { warnMetrics = append(warnMetrics, model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_CHANNELS_50]) } // If the system did not cross any of the thresholds for the Contextual Advisories if len(warnMetrics) == 0 { if numberOfActiveUsers >= model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_100].Limit && numberOfActiveUsers < model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_200].Limit && warnMetricStatusFromStore[model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_100] != model.WARN_METRIC_STATUS_RUNONCE { warnMetrics = append(warnMetrics, model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_100]) } else if numberOfActiveUsers >= model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_200].Limit && numberOfActiveUsers < model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_300].Limit && warnMetricStatusFromStore[model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_200] != model.WARN_METRIC_STATUS_RUNONCE { warnMetrics = append(warnMetrics, model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_200]) } else if numberOfActiveUsers >= model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_300].Limit && numberOfActiveUsers < model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_500].Limit && warnMetricStatusFromStore[model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_300] != model.WARN_METRIC_STATUS_RUNONCE { warnMetrics = append(warnMetrics, model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_300]) } else if numberOfActiveUsers >= model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_500].Limit { var tWarnMetric model.WarnMetric if warnMetricStatusFromStore[model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_500] != model.WARN_METRIC_STATUS_RUNONCE { tWarnMetric = model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_500] } postsCount, err4 := a.Srv().Store.Post().AnalyticsPostCount("", false, false) if err4 != nil { mlog.Error("Error attempting to get number of posts.", mlog.Err(err4)) } if postsCount > model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_POSTS_2M].Limit && warnMetricStatusFromStore[model.SYSTEM_WARN_METRIC_NUMBER_OF_POSTS_2M] != model.WARN_METRIC_STATUS_RUNONCE { tWarnMetric = model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_POSTS_2M] } if tWarnMetric != (model.WarnMetric{}) { warnMetrics = append(warnMetrics, tWarnMetric) } } } isE0Edition := model.BuildEnterpriseReady == "true" // license == nil was already validated upstream for _, warnMetric := range warnMetrics { data, nErr := a.Srv().Store.System().GetByName(warnMetric.Id) if nErr == nil && data != nil && warnMetric.IsBotOnly && data.Value == model.WARN_METRIC_STATUS_RUNONCE { mlog.Debug("This metric warning is bot only and ran once") continue } warnMetricStatus, _ := a.getWarnMetricStatusAndDisplayTextsForId(warnMetric.Id, nil, isE0Edition) if !warnMetric.IsBotOnly { // Banner and bot metric types - send websocket event every interval message := model.NewWebSocketEvent(model.WEBSOCKET_WARN_METRIC_STATUS_RECEIVED, "", "", "", nil) message.Add("warnMetricStatus", warnMetricStatus.ToJson()) a.Publish(message) // Banner and bot metric types, send the bot message only once if data != nil && data.Value == model.WARN_METRIC_STATUS_RUNONCE { continue } } if nerr := a.notifyAdminsOfWarnMetricStatus(warnMetric.Id, isE0Edition); nerr != nil { mlog.Error("Failed to send notifications to admin users.", mlog.Err(nerr)) } if warnMetric.IsRunOnce { a.setWarnMetricsStatusForId(warnMetric.Id, model.WARN_METRIC_STATUS_RUNONCE) } else { a.setWarnMetricsStatusForId(warnMetric.Id, model.WARN_METRIC_STATUS_LIMIT_REACHED) } } } func doLicenseExpirationCheck(a *App) { a.Srv().LoadLicense() license := a.Srv().License() if license == nil { mlog.Debug("License cannot be found.") return } if !license.IsPastGracePeriod() { mlog.Debug("License is not past the grace period.") return } users, err := a.Srv().Store.User().GetSystemAdminProfiles() if err != nil { mlog.Error("Failed to get system admins for license expired message from Mattermost.") return } //send email to admin(s) for _, user := range users { user := user if user.Email == "" { mlog.Error("Invalid system admin email.", mlog.String("user_email", user.Email)) continue } mlog.Debug("Sending license expired email.", mlog.String("user_email", user.Email)) a.Srv().Go(func() { if err := a.Srv().EmailService.SendRemoveExpiredLicenseEmail(user.Email, user.Locale, *a.Config().ServiceSettings.SiteURL, license.Id); err != nil { mlog.Error("Error while sending the license expired email.", mlog.String("user_email", user.Email), mlog.Err(err)) } }) } //remove the license a.Srv().RemoveLicense() } func (s *Server) StartSearchEngine() (string, string) { if s.SearchEngine.ElasticsearchEngine != nil && s.SearchEngine.ElasticsearchEngine.IsActive() { s.Go(func() { if err := s.SearchEngine.ElasticsearchEngine.Start(); err != nil { s.Log.Error(err.Error()) } }) } configListenerId := s.AddConfigListener(func(oldConfig *model.Config, newConfig *model.Config) { if s.SearchEngine == nil { return } s.SearchEngine.UpdateConfig(newConfig) if s.SearchEngine.ElasticsearchEngine != nil && !*oldConfig.ElasticsearchSettings.EnableIndexing && *newConfig.ElasticsearchSettings.EnableIndexing { s.Go(func() { if err := s.SearchEngine.ElasticsearchEngine.Start(); err != nil { mlog.Error(err.Error()) } }) } else if s.SearchEngine.ElasticsearchEngine != nil && *oldConfig.ElasticsearchSettings.EnableIndexing && !*newConfig.ElasticsearchSettings.EnableIndexing { s.Go(func() { if err := s.SearchEngine.ElasticsearchEngine.Stop(); err != nil { mlog.Error(err.Error()) } }) } else if s.SearchEngine.ElasticsearchEngine != nil && *oldConfig.ElasticsearchSettings.Password != *newConfig.ElasticsearchSettings.Password || *oldConfig.ElasticsearchSettings.Username != *newConfig.ElasticsearchSettings.Username || *oldConfig.ElasticsearchSettings.ConnectionUrl != *newConfig.ElasticsearchSettings.ConnectionUrl || *oldConfig.ElasticsearchSettings.Sniff != *newConfig.ElasticsearchSettings.Sniff { s.Go(func() { if *oldConfig.ElasticsearchSettings.EnableIndexing { if err := s.SearchEngine.ElasticsearchEngine.Stop(); err != nil { mlog.Error(err.Error()) } if err := s.SearchEngine.ElasticsearchEngine.Start(); err != nil { mlog.Error(err.Error()) } } }) } }) licenseListenerId := s.AddLicenseListener(func(oldLicense, newLicense *model.License) { if s.SearchEngine == nil { return } if oldLicense == nil && newLicense != nil { if s.SearchEngine.ElasticsearchEngine != nil && s.SearchEngine.ElasticsearchEngine.IsActive() { s.Go(func() { if err := s.SearchEngine.ElasticsearchEngine.Start(); err != nil { mlog.Error(err.Error()) } }) } } else if oldLicense != nil && newLicense == nil { if s.SearchEngine.ElasticsearchEngine != nil { s.Go(func() { if err := s.SearchEngine.ElasticsearchEngine.Stop(); err != nil { mlog.Error(err.Error()) } }) } } }) return configListenerId, licenseListenerId } func (s *Server) stopSearchEngine() { s.RemoveConfigListener(s.searchConfigListenerId) s.RemoveLicenseListener(s.searchLicenseListenerId) if s.SearchEngine != nil && s.SearchEngine.ElasticsearchEngine != nil && s.SearchEngine.ElasticsearchEngine.IsActive() { s.SearchEngine.ElasticsearchEngine.Stop() } if s.SearchEngine != nil && s.SearchEngine.BleveEngine != nil && s.SearchEngine.BleveEngine.IsActive() { s.SearchEngine.BleveEngine.Stop() } } func (s *Server) FileBackend() (filesstore.FileBackend, *model.AppError) { license := s.License() return filesstore.NewFileBackend(&s.Config().FileSettings, license != nil && *license.Features.Compliance) } func (s *Server) TotalWebsocketConnections() int { // This method is only called after the hub is initialized. // Therefore, no mutex is needed to protect s.hubs. count := int64(0) for _, hub := range s.hubs { count = count + atomic.LoadInt64(&hub.connectionCount) } return int(count) } func (s *Server) ClusterHealthScore() int { return s.Cluster.HealthScore() } func (s *Server) configOrLicenseListener() { s.regenerateClientConfig() } func (s *Server) ClientConfigHash() string { return s.clientConfigHash.Load().(string) } func (s *Server) initJobs() { s.Jobs = jobs.NewJobServer(s, s.Store) if jobsDataRetentionJobInterface != nil { s.Jobs.DataRetentionJob = jobsDataRetentionJobInterface(s) } if jobsMessageExportJobInterface != nil { s.Jobs.MessageExportJob = jobsMessageExportJobInterface(s) } if jobsElasticsearchAggregatorInterface != nil { s.Jobs.ElasticsearchAggregator = jobsElasticsearchAggregatorInterface(s) } if jobsElasticsearchIndexerInterface != nil { s.Jobs.ElasticsearchIndexer = jobsElasticsearchIndexerInterface(s) } if jobsBleveIndexerInterface != nil { s.Jobs.BleveIndexer = jobsBleveIndexerInterface(s) } if jobsMigrationsInterface != nil { s.Jobs.Migrations = jobsMigrationsInterface(s) } } func (s *Server) TelemetryId() string { if s.telemetryService == nil { return "" } return s.telemetryService.TelemetryID } func (s *Server) HttpService() httpservice.HTTPService { return s.HTTPService }
{ "pile_set_name": "Github" }
<?xml version="1.0"?> <doc> <assembly> <name>Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions</name> </assembly> <members> <member name="T:Microsoft.VisualStudio.TestTools.UnitTesting.AppContainer.UITestMethodAttribute"> <summary> Execute test code in UI thread for Windows store apps. </summary> </member> <member name="M:Microsoft.VisualStudio.TestTools.UnitTesting.AppContainer.UITestMethodAttribute.Execute(Microsoft.VisualStudio.TestTools.UnitTesting.ITestMethod)"> <summary> Executes the test method on the UI Thread. </summary> <param name="testMethod"> The test method. </param> <returns> The <see cref="!:TestResult[]"/>. </returns> Throws <exception cref="T:System.NotSupportedException"> when run on an async test method. </exception> </member> <member name="T:Microsoft.VisualStudio.TestTools.UnitTesting.TestContext"> <summary> TestContext class. This class should be fully abstract and not contain any members. The adapter will implement the members. Users in the framework should only access this via a well-defined interface. </summary> </member> <member name="P:Microsoft.VisualStudio.TestTools.UnitTesting.TestContext.Properties"> <summary> Gets test properties for a test. </summary> <value></value> </member> <member name="P:Microsoft.VisualStudio.TestTools.UnitTesting.TestContext.FullyQualifiedTestClassName"> <summary> Gets Fully-qualified name of the class containing the test method currently being executed </summary> <remarks> This property can be useful in attributes derived from ExpectedExceptionBaseAttribute. Those attributes have access to the test context, and provide messages that are included in the test results. Users can benefit from messages that include the fully-qualified class name in addition to the name of the test method currently being executed. </remarks> </member> <member name="P:Microsoft.VisualStudio.TestTools.UnitTesting.TestContext.TestName"> <summary> Gets the Name of the test method currently being executed </summary> </member> <member name="P:Microsoft.VisualStudio.TestTools.UnitTesting.TestContext.CurrentTestOutcome"> <summary> Gets the current test outcome. </summary> </member> </members> </doc>
{ "pile_set_name": "Github" }
// This file is based on the following file from the LZMA SDK (http://www.7-zip.org/sdk.html): // ./CPP/7zip/Guid.txt #pragma once #include "../CPP/Common/MyCom.h" namespace SevenZip { namespace intl { // IStream.h // {23170F69-40C1-278A-0000-000300010000} DEFINE_GUID(IID_ISequentialInStream, 0x23170F69, 0x40C1, 0x278A, 0x00, 0x00, 0x00, 0x03, 0x00, 0x01, 0x00, 0x00); // {23170F69-40C1-278A-0000-000300010000} DEFINE_GUID(IID_ISequentialOutStream, 0x23170F69, 0x40C1, 0x278A, 0x00, 0x00, 0x00, 0x03, 0x00, 0x02, 0x00, 0x00); // {23170F69-40C1-278A-0000-000300030000} DEFINE_GUID(IID_IInStream, 0x23170F69, 0x40C1, 0x278A, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00); // {23170F69-40C1-278A-0000-000300040000} DEFINE_GUID(IID_IOutStream, 0x23170F69, 0x40C1, 0x278A, 0x00, 0x00, 0x00, 0x03, 0x00, 0x04, 0x00, 0x00); // {23170F69-40C1-278A-0000-000300060000} DEFINE_GUID(IID_IStreamGetSize, 0x23170F69, 0x40C1, 0x278A, 0x00, 0x00, 0x00, 0x03, 0x00, 0x06, 0x00, 0x00); // ICoder.h // {23170F69-40C1-278A-0000-000400040000} DEFINE_GUID(IID_ICompressProgressInfo, 0x23170F69, 0x40C1, 0x278A, 0x00, 0x00, 0x00, 0x04, 0x00, 0x04, 0x00, 0x00); // IPassword.h // {23170F69-40C1-278A-0000-000500100000} DEFINE_GUID(IID_ICryptoGetTextPassword, 0x23170F69, 0x40C1, 0x278A, 0x00, 0x00, 0x00, 0x05, 0x00, 0x10, 0x00, 0x00); // {23170F69-40C1-278A-0000-000500110000} DEFINE_GUID(IID_ICryptoGetTextPassword2, 0x23170F69, 0x40C1, 0x278A, 0x00, 0x00, 0x00, 0x05, 0x00, 0x11, 0x00, 0x00); // IArchive.h // {23170F69-40C1-278A-0000-000600030000} DEFINE_GUID(IID_ISetProperties, 0x23170F69, 0x40C1, 0x278A, 0x00, 0x00, 0x00, 0x06, 0x00, 0x03, 0x00, 0x00); // {23170F69-40C1-278A-0000-000600100000} DEFINE_GUID(IID_IArchiveOpenCallback, 0x23170F69, 0x40C1, 0x278A, 0x00, 0x00, 0x00, 0x06, 0x00, 0x10, 0x00, 0x00); // {23170F69-40C1-278A-0000-000600200000} DEFINE_GUID(IID_IArchiveExtractCallback, 0x23170F69, 0x40C1, 0x278A, 0x00, 0x00, 0x00, 0x06, 0x00, 0x20, 0x00, 0x00); // {23170F69-40C1-278A-0000-000600600000} DEFINE_GUID(IID_IInArchive, 0x23170F69, 0x40C1, 0x278A, 0x00, 0x00, 0x00, 0x06, 0x00, 0x60, 0x00, 0x00); // {23170F69-40C1-278A-0000-000600800000} DEFINE_GUID(IID_IArchiveUpdateCallback, 0x23170F69, 0x40C1, 0x278A, 0x00, 0x00, 0x00, 0x06, 0x00, 0x80, 0x00, 0x00); // {23170F69-40C1-278A-0000-000600820000} DEFINE_GUID(IID_IArchiveUpdateCallback2, 0x23170F69, 0x40C1, 0x278A, 0x00, 0x00, 0x00, 0x06, 0x00, 0x82, 0x00, 0x00); // {23170F69-40C1-278A-0000-000600A00000} DEFINE_GUID(IID_IOutArchive, 0x23170F69, 0x40C1, 0x278A, 0x00, 0x00, 0x00, 0x06, 0x00, 0xA0, 0x00, 0x00); // Handler GUIDs // {23170F69-40C1-278A-1000-000110010000} DEFINE_GUID(CLSID_CFormatZip, 0x23170F69, 0x40C1, 0x278A, 0x10, 0x00, 0x00, 0x01, 0x10, 0x01, 0x00, 0x00); // {23170F69-40C1-278A-1000-000110020000} DEFINE_GUID(CLSID_CFormatBZip2, 0x23170F69, 0x40C1, 0x278A, 0x10, 0x00, 0x00, 0x01, 0x10, 0x02, 0x00, 0x00); // {23170F69-40C1-278A-1000-000110030000} DEFINE_GUID(CLSID_CFormatRar, 0x23170F69, 0x40C1, 0x278A, 0x10, 0x00, 0x00, 0x01, 0x10, 0x03, 0x00, 0x00); // {23170F69-40C1-278A-1000-000110070000} DEFINE_GUID(CLSID_CFormat7z, 0x23170F69, 0x40C1, 0x278A, 0x10, 0x00, 0x00, 0x01, 0x10, 0x07, 0x00, 0x00); // {23170F69-40C1-278A-1000-000110080000} DEFINE_GUID(CLSID_CFormatCab, 0x23170F69, 0x40C1, 0x278A, 0x10, 0x00, 0x00, 0x01, 0x10, 0x08, 0x00, 0x00); // {23170F69-40C1-278A-1000-0001100A0000} DEFINE_GUID(CLSID_CFormatLzma, 0x23170F69, 0x40C1, 0x278A, 0x10, 0x00, 0x00, 0x01, 0x10, 0x0A, 0x00, 0x00); // {23170F69-40C1-278A-1000-0001100B0000} DEFINE_GUID(CLSID_CFormatLzma86, 0x23170F69, 0x40C1, 0x278A, 0x10, 0x00, 0x00, 0x01, 0x10, 0x0B, 0x00, 0x00); // {23170F69-40C1-278A-1000-000110E70000} DEFINE_GUID(CLSID_CFormatIso, 0x23170F69, 0x40C1, 0x278A, 0x10, 0x00, 0x00, 0x01, 0x10, 0xE7, 0x00, 0x00); // {23170F69-40C1-278A-1000-000110EE0000} DEFINE_GUID(CLSID_CFormatTar, 0x23170F69, 0x40C1, 0x278A, 0x10, 0x00, 0x00, 0x01, 0x10, 0xEE, 0x00, 0x00); // {23170F69-40C1-278A-1000-000110EF0000} DEFINE_GUID(CLSID_CFormatGZip, 0x23170F69, 0x40C1, 0x278A, 0x10, 0x00, 0x00, 0x01, 0x10, 0xEF, 0x00, 0x00); } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CFBundleDevelopmentRegion</key> <string>en</string> <key>CFBundleExecutable</key> <string>$(EXECUTABLE_NAME)</string> <key>CFBundleIdentifier</key> <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>$(PRODUCT_NAME)</string> <key>CFBundlePackageType</key> <string>APPL</string> <key>CFBundleShortVersionString</key> <string>1.0</string> <key>CFBundleSignature</key> <string>????</string> <key>CFBundleVersion</key> <string>1</string> <key>LSRequiresIPhoneOS</key> <true/> <key>UILaunchStoryboardName</key> <string>LaunchScreen</string> <key>UIMainStoryboardFile</key> <string>Main</string> <key>UIRequiredDeviceCapabilities</key> <array> <string>armv7</string> </array> <key>UISupportedInterfaceOrientations</key> <array> <string>UIInterfaceOrientationPortrait</string> <string>UIInterfaceOrientationLandscapeLeft</string> <string>UIInterfaceOrientationLandscapeRight</string> </array> </dict> </plist>
{ "pile_set_name": "Github" }
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2016 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Sébastien Deronne <[email protected]> */ #ifndef WIFI_UTILS_H #define WIFI_UTILS_H #include "block-ack-type.h" namespace ns3 { class WifiMacHeader; class WifiMode; class Packet; class Time; /** * Convert from dBm to Watts. * * \param dbm the power in dBm * * \return the equivalent Watts for the given dBm */ double DbmToW (double dbm); /** * Convert from dB to ratio. * * \param db * * \return ratio */ double DbToRatio (double db); /** * Convert from Watts to dBm. * * \param w the power in Watts * * \return the equivalent dBm for the given Watts */ double WToDbm (double w); /** * Convert from ratio to dB. * * \param ratio * * \return dB */ double RatioToDb (double ratio); /** * \param frequency the frequency to check * \return whether frequency is in the 2.4 GHz band */ bool Is2_4Ghz (double frequency); /** * \param frequency the frequency to check * \return whether frequency is in the 5 GHz band */ bool Is5Ghz (double frequency); /** * Convert the guard interval to nanoseconds based on the wifimode. * * \param mode the wifimode * \param htShortGuardInterval whether HT/VHT short guard interval is enabled * \param heGuardInterval the HE guard interval duration * * \return the guard interval duration in nanoseconds */ uint16_t ConvertGuardIntervalToNanoSeconds (WifiMode mode, bool htShortGuardInterval, Time heGuardInterval); /** * Return the total ACK size (including FCS trailer). * * \return the total ACK size */ uint32_t GetAckSize (void); /** * Return the total Block ACK size (including FCS trailer). * * \param type the Block ACK type * \return the total Block ACK size */ uint32_t GetBlockAckSize (BlockAckType type); /** * Return the total RTS size (including FCS trailer). * * \return the total RTS size */ uint32_t GetRtsSize (void); /** * Return the total CTS size (including FCS trailer). * * \return the total CTS size */ uint32_t GetCtsSize (void); /** * \param seq MPDU sequence number * \param winstart sequence number window start * \param winsize the size of the sequence number window (currently default is 64) * \returns true if in the window * * This method checks if the MPDU's sequence number is inside the scoreboard boundaries or not */ bool IsInWindow (uint16_t seq, uint16_t winstart, uint16_t winsize); /** * Add FCS trailer to a packet. * * \param packet */ void AddWifiMacTrailer (Ptr<Packet> packet); /** * Return the total size of the packet after WifiMacHeader and FCS trailer * have been added. * * \param packet the packet to be encapsulated with WifiMacHeader and FCS trailer * \param hdr the WifiMacHeader * \param isAmpdu whether packet is part of an A-MPDU * \return the total packet size */ uint32_t GetSize (Ptr<const Packet> packet, const WifiMacHeader *hdr, bool isAmpdu); } // namespace ns3 #endif /* WIFI_UTILS_H */
{ "pile_set_name": "Github" }
/* * Copyright 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include <memory> #include "absl/memory/memory.h" #include "api/audio_codecs/L16/audio_decoder_L16.h" #include "api/audio_codecs/L16/audio_encoder_L16.h" #include "api/audio_codecs/audio_codec_pair_id.h" #include "api/audio_codecs/audio_decoder_factory_template.h" #include "api/audio_codecs/audio_encoder_factory_template.h" #include "api/audio_codecs/builtin_audio_decoder_factory.h" #include "api/audio_codecs/builtin_audio_encoder_factory.h" #include "rtc_base/gunit.h" #include "rtc_base/logging.h" #include "rtc_base/stringencode.h" #include "rtc_base/stringutils.h" #ifdef WEBRTC_ANDROID #include "pc/test/androidtestinitializer.h" #endif #include "pc/test/peerconnectiontestwrapper.h" // Notice that mockpeerconnectionobservers.h must be included after the above! #include "pc/test/mockpeerconnectionobservers.h" #include "test/mock_audio_decoder.h" #include "test/mock_audio_decoder_factory.h" using testing::AtLeast; using testing::Invoke; using testing::StrictMock; using testing::Values; using testing::_; using webrtc::DataChannelInterface; using webrtc::FakeConstraints; using webrtc::MediaConstraintsInterface; using webrtc::MediaStreamInterface; using webrtc::PeerConnectionInterface; using webrtc::SdpSemantics; namespace { const int kMaxWait = 25000; } // namespace class PeerConnectionEndToEndBaseTest : public sigslot::has_slots<>, public testing::Test { public: typedef std::vector<rtc::scoped_refptr<DataChannelInterface>> DataChannelList; explicit PeerConnectionEndToEndBaseTest(SdpSemantics sdp_semantics) { network_thread_ = rtc::Thread::CreateWithSocketServer(); worker_thread_ = rtc::Thread::Create(); RTC_CHECK(network_thread_->Start()); RTC_CHECK(worker_thread_->Start()); caller_ = new rtc::RefCountedObject<PeerConnectionTestWrapper>( "caller", network_thread_.get(), worker_thread_.get()); callee_ = new rtc::RefCountedObject<PeerConnectionTestWrapper>( "callee", network_thread_.get(), worker_thread_.get()); webrtc::PeerConnectionInterface::IceServer ice_server; ice_server.uri = "stun:stun.l.google.com:19302"; config_.servers.push_back(ice_server); config_.sdp_semantics = sdp_semantics; #ifdef WEBRTC_ANDROID webrtc::InitializeAndroidObjects(); #endif } void CreatePcs( const MediaConstraintsInterface* pc_constraints, rtc::scoped_refptr<webrtc::AudioEncoderFactory> audio_encoder_factory1, rtc::scoped_refptr<webrtc::AudioDecoderFactory> audio_decoder_factory1, rtc::scoped_refptr<webrtc::AudioEncoderFactory> audio_encoder_factory2, rtc::scoped_refptr<webrtc::AudioDecoderFactory> audio_decoder_factory2) { EXPECT_TRUE(caller_->CreatePc(pc_constraints, config_, audio_encoder_factory1, audio_decoder_factory1)); EXPECT_TRUE(callee_->CreatePc(pc_constraints, config_, audio_encoder_factory2, audio_decoder_factory2)); PeerConnectionTestWrapper::Connect(caller_.get(), callee_.get()); caller_->SignalOnDataChannel.connect( this, &PeerConnectionEndToEndBaseTest::OnCallerAddedDataChanel); callee_->SignalOnDataChannel.connect( this, &PeerConnectionEndToEndBaseTest::OnCalleeAddedDataChannel); } void CreatePcs( const MediaConstraintsInterface* pc_constraints, rtc::scoped_refptr<webrtc::AudioEncoderFactory> audio_encoder_factory, rtc::scoped_refptr<webrtc::AudioDecoderFactory> audio_decoder_factory) { CreatePcs(pc_constraints, audio_encoder_factory, audio_decoder_factory, audio_encoder_factory, audio_decoder_factory); } void GetAndAddUserMedia() { cricket::AudioOptions audio_options; FakeConstraints video_constraints; GetAndAddUserMedia(true, audio_options, true, video_constraints); } void GetAndAddUserMedia(bool audio, const cricket::AudioOptions& audio_options, bool video, const FakeConstraints& video_constraints) { caller_->GetAndAddUserMedia(audio, audio_options, video, video_constraints); callee_->GetAndAddUserMedia(audio, audio_options, video, video_constraints); } void Negotiate() { caller_->CreateOffer(NULL); } void WaitForCallEstablished() { caller_->WaitForCallEstablished(); callee_->WaitForCallEstablished(); } void WaitForConnection() { caller_->WaitForConnection(); callee_->WaitForConnection(); } void OnCallerAddedDataChanel(DataChannelInterface* dc) { caller_signaled_data_channels_.push_back(dc); } void OnCalleeAddedDataChannel(DataChannelInterface* dc) { callee_signaled_data_channels_.push_back(dc); } // Tests that |dc1| and |dc2| can send to and receive from each other. void TestDataChannelSendAndReceive(DataChannelInterface* dc1, DataChannelInterface* dc2, size_t size = 6) { std::unique_ptr<webrtc::MockDataChannelObserver> dc1_observer( new webrtc::MockDataChannelObserver(dc1)); std::unique_ptr<webrtc::MockDataChannelObserver> dc2_observer( new webrtc::MockDataChannelObserver(dc2)); static const std::string kDummyData = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; webrtc::DataBuffer buffer(""); size_t sizeLeft = size; while (sizeLeft > 0) { size_t chunkSize = sizeLeft > kDummyData.length() ? kDummyData.length() : sizeLeft; buffer.data.AppendData(kDummyData.data(), chunkSize); sizeLeft -= chunkSize; } EXPECT_TRUE(dc1->Send(buffer)); EXPECT_EQ_WAIT(buffer.data, rtc::CopyOnWriteBuffer(dc2_observer->last_message()), kMaxWait); EXPECT_TRUE(dc2->Send(buffer)); EXPECT_EQ_WAIT(buffer.data, rtc::CopyOnWriteBuffer(dc1_observer->last_message()), kMaxWait); EXPECT_EQ(1U, dc1_observer->received_message_count()); EXPECT_EQ(size, dc1_observer->last_message().length()); EXPECT_EQ(1U, dc2_observer->received_message_count()); EXPECT_EQ(size, dc2_observer->last_message().length()); } void WaitForDataChannelsToOpen(DataChannelInterface* local_dc, const DataChannelList& remote_dc_list, size_t remote_dc_index) { EXPECT_EQ_WAIT(DataChannelInterface::kOpen, local_dc->state(), kMaxWait); ASSERT_TRUE_WAIT(remote_dc_list.size() > remote_dc_index, kMaxWait); EXPECT_EQ_WAIT(DataChannelInterface::kOpen, remote_dc_list[remote_dc_index]->state(), kMaxWait); EXPECT_EQ(local_dc->id(), remote_dc_list[remote_dc_index]->id()); } void CloseDataChannels(DataChannelInterface* local_dc, const DataChannelList& remote_dc_list, size_t remote_dc_index) { local_dc->Close(); EXPECT_EQ_WAIT(DataChannelInterface::kClosed, local_dc->state(), kMaxWait); EXPECT_EQ_WAIT(DataChannelInterface::kClosed, remote_dc_list[remote_dc_index]->state(), kMaxWait); } protected: std::unique_ptr<rtc::Thread> network_thread_; std::unique_ptr<rtc::Thread> worker_thread_; rtc::scoped_refptr<PeerConnectionTestWrapper> caller_; rtc::scoped_refptr<PeerConnectionTestWrapper> callee_; DataChannelList caller_signaled_data_channels_; DataChannelList callee_signaled_data_channels_; webrtc::PeerConnectionInterface::RTCConfiguration config_; }; class PeerConnectionEndToEndTest : public PeerConnectionEndToEndBaseTest, public ::testing::WithParamInterface<SdpSemantics> { protected: PeerConnectionEndToEndTest() : PeerConnectionEndToEndBaseTest(GetParam()) {} }; namespace { std::unique_ptr<webrtc::AudioDecoder> CreateForwardingMockDecoder( std::unique_ptr<webrtc::AudioDecoder> real_decoder) { class ForwardingMockDecoder : public StrictMock<webrtc::MockAudioDecoder> { public: explicit ForwardingMockDecoder(std::unique_ptr<AudioDecoder> decoder) : decoder_(std::move(decoder)) {} private: std::unique_ptr<AudioDecoder> decoder_; }; const auto dec = real_decoder.get(); // For lambda capturing. auto mock_decoder = absl::make_unique<ForwardingMockDecoder>(std::move(real_decoder)); EXPECT_CALL(*mock_decoder, Channels()) .Times(AtLeast(1)) .WillRepeatedly(Invoke([dec] { return dec->Channels(); })); EXPECT_CALL(*mock_decoder, DecodeInternal(_, _, _, _, _)) .Times(AtLeast(1)) .WillRepeatedly( Invoke([dec](const uint8_t* encoded, size_t encoded_len, int sample_rate_hz, int16_t* decoded, webrtc::AudioDecoder::SpeechType* speech_type) { return dec->Decode(encoded, encoded_len, sample_rate_hz, std::numeric_limits<size_t>::max(), decoded, speech_type); })); EXPECT_CALL(*mock_decoder, Die()); EXPECT_CALL(*mock_decoder, HasDecodePlc()).WillRepeatedly(Invoke([dec] { return dec->HasDecodePlc(); })); EXPECT_CALL(*mock_decoder, IncomingPacket(_, _, _, _, _)) .Times(AtLeast(1)) .WillRepeatedly(Invoke([dec](const uint8_t* payload, size_t payload_len, uint16_t rtp_sequence_number, uint32_t rtp_timestamp, uint32_t arrival_timestamp) { return dec->IncomingPacket(payload, payload_len, rtp_sequence_number, rtp_timestamp, arrival_timestamp); })); EXPECT_CALL(*mock_decoder, PacketDuration(_, _)) .Times(AtLeast(1)) .WillRepeatedly(Invoke([dec](const uint8_t* encoded, size_t encoded_len) { return dec->PacketDuration(encoded, encoded_len); })); EXPECT_CALL(*mock_decoder, SampleRateHz()) .Times(AtLeast(1)) .WillRepeatedly(Invoke([dec] { return dec->SampleRateHz(); })); return std::move(mock_decoder); } rtc::scoped_refptr<webrtc::AudioDecoderFactory> CreateForwardingMockDecoderFactory( webrtc::AudioDecoderFactory* real_decoder_factory) { rtc::scoped_refptr<webrtc::MockAudioDecoderFactory> mock_decoder_factory = new rtc::RefCountedObject<StrictMock<webrtc::MockAudioDecoderFactory>>; EXPECT_CALL(*mock_decoder_factory, GetSupportedDecoders()) .Times(AtLeast(1)) .WillRepeatedly(Invoke([real_decoder_factory] { return real_decoder_factory->GetSupportedDecoders(); })); EXPECT_CALL(*mock_decoder_factory, IsSupportedDecoder(_)) .Times(AtLeast(1)) .WillRepeatedly( Invoke([real_decoder_factory](const webrtc::SdpAudioFormat& format) { return real_decoder_factory->IsSupportedDecoder(format); })); EXPECT_CALL(*mock_decoder_factory, MakeAudioDecoderMock(_, _, _)) .Times(AtLeast(2)) .WillRepeatedly( Invoke([real_decoder_factory]( const webrtc::SdpAudioFormat& format, absl::optional<webrtc::AudioCodecPairId> codec_pair_id, std::unique_ptr<webrtc::AudioDecoder>* return_value) { auto real_decoder = real_decoder_factory->MakeAudioDecoder(format, codec_pair_id); *return_value = real_decoder ? CreateForwardingMockDecoder(std::move(real_decoder)) : nullptr; })); return mock_decoder_factory; } struct AudioEncoderUnicornSparklesRainbow { using Config = webrtc::AudioEncoderL16::Config; static absl::optional<Config> SdpToConfig(webrtc::SdpAudioFormat format) { if (STR_CASE_CMP(format.name.c_str(), "UnicornSparklesRainbow") == 0) { const webrtc::SdpAudioFormat::Parameters expected_params = { {"num_horns", "1"}}; EXPECT_EQ(expected_params, format.parameters); format.parameters.clear(); format.name = "L16"; return webrtc::AudioEncoderL16::SdpToConfig(format); } else { return absl::nullopt; } } static void AppendSupportedEncoders( std::vector<webrtc::AudioCodecSpec>* specs) { std::vector<webrtc::AudioCodecSpec> new_specs; webrtc::AudioEncoderL16::AppendSupportedEncoders(&new_specs); for (auto& spec : new_specs) { spec.format.name = "UnicornSparklesRainbow"; EXPECT_TRUE(spec.format.parameters.empty()); spec.format.parameters.emplace("num_horns", "1"); specs->push_back(spec); } } static webrtc::AudioCodecInfo QueryAudioEncoder(const Config& config) { return webrtc::AudioEncoderL16::QueryAudioEncoder(config); } static std::unique_ptr<webrtc::AudioEncoder> MakeAudioEncoder( const Config& config, int payload_type, absl::optional<webrtc::AudioCodecPairId> codec_pair_id = absl::nullopt) { return webrtc::AudioEncoderL16::MakeAudioEncoder(config, payload_type, codec_pair_id); } }; struct AudioDecoderUnicornSparklesRainbow { using Config = webrtc::AudioDecoderL16::Config; static absl::optional<Config> SdpToConfig(webrtc::SdpAudioFormat format) { if (STR_CASE_CMP(format.name.c_str(), "UnicornSparklesRainbow") == 0) { const webrtc::SdpAudioFormat::Parameters expected_params = { {"num_horns", "1"}}; EXPECT_EQ(expected_params, format.parameters); format.parameters.clear(); format.name = "L16"; return webrtc::AudioDecoderL16::SdpToConfig(format); } else { return absl::nullopt; } } static void AppendSupportedDecoders( std::vector<webrtc::AudioCodecSpec>* specs) { std::vector<webrtc::AudioCodecSpec> new_specs; webrtc::AudioDecoderL16::AppendSupportedDecoders(&new_specs); for (auto& spec : new_specs) { spec.format.name = "UnicornSparklesRainbow"; EXPECT_TRUE(spec.format.parameters.empty()); spec.format.parameters.emplace("num_horns", "1"); specs->push_back(spec); } } static std::unique_ptr<webrtc::AudioDecoder> MakeAudioDecoder( const Config& config, absl::optional<webrtc::AudioCodecPairId> codec_pair_id = absl::nullopt) { return webrtc::AudioDecoderL16::MakeAudioDecoder(config, codec_pair_id); } }; } // namespace TEST_P(PeerConnectionEndToEndTest, Call) { rtc::scoped_refptr<webrtc::AudioDecoderFactory> real_decoder_factory = webrtc::CreateBuiltinAudioDecoderFactory(); CreatePcs(nullptr, webrtc::CreateBuiltinAudioEncoderFactory(), CreateForwardingMockDecoderFactory(real_decoder_factory.get())); GetAndAddUserMedia(); Negotiate(); WaitForCallEstablished(); } TEST_P(PeerConnectionEndToEndTest, CallWithLegacySdp) { FakeConstraints pc_constraints; pc_constraints.AddMandatory(MediaConstraintsInterface::kEnableDtlsSrtp, false); CreatePcs(&pc_constraints, webrtc::CreateBuiltinAudioEncoderFactory(), webrtc::CreateBuiltinAudioDecoderFactory()); GetAndAddUserMedia(); Negotiate(); WaitForCallEstablished(); } TEST_P(PeerConnectionEndToEndTest, CallWithCustomCodec) { class IdLoggingAudioEncoderFactory : public webrtc::AudioEncoderFactory { public: IdLoggingAudioEncoderFactory( rtc::scoped_refptr<AudioEncoderFactory> real_factory, std::vector<webrtc::AudioCodecPairId>* const codec_ids) : fact_(real_factory), codec_ids_(codec_ids) {} std::vector<webrtc::AudioCodecSpec> GetSupportedEncoders() override { return fact_->GetSupportedEncoders(); } absl::optional<webrtc::AudioCodecInfo> QueryAudioEncoder( const webrtc::SdpAudioFormat& format) override { return fact_->QueryAudioEncoder(format); } std::unique_ptr<webrtc::AudioEncoder> MakeAudioEncoder( int payload_type, const webrtc::SdpAudioFormat& format, absl::optional<webrtc::AudioCodecPairId> codec_pair_id) override { EXPECT_TRUE(codec_pair_id.has_value()); codec_ids_->push_back(*codec_pair_id); return fact_->MakeAudioEncoder(payload_type, format, codec_pair_id); } private: const rtc::scoped_refptr<webrtc::AudioEncoderFactory> fact_; std::vector<webrtc::AudioCodecPairId>* const codec_ids_; }; class IdLoggingAudioDecoderFactory : public webrtc::AudioDecoderFactory { public: IdLoggingAudioDecoderFactory( rtc::scoped_refptr<AudioDecoderFactory> real_factory, std::vector<webrtc::AudioCodecPairId>* const codec_ids) : fact_(real_factory), codec_ids_(codec_ids) {} std::vector<webrtc::AudioCodecSpec> GetSupportedDecoders() override { return fact_->GetSupportedDecoders(); } bool IsSupportedDecoder(const webrtc::SdpAudioFormat& format) override { return fact_->IsSupportedDecoder(format); } std::unique_ptr<webrtc::AudioDecoder> MakeAudioDecoder( const webrtc::SdpAudioFormat& format, absl::optional<webrtc::AudioCodecPairId> codec_pair_id) override { EXPECT_TRUE(codec_pair_id.has_value()); codec_ids_->push_back(*codec_pair_id); return fact_->MakeAudioDecoder(format, codec_pair_id); } private: const rtc::scoped_refptr<webrtc::AudioDecoderFactory> fact_; std::vector<webrtc::AudioCodecPairId>* const codec_ids_; }; std::vector<webrtc::AudioCodecPairId> encoder_id1, encoder_id2, decoder_id1, decoder_id2; CreatePcs(nullptr, rtc::scoped_refptr<webrtc::AudioEncoderFactory>( new rtc::RefCountedObject<IdLoggingAudioEncoderFactory>( webrtc::CreateAudioEncoderFactory< AudioEncoderUnicornSparklesRainbow>(), &encoder_id1)), rtc::scoped_refptr<webrtc::AudioDecoderFactory>( new rtc::RefCountedObject<IdLoggingAudioDecoderFactory>( webrtc::CreateAudioDecoderFactory< AudioDecoderUnicornSparklesRainbow>(), &decoder_id1)), rtc::scoped_refptr<webrtc::AudioEncoderFactory>( new rtc::RefCountedObject<IdLoggingAudioEncoderFactory>( webrtc::CreateAudioEncoderFactory< AudioEncoderUnicornSparklesRainbow>(), &encoder_id2)), rtc::scoped_refptr<webrtc::AudioDecoderFactory>( new rtc::RefCountedObject<IdLoggingAudioDecoderFactory>( webrtc::CreateAudioDecoderFactory< AudioDecoderUnicornSparklesRainbow>(), &decoder_id2))); GetAndAddUserMedia(); Negotiate(); WaitForCallEstablished(); // Each codec factory has been used to create one codec. The first pair got // the same ID because they were passed to the same PeerConnectionFactory, // and the second pair got the same ID---but these two IDs are not equal, // because each PeerConnectionFactory has its own ID. EXPECT_EQ(1U, encoder_id1.size()); EXPECT_EQ(1U, encoder_id2.size()); EXPECT_EQ(encoder_id1, decoder_id1); EXPECT_EQ(encoder_id2, decoder_id2); EXPECT_NE(encoder_id1, encoder_id2); } #ifdef HAVE_SCTP // Verifies that a DataChannel created before the negotiation can transition to // "OPEN" and transfer data. TEST_P(PeerConnectionEndToEndTest, CreateDataChannelBeforeNegotiate) { CreatePcs(nullptr, webrtc::CreateBuiltinAudioEncoderFactory(), webrtc::MockAudioDecoderFactory::CreateEmptyFactory()); webrtc::DataChannelInit init; rtc::scoped_refptr<DataChannelInterface> caller_dc( caller_->CreateDataChannel("data", init)); rtc::scoped_refptr<DataChannelInterface> callee_dc( callee_->CreateDataChannel("data", init)); Negotiate(); WaitForConnection(); WaitForDataChannelsToOpen(caller_dc, callee_signaled_data_channels_, 0); WaitForDataChannelsToOpen(callee_dc, caller_signaled_data_channels_, 0); TestDataChannelSendAndReceive(caller_dc, callee_signaled_data_channels_[0]); TestDataChannelSendAndReceive(callee_dc, caller_signaled_data_channels_[0]); CloseDataChannels(caller_dc, callee_signaled_data_channels_, 0); CloseDataChannels(callee_dc, caller_signaled_data_channels_, 0); } // Verifies that a DataChannel created after the negotiation can transition to // "OPEN" and transfer data. TEST_P(PeerConnectionEndToEndTest, CreateDataChannelAfterNegotiate) { CreatePcs(nullptr, webrtc::CreateBuiltinAudioEncoderFactory(), webrtc::MockAudioDecoderFactory::CreateEmptyFactory()); webrtc::DataChannelInit init; // This DataChannel is for creating the data content in the negotiation. rtc::scoped_refptr<DataChannelInterface> dummy( caller_->CreateDataChannel("data", init)); Negotiate(); WaitForConnection(); // Wait for the data channel created pre-negotiation to be opened. WaitForDataChannelsToOpen(dummy, callee_signaled_data_channels_, 0); // Create new DataChannels after the negotiation and verify their states. rtc::scoped_refptr<DataChannelInterface> caller_dc( caller_->CreateDataChannel("hello", init)); rtc::scoped_refptr<DataChannelInterface> callee_dc( callee_->CreateDataChannel("hello", init)); WaitForDataChannelsToOpen(caller_dc, callee_signaled_data_channels_, 1); WaitForDataChannelsToOpen(callee_dc, caller_signaled_data_channels_, 0); TestDataChannelSendAndReceive(caller_dc, callee_signaled_data_channels_[1]); TestDataChannelSendAndReceive(callee_dc, caller_signaled_data_channels_[0]); CloseDataChannels(caller_dc, callee_signaled_data_channels_, 1); CloseDataChannels(callee_dc, caller_signaled_data_channels_, 0); } // Verifies that a DataChannel created can transfer large messages. TEST_P(PeerConnectionEndToEndTest, CreateDataChannelLargeTransfer) { CreatePcs(nullptr, webrtc::CreateBuiltinAudioEncoderFactory(), webrtc::MockAudioDecoderFactory::CreateEmptyFactory()); webrtc::DataChannelInit init; // This DataChannel is for creating the data content in the negotiation. rtc::scoped_refptr<DataChannelInterface> dummy( caller_->CreateDataChannel("data", init)); Negotiate(); WaitForConnection(); // Wait for the data channel created pre-negotiation to be opened. WaitForDataChannelsToOpen(dummy, callee_signaled_data_channels_, 0); // Create new DataChannels after the negotiation and verify their states. rtc::scoped_refptr<DataChannelInterface> caller_dc( caller_->CreateDataChannel("hello", init)); rtc::scoped_refptr<DataChannelInterface> callee_dc( callee_->CreateDataChannel("hello", init)); WaitForDataChannelsToOpen(caller_dc, callee_signaled_data_channels_, 1); WaitForDataChannelsToOpen(callee_dc, caller_signaled_data_channels_, 0); TestDataChannelSendAndReceive(caller_dc, callee_signaled_data_channels_[1], 256 * 1024); TestDataChannelSendAndReceive(callee_dc, caller_signaled_data_channels_[0], 256 * 1024); CloseDataChannels(caller_dc, callee_signaled_data_channels_, 1); CloseDataChannels(callee_dc, caller_signaled_data_channels_, 0); } // Verifies that DataChannel IDs are even/odd based on the DTLS roles. TEST_P(PeerConnectionEndToEndTest, DataChannelIdAssignment) { CreatePcs(nullptr, webrtc::CreateBuiltinAudioEncoderFactory(), webrtc::MockAudioDecoderFactory::CreateEmptyFactory()); webrtc::DataChannelInit init; rtc::scoped_refptr<DataChannelInterface> caller_dc_1( caller_->CreateDataChannel("data", init)); rtc::scoped_refptr<DataChannelInterface> callee_dc_1( callee_->CreateDataChannel("data", init)); Negotiate(); WaitForConnection(); EXPECT_EQ(1, caller_dc_1->id() % 2); EXPECT_EQ(0, callee_dc_1->id() % 2); rtc::scoped_refptr<DataChannelInterface> caller_dc_2( caller_->CreateDataChannel("data", init)); rtc::scoped_refptr<DataChannelInterface> callee_dc_2( callee_->CreateDataChannel("data", init)); EXPECT_EQ(1, caller_dc_2->id() % 2); EXPECT_EQ(0, callee_dc_2->id() % 2); } // Verifies that the message is received by the right remote DataChannel when // there are multiple DataChannels. TEST_P(PeerConnectionEndToEndTest, MessageTransferBetweenTwoPairsOfDataChannels) { CreatePcs(nullptr, webrtc::CreateBuiltinAudioEncoderFactory(), webrtc::MockAudioDecoderFactory::CreateEmptyFactory()); webrtc::DataChannelInit init; rtc::scoped_refptr<DataChannelInterface> caller_dc_1( caller_->CreateDataChannel("data", init)); rtc::scoped_refptr<DataChannelInterface> caller_dc_2( caller_->CreateDataChannel("data", init)); Negotiate(); WaitForConnection(); WaitForDataChannelsToOpen(caller_dc_1, callee_signaled_data_channels_, 0); WaitForDataChannelsToOpen(caller_dc_2, callee_signaled_data_channels_, 1); std::unique_ptr<webrtc::MockDataChannelObserver> dc_1_observer( new webrtc::MockDataChannelObserver(callee_signaled_data_channels_[0])); std::unique_ptr<webrtc::MockDataChannelObserver> dc_2_observer( new webrtc::MockDataChannelObserver(callee_signaled_data_channels_[1])); const std::string message_1 = "hello 1"; const std::string message_2 = "hello 2"; caller_dc_1->Send(webrtc::DataBuffer(message_1)); EXPECT_EQ_WAIT(message_1, dc_1_observer->last_message(), kMaxWait); caller_dc_2->Send(webrtc::DataBuffer(message_2)); EXPECT_EQ_WAIT(message_2, dc_2_observer->last_message(), kMaxWait); EXPECT_EQ(1U, dc_1_observer->received_message_count()); EXPECT_EQ(1U, dc_2_observer->received_message_count()); } // Verifies that a DataChannel added from an OPEN message functions after // a channel has been previously closed (webrtc issue 3778). // This previously failed because the new channel re-used the ID of the closed // channel, and the closed channel was incorrectly still assigned to the ID. TEST_P(PeerConnectionEndToEndTest, DataChannelFromOpenWorksAfterPreviousChannelClosed) { CreatePcs(nullptr, webrtc::CreateBuiltinAudioEncoderFactory(), webrtc::MockAudioDecoderFactory::CreateEmptyFactory()); webrtc::DataChannelInit init; rtc::scoped_refptr<DataChannelInterface> caller_dc( caller_->CreateDataChannel("data", init)); Negotiate(); WaitForConnection(); WaitForDataChannelsToOpen(caller_dc, callee_signaled_data_channels_, 0); int first_channel_id = caller_dc->id(); // Wait for the local side to say it's closed, but not the remote side. // Previously, the channel on which Close is called reported being closed // prematurely, and this caused issues; see bugs.webrtc.org/4453. caller_dc->Close(); EXPECT_EQ_WAIT(DataChannelInterface::kClosed, caller_dc->state(), kMaxWait); // Create a new channel and ensure it works after closing the previous one. caller_dc = caller_->CreateDataChannel("data2", init); WaitForDataChannelsToOpen(caller_dc, callee_signaled_data_channels_, 1); // Since the second channel was created after the first finished closing, it // should be able to re-use the first one's ID. EXPECT_EQ(first_channel_id, caller_dc->id()); TestDataChannelSendAndReceive(caller_dc, callee_signaled_data_channels_[1]); CloseDataChannels(caller_dc, callee_signaled_data_channels_, 1); } // Similar to the above test, but don't wait for the first channel to finish // closing before creating the second one. TEST_P(PeerConnectionEndToEndTest, DataChannelFromOpenWorksWhilePreviousChannelClosing) { CreatePcs(nullptr, webrtc::CreateBuiltinAudioEncoderFactory(), webrtc::MockAudioDecoderFactory::CreateEmptyFactory()); webrtc::DataChannelInit init; rtc::scoped_refptr<DataChannelInterface> caller_dc( caller_->CreateDataChannel("data", init)); Negotiate(); WaitForConnection(); WaitForDataChannelsToOpen(caller_dc, callee_signaled_data_channels_, 0); int first_channel_id = caller_dc->id(); caller_dc->Close(); // Immediately create a new channel, before waiting for the previous one to // transition to "closed". caller_dc = caller_->CreateDataChannel("data2", init); WaitForDataChannelsToOpen(caller_dc, callee_signaled_data_channels_, 1); // Since the second channel was created while the first was still closing, // it should have been assigned a different ID. EXPECT_NE(first_channel_id, caller_dc->id()); TestDataChannelSendAndReceive(caller_dc, callee_signaled_data_channels_[1]); CloseDataChannels(caller_dc, callee_signaled_data_channels_, 1); } // This tests that if a data channel is closed remotely while not referenced // by the application (meaning only the PeerConnection contributes to its // reference count), no memory access violation will occur. // See: https://code.google.com/p/chromium/issues/detail?id=565048 TEST_P(PeerConnectionEndToEndTest, CloseDataChannelRemotelyWhileNotReferenced) { CreatePcs(nullptr, webrtc::CreateBuiltinAudioEncoderFactory(), webrtc::MockAudioDecoderFactory::CreateEmptyFactory()); webrtc::DataChannelInit init; rtc::scoped_refptr<DataChannelInterface> caller_dc( caller_->CreateDataChannel("data", init)); Negotiate(); WaitForConnection(); WaitForDataChannelsToOpen(caller_dc, callee_signaled_data_channels_, 0); // This removes the reference to the remote data channel that we hold. callee_signaled_data_channels_.clear(); caller_dc->Close(); EXPECT_EQ_WAIT(DataChannelInterface::kClosed, caller_dc->state(), kMaxWait); // Wait for a bit longer so the remote data channel will receive the // close message and be destroyed. rtc::Thread::Current()->ProcessMessages(100); } #endif // HAVE_SCTP INSTANTIATE_TEST_CASE_P(PeerConnectionEndToEndTest, PeerConnectionEndToEndTest, Values(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan));
{ "pile_set_name": "Github" }
/* Copyright The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // This file was autogenerated by go-to-protobuf. Do not edit it manually! syntax = 'proto2'; package k8s.io.apiextensions_apiserver.pkg.apis.apiextensions.v1beta1; import "k8s.io/apimachinery/pkg/apis/meta/v1/generated.proto"; import "k8s.io/apimachinery/pkg/runtime/generated.proto"; import "k8s.io/apimachinery/pkg/runtime/schema/generated.proto"; // Package-wide variables from generator "generated". option go_package = "v1beta1"; // ConversionRequest describes the conversion request parameters. message ConversionRequest { // uid is an identifier for the individual request/response. It allows distinguishing instances of requests which are // otherwise identical (parallel requests, etc). // The UID is meant to track the round trip (request/response) between the Kubernetes API server and the webhook, not the user request. // It is suitable for correlating log entries between the webhook and apiserver, for either auditing or debugging. optional string uid = 1; // desiredAPIVersion is the version to convert given objects to. e.g. "myapi.example.com/v1" optional string desiredAPIVersion = 2; // objects is the list of custom resource objects to be converted. repeated k8s.io.apimachinery.pkg.runtime.RawExtension objects = 3; } // ConversionResponse describes a conversion response. message ConversionResponse { // uid is an identifier for the individual request/response. // This should be copied over from the corresponding `request.uid`. optional string uid = 1; // convertedObjects is the list of converted version of `request.objects` if the `result` is successful, otherwise empty. // The webhook is expected to set `apiVersion` of these objects to the `request.desiredAPIVersion`. The list // must also have the same size as the input list with the same objects in the same order (equal kind, metadata.uid, metadata.name and metadata.namespace). // The webhook is allowed to mutate labels and annotations. Any other change to the metadata is silently ignored. repeated k8s.io.apimachinery.pkg.runtime.RawExtension convertedObjects = 2; // result contains the result of conversion with extra details if the conversion failed. `result.status` determines if // the conversion failed or succeeded. The `result.status` field is required and represents the success or failure of the // conversion. A successful conversion must set `result.status` to `Success`. A failed conversion must set // `result.status` to `Failure` and provide more details in `result.message` and return http status 200. The `result.message` // will be used to construct an error message for the end user. optional k8s.io.apimachinery.pkg.apis.meta.v1.Status result = 3; } // ConversionReview describes a conversion request/response. message ConversionReview { // request describes the attributes for the conversion request. // +optional optional ConversionRequest request = 1; // response describes the attributes for the conversion response. // +optional optional ConversionResponse response = 2; } // CustomResourceColumnDefinition specifies a column for server side printing. message CustomResourceColumnDefinition { // name is a human readable name for the column. optional string name = 1; // type is an OpenAPI type definition for this column. // See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types for details. optional string type = 2; // format is an optional OpenAPI type definition for this column. The 'name' format is applied // to the primary identifier column to assist in clients identifying column is the resource name. // See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types for details. // +optional optional string format = 3; // description is a human readable description of this column. // +optional optional string description = 4; // priority is an integer defining the relative importance of this column compared to others. Lower // numbers are considered higher priority. Columns that may be omitted in limited space scenarios // should be given a priority greater than 0. // +optional optional int32 priority = 5; // JSONPath is a simple JSON path (i.e. with array notation) which is evaluated against // each custom resource to produce the value for this column. optional string JSONPath = 6; } // CustomResourceConversion describes how to convert different versions of a CR. message CustomResourceConversion { // strategy specifies how custom resources are converted between versions. Allowed values are: // - `None`: The converter only change the apiVersion and would not touch any other field in the custom resource. // - `Webhook`: API Server will call to an external webhook to do the conversion. Additional information // is needed for this option. This requires spec.preserveUnknownFields to be false, and spec.conversion.webhookClientConfig to be set. optional string strategy = 1; // webhookClientConfig is the instructions for how to call the webhook if strategy is `Webhook`. // Required when `strategy` is set to `Webhook`. // +optional optional WebhookClientConfig webhookClientConfig = 2; // conversionReviewVersions is an ordered list of preferred `ConversionReview` // versions the Webhook expects. The API server will use the first version in // the list which it supports. If none of the versions specified in this list // are supported by API server, conversion will fail for the custom resource. // If a persisted Webhook configuration specifies allowed versions and does not // include any versions known to the API Server, calls to the webhook will fail. // Defaults to `["v1beta1"]`. // +optional repeated string conversionReviewVersions = 3; } // CustomResourceDefinition represents a resource that should be exposed on the API server. Its name MUST be in the format // <.spec.name>.<.spec.group>. // Deprecated in v1.16, planned for removal in v1.22. Use apiextensions.k8s.io/v1 CustomResourceDefinition instead. message CustomResourceDefinition { optional k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1; // spec describes how the user wants the resources to appear optional CustomResourceDefinitionSpec spec = 2; // status indicates the actual state of the CustomResourceDefinition // +optional optional CustomResourceDefinitionStatus status = 3; } // CustomResourceDefinitionCondition contains details for the current condition of this pod. message CustomResourceDefinitionCondition { // type is the type of the condition. Types include Established, NamesAccepted and Terminating. optional string type = 1; // status is the status of the condition. // Can be True, False, Unknown. optional string status = 2; // lastTransitionTime last time the condition transitioned from one status to another. // +optional optional k8s.io.apimachinery.pkg.apis.meta.v1.Time lastTransitionTime = 3; // reason is a unique, one-word, CamelCase reason for the condition's last transition. // +optional optional string reason = 4; // message is a human-readable message indicating details about last transition. // +optional optional string message = 5; } // CustomResourceDefinitionList is a list of CustomResourceDefinition objects. message CustomResourceDefinitionList { optional k8s.io.apimachinery.pkg.apis.meta.v1.ListMeta metadata = 1; // items list individual CustomResourceDefinition objects repeated CustomResourceDefinition items = 2; } // CustomResourceDefinitionNames indicates the names to serve this CustomResourceDefinition message CustomResourceDefinitionNames { // plural is the plural name of the resource to serve. // The custom resources are served under `/apis/<group>/<version>/.../<plural>`. // Must match the name of the CustomResourceDefinition (in the form `<names.plural>.<group>`). // Must be all lowercase. optional string plural = 1; // singular is the singular name of the resource. It must be all lowercase. Defaults to lowercased `kind`. // +optional optional string singular = 2; // shortNames are short names for the resource, exposed in API discovery documents, // and used by clients to support invocations like `kubectl get <shortname>`. // It must be all lowercase. // +optional repeated string shortNames = 3; // kind is the serialized kind of the resource. It is normally CamelCase and singular. // Custom resource instances will use this value as the `kind` attribute in API calls. optional string kind = 4; // listKind is the serialized kind of the list for this resource. Defaults to "`kind`List". // +optional optional string listKind = 5; // categories is a list of grouped resources this custom resource belongs to (e.g. 'all'). // This is published in API discovery documents, and used by clients to support invocations like // `kubectl get all`. // +optional repeated string categories = 6; } // CustomResourceDefinitionSpec describes how a user wants their resource to appear message CustomResourceDefinitionSpec { // group is the API group of the defined custom resource. // The custom resources are served under `/apis/<group>/...`. // Must match the name of the CustomResourceDefinition (in the form `<names.plural>.<group>`). optional string group = 1; // version is the API version of the defined custom resource. // The custom resources are served under `/apis/<group>/<version>/...`. // Must match the name of the first item in the `versions` list if `version` and `versions` are both specified. // Optional if `versions` is specified. // Deprecated: use `versions` instead. // +optional optional string version = 2; // names specify the resource and kind names for the custom resource. optional CustomResourceDefinitionNames names = 3; // scope indicates whether the defined custom resource is cluster- or namespace-scoped. // Allowed values are `Cluster` and `Namespaced`. Default is `Namespaced`. optional string scope = 4; // validation describes the schema used for validation and pruning of the custom resource. // If present, this validation schema is used to validate all versions. // Top-level and per-version schemas are mutually exclusive. // +optional optional CustomResourceValidation validation = 5; // subresources specify what subresources the defined custom resource has. // If present, this field configures subresources for all versions. // Top-level and per-version subresources are mutually exclusive. // +optional optional CustomResourceSubresources subresources = 6; // versions is the list of all API versions of the defined custom resource. // Optional if `version` is specified. // The name of the first item in the `versions` list must match the `version` field if `version` and `versions` are both specified. // Version names are used to compute the order in which served versions are listed in API discovery. // If the version string is "kube-like", it will sort above non "kube-like" version strings, which are ordered // lexicographically. "Kube-like" versions start with a "v", then are followed by a number (the major version), // then optionally the string "alpha" or "beta" and another number (the minor version). These are sorted first // by GA > beta > alpha (where GA is a version with no suffix such as beta or alpha), and then by comparing // major version, then minor version. An example sorted list of versions: // v10, v2, v1, v11beta2, v10beta3, v3beta1, v12alpha1, v11alpha2, foo1, foo10. // +optional repeated CustomResourceDefinitionVersion versions = 7; // additionalPrinterColumns specifies additional columns returned in Table output. // See https://kubernetes.io/docs/reference/using-api/api-concepts/#receiving-resources-as-tables for details. // If present, this field configures columns for all versions. // Top-level and per-version columns are mutually exclusive. // If no top-level or per-version columns are specified, a single column displaying the age of the custom resource is used. // +optional repeated CustomResourceColumnDefinition additionalPrinterColumns = 8; // conversion defines conversion settings for the CRD. // +optional optional CustomResourceConversion conversion = 9; // preserveUnknownFields indicates that object fields which are not specified // in the OpenAPI schema should be preserved when persisting to storage. // apiVersion, kind, metadata and known fields inside metadata are always preserved. // If false, schemas must be defined for all versions. // Defaults to true in v1beta for backwards compatibility. // Deprecated: will be required to be false in v1. Preservation of unknown fields can be specified // in the validation schema using the `x-kubernetes-preserve-unknown-fields: true` extension. // See https://kubernetes.io/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions/#pruning-versus-preserving-unknown-fields for details. // +optional optional bool preserveUnknownFields = 10; } // CustomResourceDefinitionStatus indicates the state of the CustomResourceDefinition message CustomResourceDefinitionStatus { // conditions indicate state for particular aspects of a CustomResourceDefinition // +optional repeated CustomResourceDefinitionCondition conditions = 1; // acceptedNames are the names that are actually being used to serve discovery. // They may be different than the names in spec. // +optional optional CustomResourceDefinitionNames acceptedNames = 2; // storedVersions lists all versions of CustomResources that were ever persisted. Tracking these // versions allows a migration path for stored versions in etcd. The field is mutable // so a migration controller can finish a migration to another version (ensuring // no old objects are left in storage), and then remove the rest of the // versions from this list. // Versions may not be removed from `spec.versions` while they exist in this list. // +optional repeated string storedVersions = 3; } // CustomResourceDefinitionVersion describes a version for CRD. message CustomResourceDefinitionVersion { // name is the version name, e.g. “v1”, “v2beta1”, etc. // The custom resources are served under this version at `/apis/<group>/<version>/...` if `served` is true. optional string name = 1; // served is a flag enabling/disabling this version from being served via REST APIs optional bool served = 2; // storage indicates this version should be used when persisting custom resources to storage. // There must be exactly one version with storage=true. optional bool storage = 3; // deprecated indicates this version of the custom resource API is deprecated. // When set to true, API requests to this version receive a warning header in the server response. // Defaults to false. // +optional optional bool deprecated = 7; // deprecationWarning overrides the default warning returned to API clients. // May only be set when `deprecated` is true. // The default warning indicates this version is deprecated and recommends use // of the newest served version of equal or greater stability, if one exists. // +optional optional string deprecationWarning = 8; // schema describes the schema used for validation and pruning of this version of the custom resource. // Top-level and per-version schemas are mutually exclusive. // Per-version schemas must not all be set to identical values (top-level validation schema should be used instead). // +optional optional CustomResourceValidation schema = 4; // subresources specify what subresources this version of the defined custom resource have. // Top-level and per-version subresources are mutually exclusive. // Per-version subresources must not all be set to identical values (top-level subresources should be used instead). // +optional optional CustomResourceSubresources subresources = 5; // additionalPrinterColumns specifies additional columns returned in Table output. // See https://kubernetes.io/docs/reference/using-api/api-concepts/#receiving-resources-as-tables for details. // Top-level and per-version columns are mutually exclusive. // Per-version columns must not all be set to identical values (top-level columns should be used instead). // If no top-level or per-version columns are specified, a single column displaying the age of the custom resource is used. // +optional repeated CustomResourceColumnDefinition additionalPrinterColumns = 6; } // CustomResourceSubresourceScale defines how to serve the scale subresource for CustomResources. message CustomResourceSubresourceScale { // specReplicasPath defines the JSON path inside of a custom resource that corresponds to Scale `spec.replicas`. // Only JSON paths without the array notation are allowed. // Must be a JSON Path under `.spec`. // If there is no value under the given path in the custom resource, the `/scale` subresource will return an error on GET. optional string specReplicasPath = 1; // statusReplicasPath defines the JSON path inside of a custom resource that corresponds to Scale `status.replicas`. // Only JSON paths without the array notation are allowed. // Must be a JSON Path under `.status`. // If there is no value under the given path in the custom resource, the `status.replicas` value in the `/scale` subresource // will default to 0. optional string statusReplicasPath = 2; // labelSelectorPath defines the JSON path inside of a custom resource that corresponds to Scale `status.selector`. // Only JSON paths without the array notation are allowed. // Must be a JSON Path under `.status` or `.spec`. // Must be set to work with HorizontalPodAutoscaler. // The field pointed by this JSON path must be a string field (not a complex selector struct) // which contains a serialized label selector in string form. // More info: https://kubernetes.io/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions#scale-subresource // If there is no value under the given path in the custom resource, the `status.selector` value in the `/scale` // subresource will default to the empty string. // +optional optional string labelSelectorPath = 3; } // CustomResourceSubresourceStatus defines how to serve the status subresource for CustomResources. // Status is represented by the `.status` JSON path inside of a CustomResource. When set, // * exposes a /status subresource for the custom resource // * PUT requests to the /status subresource take a custom resource object, and ignore changes to anything except the status stanza // * PUT/POST/PATCH requests to the custom resource ignore changes to the status stanza message CustomResourceSubresourceStatus { } // CustomResourceSubresources defines the status and scale subresources for CustomResources. message CustomResourceSubresources { // status indicates the custom resource should serve a `/status` subresource. // When enabled: // 1. requests to the custom resource primary endpoint ignore changes to the `status` stanza of the object. // 2. requests to the custom resource `/status` subresource ignore changes to anything other than the `status` stanza of the object. // +optional optional CustomResourceSubresourceStatus status = 1; // scale indicates the custom resource should serve a `/scale` subresource that returns an `autoscaling/v1` Scale object. // +optional optional CustomResourceSubresourceScale scale = 2; } // CustomResourceValidation is a list of validation methods for CustomResources. message CustomResourceValidation { // openAPIV3Schema is the OpenAPI v3 schema to use for validation and pruning. // +optional optional JSONSchemaProps openAPIV3Schema = 1; } // ExternalDocumentation allows referencing an external resource for extended documentation. message ExternalDocumentation { optional string description = 1; optional string url = 2; } // JSON represents any valid JSON value. // These types are supported: bool, int64, float64, string, []interface{}, map[string]interface{} and nil. message JSON { optional bytes raw = 1; } // JSONSchemaProps is a JSON-Schema following Specification Draft 4 (http://json-schema.org/). message JSONSchemaProps { optional string id = 1; optional string schema = 2; optional string ref = 3; optional string description = 4; optional string type = 5; // format is an OpenAPI v3 format string. Unknown formats are ignored. The following formats are validated: // // - bsonobjectid: a bson object ID, i.e. a 24 characters hex string // - uri: an URI as parsed by Golang net/url.ParseRequestURI // - email: an email address as parsed by Golang net/mail.ParseAddress // - hostname: a valid representation for an Internet host name, as defined by RFC 1034, section 3.1 [RFC1034]. // - ipv4: an IPv4 IP as parsed by Golang net.ParseIP // - ipv6: an IPv6 IP as parsed by Golang net.ParseIP // - cidr: a CIDR as parsed by Golang net.ParseCIDR // - mac: a MAC address as parsed by Golang net.ParseMAC // - uuid: an UUID that allows uppercase defined by the regex (?i)^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$ // - uuid3: an UUID3 that allows uppercase defined by the regex (?i)^[0-9a-f]{8}-?[0-9a-f]{4}-?3[0-9a-f]{3}-?[0-9a-f]{4}-?[0-9a-f]{12}$ // - uuid4: an UUID4 that allows uppercase defined by the regex (?i)^[0-9a-f]{8}-?[0-9a-f]{4}-?4[0-9a-f]{3}-?[89ab][0-9a-f]{3}-?[0-9a-f]{12}$ // - uuid5: an UUID5 that allows uppercase defined by the regex (?i)^[0-9a-f]{8}-?[0-9a-f]{4}-?5[0-9a-f]{3}-?[89ab][0-9a-f]{3}-?[0-9a-f]{12}$ // - isbn: an ISBN10 or ISBN13 number string like "0321751043" or "978-0321751041" // - isbn10: an ISBN10 number string like "0321751043" // - isbn13: an ISBN13 number string like "978-0321751041" // - creditcard: a credit card number defined by the regex ^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\\d{3})\\d{11})$ with any non digit characters mixed in // - ssn: a U.S. social security number following the regex ^\\d{3}[- ]?\\d{2}[- ]?\\d{4}$ // - hexcolor: an hexadecimal color code like "#FFFFFF: following the regex ^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$ // - rgbcolor: an RGB color code like rgb like "rgb(255,255,2559" // - byte: base64 encoded binary data // - password: any kind of string // - date: a date string like "2006-01-02" as defined by full-date in RFC3339 // - duration: a duration string like "22 ns" as parsed by Golang time.ParseDuration or compatible with Scala duration format // - datetime: a date time string like "2014-12-15T19:30:20.000Z" as defined by date-time in RFC3339. optional string format = 6; optional string title = 7; // default is a default value for undefined object fields. // Defaulting is a beta feature under the CustomResourceDefaulting feature gate. // CustomResourceDefinitions with defaults must be created using the v1 (or newer) CustomResourceDefinition API. optional JSON default = 8; optional double maximum = 9; optional bool exclusiveMaximum = 10; optional double minimum = 11; optional bool exclusiveMinimum = 12; optional int64 maxLength = 13; optional int64 minLength = 14; optional string pattern = 15; optional int64 maxItems = 16; optional int64 minItems = 17; optional bool uniqueItems = 18; optional double multipleOf = 19; repeated JSON enum = 20; optional int64 maxProperties = 21; optional int64 minProperties = 22; repeated string required = 23; optional JSONSchemaPropsOrArray items = 24; repeated JSONSchemaProps allOf = 25; repeated JSONSchemaProps oneOf = 26; repeated JSONSchemaProps anyOf = 27; optional JSONSchemaProps not = 28; map<string, JSONSchemaProps> properties = 29; optional JSONSchemaPropsOrBool additionalProperties = 30; map<string, JSONSchemaProps> patternProperties = 31; map<string, JSONSchemaPropsOrStringArray> dependencies = 32; optional JSONSchemaPropsOrBool additionalItems = 33; map<string, JSONSchemaProps> definitions = 34; optional ExternalDocumentation externalDocs = 35; optional JSON example = 36; optional bool nullable = 37; // x-kubernetes-preserve-unknown-fields stops the API server // decoding step from pruning fields which are not specified // in the validation schema. This affects fields recursively, // but switches back to normal pruning behaviour if nested // properties or additionalProperties are specified in the schema. // This can either be true or undefined. False is forbidden. optional bool xKubernetesPreserveUnknownFields = 38; // x-kubernetes-embedded-resource defines that the value is an // embedded Kubernetes runtime.Object, with TypeMeta and // ObjectMeta. The type must be object. It is allowed to further // restrict the embedded object. kind, apiVersion and metadata // are validated automatically. x-kubernetes-preserve-unknown-fields // is allowed to be true, but does not have to be if the object // is fully specified (up to kind, apiVersion, metadata). optional bool xKubernetesEmbeddedResource = 39; // x-kubernetes-int-or-string specifies that this value is // either an integer or a string. If this is true, an empty // type is allowed and type as child of anyOf is permitted // if following one of the following patterns: // // 1) anyOf: // - type: integer // - type: string // 2) allOf: // - anyOf: // - type: integer // - type: string // - ... zero or more optional bool xKubernetesIntOrString = 40; // x-kubernetes-list-map-keys annotates an array with the x-kubernetes-list-type `map` by specifying the keys used // as the index of the map. // // This tag MUST only be used on lists that have the "x-kubernetes-list-type" // extension set to "map". Also, the values specified for this attribute must // be a scalar typed field of the child structure (no nesting is supported). // // The properties specified must either be required or have a default value, // to ensure those properties are present for all list items. // // +optional repeated string xKubernetesListMapKeys = 41; // x-kubernetes-list-type annotates an array to further describe its topology. // This extension must only be used on lists and may have 3 possible values: // // 1) `atomic`: the list is treated as a single entity, like a scalar. // Atomic lists will be entirely replaced when updated. This extension // may be used on any type of list (struct, scalar, ...). // 2) `set`: // Sets are lists that must not have multiple items with the same value. Each // value must be a scalar, an object with x-kubernetes-map-type `atomic` or an // array with x-kubernetes-list-type `atomic`. // 3) `map`: // These lists are like maps in that their elements have a non-index key // used to identify them. Order is preserved upon merge. The map tag // must only be used on a list with elements of type object. // Defaults to atomic for arrays. // +optional optional string xKubernetesListType = 42; // x-kubernetes-map-type annotates an object to further describe its topology. // This extension must only be used when type is object and may have 2 possible values: // // 1) `granular`: // These maps are actual maps (key-value pairs) and each fields are independent // from each other (they can each be manipulated by separate actors). This is // the default behaviour for all maps. // 2) `atomic`: the list is treated as a single entity, like a scalar. // Atomic maps will be entirely replaced when updated. // +optional optional string xKubernetesMapType = 43; } // JSONSchemaPropsOrArray represents a value that can either be a JSONSchemaProps // or an array of JSONSchemaProps. Mainly here for serialization purposes. message JSONSchemaPropsOrArray { optional JSONSchemaProps schema = 1; repeated JSONSchemaProps jSONSchemas = 2; } // JSONSchemaPropsOrBool represents JSONSchemaProps or a boolean value. // Defaults to true for the boolean property. message JSONSchemaPropsOrBool { optional bool allows = 1; optional JSONSchemaProps schema = 2; } // JSONSchemaPropsOrStringArray represents a JSONSchemaProps or a string array. message JSONSchemaPropsOrStringArray { optional JSONSchemaProps schema = 1; repeated string property = 2; } // ServiceReference holds a reference to Service.legacy.k8s.io message ServiceReference { // namespace is the namespace of the service. // Required optional string namespace = 1; // name is the name of the service. // Required optional string name = 2; // path is an optional URL path at which the webhook will be contacted. // +optional optional string path = 3; // port is an optional service port at which the webhook will be contacted. // `port` should be a valid port number (1-65535, inclusive). // Defaults to 443 for backward compatibility. // +optional optional int32 port = 4; } // WebhookClientConfig contains the information to make a TLS connection with the webhook. message WebhookClientConfig { // url gives the location of the webhook, in standard URL form // (`scheme://host:port/path`). Exactly one of `url` or `service` // must be specified. // // The `host` should not refer to a service running in the cluster; use // the `service` field instead. The host might be resolved via external // DNS in some apiservers (e.g., `kube-apiserver` cannot resolve // in-cluster DNS as that would be a layering violation). `host` may // also be an IP address. // // Please note that using `localhost` or `127.0.0.1` as a `host` is // risky unless you take great care to run this webhook on all hosts // which run an apiserver which might need to make calls to this // webhook. Such installs are likely to be non-portable, i.e., not easy // to turn up in a new cluster. // // The scheme must be "https"; the URL must begin with "https://". // // A path is optional, and if present may be any string permissible in // a URL. You may use the path to pass an arbitrary string to the // webhook, for example, a cluster identifier. // // Attempting to use a user or basic auth e.g. "user:password@" is not // allowed. Fragments ("#...") and query parameters ("?...") are not // allowed, either. // // +optional optional string url = 3; // service is a reference to the service for this webhook. Either // service or url must be specified. // // If the webhook is running within the cluster, then you should use `service`. // // +optional optional ServiceReference service = 1; // caBundle is a PEM encoded CA bundle which will be used to validate the webhook's server certificate. // If unspecified, system trust roots on the apiserver are used. // +optional optional bytes caBundle = 2; }
{ "pile_set_name": "Github" }
(function($) { $(document).ready(function() { // Add anchor tag for Show/Hide link $("fieldset.collapse").each(function(i, elem) { // Don't hide if fields in this fieldset have errors if ($(elem).find("div.errors").length == 0) { $(elem).addClass("collapsed").find("h2").first().append(' (<a id="fieldsetcollapser' + i +'" class="collapse-toggle" href="#">' + gettext("Show") + '</a>)'); } }); // Add toggle to anchor tag $("fieldset.collapse a.collapse-toggle").click(function(ev) { if ($(this).closest("fieldset").hasClass("collapsed")) { // Show $(this).text(gettext("Hide")).closest("fieldset").removeClass("collapsed").trigger("show.fieldset", [$(this).attr("id")]); } else { // Hide $(this).text(gettext("Show")).closest("fieldset").addClass("collapsed").trigger("hide.fieldset", [$(this).attr("id")]); } return false; }); }); })(django.jQuery);
{ "pile_set_name": "Github" }
e# Program: Portable C client makefile -- OS/2 version # # Author: Mark Crispin # Networks and Distributed Computing # Computing & Communications # University of Washington # Administration Building, AG-44 # Seattle, WA 98195 # Internet: [email protected] # # Date: 11 May 1989 # Last Edited: 14 October 2003 # # The IMAP toolkit provided in this Distribution is # Copyright 2001 University of Washington. # # The full text of our legal notices is contained in the file called # CPYRIGHT, included with this Distribution. EXTRAAUTHENTICATORS = EXTRADRIVERS = EXTRACFLAGS = DEFAULTAUTHENTICATORS = md5 pla log DRIVERS = imap nntp pop3 mbx mtx tenex unix DEFAULTDRIVER = mbx CFLAGS = -DOMF -O2 -Zomf $(EXTRACFLAGS) CC = gcc CCLIENTLIB = cclient.lib all: $(CCLIENTLIB) .c.obj: $(CC) $(CFLAGS) -o $@ -c $*.c osdep.h: os_os2.h copy os_os2.h osdep.h drivers.cmd $(EXTRADRIVERS) $(DRIVERS) dummy auths.cmd $(EXTRAAUTHENTICATORS) $(DEFAULTAUTHENTICATORS) setproto.cmd $(DEFAULTDRIVER) mail.obj: mail.h misc.h osdep.h mail.c misc.obj: mail.h misc.h misc.c fdstring.obj: mail.h misc.h osdep.h fdstring.h fdstring.c flstring.obj: mail.h misc.h osdep.h flstring.h flstring.c netmsg.obj: mail.h misc.h netmsg.h osdep.h netmsg.c newsrc.obj: mail.h misc.h newsrc.h osdep.h newsrc.c rfc822.obj: mail.h rfc822.h misc.h rfc822.c smanager.obj: mail.h misc.h smanager.c utf8.obj: mail.h misc.h osdep.h utf8.h imap4r1.obj: mail.h imap4r1.h misc.h osdep.h imap4r1.c nntp.obj: mail.h nntp.h smtp.h rfc822.h misc.h osdep.h nntp.c pop3.obj: mail.h rfc822.h misc.h osdep.h pop3.c smtp.obj: mail.h smtp.h rfc822.h misc.h osdep.h smtp.c os_os2.obj: mail.h osdep.h env_os2.h fs.h ftl.h nl.h tcp.h tcp_os2.h \ os_os2.c fs_os2.c ftl_os2.c nl_os2.c env_os2.c tcp_os2.c \ mailfile.h auth_md5.c auth_log.c pmatch.c write.c mbxnt.obj: mail.h mbxnt.h misc.h osdep.h mbxnt.c mtxnt.obj: mail.h misc.h osdep.h mtxnt.c tenexnt.obj: mail.h misc.h osdep.h tenexnt.c unixnt.obj: mail.h unixnt.h pseudo.h misc.h osdep.h unixnt.c dummyos2.obj: mail.h dummy.h misc.h osdep.h dummyos2.c pseudo.obj: pseudo.h $(CCLIENTLIB): mail.obj misc.obj fdstring.obj flstring.obj netmsg.obj \ newsrc.obj rfc822.obj smanager.obj utf8.obj \ imap4r1.obj nntp.obj pop3.obj smtp.obj os_os2.obj \ mbxnt.obj mtxnt.obj tenexnt.obj unixnt.obj dummynt.obj pseudo.obj del $(CCLIENTLIB) LIB /NOLOGO /OUT:$(CCLIENTLIB) \ mail.obj misc.obj fdstring.obj flstring.obj netmsg.obj \ newsrc.obj rfc822.obj smanager.obj utf8.obj \ imap4r1.obj nntp.obj pop3.obj smtp.obj os_os2.obj \ mbxnt.obj mtxnt.obj tenexnt.obj unixnt.obj dummynt.obj pseudo.obj clean: del *.lib *.obj linkage.* osdep.* auths.c *.exe *.exp # A monument to a hack of long ago and far away... love: @echo not war?
{ "pile_set_name": "Github" }
/* * Copyright (C) 2020 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thoughtworks.gauge.language.psi; import com.intellij.lang.ASTNode; import com.intellij.navigation.ItemPresentation; import com.intellij.openapi.module.Module; import com.intellij.psi.PsiElement; import com.thoughtworks.gauge.GaugeBootstrapService; import com.thoughtworks.gauge.StepValue; import com.thoughtworks.gauge.connection.GaugeConnection; import com.thoughtworks.gauge.core.GaugeCli; import com.thoughtworks.gauge.language.psi.impl.SpecStepImpl; import com.thoughtworks.gauge.util.GaugeUtil; import com.thoughtworks.gauge.util.StepUtil; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.ArrayList; public final class SpecPsiImplUtil { private SpecPsiImplUtil() { } public static StepValue getStepValue(SpecStep element) { ASTNode step = element.getNode(); String stepText = step.getText().trim(); int newLineIndex = stepText.indexOf("\n"); int endIndex = newLineIndex == -1 ? stepText.length() : newLineIndex; SpecTable inlineTable = element.getInlineTable(); stepText = stepText.substring(1, endIndex).trim(); return getStepValueFor(element, stepText, inlineTable != null); } public static StepValue getStepValueFor(PsiElement element, String stepText, Boolean hasInlineTable) { return getStepValueFor(GaugeUtil.moduleForPsiElement(element), element, stepText, hasInlineTable); } public static StepValue getStepValueFor(Module module, PsiElement element, String stepText, Boolean hasInlineTable) { GaugeBootstrapService bootstrapService = GaugeBootstrapService.getInstance(module.getProject()); GaugeCli gaugeCli = bootstrapService.getGaugeCli(module, false); if (gaugeCli == null) { return getDefaultStepValue(element); } GaugeConnection apiConnection = gaugeCli.getGaugeConnection(); if (apiConnection == null) { return getDefaultStepValue(element); } StepValue value = StepUtil.getStepValue(apiConnection, stepText, hasInlineTable); return value == null ? getDefaultStepValue(element) : value; } private static StepValue getDefaultStepValue(PsiElement element) { return new StepValue(element.getText(), element.getText(), new ArrayList<>()); } public static ItemPresentation getPresentation(final SpecStepImpl element) { return new ItemPresentation() { @Nullable @Override public String getPresentableText() { return element.getText(); } @Override public String getLocationString() { return element.getContainingFile().getName(); } @Nullable @Override public Icon getIcon(boolean unused) { return null; } }; } }
{ "pile_set_name": "Github" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <!-- http://hge.relishgames.com --> <html> <head> <meta name="Keywords" content="game engine, 2d, hardware accelerated, hge, engine, relish games, game development"> <meta name="Description" content="Haaf's Game Engine - Hardware accelerated 2D games engine"> <title>Haaf's Game Engine - Hardware accelerated 2D games engine</title> <link rel=stylesheet type=text/css href=hge.css> <script language="JavaScript" src="hge.js"></script> </head> <body onload="setContents('cnt_hgeparticle.html');" bgcolor=#ffffff text=#000000 link=#7F0000 vlink=#7F0000 alink=#7F0000 marginwidth=0 marginheight=0 leftmargin=0 topmargin=0> <table height=100% cellspacing=0 cellpadding=0 border=0><tr> <td valign=top> <table width=566 cellspacing=0 cellpadding=20 border=0><tr><td> <h1 style="margin-top:0px">hgeParticleSystem Constructors</h1> <p> To create and initalize a <b>hgeParticleSystem</b> object you may use one of these constructors: </p> <pre> hgeParticleSystem( const char *<i><b>filename</b></i>, hgeSprite *<i><b>sprite</b></i> ); hgeParticleSystem( hgeParticleSystemInfo *<i><b>psi</b></i> ); hgeParticleSystem( const hgeParticleSystem &<i><b>ps</b></i> ); </pre> <h2>Parameters</h2> <dl> <dt><i>filename</i> <dd>Particle system description file name. This file should just hold a disk image of <a href="hgeparticle_psinfo.html">hgeParticleSystemInfo</a> structure, describing the particle system. <dt><i>sprite</i> <dd>Pointer to a valid <a href="hgesprite__main.html">hgeSprite</a> object to use for the particle system. <dt><i>psi</i> <dd>Pointer to a valid <a href="hgeparticle_psinfo.html">hgeParticleSystemInfo</a> structure, describing the particle system. </dl> <h2>Remarks</h2> <p> The particle system description file is loaded with <a href="hgefunc_resourceload.html">Resource_Load</a> function, so all it's features are applicable. </p> <h2>Requirements</h2> <p> <b>Header:</b> hgeparticle.h<br> <b>Import library:</b> hgehelp.lib<br> </p> <br> </td></tr></table> </td> </tr></table> </body> </html>
{ "pile_set_name": "Github" }
CHANGELOG: - 2010/02/19 - initial release - 2010/03/12 - add support for 0.24.8 and newer - make the location of sort configurable - add the ability to add shell comment based warnings to top of files - add the ablity to create empty files - 2010/04/05 - fix parsing of WARN and change code style to match rest of the code - Better and safer boolean handling for warn and force - Don't use hard coded paths in the shell script, set PATH top of the script - Use file{} to copy the result and make all fragments owned by root. This means we can chnage the ownership/group of the resulting file at any time. - You can specify ensure => "/some/other/file" in concat::fragment to include the contents of a symlink into the final file. - 2010/04/16 - Add more cleaning of the fragment name - removing / from the $name - 2010/05/22 - Improve documentation and show the use of ensure => - 2010/07/14 - Add support for setting the filebucket behavior of files - 2010/10/04 - Make the warning message configurable - 2010/12/03 - Add flags to make concat work better on Solaris - thanks Jonathan Boyett - 2011/02/03 - Make the shell script more portable and add a config option for root group - 2011/06/21 - Make base dir root readable only for security - 2011/06/23 - Set base directory using a fact instead of hardcoding it - 2011/06/23 - Support operating as non privileged user - 2011/06/23 - Support dash instead of bash or sh - 2011/07/11 - Better solaris support - 2011/12/05 - Use fully qualified variables - 2011/12/13 - Improve Nexenta support - 2012/04/11 - Do not use any GNU specific extensions in the shell script - 2012/03/24 - Comply to community style guides - 2012/05/23 - Better errors when basedir isnt set - 2012/05/31 - Add spec tests - 2012/07/11 - Include concat::setup in concat improving UX - 2012/08/14 - Puppet Lint improvements - 2012/08/30 - The target path can be different from the $name - 2012/08/30 - More Puppet Lint cleanup - 2012/09/04 - RELEASE 0.2.0
{ "pile_set_name": "Github" }
# -*- test-case-name: twisted.test.test_process -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ http://isometric.sixsided.org/_/gates_in_the_head/ """ import os # Win32 imports import win32api import win32con import win32event import win32file import win32pipe import win32process import win32security import pywintypes # security attributes for pipes PIPE_ATTRS_INHERITABLE = win32security.SECURITY_ATTRIBUTES() PIPE_ATTRS_INHERITABLE.bInheritHandle = 1 from zope.interface import implements from twisted.internet.interfaces import IProcessTransport, IConsumer, IProducer from twisted.python.win32 import quoteArguments from twisted.internet import error from twisted.internet import _pollingfile from twisted.internet._baseprocess import BaseProcess def debug(msg): import sys print msg sys.stdout.flush() class _Reaper(_pollingfile._PollableResource): def __init__(self, proc): self.proc = proc def checkWork(self): if win32event.WaitForSingleObject(self.proc.hProcess, 0) != win32event.WAIT_OBJECT_0: return 0 exitCode = win32process.GetExitCodeProcess(self.proc.hProcess) self.deactivate() self.proc.processEnded(exitCode) return 0 def _findShebang(filename): """ Look for a #! line, and return the value following the #! if one exists, or None if this file is not a script. I don't know if there are any conventions for quoting in Windows shebang lines, so this doesn't support any; therefore, you may not pass any arguments to scripts invoked as filters. That's probably wrong, so if somebody knows more about the cultural expectations on Windows, please feel free to fix. This shebang line support was added in support of the CGI tests; appropriately enough, I determined that shebang lines are culturally accepted in the Windows world through this page:: http://www.cgi101.com/learn/connect/winxp.html @param filename: str representing a filename @return: a str representing another filename. """ f = file(filename, 'rU') if f.read(2) == '#!': exe = f.readline(1024).strip('\n') return exe def _invalidWin32App(pywinerr): """ Determine if a pywintypes.error is telling us that the given process is 'not a valid win32 application', i.e. not a PE format executable. @param pywinerr: a pywintypes.error instance raised by CreateProcess @return: a boolean """ # Let's do this better in the future, but I have no idea what this error # is; MSDN doesn't mention it, and there is no symbolic constant in # win32process module that represents 193. return pywinerr.args[0] == 193 class Process(_pollingfile._PollingTimer, BaseProcess): """A process that integrates with the Twisted event loop. If your subprocess is a python program, you need to: - Run python.exe with the '-u' command line option - this turns on unbuffered I/O. Buffering stdout/err/in can cause problems, see e.g. http://support.microsoft.com/default.aspx?scid=kb;EN-US;q1903 - If you don't want Windows messing with data passed over stdin/out/err, set the pipes to be in binary mode:: import os, sys, mscvrt msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY) msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) msvcrt.setmode(sys.stderr.fileno(), os.O_BINARY) """ implements(IProcessTransport, IConsumer, IProducer) closedNotifies = 0 def __init__(self, reactor, protocol, command, args, environment, path): """ Create a new child process. """ _pollingfile._PollingTimer.__init__(self, reactor) BaseProcess.__init__(self, protocol) # security attributes for pipes sAttrs = win32security.SECURITY_ATTRIBUTES() sAttrs.bInheritHandle = 1 # create the pipes which will connect to the secondary process self.hStdoutR, hStdoutW = win32pipe.CreatePipe(sAttrs, 0) self.hStderrR, hStderrW = win32pipe.CreatePipe(sAttrs, 0) hStdinR, self.hStdinW = win32pipe.CreatePipe(sAttrs, 0) win32pipe.SetNamedPipeHandleState(self.hStdinW, win32pipe.PIPE_NOWAIT, None, None) # set the info structure for the new process. StartupInfo = win32process.STARTUPINFO() StartupInfo.hStdOutput = hStdoutW StartupInfo.hStdError = hStderrW StartupInfo.hStdInput = hStdinR StartupInfo.dwFlags = win32process.STARTF_USESTDHANDLES # Create new handles whose inheritance property is false currentPid = win32api.GetCurrentProcess() tmp = win32api.DuplicateHandle(currentPid, self.hStdoutR, currentPid, 0, 0, win32con.DUPLICATE_SAME_ACCESS) win32file.CloseHandle(self.hStdoutR) self.hStdoutR = tmp tmp = win32api.DuplicateHandle(currentPid, self.hStderrR, currentPid, 0, 0, win32con.DUPLICATE_SAME_ACCESS) win32file.CloseHandle(self.hStderrR) self.hStderrR = tmp tmp = win32api.DuplicateHandle(currentPid, self.hStdinW, currentPid, 0, 0, win32con.DUPLICATE_SAME_ACCESS) win32file.CloseHandle(self.hStdinW) self.hStdinW = tmp # Add the specified environment to the current environment - this is # necessary because certain operations are only supported on Windows # if certain environment variables are present. env = os.environ.copy() env.update(environment or {}) cmdline = quoteArguments(args) # TODO: error detection here. See #2787 and #4184. def doCreate(): self.hProcess, self.hThread, self.pid, dwTid = win32process.CreateProcess( command, cmdline, None, None, 1, 0, env, path, StartupInfo) try: try: doCreate() except TypeError, e: # win32process.CreateProcess cannot deal with mixed # str/unicode environment, so we make it all Unicode if e.args != ('All dictionary items must be strings, or ' 'all must be unicode',): raise newenv = {} for key, value in env.items(): newenv[unicode(key)] = unicode(value) env = newenv doCreate() except pywintypes.error, pwte: if not _invalidWin32App(pwte): # This behavior isn't _really_ documented, but let's make it # consistent with the behavior that is documented. raise OSError(pwte) else: # look for a shebang line. Insert the original 'command' # (actually a script) into the new arguments list. sheb = _findShebang(command) if sheb is None: raise OSError( "%r is neither a Windows executable, " "nor a script with a shebang line" % command) else: args = list(args) args.insert(0, command) cmdline = quoteArguments(args) origcmd = command command = sheb try: # Let's try again. doCreate() except pywintypes.error, pwte2: # d'oh, failed again! if _invalidWin32App(pwte2): raise OSError( "%r has an invalid shebang line: " "%r is not a valid executable" % ( origcmd, sheb)) raise OSError(pwte2) # close handles which only the child will use win32file.CloseHandle(hStderrW) win32file.CloseHandle(hStdoutW) win32file.CloseHandle(hStdinR) # set up everything self.stdout = _pollingfile._PollableReadPipe( self.hStdoutR, lambda data: self.proto.childDataReceived(1, data), self.outConnectionLost) self.stderr = _pollingfile._PollableReadPipe( self.hStderrR, lambda data: self.proto.childDataReceived(2, data), self.errConnectionLost) self.stdin = _pollingfile._PollableWritePipe( self.hStdinW, self.inConnectionLost) for pipewatcher in self.stdout, self.stderr, self.stdin: self._addPollableResource(pipewatcher) # notify protocol self.proto.makeConnection(self) self._addPollableResource(_Reaper(self)) def signalProcess(self, signalID): if self.pid is None: raise error.ProcessExitedAlready() if signalID in ("INT", "TERM", "KILL"): win32process.TerminateProcess(self.hProcess, 1) def _getReason(self, status): if status == 0: return error.ProcessDone(status) return error.ProcessTerminated(status) def write(self, data): """Write data to the process' stdin.""" self.stdin.write(data) def writeSequence(self, seq): """Write data to the process' stdin.""" self.stdin.writeSequence(seq) def closeChildFD(self, fd): if fd == 0: self.closeStdin() elif fd == 1: self.closeStdout() elif fd == 2: self.closeStderr() else: raise NotImplementedError("Only standard-IO file descriptors available on win32") def closeStdin(self): """Close the process' stdin. """ self.stdin.close() def closeStderr(self): self.stderr.close() def closeStdout(self): self.stdout.close() def loseConnection(self): """Close the process' stdout, in and err.""" self.closeStdin() self.closeStdout() self.closeStderr() def outConnectionLost(self): self.proto.childConnectionLost(1) self.connectionLostNotify() def errConnectionLost(self): self.proto.childConnectionLost(2) self.connectionLostNotify() def inConnectionLost(self): self.proto.childConnectionLost(0) self.connectionLostNotify() def connectionLostNotify(self): """ Will be called 3 times, by stdout/err threads and process handle. """ self.closedNotifies += 1 self.maybeCallProcessEnded() def maybeCallProcessEnded(self): if self.closedNotifies == 3 and self.lostProcess: win32file.CloseHandle(self.hProcess) win32file.CloseHandle(self.hThread) self.hProcess = None self.hThread = None BaseProcess.maybeCallProcessEnded(self) # IConsumer def registerProducer(self, producer, streaming): self.stdin.registerProducer(producer, streaming) def unregisterProducer(self): self.stdin.unregisterProducer() # IProducer def pauseProducing(self): self._pause() def resumeProducing(self): self._unpause() def stopProducing(self): self.loseConnection() def __repr__(self): """ Return a string representation of the process. """ return "<%s pid=%s>" % (self.__class__.__name__, self.pid)
{ "pile_set_name": "Github" }
/* * JPEG2000 encoder and decoder common functions * Copyright (c) 2007 Kamil Nowosad * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * JPEG2000 image encoder and decoder common functions * @file * @author Kamil Nowosad */ #include "avcodec.h" #include "j2k.h" #define SHL(a, n) ((n)>=0 ? (a) << (n) : (a) >> -(n)) #if 0 void ff_j2k_printv(int *tab, int l) { int i; for (i = 0; i < l; i++) printf("%.3d ", tab[i]); printf("\n"); } void ff_j2k_printu(uint8_t *tab, int l) { int i; for (i = 0; i < l; i++) printf("%.3hd ", tab[i]); printf("\n"); } #endif /* tag tree routines */ /** allocate the memory for tag tree */ static int tag_tree_size(int w, int h) { int res = 0; while (w > 1 || h > 1){ res += w * h; w = (w+1) >> 1; h = (h+1) >> 1; } return res + 1; } J2kTgtNode *ff_j2k_tag_tree_init(int w, int h) { int pw = w, ph = h; J2kTgtNode *res, *t, *t2; t = res = av_mallocz(tag_tree_size(w, h)*sizeof(J2kTgtNode)); if (res == NULL) return NULL; while (w > 1 || h > 1){ int i, j; pw = w; ph = h; w = (w+1) >> 1; h = (h+1) >> 1; t2 = t + pw*ph; for (i = 0; i < ph; i++) for (j = 0; j < pw; j++){ t[i*pw + j].parent = &t2[(i>>1)*w + (j>>1)]; } t = t2; } t[0].parent = NULL; return res; } static void tag_tree_zero(J2kTgtNode *t, int w, int h) { int i, siz = tag_tree_size(w, h); for (i = 0; i < siz; i++){ t[i].val = 0; t[i].vis = 0; } } uint8_t ff_j2k_nbctxno_lut[256][4]; static int getnbctxno(int flag, int bandno, int vert_causal_ctx_csty_symbol) { int h, v, d; h = ((flag & J2K_T1_SIG_E) ? 1:0)+ ((flag & J2K_T1_SIG_W) ? 1:0); v = ((flag & J2K_T1_SIG_N) ? 1:0); if (!vert_causal_ctx_csty_symbol) v = v + ((flag & J2K_T1_SIG_S) ? 1:0); d = ((flag & J2K_T1_SIG_NE) ? 1:0)+ ((flag & J2K_T1_SIG_NW) ? 1:0); if (!vert_causal_ctx_csty_symbol) d = d + ((flag & J2K_T1_SIG_SE) ? 1:0)+ ((flag & J2K_T1_SIG_SW) ? 1:0); if (bandno < 3){ if (bandno == 1) FFSWAP(int, h, v); if (h == 2) return 8; if (h == 1){ if (v >= 1) return 7; if (d >= 1) return 6; return 5; } if (v == 2) return 4; if (v == 1) return 3; if (d >= 2) return 2; if (d == 1) return 1; return 0; } else{ if (d >= 3) return 8; if (d == 2){ if (h+v >= 1) return 7; return 6; } if (d == 1){ if (h+v >= 2) return 5; if (h+v == 1) return 4; return 3; } if (h+v >= 2) return 2; if (h+v == 1) return 1; return 0; } assert(0); } uint8_t ff_j2k_sgnctxno_lut[16][16], ff_j2k_xorbit_lut[16][16]; static int getsgnctxno(int flag, uint8_t *xorbit) { int vcontrib, hcontrib; static const int contribtab[3][3] = {{0, -1, 1}, {-1, -1, 0}, {1, 0, 1}}; static const int ctxlbltab[3][3] = {{13, 12, 11}, {10, 9, 10}, {11, 12, 13}}; static const int xorbittab[3][3] = {{1, 1, 1,}, {1, 0, 0}, {0, 0, 0}}; hcontrib = contribtab[flag & J2K_T1_SIG_E ? flag & J2K_T1_SGN_E ? 1:2:0] [flag & J2K_T1_SIG_W ? flag & J2K_T1_SGN_W ? 1:2:0]+1; vcontrib = contribtab[flag & J2K_T1_SIG_S ? flag & J2K_T1_SGN_S ? 1:2:0] [flag & J2K_T1_SIG_N ? flag & J2K_T1_SGN_N ? 1:2:0]+1; *xorbit = xorbittab[hcontrib][vcontrib]; return ctxlbltab[hcontrib][vcontrib]; } void ff_j2k_init_tier1_luts(void) { int i, j; for (i = 0; i < 256; i++) for (j = 0; j < 4; j++) ff_j2k_nbctxno_lut[i][j] = getnbctxno(i, j, 0); for (i = 0; i < 16; i++) for (j = 0; j < 16; j++) ff_j2k_sgnctxno_lut[i][j] = getsgnctxno(i + (j << 8), &ff_j2k_xorbit_lut[i][j]); } void ff_j2k_set_significant(J2kT1Context *t1, int x, int y, int negative) { x++; y++; t1->flags[y][x] |= J2K_T1_SIG; if (negative){ t1->flags[y][x+1] |= J2K_T1_SIG_W | J2K_T1_SGN_W; t1->flags[y][x-1] |= J2K_T1_SIG_E | J2K_T1_SGN_E; t1->flags[y+1][x] |= J2K_T1_SIG_N | J2K_T1_SGN_N; t1->flags[y-1][x] |= J2K_T1_SIG_S | J2K_T1_SGN_S; } else{ t1->flags[y][x+1] |= J2K_T1_SIG_W; t1->flags[y][x-1] |= J2K_T1_SIG_E; t1->flags[y+1][x] |= J2K_T1_SIG_N; t1->flags[y-1][x] |= J2K_T1_SIG_S; } t1->flags[y+1][x+1] |= J2K_T1_SIG_NW; t1->flags[y+1][x-1] |= J2K_T1_SIG_NE; t1->flags[y-1][x+1] |= J2K_T1_SIG_SW; t1->flags[y-1][x-1] |= J2K_T1_SIG_SE; } int ff_j2k_init_component(J2kComponent *comp, J2kCodingStyle *codsty, J2kQuantStyle *qntsty, int cbps, int dx, int dy) { int reslevelno, bandno, gbandno = 0, ret, i, j, csize = 1; if (ret=ff_j2k_dwt_init(&comp->dwt, comp->coord, codsty->nreslevels-1, codsty->transform)) return ret; for (i = 0; i < 2; i++) csize *= comp->coord[i][1] - comp->coord[i][0]; comp->data = av_malloc(csize * sizeof(int)); if (!comp->data) return AVERROR(ENOMEM); comp->reslevel = av_malloc(codsty->nreslevels * sizeof(J2kResLevel)); if (!comp->reslevel) return AVERROR(ENOMEM); for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){ int declvl = codsty->nreslevels - reslevelno; J2kResLevel *reslevel = comp->reslevel + reslevelno; for (i = 0; i < 2; i++) for (j = 0; j < 2; j++) reslevel->coord[i][j] = ff_j2k_ceildivpow2(comp->coord[i][j], declvl - 1); if (reslevelno == 0) reslevel->nbands = 1; else reslevel->nbands = 3; if (reslevel->coord[0][1] == reslevel->coord[0][0]) reslevel->num_precincts_x = 0; else reslevel->num_precincts_x = ff_j2k_ceildivpow2(reslevel->coord[0][1], codsty->log2_prec_width) - (reslevel->coord[0][0] >> codsty->log2_prec_width); if (reslevel->coord[1][1] == reslevel->coord[1][0]) reslevel->num_precincts_y = 0; else reslevel->num_precincts_y = ff_j2k_ceildivpow2(reslevel->coord[1][1], codsty->log2_prec_height) - (reslevel->coord[1][0] >> codsty->log2_prec_height); reslevel->band = av_malloc(reslevel->nbands * sizeof(J2kBand)); if (!reslevel->band) return AVERROR(ENOMEM); for (bandno = 0; bandno < reslevel->nbands; bandno++, gbandno++){ J2kBand *band = reslevel->band + bandno; int cblkno, precx, precy, precno; int x0, y0, x1, y1; int xi0, yi0, xi1, yi1; int cblkperprecw, cblkperprech; if (qntsty->quantsty != J2K_QSTY_NONE){ const static uint8_t lut_gain[2][4] = {{0, 0, 0, 0}, {0, 1, 1, 2}}; int numbps; numbps = cbps + lut_gain[codsty->transform][bandno + reslevelno>0]; band->stepsize = SHL(2048 + qntsty->mant[gbandno], 2 + numbps - qntsty->expn[gbandno]); } else band->stepsize = 1 << 13; if (reslevelno == 0){ // the same everywhere band->codeblock_width = 1 << FFMIN(codsty->log2_cblk_width, codsty->log2_prec_width-1); band->codeblock_height = 1 << FFMIN(codsty->log2_cblk_height, codsty->log2_prec_height-1); for (i = 0; i < 2; i++) for (j = 0; j < 2; j++) band->coord[i][j] = ff_j2k_ceildivpow2(comp->coord[i][j], declvl-1); } else{ band->codeblock_width = 1 << FFMIN(codsty->log2_cblk_width, codsty->log2_prec_width); band->codeblock_height = 1 << FFMIN(codsty->log2_cblk_height, codsty->log2_prec_height); for (i = 0; i < 2; i++) for (j = 0; j < 2; j++) band->coord[i][j] = ff_j2k_ceildivpow2(comp->coord[i][j] - (((bandno+1>>i)&1) << declvl-1), declvl); } band->cblknx = ff_j2k_ceildiv(band->coord[0][1], band->codeblock_width) - band->coord[0][0] / band->codeblock_width; band->cblkny = ff_j2k_ceildiv(band->coord[1][1], band->codeblock_height) - band->coord[1][0] / band->codeblock_height; for (j = 0; j < 2; j++) band->coord[0][j] = ff_j2k_ceildiv(band->coord[0][j], dx); for (j = 0; j < 2; j++) band->coord[1][j] = ff_j2k_ceildiv(band->coord[1][j], dy); band->cblknx = ff_j2k_ceildiv(band->cblknx, dx); band->cblkny = ff_j2k_ceildiv(band->cblkny, dy); band->cblk = av_malloc(band->cblknx * band->cblkny * sizeof(J2kCblk)); if (!band->cblk) return AVERROR(ENOMEM); band->prec = av_malloc(reslevel->num_precincts_x * reslevel->num_precincts_y * sizeof(J2kPrec)); if (!band->prec) return AVERROR(ENOMEM); for (cblkno = 0; cblkno < band->cblknx * band->cblkny; cblkno++){ J2kCblk *cblk = band->cblk + cblkno; cblk->zero = 0; cblk->lblock = 3; cblk->length = 0; cblk->lengthinc = 0; cblk->npasses = 0; } y0 = band->coord[1][0]; y1 = ((band->coord[1][0] + (1<<codsty->log2_prec_height)) & ~((1<<codsty->log2_prec_height)-1)) - y0; yi0 = 0; yi1 = ff_j2k_ceildivpow2(y1 - y0, codsty->log2_cblk_height) << codsty->log2_cblk_height; yi1 = FFMIN(yi1, band->cblkny); cblkperprech = 1<<(codsty->log2_prec_height - codsty->log2_cblk_height); for (precy = 0, precno = 0; precy < reslevel->num_precincts_y; precy++){ for (precx = 0; precx < reslevel->num_precincts_x; precx++, precno++){ band->prec[precno].yi0 = yi0; band->prec[precno].yi1 = yi1; } yi1 += cblkperprech; yi0 = yi1 - cblkperprech; yi1 = FFMIN(yi1, band->cblkny); } x0 = band->coord[0][0]; x1 = ((band->coord[0][0] + (1<<codsty->log2_prec_width)) & ~((1<<codsty->log2_prec_width)-1)) - x0; xi0 = 0; xi1 = ff_j2k_ceildivpow2(x1 - x0, codsty->log2_cblk_width) << codsty->log2_cblk_width; xi1 = FFMIN(xi1, band->cblknx); cblkperprecw = 1<<(codsty->log2_prec_width - codsty->log2_cblk_width); for (precx = 0, precno = 0; precx < reslevel->num_precincts_x; precx++){ for (precy = 0; precy < reslevel->num_precincts_y; precy++, precno = 0){ J2kPrec *prec = band->prec + precno; prec->xi0 = xi0; prec->xi1 = xi1; prec->cblkincl = ff_j2k_tag_tree_init(prec->xi1 - prec->xi0, prec->yi1 - prec->yi0); prec->zerobits = ff_j2k_tag_tree_init(prec->xi1 - prec->xi0, prec->yi1 - prec->yi0); if (!prec->cblkincl || !prec->zerobits) return AVERROR(ENOMEM); } xi1 += cblkperprecw; xi0 = xi1 - cblkperprecw; xi1 = FFMIN(xi1, band->cblknx); } } } return 0; } void ff_j2k_reinit(J2kComponent *comp, J2kCodingStyle *codsty) { int reslevelno, bandno, cblkno, precno; for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){ J2kResLevel *rlevel = comp->reslevel + reslevelno; for (bandno = 0; bandno < rlevel->nbands; bandno++){ J2kBand *band = rlevel->band + bandno; for(precno = 0; precno < rlevel->num_precincts_x * rlevel->num_precincts_y; precno++){ J2kPrec *prec = band->prec + precno; tag_tree_zero(prec->zerobits, prec->xi1 - prec->xi0, prec->yi1 - prec->yi0); tag_tree_zero(prec->cblkincl, prec->xi1 - prec->xi0, prec->yi1 - prec->yi0); } for (cblkno = 0; cblkno < band->cblknx * band->cblkny; cblkno++){ J2kCblk *cblk = band->cblk + cblkno; cblk->length = 0; cblk->lblock = 3; } } } } void ff_j2k_cleanup(J2kComponent *comp, J2kCodingStyle *codsty) { int reslevelno, bandno, precno; for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){ J2kResLevel *reslevel = comp->reslevel + reslevelno; for (bandno = 0; bandno < reslevel->nbands ; bandno++){ J2kBand *band = reslevel->band + bandno; for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){ J2kPrec *prec = band->prec + precno; av_freep(&prec->zerobits); av_freep(&prec->cblkincl); } av_freep(&band->cblk); av_freep(&band->prec); } av_freep(&reslevel->band); } ff_j2k_dwt_destroy(&comp->dwt); av_freep(&comp->reslevel); av_freep(&comp->data); }
{ "pile_set_name": "Github" }
// Copyright (C) 2004 Arkadiy Vertleyb // Copyright (C) 2005 Peder Holt // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_TYPEOF_TEMPLATE_ENCODING_HPP_INCLUDED #define BOOST_TYPEOF_TEMPLATE_ENCODING_HPP_INCLUDED #include <boost/preprocessor/cat.hpp> #include <boost/preprocessor/repetition/enum_trailing.hpp> #include <boost/preprocessor/control/iif.hpp> #include <boost/preprocessor/detail/is_unary.hpp> #include <boost/preprocessor/repetition/repeat.hpp> #include <boost/preprocessor/tuple/eat.hpp> #include <boost/preprocessor/seq/transform.hpp> #include <boost/preprocessor/seq/for_each_i.hpp> #include <boost/preprocessor/seq/cat.hpp> #include <boost/typeof/encode_decode.hpp> #include <boost/typeof/int_encoding.hpp> #include <boost/typeof/type_template_param.hpp> #include <boost/typeof/integral_template_param.hpp> #include <boost/typeof/template_template_param.hpp> #ifdef __BORLANDC__ #define BOOST_TYPEOF_QUALIFY(P) self_t::P #else #define BOOST_TYPEOF_QUALIFY(P) P #endif // The template parameter description, entered by the user, // is converted into a polymorphic "object" // that is used to generate the code responsible for // encoding/decoding the parameter, etc. // make sure to cat the sequence first, and only then add the prefix. #define BOOST_TYPEOF_MAKE_OBJ(elem) BOOST_PP_CAT(\ BOOST_TYPEOF_MAKE_OBJ,\ BOOST_PP_SEQ_CAT((_) BOOST_TYPEOF_TO_SEQ(elem))\ ) #define BOOST_TYPEOF_TO_SEQ(tokens) BOOST_TYPEOF_ ## tokens ## _BOOST_TYPEOF // BOOST_TYPEOF_REGISTER_TEMPLATE #define BOOST_TYPEOF_REGISTER_TEMPLATE_EXPLICIT_ID(Name, Params, Id)\ BOOST_TYPEOF_REGISTER_TEMPLATE_IMPL(\ Name,\ BOOST_TYPEOF_MAKE_OBJS(BOOST_TYPEOF_TOSEQ(Params)),\ BOOST_PP_SEQ_SIZE(BOOST_TYPEOF_TOSEQ(Params)),\ Id) #define BOOST_TYPEOF_REGISTER_TEMPLATE(Name, Params)\ BOOST_TYPEOF_REGISTER_TEMPLATE_EXPLICIT_ID(Name, Params, BOOST_TYPEOF_UNIQUE_ID()) #define BOOST_TYPEOF_OBJECT_MAKER(s, data, elem)\ BOOST_TYPEOF_MAKE_OBJ(elem) #define BOOST_TYPEOF_MAKE_OBJS(Params)\ BOOST_PP_SEQ_TRANSFORM(BOOST_TYPEOF_OBJECT_MAKER, ~, Params) // As suggested by Paul Mensonides: #define BOOST_TYPEOF_TOSEQ(x)\ BOOST_PP_IIF(\ BOOST_PP_IS_UNARY(x),\ x BOOST_PP_TUPLE_EAT(3), BOOST_PP_REPEAT\ )(x, BOOST_TYPEOF_TOSEQ_2, ~) #define BOOST_TYPEOF_TOSEQ_2(z, n, _) (class) // BOOST_TYPEOF_VIRTUAL #define BOOST_TYPEOF_CAT_4(a, b, c, d) BOOST_TYPEOF_CAT_4_I(a, b, c, d) #define BOOST_TYPEOF_CAT_4_I(a, b, c, d) a ## b ## c ## d #define BOOST_TYPEOF_VIRTUAL(Fun, Obj)\ BOOST_TYPEOF_CAT_4(BOOST_TYPEOF_, BOOST_PP_SEQ_HEAD(Obj), _, Fun) // BOOST_TYPEOF_SEQ_ENUM[_TRAILING][_1] // Two versions provided due to reentrancy issue #define BOOST_TYPEOF_SEQ_EXPAND_ELEMENT(z,n,seq)\ BOOST_PP_SEQ_ELEM(0,seq) (z,n,BOOST_PP_SEQ_ELEM(n,BOOST_PP_SEQ_ELEM(1,seq))) #define BOOST_TYPEOF_SEQ_ENUM(seq,macro)\ BOOST_PP_ENUM(BOOST_PP_SEQ_SIZE(seq),BOOST_TYPEOF_SEQ_EXPAND_ELEMENT,(macro)(seq)) #define BOOST_TYPEOF_SEQ_ENUM_TRAILING(seq,macro)\ BOOST_PP_ENUM_TRAILING(BOOST_PP_SEQ_SIZE(seq),BOOST_TYPEOF_SEQ_EXPAND_ELEMENT,(macro)(seq)) #define BOOST_TYPEOF_SEQ_EXPAND_ELEMENT_1(z,n,seq)\ BOOST_PP_SEQ_ELEM(0,seq) (z,n,BOOST_PP_SEQ_ELEM(n,BOOST_PP_SEQ_ELEM(1,seq))) #define BOOST_TYPEOF_SEQ_ENUM_1(seq,macro)\ BOOST_PP_ENUM(BOOST_PP_SEQ_SIZE(seq),BOOST_TYPEOF_SEQ_EXPAND_ELEMENT_1,(macro)(seq)) #define BOOST_TYPEOF_SEQ_ENUM_TRAILING_1(seq,macro)\ BOOST_PP_ENUM_TRAILING(BOOST_PP_SEQ_SIZE(seq),BOOST_TYPEOF_SEQ_EXPAND_ELEMENT_1,(macro)(seq)) // #define BOOST_TYPEOF_PLACEHOLDER(z, n, elem)\ BOOST_TYPEOF_VIRTUAL(PLACEHOLDER, elem)(elem) #define BOOST_TYPEOF_PLACEHOLDER_TYPES(z, n, elem)\ BOOST_TYPEOF_VIRTUAL(PLACEHOLDER_TYPES, elem)(elem, n) #define BOOST_TYPEOF_REGISTER_TEMPLATE_ENCODE_PARAM(r, data, n, elem)\ BOOST_TYPEOF_VIRTUAL(ENCODE, elem)(elem, n) #define BOOST_TYPEOF_REGISTER_TEMPLATE_DECODE_PARAM(r, data, n, elem)\ BOOST_TYPEOF_VIRTUAL(DECODE, elem)(elem, n) #define BOOST_TYPEOF_REGISTER_TEMPLATE_PARAM_PAIR(z, n, elem) \ BOOST_TYPEOF_VIRTUAL(EXPANDTYPE, elem)(elem) BOOST_PP_CAT(P, n) #define BOOST_TYPEOF_REGISTER_DEFAULT_TEMPLATE_TYPE(Name,Params,ID)\ Name< BOOST_PP_ENUM_PARAMS(BOOST_PP_SEQ_SIZE(Params), P) > //Since we are creating an internal decode struct, we need to use different template names, T instead of P. #define BOOST_TYPEOF_REGISTER_DECODER_TYPE_PARAM_PAIR(z,n,elem) \ BOOST_TYPEOF_VIRTUAL(EXPANDTYPE, elem)(elem) BOOST_PP_CAT(T, n) //Default template param decoding #define BOOST_TYPEOF_TYPEDEF_DECODED_TEMPLATE_TYPE(Name,Params)\ typedef Name<BOOST_PP_ENUM_PARAMS(BOOST_PP_SEQ_SIZE(Params),BOOST_TYPEOF_QUALIFY(P))> type; //Branch the decoding #define BOOST_TYPEOF_TYPEDEF_DECODED_TYPE(Name,Params)\ BOOST_PP_IF(BOOST_TYPEOF_HAS_TEMPLATES(Params),\ BOOST_TYPEOF_TYPEDEF_DECODED_TEMPLATE_TEMPLATE_TYPE,\ BOOST_TYPEOF_TYPEDEF_DECODED_TEMPLATE_TYPE)(Name,Params) #define BOOST_TYPEOF_REGISTER_TEMPLATE_IMPL(Name, Params, Size, ID)\ BOOST_TYPEOF_BEGIN_ENCODE_NS\ BOOST_TYPEOF_REGISTER_TEMPLATE_TEMPLATE_IMPL(Name, Params, ID)\ template<class V\ BOOST_TYPEOF_SEQ_ENUM_TRAILING(Params, BOOST_TYPEOF_REGISTER_TEMPLATE_PARAM_PAIR)\ >\ struct encode_type_impl<V, Name<BOOST_PP_ENUM_PARAMS(Size, P)> >\ {\ typedef typename boost::type_of::push_back<V, boost::mpl::size_t<ID> >::type V0;\ BOOST_PP_SEQ_FOR_EACH_I(BOOST_TYPEOF_REGISTER_TEMPLATE_ENCODE_PARAM, ~, Params)\ typedef BOOST_PP_CAT(V, Size) type;\ };\ template<class Iter>\ struct decode_type_impl<boost::mpl::size_t<ID>, Iter>\ {\ typedef decode_type_impl<boost::mpl::size_t<ID>, Iter> self_t;\ typedef boost::mpl::size_t<ID> self_id;\ typedef Iter iter0;\ BOOST_PP_SEQ_FOR_EACH_I(BOOST_TYPEOF_REGISTER_TEMPLATE_DECODE_PARAM, ~, Params)\ BOOST_TYPEOF_TYPEDEF_DECODED_TYPE(Name, Params)\ typedef BOOST_PP_CAT(iter, Size) iter;\ };\ BOOST_TYPEOF_END_ENCODE_NS #endif//BOOST_TYPEOF_TEMPLATE_ENCODING_HPP_INCLUDED
{ "pile_set_name": "Github" }
' Copyright (c) Microsoft Corporation. All rights reserved. ''' <summary> '''The customer class represents a customer name and an ID number. By implementing the IComparable ''' interface we can support sorting array's and collections of this class. ''' </summary> Public Class Customer Implements IComparable Private mName As String Private mId As Integer Public Sub New(ByVal new_name As String, ByVal new_id As Integer) mName = new_name mId = new_id End Sub Public Overrides Function ToString() As String Return mId.ToString() + ": " + mName End Function ''' <summary> '''The compare to function is the implementation of the IComarable interface. For the customer ''' class we will only implement the comparison of the ID field. This means that any sorting ''' done on an array or collection of these objects will sort by the customer ID. ''' </summary> Public Function CompareTo(ByVal obj As Object) As Integer Implements IComparable.CompareTo ' First check to make sure that we are comparing this instance to another customer. If TypeOf obj Is Customer Then ' Create a strongly typed instance of obj. Dim c As Customer c = CType(obj, Customer) If c.ID = Me.ID Then Return 0 ElseIf c.ID < Me.ID Then Return 1 Else Return -1 End If Else Throw New ArgumentException("Customers can only be compared to other customers.") End If End Function ''' <summary> ''' The name of the customer ''' </summary> Public Property Name() As String Get Return mName End Get Set(ByVal Value As String) mName = Value End Set End Property ''' <summary> ''' The ID of the customer ''' </summary> Public Property ID() As Integer Get Return mId End Get Set(ByVal Value As Integer) mId = Value End Set End Property End Class
{ "pile_set_name": "Github" }
<div id="time" class="form-group has-feedback formio-component formio-component-time formio-component-time " ref="component"> <label class="col-form-label " for="time-time"> Time </label> <div ref="element"> <div ref="value">-</div> </div> <div ref="messageContainer" class="formio-errors invalid-feedback"></div> </div>
{ "pile_set_name": "Github" }
/* * This file is part of RskJ * Copyright (C) 2017 RSK Labs Ltd. * (derived from ethereumJ library, Copyright (c) 2016 <ether.camp>) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.rlpx; import co.rsk.net.NodeID; import org.bouncycastle.util.encoders.Hex; import org.ethereum.util.ByteUtil; import org.ethereum.util.RLP; import org.ethereum.util.RLPList; import java.io.Serializable; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Objects; import static org.ethereum.util.ByteUtil.byteArrayToInt; public class Node implements Serializable { private static final long serialVersionUID = -4267600517925770636L; private final byte[] id; private final String host; private final int port; public Node(String enodeURL) { try { URI uri = new URI(enodeURL); if (!uri.getScheme().equals("enode")) { throw new RuntimeException("expecting URL in the format enode://PUBKEY@HOST:PORT"); } this.id = Hex.decode(uri.getUserInfo()); this.host = uri.getHost(); this.port = uri.getPort(); } catch (URISyntaxException e) { throw new RuntimeException("expecting URL in the format enode://PUBKEY@HOST:PORT", e); } } public Node(byte[] id, String host, int port) { this.id = id; this.host = host; this.port = port; } public Node(byte[] rlp) { RLPList nodeRLP = (RLPList)RLP.decode2(rlp).get(0); byte[] hostB = nodeRLP.get(0).getRLPData(); byte[] portB = nodeRLP.get(1).getRLPData(); byte[] idB; //Check getRLP() if (nodeRLP.size() > 3) { idB = nodeRLP.get(3).getRLPData(); } else { idB = nodeRLP.get(2).getRLPData(); } String host = new String(hostB, Charset.forName("UTF-8")); int port = byteArrayToInt(portB); this.id = idB; this.host = host; this.port = port; } public NodeID getId() { return new NodeID(id); } public String getHexId() { return ByteUtil.toHexString(id); } public String getHost() { return host; } public int getPort() { return port; } public byte[] getRLP() { byte[] rlphost = RLP.encodeElement(host.getBytes(StandardCharsets.UTF_8)); byte[] rlpTCPPort = RLP.encodeInt(port); byte[] rlpUDPPort = RLP.encodeInt(port); byte[] rlpId = RLP.encodeElement(id); return RLP.encodeList(rlphost, rlpUDPPort, rlpTCPPort, rlpId); } public InetSocketAddress getAddress() { return new InetSocketAddress(this.getHost(), this.getPort()); } public String getAddressAsString() { InetSocketAddress address = this.getAddress(); InetAddress addr = address.getAddress(); // addr == null if the hostname can't be resolved return (addr == null ? address.getHostString() : addr.getHostAddress()) + ":" + address.getPort(); } @Override public String toString() { return "Node{" + " host='" + host + '\'' + ", port=" + port + ", id=" + getHexId() + '}'; } @Override public int hashCode() { return Objects.hash(host, port, id); } @Override public boolean equals(Object o) { if (o == null) { return false; } if (o == this) { return true; } if (!(o instanceof Node)) { return false; } // TODO(mc): do we need to check host and port too? return Arrays.equals(id, ((Node) o).id); } }
{ "pile_set_name": "Github" }
object E extends App { assert(D.x == "3") }
{ "pile_set_name": "Github" }
/** * Copyright (c) 2014,2019 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.eclipse.smarthome.io.http.servlet; import org.osgi.service.http.HttpContext; /** * Base class for HTTP servlets which share certain {@link HttpContext} instance. * * @author Łukasz Dywicki - initial implementation. */ public abstract class SmartHomeServlet extends BaseSmartHomeServlet { private static final long serialVersionUID = 6854521240046714164L; /** * Http context. */ protected HttpContext httpContext; protected void setHttpContext(HttpContext httpContext) { this.httpContext = httpContext; } protected void unsetHttpContext(HttpContext httpContext) { this.httpContext = null; } protected void activate(String alias) { super.activate(alias, httpContext); } }
{ "pile_set_name": "Github" }
#include <rs_config.h> #include <rs_core.h> static rs_str_t *rs_sys_errlist = NULL; static rs_str_t rs_unknown_error = rs_string("Unknown error"); char *rs_strerror(rs_err_t err, char *errstr, size_t size) { rs_str_t *msg; msg = ((uint32_t) err < RS_SYS_NERR) ? &rs_sys_errlist[err] : &rs_unknown_error; // not modify size = rs_min(size, msg->len); return rs_cpymem(errstr, msg->data, size); } int rs_init_strerror() { char *msg, *p; size_t len; rs_err_t err; len = RS_SYS_NERR * sizeof(rs_str_t); rs_sys_errlist = malloc(len); if (rs_sys_errlist == NULL) { goto failed; } for (err = 0; err < RS_SYS_NERR; err++) { msg = NULL; p = NULL; msg = strerror(err); len = rs_strlen(msg); p = malloc(len); if(p == NULL) { goto failed; } rs_memcpy(p, msg, len); rs_sys_errlist[err].len = len; rs_sys_errlist[err].data = p; } return RS_OK; failed: err = rs_errno; rs_log_stderr(0, "malloc(%uz) failed (%d: %s)", len, err, strerror(err)); return RS_ERR; } void rs_free_strerr() { rs_err_t err; if(rs_sys_errlist != NULL) { for (err = 0; err < RS_SYS_NERR; err++) { if(rs_sys_errlist[err].len != 0) { free(rs_sys_errlist[err].data); } } free(rs_sys_errlist); } }
{ "pile_set_name": "Github" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.3"/> <title>csi2txss: Csi2txss_v1_0</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); $(window).load(resizeHeight); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> <link href="HTML_custom.css" rel="stylesheet" type="text/css"/> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectlogo"><img alt="Logo" src="xlogo_bg.gif"/></td> <td style="padding-left: 0.5em;"> <div id="projectname">csi2txss </div> <div id="projectbrief">Xilinx Vitis Drivers API Documentation</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.3 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Overview</span></a></li> <li><a href="annotated.html"><span>Data&#160;Structures</span></a></li> <li><a href="globals.html"><span>APIs</span></a></li> <li><a href="files.html"><span>File&#160;List</span></a></li> <li><a href="pages.html"><span>Examples</span></a></li> </ul> </div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('group__csi2txss__v1__0.html','');}); </script> <div id="doc-content"> <div class="header"> <div class="summary"> <a href="#func-members">Functions</a> </div> <div class="headertitle"> <div class="title">Csi2txss_v1_0</div> </div> </div><!--header--> <div class="contents"> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="func-members"></a> Functions</h2></td></tr> <tr class="memitem:ga4f003f0f154d0a6f6d7c06498ff3c655"><td class="memItemLeft" align="right" valign="top">u32&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__csi2txss__v1__0.html#ga4f003f0f154d0a6f6d7c06498ff3c655">Csi2TxSs_IntrExample</a> (u32 DeviceId)</td></tr> <tr class="memdesc:ga4f003f0f154d0a6f6d7c06498ff3c655"><td class="mdescLeft">&#160;</td><td class="mdescRight">This function is the main entry point for the interrupt example using the <a class="el" href="struct_x_csi2_tx_ss.html" title="The XCsi2TxSs driver instance data.">XCsi2TxSs</a> driver. <a href="#ga4f003f0f154d0a6f6d7c06498ff3c655"></a><br/></td></tr> <tr class="separator:ga4f003f0f154d0a6f6d7c06498ff3c655"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga7f3c94a567227794158a9e77850ad45a"><td class="memItemLeft" align="right" valign="top">u32&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__csi2txss__v1__0.html#ga7f3c94a567227794158a9e77850ad45a">Csi2TxSs_PlatformInit</a> (void)</td></tr> <tr class="memdesc:ga7f3c94a567227794158a9e77850ad45a"><td class="mdescLeft">&#160;</td><td class="mdescRight">This function initialize required platform-specifc peripherals. <a href="#ga7f3c94a567227794158a9e77850ad45a"></a><br/></td></tr> <tr class="separator:ga7f3c94a567227794158a9e77850ad45a"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga4261a1f4e4767eee83fa1ab1990fd25e"><td class="memItemLeft" align="right" valign="top">u32&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__csi2txss__v1__0.html#ga4261a1f4e4767eee83fa1ab1990fd25e">Csi2TxSs_SetupIntrSystem</a> (XINTC *IntcInstPtr)</td></tr> <tr class="memdesc:ga4261a1f4e4767eee83fa1ab1990fd25e"><td class="mdescLeft">&#160;</td><td class="mdescRight">This function sets up the interrupt system so interrupts can occur for the MIPI CSI2Tx Subsystem core. <a href="#ga4261a1f4e4767eee83fa1ab1990fd25e"></a><br/></td></tr> <tr class="separator:ga4261a1f4e4767eee83fa1ab1990fd25e"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga9cb8d015cac4e68c6cbe5b9c0b76bac9"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__csi2txss__v1__0.html#ga9cb8d015cac4e68c6cbe5b9c0b76bac9">Csi2TxSs_WrgLaneEventHandler</a> (void *InstancePtr, u32 Mask)</td></tr> <tr class="memdesc:ga9cb8d015cac4e68c6cbe5b9c0b76bac9"><td class="mdescLeft">&#160;</td><td class="mdescRight">This function is called when Wrong number of lanes are configured by the MIPI CSI2Tx Subsystem core. <a href="#ga9cb8d015cac4e68c6cbe5b9c0b76bac9"></a><br/></td></tr> <tr class="separator:ga9cb8d015cac4e68c6cbe5b9c0b76bac9"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga5e477c7bc4aee8614bb89b403165d59c"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__csi2txss__v1__0.html#ga5e477c7bc4aee8614bb89b403165d59c">Csi2TxSs_GSPFullEventHandler</a> (void *InstancePtr, u32 Mask)</td></tr> <tr class="memdesc:ga5e477c7bc4aee8614bb89b403165d59c"><td class="mdescLeft">&#160;</td><td class="mdescRight">This function is called when Genric Short Packet FIFO is found full by the MIPI CSI2Tx Subsystem core. <a href="#ga5e477c7bc4aee8614bb89b403165d59c"></a><br/></td></tr> <tr class="separator:ga5e477c7bc4aee8614bb89b403165d59c"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gadc28c0547eca7d2f3f09cc4151c7cab5"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__csi2txss__v1__0.html#gadc28c0547eca7d2f3f09cc4151c7cab5">Csi2TxSs_UlpsEventHandler</a> (void *InstancePtr, u32 Mask)</td></tr> <tr class="memdesc:gadc28c0547eca7d2f3f09cc4151c7cab5"><td class="mdescLeft">&#160;</td><td class="mdescRight">This function is called when there is a change in ULPS state of D-PHY Lanes. <a href="#gadc28c0547eca7d2f3f09cc4151c7cab5"></a><br/></td></tr> <tr class="separator:gadc28c0547eca7d2f3f09cc4151c7cab5"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga003874deb0dc72b7d5f78b4d00a68561"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__csi2txss__v1__0.html#ga003874deb0dc72b7d5f78b4d00a68561">Csi2TxSs_LinebufEventHandler</a> (void *InstancePtr, u32 Mask)</td></tr> <tr class="memdesc:ga003874deb0dc72b7d5f78b4d00a68561"><td class="mdescLeft">&#160;</td><td class="mdescRight">This function is called when a Line buffer is full event recieved by MIPI CSI2Tx Subsystem core. <a href="#ga003874deb0dc72b7d5f78b4d00a68561"></a><br/></td></tr> <tr class="separator:ga003874deb0dc72b7d5f78b4d00a68561"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gacf6090a5e28c69c648d3688cf32069db"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__csi2txss__v1__0.html#gacf6090a5e28c69c648d3688cf32069db">Csi2TxSs_WrgDTypeEventHandler</a> (void *InstancePtr, u32 Mask)</td></tr> <tr class="memdesc:gacf6090a5e28c69c648d3688cf32069db"><td class="mdescLeft">&#160;</td><td class="mdescRight">This function is called when a event generated by unspported data type in GSP request to the MIPI CSI2Tx Subsystem core. <a href="#gacf6090a5e28c69c648d3688cf32069db"></a><br/></td></tr> <tr class="separator:gacf6090a5e28c69c648d3688cf32069db"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gab5d956c45981158d58b15833b9f570d0"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__csi2txss__v1__0.html#gab5d956c45981158d58b15833b9f570d0">Csi2TxSs_UrunPixelEventHandler</a> (void *InstancePtr, u32 Mask)</td></tr> <tr class="memdesc:gab5d956c45981158d58b15833b9f570d0"><td class="mdescLeft">&#160;</td><td class="mdescRight">This function is called when during packet transmission, byte stream FIFO is found to be starves for pixel by the MIPI CSI2Tx Subsystem core. <a href="#gab5d956c45981158d58b15833b9f570d0"></a><br/></td></tr> <tr class="separator:gab5d956c45981158d58b15833b9f570d0"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gae66f6b31b5ad750f1fe042a706a4e3d4"><td class="memItemLeft" align="right" valign="top">int&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__csi2txss__v1__0.html#gae66f6b31b5ad750f1fe042a706a4e3d4">main</a> ()</td></tr> <tr class="memdesc:gae66f6b31b5ad750f1fe042a706a4e3d4"><td class="mdescLeft">&#160;</td><td class="mdescRight">This is the main function for <a class="el" href="struct_x_csi2_tx_ss.html" title="The XCsi2TxSs driver instance data.">XCsi2TxSs</a> interrupt example. <a href="#gae66f6b31b5ad750f1fe042a706a4e3d4"></a><br/></td></tr> <tr class="separator:gae66f6b31b5ad750f1fe042a706a4e3d4"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga1e0a474f9469d041cee3f863c5a6de97"><td class="memItemLeft" align="right" valign="top">u32&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__csi2txss__v1__0.html#ga1e0a474f9469d041cee3f863c5a6de97">Csi2TxSs_SelfTestExample</a> (u32 DeviceId)</td></tr> <tr class="memdesc:ga1e0a474f9469d041cee3f863c5a6de97"><td class="mdescLeft">&#160;</td><td class="mdescRight">This function is the main entry point for the self test example using the <a class="el" href="struct_x_csi2_tx_ss.html" title="The XCsi2TxSs driver instance data.">XCsi2TxSs</a> driver. <a href="#ga1e0a474f9469d041cee3f863c5a6de97"></a><br/></td></tr> <tr class="separator:ga1e0a474f9469d041cee3f863c5a6de97"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <h2 class="groupheader">Function Documentation</h2> <a class="anchor" id="ga5e477c7bc4aee8614bb89b403165d59c"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void Csi2TxSs_GSPFullEventHandler </td> <td>(</td> <td class="paramtype">void *&#160;</td> <td class="paramname"><em>InstancePtr</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">u32&#160;</td> <td class="paramname"><em>Mask</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </div><div class="memdoc"> <p>This function is called when Genric Short Packet FIFO is found full by the MIPI CSI2Tx Subsystem core. </p> <dl class="params"><dt>Parameters</dt><dd> <table class="params"> <tr><td class="paramname">InstancePtr</td><td>is a pointer to the <a class="el" href="struct_x_csi2_tx_ss.html" title="The XCsi2TxSs driver instance data.">XCsi2TxSs</a> instance. </td></tr> <tr><td class="paramname">Mask</td><td>of interrupt which caused this event</td></tr> </table> </dd> </dl> <dl class="section return"><dt>Returns</dt><dd>None.</dd></dl> <dl class="section note"><dt>Note</dt><dd>Use the XCsi2TxSs_SetCallback driver function to set this function as the handler for Packet level error event. </dd></dl> <p>Referenced by <a class="el" href="group__csi2txss__v1__0.html#ga4261a1f4e4767eee83fa1ab1990fd25e">Csi2TxSs_SetupIntrSystem()</a>.</p> </div> </div> <a class="anchor" id="ga4f003f0f154d0a6f6d7c06498ff3c655"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">u32 Csi2TxSs_IntrExample </td> <td>(</td> <td class="paramtype">u32&#160;</td> <td class="paramname"><em>DeviceId</em></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>This function is the main entry point for the interrupt example using the <a class="el" href="struct_x_csi2_tx_ss.html" title="The XCsi2TxSs driver instance data.">XCsi2TxSs</a> driver. </p> <p>This function will set up the system with interrupts handlers.</p> <dl class="params"><dt>Parameters</dt><dd> <table class="params"> <tr><td class="paramname">DeviceId</td><td>is the unique device ID of the MIPI CSI2Tx Subsystem core.</td></tr> </table> </dd> </dl> <dl class="section return"><dt>Returns</dt><dd><ul> <li>XST_FAILURE if the system setup failed.</li> <li>XST_SUCCESS should never return since this function, if setup was successful, is blocking.</li> </ul> </dd></dl> <dl class="section note"><dt>Note</dt><dd>If system setup was successful, this function is blocking in order to illustrate interrupt handling. </dd></dl> <p>References <a class="el" href="struct_x_csi2_tx_ss___config.html#a81d81ca026f814b36aaa4f640886fb9b">XCsi2TxSs_Config::BaseAddr</a>, <a class="el" href="group__csi2txss__v1__0.html#ga7f3c94a567227794158a9e77850ad45a">Csi2TxSs_PlatformInit()</a>, <a class="el" href="group__csi2txss__v1__0.html#ga4261a1f4e4767eee83fa1ab1990fd25e">Csi2TxSs_SetupIntrSystem()</a>, <a class="el" href="group__csi2txss__v1__3.html#gac74b7b2f7be7e695c3034f45d681c8ed">XCsi2TxSs_Activate()</a>, <a class="el" href="group__csi2txss__v1__3.html#ga05a335318d3ee341c8288279cf4d8683">XCsi2TxSs_CfgInitialize()</a>, <a class="el" href="group__csi2txss__v1__3.html#ga20a5a3fc9695ca1ac7fdbea4300da836">XCsi2TxSs_Configure()</a>, <a class="el" href="group__csi2txss__v1__3.html#ga011ccc31eea54a9b72e6ece5efed6853">XCsi2TxSs_LookupConfig()</a>, <a class="el" href="group__csi2txss__v1__3.html#gad5067597d1a3f39b5be158ce026e3f8c">XCsi2TxSs_ReportCoreInfo()</a>, and <a class="el" href="group__csi2txss__v1__3.html#ga9933630512ea21627aae263ff1833372">XCsi2TxSs_Reset()</a>.</p> <p>Referenced by <a class="el" href="group__csi2txss__v1__0.html#gae66f6b31b5ad750f1fe042a706a4e3d4">main()</a>.</p> </div> </div> <a class="anchor" id="ga003874deb0dc72b7d5f78b4d00a68561"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void Csi2TxSs_LinebufEventHandler </td> <td>(</td> <td class="paramtype">void *&#160;</td> <td class="paramname"><em>InstancePtr</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">u32&#160;</td> <td class="paramname"><em>Mask</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </div><div class="memdoc"> <p>This function is called when a Line buffer is full event recieved by MIPI CSI2Tx Subsystem core. </p> <dl class="params"><dt>Parameters</dt><dd> <table class="params"> <tr><td class="paramname">InstancePtr</td><td>is a pointer to the <a class="el" href="struct_x_csi2_tx_ss.html" title="The XCsi2TxSs driver instance data.">XCsi2TxSs</a> instance. </td></tr> <tr><td class="paramname">Mask</td><td>of interrupt which caused this event</td></tr> </table> </dd> </dl> <dl class="section return"><dt>Returns</dt><dd>None.</dd></dl> <dl class="section note"><dt>Note</dt><dd>Use the XCsi2TxSs_SetCallback driver function to set this function as the handler for Line buffer full event. </dd></dl> <p>Referenced by <a class="el" href="group__csi2txss__v1__0.html#ga4261a1f4e4767eee83fa1ab1990fd25e">Csi2TxSs_SetupIntrSystem()</a>.</p> </div> </div> <a class="anchor" id="ga7f3c94a567227794158a9e77850ad45a"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">u32 Csi2TxSs_PlatformInit </td> <td>(</td> <td class="paramtype">void&#160;</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>This function initialize required platform-specifc peripherals. </p> <dl class="params"><dt>Parameters</dt><dd> <table class="params"> <tr><td class="paramname">None.</td><td></td></tr> </table> </dd> </dl> <dl class="section return"><dt>Returns</dt><dd><ul> <li>XST_SUCCESS if required peripherals are initialized and configured successfully.</li> <li>XST_FAILURE, otherwise.</li> </ul> </dd></dl> <dl class="section note"><dt>Note</dt><dd>None. </dd></dl> <p>Referenced by <a class="el" href="group__csi2txss__v1__0.html#ga4f003f0f154d0a6f6d7c06498ff3c655">Csi2TxSs_IntrExample()</a>.</p> </div> </div> <a class="anchor" id="ga1e0a474f9469d041cee3f863c5a6de97"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">u32 Csi2TxSs_SelfTestExample </td> <td>(</td> <td class="paramtype">u32&#160;</td> <td class="paramname"><em>DeviceId</em></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>This function is the main entry point for the self test example using the <a class="el" href="struct_x_csi2_tx_ss.html" title="The XCsi2TxSs driver instance data.">XCsi2TxSs</a> driver. </p> <p>This function check whether or not its sub-core drivers self test functions are in working state.</p> <dl class="params"><dt>Parameters</dt><dd> <table class="params"> <tr><td class="paramname">DeviceId</td><td>is the unique device ID of the MIPI CSI2 TX Subsystem core.</td></tr> </table> </dd> </dl> <dl class="section return"><dt>Returns</dt><dd><ul> <li>XST_FAILURE if any of MIPI CSI2 TX Subsystem sub-core self test failed.</li> <li>XST_SUCCESS, if all of MIPI CSI2 TX Subsystem sub-core self test passed.</li> </ul> </dd></dl> <dl class="section note"><dt>Note</dt><dd>None. </dd></dl> <p>References <a class="el" href="struct_x_csi2_tx_ss___config.html#a81d81ca026f814b36aaa4f640886fb9b">XCsi2TxSs_Config::BaseAddr</a>, <a class="el" href="group__csi2txss__v1__3.html#ga05a335318d3ee341c8288279cf4d8683">XCsi2TxSs_CfgInitialize()</a>, <a class="el" href="group__csi2txss__v1__3.html#ga011ccc31eea54a9b72e6ece5efed6853">XCsi2TxSs_LookupConfig()</a>, and <a class="el" href="group__csi2txss__v1__3.html#ga55777b4afc7abf235debe2d797969577">XCsi2TxSs_SelfTest()</a>.</p> </div> </div> <a class="anchor" id="ga4261a1f4e4767eee83fa1ab1990fd25e"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">u32 Csi2TxSs_SetupIntrSystem </td> <td>(</td> <td class="paramtype">XINTC *&#160;</td> <td class="paramname"><em>IntcInstPtr</em></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>This function sets up the interrupt system so interrupts can occur for the MIPI CSI2Tx Subsystem core. </p> <p>The function is application-specific since the actual system may or may not have an interrupt controller. The MIPI CSI Subsystem core could be directly connected to a processor without an interrupt controller. The user should modify this function to fit the application.</p> <dl class="params"><dt>Parameters</dt><dd> <table class="params"> <tr><td class="paramname">IntcInstPtr</td><td>is a pointer to interrupt controller</td></tr> </table> </dd> </dl> <dl class="section return"><dt>Returns</dt><dd><ul> <li>XST_SUCCESS if interrupt setup was successful.</li> <li>A specific error code defined in "xstatus.h" if an error occurs.</li> </ul> </dd></dl> <dl class="section note"><dt>Note</dt><dd>None. </dd></dl> <p>References <a class="el" href="group__csi2txss__v1__0.html#ga5e477c7bc4aee8614bb89b403165d59c">Csi2TxSs_GSPFullEventHandler()</a>, <a class="el" href="group__csi2txss__v1__0.html#ga003874deb0dc72b7d5f78b4d00a68561">Csi2TxSs_LinebufEventHandler()</a>, <a class="el" href="group__csi2txss__v1__0.html#gadc28c0547eca7d2f3f09cc4151c7cab5">Csi2TxSs_UlpsEventHandler()</a>, <a class="el" href="group__csi2txss__v1__0.html#gab5d956c45981158d58b15833b9f570d0">Csi2TxSs_UrunPixelEventHandler()</a>, <a class="el" href="group__csi2txss__v1__0.html#gacf6090a5e28c69c648d3688cf32069db">Csi2TxSs_WrgDTypeEventHandler()</a>, <a class="el" href="group__csi2txss__v1__0.html#ga9cb8d015cac4e68c6cbe5b9c0b76bac9">Csi2TxSs_WrgLaneEventHandler()</a>, <a class="el" href="group__csi2txss__v1__3.html#ga8d8dd9ec87494c3d3b90dcafd05a6028">XCsi2TxSs_IntrHandler()</a>, and <a class="el" href="group__csi2txss__v1__3.html#ga445feeebfebea8ae0119be48a4a27ede">XCsi2TxSs_SetCallBack()</a>.</p> <p>Referenced by <a class="el" href="group__csi2txss__v1__0.html#ga4f003f0f154d0a6f6d7c06498ff3c655">Csi2TxSs_IntrExample()</a>.</p> </div> </div> <a class="anchor" id="gadc28c0547eca7d2f3f09cc4151c7cab5"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void Csi2TxSs_UlpsEventHandler </td> <td>(</td> <td class="paramtype">void *&#160;</td> <td class="paramname"><em>InstancePtr</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">u32&#160;</td> <td class="paramname"><em>Mask</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </div><div class="memdoc"> <p>This function is called when there is a change in ULPS state of D-PHY Lanes. </p> <dl class="params"><dt>Parameters</dt><dd> <table class="params"> <tr><td class="paramname">InstancePtr</td><td>is a pointer to the <a class="el" href="struct_x_csi2_tx_ss.html" title="The XCsi2TxSs driver instance data.">XCsi2TxSs</a> instance. </td></tr> <tr><td class="paramname">Mask</td><td>of interrupt which caused this event</td></tr> </table> </dd> </dl> <dl class="section return"><dt>Returns</dt><dd>None.</dd></dl> <dl class="section note"><dt>Note</dt><dd>Use the XCsi2TxSs_SetCallback driver function to set this function as the handler for ULPS mode detection event. </dd></dl> <p>Referenced by <a class="el" href="group__csi2txss__v1__0.html#ga4261a1f4e4767eee83fa1ab1990fd25e">Csi2TxSs_SetupIntrSystem()</a>.</p> </div> </div> <a class="anchor" id="gab5d956c45981158d58b15833b9f570d0"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void Csi2TxSs_UrunPixelEventHandler </td> <td>(</td> <td class="paramtype">void *&#160;</td> <td class="paramname"><em>InstancePtr</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">u32&#160;</td> <td class="paramname"><em>Mask</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </div><div class="memdoc"> <p>This function is called when during packet transmission, byte stream FIFO is found to be starves for pixel by the MIPI CSI2Tx Subsystem core. </p> <dl class="params"><dt>Parameters</dt><dd> <table class="params"> <tr><td class="paramname">InstancePtr</td><td>is a pointer to the <a class="el" href="struct_x_csi2_tx_ss.html" title="The XCsi2TxSs driver instance data.">XCsi2TxSs</a> instance.</td></tr> <tr><td class="paramname">Mask</td><td>of interrupt which caused this event</td></tr> </table> </dd> </dl> <dl class="section return"><dt>Returns</dt><dd>None.</dd></dl> <dl class="section note"><dt>Note</dt><dd>Use the XCsi2TxSs_SetCallback driver function to set this function as the handler for Byte stream FIFO starve event. </dd></dl> <p>Referenced by <a class="el" href="group__csi2txss__v1__0.html#ga4261a1f4e4767eee83fa1ab1990fd25e">Csi2TxSs_SetupIntrSystem()</a>.</p> </div> </div> <a class="anchor" id="gacf6090a5e28c69c648d3688cf32069db"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void Csi2TxSs_WrgDTypeEventHandler </td> <td>(</td> <td class="paramtype">void *&#160;</td> <td class="paramname"><em>InstancePtr</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">u32&#160;</td> <td class="paramname"><em>Mask</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </div><div class="memdoc"> <p>This function is called when a event generated by unspported data type in GSP request to the MIPI CSI2Tx Subsystem core. </p> <dl class="params"><dt>Parameters</dt><dd> <table class="params"> <tr><td class="paramname">InstancePtr</td><td>is a pointer to the <a class="el" href="struct_x_csi2_tx_ss.html" title="The XCsi2TxSs driver instance data.">XCsi2TxSs</a> instance.</td></tr> <tr><td class="paramname">Mask</td><td>of interrupt which caused this event</td></tr> </table> </dd> </dl> <dl class="section return"><dt>Returns</dt><dd>None.</dd></dl> <dl class="section note"><dt>Note</dt><dd>Use the XCsi2TxSs_SetCallback driver function to set this function as the handler for Short Packet FIFO error event. </dd></dl> <p>Referenced by <a class="el" href="group__csi2txss__v1__0.html#ga4261a1f4e4767eee83fa1ab1990fd25e">Csi2TxSs_SetupIntrSystem()</a>.</p> </div> </div> <a class="anchor" id="ga9cb8d015cac4e68c6cbe5b9c0b76bac9"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void Csi2TxSs_WrgLaneEventHandler </td> <td>(</td> <td class="paramtype">void *&#160;</td> <td class="paramname"><em>InstancePtr</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">u32&#160;</td> <td class="paramname"><em>Mask</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </div><div class="memdoc"> <p>This function is called when Wrong number of lanes are configured by the MIPI CSI2Tx Subsystem core. </p> <dl class="params"><dt>Parameters</dt><dd> <table class="params"> <tr><td class="paramname">InstancePtr</td><td>is a pointer to the <a class="el" href="struct_x_csi2_tx_ss.html" title="The XCsi2TxSs driver instance data.">XCsi2TxSs</a> instance. </td></tr> <tr><td class="paramname">Mask</td><td>of interrupt which caused this event</td></tr> </table> </dd> </dl> <dl class="section return"><dt>Returns</dt><dd>None.</dd></dl> <dl class="section note"><dt>Note</dt><dd>Use the XCsi2TxSs_SetCallback driver function to set this function as the handler for wrong lane configuration event. </dd></dl> <p>Referenced by <a class="el" href="group__csi2txss__v1__0.html#ga4261a1f4e4767eee83fa1ab1990fd25e">Csi2TxSs_SetupIntrSystem()</a>.</p> </div> </div> <a class="anchor" id="gae66f6b31b5ad750f1fe042a706a4e3d4"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">int main </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>This is the main function for <a class="el" href="struct_x_csi2_tx_ss.html" title="The XCsi2TxSs driver instance data.">XCsi2TxSs</a> interrupt example. </p> <p>This is the main function for <a class="el" href="struct_x_csi2_tx_ss.html" title="The XCsi2TxSs driver instance data.">XCsi2TxSs</a> self test example.</p> <p>If the Csi2TxSs_IntrExample function which sets up the system succeeds, this function will wait for the interrupts. Once a connection event or pulse is detected, Csi2TxSs will TX device capabilities and re-start the subsystem.</p> <dl class="params"><dt>Parameters</dt><dd> <table class="params"> <tr><td class="paramname">None.</td><td></td></tr> </table> </dd> </dl> <dl class="section return"><dt>Returns</dt><dd><ul> <li>XST_FAILURE if the interrupt example was unsuccessful.</li> <li>XST_SUCCESS if the interrupt example was successful.</li> </ul> </dd></dl> <dl class="params"><dt>Parameters</dt><dd> <table class="params"> <tr><td class="paramname">None.</td><td></td></tr> </table> </dd> </dl> <dl class="section return"><dt>Returns</dt><dd><ul> <li>XST_SUCCESS if the self test example passed.</li> <li>XST_FAILURE if the self test example was unsuccessful.</li> </ul> </dd></dl> <dl class="section note"><dt>Note</dt><dd>None. </dd></dl> <p>References <a class="el" href="group__csi2txss__v1__0.html#ga4f003f0f154d0a6f6d7c06498ff3c655">Csi2TxSs_IntrExample()</a>.</p> </div> </div> </div><!-- contents --> </div><!-- doc-content --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="footer">Copyright &copy; 2015 Xilinx Inc. All rights reserved.</li> </ul> </div> </body> </html>
{ "pile_set_name": "Github" }
--- layout: documentation title: Postgres.app Documentation --- ## Documentation - [Installing and Uninstalling](install.html) - [Updating](update.html) - [Migrating data](migrating-data.html) - [Removing other PostgreSQL installations](remove.html) - [CLI Tools](cli-tools.html) - [GUI Apps](gui-tools.html) - [Using PL/Python](plpython.html) - [Troubleshooting & Support](troubleshooting.html) ## Additional Resources - [PostgreSQL Website](http://www.postgresql.org/) - The source for all of the latest PostgreSQL news and information. - [PostgreSQL Docs](http://www.postgresql.org/docs/current/static/index.html) - The canonical reference for everything you need to know about PostgreSQL. - [Postgres Guide](http://postgresguide.com/) - A promising new PostgreSQL resource that reads well and introduces advanced topics in a way that's easy to understand.
{ "pile_set_name": "Github" }
/* This file is part of Cute Chess. Copyright (C) 2008-2018 Cute Chess authors Cute Chess is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Cute Chess is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Cute Chess. If not, see <http://www.gnu.org/licenses/>. */ #ifndef SPRT_H #define SPRT_H /*! * \brief A Sequential Probability Ratio Test * * The Sprt class implements a Sequential Probability Ratio Test (SPRT) that * can be used as a termination criterion for stopping a match between two * players when the Elo difference is known to be outside of the specified * interval. * * \sa http://en.wikipedia.org/wiki/Sequential_probability_ratio_test */ class LIB_EXPORT Sprt { public: /*! The result of the test. */ enum Result { Continue, //!< Continue monitoring AcceptH0, //!< Accept null hypothesis H0 AcceptH1 //!< Accept alternative hypothesis H1 }; /*! The result of a chess game. */ enum GameResult { NoResult, //!< Game ended with no result Win, //!< First player won Loss, //!< First player lost Draw //!< Game was drawn }; /*! The status of the test. */ struct Status { Result result; //!< Test result double llr; //!< Log-likelihood ratio double lBound; //!< Lower bound double uBound; //!< Upper bound }; /*! Creates a new uninitialized Sprt object. */ Sprt(); /*! * Returns true if the SPRT is uninitialized; otherwise * returns false. */ bool isNull() const; /*! * Initializes the SPRT. * * \a elo0 is the Elo difference between player A and * player B for H0 and \a elo1 for H1. * * \a alpha is the maximum probability for a type I error and * \a beta for a type II error outside interval [elo0, elo1]. */ void initialize(double elo0, double elo1, double alpha, double beta); /*! Returns the current status of the test. */ Status status() const; /*! * Updates the test with \a result. * * After calling this function, status() should be called to * check if H0 or H1 can be accepted. */ void addGameResult(GameResult result); private: double m_elo0; double m_elo1; double m_alpha; double m_beta; int m_wins; int m_losses; int m_draws; }; #endif // SPRT_H
{ "pile_set_name": "Github" }
#ifndef MTOON_CORE_INCLUDED #define MTOON_CORE_INCLUDED #include "Lighting.cginc" #include "AutoLight.cginc" half _Cutoff; fixed4 _Color; fixed4 _ShadeColor; sampler2D _MainTex; float4 _MainTex_ST; sampler2D _ShadeTexture; half _BumpScale; sampler2D _BumpMap; sampler2D _ReceiveShadowTexture; half _ReceiveShadowRate; sampler2D _ShadingGradeTexture; half _ShadingGradeRate; half _ShadeShift; half _ShadeToony; half _LightColorAttenuation; half _IndirectLightIntensity; sampler2D _SphereAdd; half4 _EmissionColor; sampler2D _EmissionMap; sampler2D _OutlineWidthTexture; half _OutlineWidth; half _OutlineScaledMaxDistance; fixed4 _OutlineColor; half _OutlineLightingMix; //UNITY_INSTANCING_BUFFER_START(Props) //UNITY_INSTANCING_BUFFER_END(Props) struct v2f { float4 pos : SV_POSITION; float4 posWorld : TEXCOORD0; half3 tspace0 : TEXCOORD1; half3 tspace1 : TEXCOORD2; half3 tspace2 : TEXCOORD3; float2 uv0 : TEXCOORD4; float isOutline : TEXCOORD5; fixed4 color : TEXCOORD6; LIGHTING_COORDS(7,8) UNITY_FOG_COORDS(9) //UNITY_VERTEX_INPUT_INSTANCE_ID // necessary only if any instanced properties are going to be accessed in the fragment Shader. }; inline v2f InitializeV2F(appdata_full v, float4 projectedVertex, float isOutline) { v2f o; UNITY_SETUP_INSTANCE_ID(v); //UNITY_TRANSFER_INSTANCE_ID(v, o); o.pos = projectedVertex; o.posWorld = mul(unity_ObjectToWorld, v.vertex); o.uv0 = v.texcoord; half3 worldNormal = UnityObjectToWorldNormal(v.normal); half3 worldTangent = UnityObjectToWorldDir(v.tangent); half tangentSign = v.tangent.w * unity_WorldTransformParams.w; half3 worldBitangent = cross(worldNormal, worldTangent) * tangentSign; o.tspace0 = half3(worldTangent.x, worldBitangent.x, worldNormal.x); o.tspace1 = half3(worldTangent.y, worldBitangent.y, worldNormal.y); o.tspace2 = half3(worldTangent.z, worldBitangent.z, worldNormal.z); o.isOutline = isOutline; o.color = v.color; TRANSFER_VERTEX_TO_FRAGMENT(o); UNITY_TRANSFER_FOG(o, o.pos); return o; } inline float4 CalculateOutlineVertexClipPosition(appdata_full v) { float outlineTex = tex2Dlod(_OutlineWidthTexture, float4(TRANSFORM_TEX(v.texcoord, _MainTex), 0, 0)).r; #if defined(MTOON_OUTLINE_WIDTH_WORLD) float3 worldNormalLength = length(mul((float3x3)transpose(unity_WorldToObject), v.normal)); float3 outlineOffset = 0.01 * _OutlineWidth * outlineTex * worldNormalLength * v.normal; float4 vertex = UnityObjectToClipPos(v.vertex + outlineOffset); #elif defined(MTOON_OUTLINE_WIDTH_SCREEN) float4 nearUpperRight = mul(unity_CameraInvProjection, float4(1, 1, UNITY_NEAR_CLIP_VALUE, _ProjectionParams.y)); float aspect = abs(nearUpperRight.y / nearUpperRight.x); float4 vertex = UnityObjectToClipPos(v.vertex); float3 viewNormal = mul((float3x3)UNITY_MATRIX_IT_MV, v.normal.xyz); float3 clipNormal = TransformViewToProjection(viewNormal.xyz); float2 projectedNormal = normalize(clipNormal.xy); projectedNormal *= min(vertex.w, _OutlineScaledMaxDistance); projectedNormal.x *= aspect; vertex.xy += 0.01 * _OutlineWidth * outlineTex * projectedNormal.xy; #else float4 vertex = 0; #endif return vertex; } float4 frag_forward(v2f i) : SV_TARGET { #ifdef MTOON_CLIP_IF_OUTLINE_IS_NONE #ifdef MTOON_OUTLINE_WIDTH_WORLD #elif MTOON_OUTLINE_WIDTH_SCREEN #else clip(-1); #endif #endif //UNITY_TRANSFER_INSTANCE_ID(v, o); // main tex float2 mainUv = TRANSFORM_TEX(i.uv0, _MainTex); half4 mainTex = tex2D(_MainTex, mainUv); // alpha half alpha = 1; #ifdef _ALPHATEST_ON alpha = _Color.a * mainTex.a; clip(alpha - _Cutoff); #endif #ifdef _ALPHABLEND_ON alpha = _Color.a * mainTex.a; #endif // normal #ifdef _NORMALMAP half3 tangentNormal = UnpackScaleNormal(tex2D(_BumpMap, mainUv), _BumpScale); half3 worldNormal; worldNormal.x = dot(i.tspace0, tangentNormal); worldNormal.y = dot(i.tspace1, tangentNormal); worldNormal.z = dot(i.tspace2, tangentNormal); #else half3 worldNormal = half3(i.tspace0.z, i.tspace1.z, i.tspace2.z); #endif worldNormal *= step(0, dot(_WorldSpaceCameraPos.xyz - i.posWorld.xyz, worldNormal)) * 2 - 1; worldNormal *= lerp(+1.0, -1.0, i.isOutline); worldNormal = normalize(worldNormal); // lighting intensity half3 lightDir = lerp(_WorldSpaceLightPos0.xyz, normalize(_WorldSpaceLightPos0.xyz - i.posWorld.xyz), _WorldSpaceLightPos0.w); half receiveShadow = _ReceiveShadowRate * tex2D(_ReceiveShadowTexture, mainUv).a; half shadingGrade = 1.0 - _ShadingGradeRate * (1.0 - tex2D(_ShadingGradeTexture, mainUv).r); UNITY_LIGHT_ATTENUATION(atten, i, i.posWorld.xyz); half lightIntensity = dot(lightDir, worldNormal); lightIntensity = lightIntensity * 0.5 + 0.5; // from [-1, +1] to [0, 1] lightIntensity = lightIntensity * (1.0 - receiveShadow * (1.0 - (atten * 0.5 + 0.5))); // receive shadow lightIntensity = lightIntensity * shadingGrade; // darker lightIntensity = lightIntensity * 2.0 - 1.0; // from [0, 1] to [-1, +1] lightIntensity = smoothstep(_ShadeShift, _ShadeShift + (1.0 - _ShadeToony), lightIntensity); // shade & tooned // lighting with color half3 directLighting = lightIntensity * _LightColor0.rgb; // direct half3 indirectLighting = _IndirectLightIntensity * ShadeSH9(half4(worldNormal, 1)); // ambient half3 lighting = directLighting + indirectLighting; lighting = lerp(lighting, max(0.001, max(lighting.x, max(lighting.y, lighting.z))), _LightColorAttenuation); // color atten // color lerp half4 shade = _ShadeColor * tex2D(_ShadeTexture, mainUv); half4 lit = _Color * mainTex; #ifdef MTOON_FORWARD_ADD half3 col = lerp(half3(0,0,0), lit.rgb, lighting); #else half3 col = lerp(shade.rgb, lit.rgb, lighting); #endif // energy conservation half3 lightPower = _LightColor0.rgb + ShadeSH9(half4(0, 1, 0, 1)); half lightPowerV = max(0.001, max(lightPower.x, max(lightPower.y, lightPower.z))); col *= saturate(lightPowerV); // additive matcap #ifdef MTOON_FORWARD_ADD #else half3 worldCameraUp = normalize(UNITY_MATRIX_V[1].xyz); half3 worldView = normalize(_WorldSpaceCameraPos.xyz - i.posWorld.xyz); half3 worldViewUp = normalize(worldCameraUp - worldView * dot(worldView, worldCameraUp)); half3 worldViewRight = normalize(cross(worldView, worldViewUp)); half2 rimUv = half2(dot(worldViewRight, worldNormal), dot(worldViewUp, worldNormal)) * 0.5 + 0.5; half3 rimLighting = tex2D(_SphereAdd, rimUv); col += lerp(rimLighting, half3(0, 0, 0), i.isOutline); #endif // Emission #ifdef MTOON_FORWARD_ADD #else half3 emission = tex2D(_EmissionMap, mainUv).rgb * _EmissionColor.rgb; col += lerp(emission, half3(0, 0, 0), i.isOutline); #endif // outline #ifdef MTOON_OUTLINE_COLOR_FIXED col = lerp(col, _OutlineColor, i.isOutline); #elif MTOON_OUTLINE_COLOR_MIXED col = lerp(col, _OutlineColor * lerp(half3(1, 1, 1), col, _OutlineLightingMix), i.isOutline); #else #endif // debug #ifdef MTOON_DEBUG_NORMAL #ifdef MTOON_FORWARD_ADD return float4(0, 0, 0, 0); #else return float4(worldNormal * 0.5 + 0.5, alpha); #endif #elif MTOON_DEBUG_LITSHADERATE #ifdef MTOON_FORWARD_ADD return float4(0, 0, 0, 0); #else return float4(lighting, alpha); #endif #endif half4 result = half4(col, alpha); UNITY_APPLY_FOG(i.fogCoord, result); return result; } #endif // MTOON_CORE_INCLUDED
{ "pile_set_name": "Github" }
/* Copyright 2015-present MongoDB Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using MongoDB.Bson.Serialization; using MongoDB.Bson.Serialization.Serializers; using MongoDB.Driver.Core.Misc; namespace MongoDB.Driver.Linq.Expressions.ResultOperators { internal sealed class ArrayResultOperator : ResultOperator { private readonly IBsonSerializer _serializer; private readonly Type _type; public ArrayResultOperator(Type type, IBsonSerializer serializer) { _type = Ensure.IsNotNull(type, nameof(type)); _serializer = Ensure.IsNotNull(serializer, nameof(serializer)); } public override string Name { get { return "Array"; } } public override IBsonSerializer Serializer { get { return _serializer; } } public override Type Type { get { return _type; } } } }
{ "pile_set_name": "Github" }
apiVersion: extensions/v1beta1 kind: Deployment metadata: name: nginx-deployment spec: replicas: 3 template: metadata: labels: app: nginx spec: containers: - name: nginx image: nginx:1.7.9 ports: - containerPort: 80
{ "pile_set_name": "Github" }
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
{ "pile_set_name": "Github" }
version: 0.{build} skip_tags: true cache: C:\Users\appveyor\AppData\Local\NuGet\Cache build_script: - SET GOPATH=c:\workspace - go test -v -race ./... test: off clone_folder: c:\workspace\src\github.com\nxadm\tail branches: only: - master
{ "pile_set_name": "Github" }