max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
3,227
<filename>sandbox.config.json { "infiniteLoopProtection": true, "hardReloadOnChange": false, "template": "node", "container": { "port": 3000, "startScript": "start:codesandbox" } }
77
312
/******************************************************************************* Copyright (c) 2018 Eclipse RDF4J contributors. All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Distribution License v1.0 which accompanies this distribution, and is available at http://www.eclipse.org/org/documents/edl-v10.php. *******************************************************************************/ package org.eclipse.rdf4j.sparqlbuilder.core.query; import java.util.Optional; import org.eclipse.rdf4j.sparqlbuilder.core.Base; import org.eclipse.rdf4j.sparqlbuilder.core.Prefix; import org.eclipse.rdf4j.sparqlbuilder.core.PrefixDeclarations; import org.eclipse.rdf4j.sparqlbuilder.core.SparqlBuilder; import org.eclipse.rdf4j.sparqlbuilder.rdf.Iri; import org.eclipse.rdf4j.sparqlbuilder.util.SparqlBuilderUtils; /** * A non-subquery query. * * @param <T> The query type. Used to support fluency. */ @SuppressWarnings("unchecked") public abstract class OuterQuery<T extends OuterQuery<T>> extends Query<T> { protected Optional<Base> base = Optional.empty(); protected Optional<PrefixDeclarations> prefixes = Optional.empty(); /** * Set the base IRI of this query * * @param iri the base IRI * @return this */ public T base(Iri iri) { this.base = Optional.of(SparqlBuilder.base(iri)); return (T) this; } /** * Set the Base clause of this query * * @param base the {@link Base} clause to set * @return this */ public T base(Base base) { this.base = Optional.of(base); return (T) this; } /** * Add prefix declarations to this query * * @param prefixes the prefixes to add * @return this */ public T prefix(Prefix... prefixes) { this.prefixes = SparqlBuilderUtils.getOrCreateAndModifyOptional(this.prefixes, SparqlBuilder::prefixes, p -> p.addPrefix(prefixes)); return (T) this; } /** * Set the Prefix declarations of this query * * @param prefixes the {@link PrefixDeclarations} to set * @return this */ public T prefix(PrefixDeclarations prefixes) { this.prefixes = Optional.of(prefixes); return (T) this; } @Override public String getQueryString() { StringBuilder query = new StringBuilder(); SparqlBuilderUtils.appendAndNewlineIfPresent(base, query); SparqlBuilderUtils.appendAndNewlineIfPresent(prefixes, query); query.append(super.getQueryString()); return query.toString(); } }
799
903
<reponame>TsSaltan/jphp package org.develnext.jphp.core.tokenizer.token.stmt; import org.develnext.jphp.core.tokenizer.TokenType; import org.develnext.jphp.core.tokenizer.TokenMeta; import org.develnext.jphp.core.tokenizer.token.expr.value.VariableExprToken; import java.util.Set; public class DoStmtToken extends StmtToken { private Set<VariableExprToken> local; private ExprStmtToken condition; private BodyStmtToken body; public DoStmtToken(TokenMeta meta) { super(meta, TokenType.T_DO); } public ExprStmtToken getCondition() { return condition; } public void setCondition(ExprStmtToken condition) { this.condition = condition; } public BodyStmtToken getBody() { return body; } public void setBody(BodyStmtToken body) { this.body = body; } public Set<VariableExprToken> getLocal() { return local; } public void setLocal(Set<VariableExprToken> local) { this.local = local; } }
399
986
<reponame>exNTLDR/audacity /* ** Copyright (C) 1999-2018 <NAME> <<EMAIL>> ** ** 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 2.1 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, write to the Free Software ** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef SFENDIAN_INCLUDED #define SFENDIAN_INCLUDED #include "sfconfig.h" #include <stdint.h> #include <inttypes.h> #if HAVE_BYTESWAP_H /* Linux, any CPU */ #include <byteswap.h> #define ENDSWAP_16(x) (bswap_16 (x)) #define ENDSWAP_32(x) (bswap_32 (x)) #define ENDSWAP_64(x) (bswap_64 (x)) #endif #if (HAVE_BYTESWAP_H == 0) && COMPILER_IS_GCC #if CPU_IS_X86 static inline int16_t ENDSWAP_16 (int16_t x) { int16_t y ; __asm__ ("rorw $8, %w0" : "=r" (y) : "0" (x) : "cc") ; return y ; } /* ENDSWAP_16 */ static inline int32_t ENDSWAP_32 (int32_t x) { int32_t y ; __asm__ ("bswap %0" : "=r" (y) : "0" (x)) ; return y ; } /* ENDSWAP_32 */ #endif #if CPU_IS_X86_64 static inline int64_t ENDSWAP_64X (int64_t x) { int64_t y ; __asm__ ("bswap %q0" : "=r" (y) : "0" (x)) ; return y ; } /* ENDSWAP_64X */ #define ENDSWAP_64 ENDSWAP_64X #endif #endif #ifdef _MSC_VER #include <stdlib.h> #define ENDSWAP_16(x) (_byteswap_ushort (x)) #define ENDSWAP_32(x) (_byteswap_ulong (x)) #define ENDSWAP_64(x) (_byteswap_uint64 (x)) #endif #ifndef ENDSWAP_16 #define ENDSWAP_16(x) ((((x) >> 8) & 0xFF) + (((x) & 0xFF) << 8)) #endif #ifndef ENDSWAP_32 #define ENDSWAP_32(x) ((((x) >> 24) & 0xFF) + (((x) >> 8) & 0xFF00) + (((x) & 0xFF00) << 8) + (((x) & 0xFF) << 24)) #endif #ifndef ENDSWAP_64 static inline uint64_t ENDSWAP_64 (uint64_t x) { union { uint32_t parts [2] ; uint64_t whole ; } u ; uint32_t temp ; u.whole = x ; temp = u.parts [0] ; u.parts [0] = ENDSWAP_32 (u.parts [1]) ; u.parts [1] = ENDSWAP_32 (temp) ; return u.whole ; } #endif /* ** Many file types (ie WAV, AIFF) use sets of four consecutive bytes as a ** marker indicating different sections of the file. ** The following MAKE_MARKER macro allows th creation of integer constants ** for these markers. */ #if (CPU_IS_LITTLE_ENDIAN == 1) #define MAKE_MARKER(a, b, c, d) ((uint32_t) ((a) | ((b) << 8) | ((c) << 16) | (((uint32_t) (d)) << 24))) #elif (CPU_IS_BIG_ENDIAN == 1) #define MAKE_MARKER(a, b, c, d) ((uint32_t) ((((uint32_t) (a)) << 24) | ((b) << 16) | ((c) << 8) | (d))) #else #error "Target CPU endian-ness unknown. May need to hand edit src/sfconfig.h" #endif /* ** Macros to handle reading of data of a specific endian-ness into host endian ** shorts and ints. The single input is an unsigned char* pointer to the start ** of the object. There are two versions of each macro as we need to deal with ** both big and little endian CPUs. */ #if (CPU_IS_LITTLE_ENDIAN == 1) #define LE2H_16(x) (x) #define LE2H_32(x) (x) #define BE2H_16(x) ENDSWAP_16 (x) #define BE2H_32(x) ENDSWAP_32 (x) #define BE2H_64(x) ENDSWAP_64 (x) #define H2BE_16(x) ENDSWAP_16 (x) #define H2BE_32(x) ENDSWAP_32 (x) #define H2LE_16(x) (x) #define H2LE_32(x) (x) #elif (CPU_IS_BIG_ENDIAN == 1) #define LE2H_16(x) ENDSWAP_16 (x) #define LE2H_32(x) ENDSWAP_32 (x) #define BE2H_16(x) (x) #define BE2H_32(x) (x) #define BE2H_64(x) (x) #define H2BE_16(x) (x) #define H2BE_32(x) (x) #define H2LE_16(x) ENDSWAP_16 (x) #define H2LE_32(x) ENDSWAP_32 (x) #else #error "Target CPU endian-ness unknown. May need to hand edit src/sfconfig.h" #endif #define LE2H_32_PTR(x) (((x) [0]) + ((x) [1] << 8) + ((x) [2] << 16) + ((x) [3] << 24)) #define LET2H_16_PTR(x) ((x) [1] + ((x) [2] << 8)) #define LET2H_32_PTR(x) (((x) [0] << 8) + ((x) [1] << 16) + ((x) [2] << 24)) #define BET2H_16_PTR(x) (((x) [0] << 8) + (x) [1]) #define BET2H_32_PTR(x) (((x) [0] << 24) + ((x) [1] << 16) + ((x) [2] << 8)) static inline void psf_put_be64 (uint8_t *ptr, int offset, int64_t value) { ptr [offset] = value >> 56 ; ptr [offset + 1] = value >> 48 ; ptr [offset + 2] = value >> 40 ; ptr [offset + 3] = value >> 32 ; ptr [offset + 4] = value >> 24 ; ptr [offset + 5] = value >> 16 ; ptr [offset + 6] = value >> 8 ; ptr [offset + 7] = value ; } /* psf_put_be64 */ static inline void psf_put_be32 (uint8_t *ptr, int offset, int32_t value) { ptr [offset] = value >> 24 ; ptr [offset + 1] = value >> 16 ; ptr [offset + 2] = value >> 8 ; ptr [offset + 3] = value ; } /* psf_put_be32 */ static inline void psf_put_be16 (uint8_t *ptr, int offset, int16_t value) { ptr [offset] = value >> 8 ; ptr [offset + 1] = value ; } /* psf_put_be16 */ static inline int64_t psf_get_be64 (uint8_t *ptr, int offset) { int64_t value ; value = ((uint32_t) ptr [offset]) << 24 ; value += ptr [offset + 1] << 16 ; value += ptr [offset + 2] << 8 ; value += ptr [offset + 3] ; value = ((uint64_t) value) << 32 ; value += ((uint32_t) ptr [offset + 4]) << 24 ; value += ptr [offset + 5] << 16 ; value += ptr [offset + 6] << 8 ; value += ptr [offset + 7] ; return value ; } /* psf_get_be64 */ static inline int64_t psf_get_le64 (uint8_t *ptr, int offset) { int64_t value ; value = ((uint32_t) ptr [offset + 7]) << 24 ; value += ptr [offset + 6] << 16 ; value += ptr [offset + 5] << 8 ; value += ptr [offset + 4] ; value = ((uint64_t) value) << 32 ; value += ((uint32_t) ptr [offset + 3]) << 24 ; value += ptr [offset + 2] << 16 ; value += ptr [offset + 1] << 8 ; value += ptr [offset] ; return value ; } /* psf_get_le64 */ static inline int32_t psf_get_be32 (uint8_t *ptr, int offset) { int32_t value ; value = ((uint32_t) ptr [offset]) << 24 ; value += ptr [offset + 1] << 16 ; value += ptr [offset + 2] << 8 ; value += ptr [offset + 3] ; return value ; } /* psf_get_be32 */ static inline int32_t psf_get_le32 (uint8_t *ptr, int offset) { int32_t value ; value = ((uint32_t) ptr [offset + 3]) << 24 ; value += ptr [offset + 2] << 16 ; value += ptr [offset + 1] << 8 ; value += ptr [offset] ; return value ; } /* psf_get_le32 */ static inline int32_t psf_get_be24 (uint8_t *ptr, int offset) { int32_t value ; value = ((uint32_t) ptr [offset]) << 24 ; value += ptr [offset + 1] << 16 ; value += ptr [offset + 2] << 8 ; return value ; } /* psf_get_be24 */ static inline int32_t psf_get_le24 (uint8_t *ptr, int offset) { int32_t value ; value = ((uint32_t) ptr [offset + 2]) << 24 ; value += ptr [offset + 1] << 16 ; value += ptr [offset] << 8 ; return value ; } /* psf_get_le24 */ static inline int16_t psf_get_be16 (uint8_t *ptr, int offset) { return (ptr [offset] << 8) + ptr [offset + 1] ; } /* psf_get_be16 */ /*----------------------------------------------------------------------------------------------- ** Generic functions for performing endian swapping on integer arrays. */ static inline void endswap_short_array (short *ptr, int len) { short temp ; while (--len >= 0) { temp = ptr [len] ; ptr [len] = ENDSWAP_16 (temp) ; } ; } /* endswap_short_array */ static inline void endswap_short_copy (short *dest, const short *src, int len) { while (--len >= 0) { dest [len] = ENDSWAP_16 (src [len]) ; } ; } /* endswap_short_copy */ static inline void endswap_int_array (int *ptr, int len) { int temp ; while (--len >= 0) { temp = ptr [len] ; ptr [len] = ENDSWAP_32 (temp) ; } ; } /* endswap_int_array */ static inline void endswap_int_copy (int *dest, const int *src, int len) { while (--len >= 0) { dest [len] = ENDSWAP_32 (src [len]) ; } ; } /* endswap_int_copy */ /*======================================================================================== */ static inline void endswap_int64_t_array (int64_t *ptr, int len) { int64_t value ; while (--len >= 0) { value = ptr [len] ; ptr [len] = ENDSWAP_64 (value) ; } ; } /* endswap_int64_t_array */ static inline void endswap_int64_t_copy (int64_t *dest, const int64_t *src, int len) { int64_t value ; while (--len >= 0) { value = src [len] ; dest [len] = ENDSWAP_64 (value) ; } ; } /* endswap_int64_t_copy */ /* A couple of wrapper functions. */ static inline void endswap_float_array (float *ptr, int len) { endswap_int_array ((int *) ptr, len) ; } /* endswap_float_array */ static inline void endswap_double_array (double *ptr, int len) { endswap_int64_t_array ((int64_t *) ptr, len) ; } /* endswap_double_array */ static inline void endswap_float_copy (float *dest, const float *src, int len) { endswap_int_copy ((int *) dest, (const int *) src, len) ; } /* endswap_float_copy */ static inline void endswap_double_copy (double *dest, const double *src, int len) { endswap_int64_t_copy ((int64_t *) dest, (const int64_t *) src, len) ; } /* endswap_double_copy */ #endif /* SFENDIAN_INCLUDED */
3,958
496
#include "simit-test.h" #include "init.h" #include "graph.h" #include "tensor.h" #include "program.h" #include "error.h" using namespace std; using namespace simit; TEST(assembly, vertices) { Set V; ElementRef v0 = V.add(); ElementRef v1 = V.add(); ElementRef v2 = V.add(); FieldRef<int> a = V.addField<int>("a"); FieldRef<int> b = V.addField<int>("b"); a(v0) = 1; a(v1) = 2; a(v2) = 3; Function func = loadFunction(TEST_FILE_NAME, "main"); if (!func.defined()) FAIL(); func.bind("V", &V); func.runSafe(); ASSERT_EQ(2, b(v0)); ASSERT_EQ(4, b(v1)); ASSERT_EQ(6, b(v2)); } TEST(assembly, vertices_two_results) { Set V; ElementRef v0 = V.add(); ElementRef v1 = V.add(); ElementRef v2 = V.add(); FieldRef<int> a = V.addField<int>("a"); FieldRef<int> b = V.addField<int>("b"); a(v0) = 1; a(v1) = 2; a(v2) = 3; Function func = loadFunction(TEST_FILE_NAME, "main"); if (!func.defined()) FAIL(); func.bind("V", &V); func.runSafe(); ASSERT_EQ( 6, (int)b(v0)); ASSERT_EQ(24, (int)b(v1)); ASSERT_EQ(54, (int)b(v2)); } TEST(assembly, edges_heterogeneous) { Set P; ElementRef p0 = P.add(); ElementRef p1 = P.add(); ElementRef p2 = P.add(); FieldRef<int> c = P.addField<int>("c"); c(p0) = 2; c(p1) = 3; c(p2) = 4; Set V; ElementRef v0 = V.add(); ElementRef v1 = V.add(); ElementRef v2 = V.add(); FieldRef<int> b = V.addField<int>("b"); b(v0) = 1; b(v1) = 2; b(v2) = 3; Set E(P,V); ElementRef e0 = E.add(p0,v0); ElementRef e1 = E.add(p1,v0); ElementRef e2 = E.add(p1,v1); ElementRef e3 = E.add(p1,v2); ElementRef e4 = E.add(p2,v2); FieldRef<int> a = E.addField<int>("a"); a(e0) = 3; a(e1) = 4; a(e2) = 5; a(e3) = 6; a(e4) = 7; Function func = loadFunction(TEST_FILE_NAME, "main"); if (!func.defined()) FAIL(); func.bind("P", &P); func.bind("V", &V); func.bind("E", &E); func.runSafe(); ASSERT_EQ(6, (int)c(p0)); ASSERT_EQ(64, (int)c(p1)); ASSERT_EQ(42, (int)c(p2)); } TEST(assembly, edges_no_endpoints) { Set V; ElementRef v0 = V.add(); ElementRef v1 = V.add(); ElementRef v2 = V.add(); Set E(V,V); ElementRef e0 = E.add(v0,v1); ElementRef e1 = E.add(v1,v2); FieldRef<int> a = E.addField<int>("a"); FieldRef<int> b = E.addField<int>("b"); a(e0) = 1; a(e1) = 2; Function func = loadFunction(TEST_FILE_NAME, "main"); if (!func.defined()) FAIL(); func.bind("V", &V); func.bind("E", &E); func.runSafe(); ASSERT_EQ(2, (int)b(e0)); ASSERT_EQ(4, (int)b(e1)); } TEST(assembly, edges_unary) { Set V; ElementRef v0 = V.add(); ElementRef v1 = V.add(); ElementRef v2 = V.add(); FieldRef<int> a = V.addField<int>("a"); Set E(V); E.add(v0); E.add(v2); Function func = loadFunction(TEST_FILE_NAME, "main"); if (!func.defined()) FAIL(); func.bind("V", &V); func.bind("E", &E); func.runSafe(); ASSERT_EQ((int)a(v0), 1); ASSERT_EQ((int)a(v1), 0); ASSERT_EQ((int)a(v2), 1); } TEST(assembly, edges_binary) { Set V; ElementRef v0 = V.add(); ElementRef v1 = V.add(); ElementRef v2 = V.add(); FieldRef<int> a = V.addField<int>("a"); Set E(V,V); E.add(v0,v1); E.add(v1,v2); Function func = loadFunction(TEST_FILE_NAME, "main"); if (!func.defined()) FAIL(); func.bind("V", &V); func.bind("E", &E); func.runSafe(); ASSERT_EQ((int)a(v0), 1); ASSERT_EQ((int)a(v1), 2); ASSERT_EQ((int)a(v2), 1); } TEST(assembly, edges_tertiary) { Set V; ElementRef v0 = V.add(); ElementRef v1 = V.add(); ElementRef v2 = V.add(); ElementRef v3 = V.add(); FieldRef<int> b = V.addField<int>("b"); Set E(V,V,V); ElementRef e0 = E.add(v0,v1,v2); ElementRef e1 = E.add(v1,v2,v3); simit::FieldRef<int> a = E.addField<int>("a"); a(e0) = 10; a(e1) = 1; Function func = loadFunction(TEST_FILE_NAME, "main"); if (!func.defined()) FAIL(); func.bind("V", &V); func.bind("E", &E); func.runSafe(); ASSERT_EQ(10, b(v0)); ASSERT_EQ(11, b(v1)); ASSERT_EQ(11, b(v2)); ASSERT_EQ(1, b(v3)); } TEST(assembly, edges_two_results) { Set V; ElementRef v0 = V.add(); ElementRef v1 = V.add(); ElementRef v2 = V.add(); FieldRef<int> b = V.addField<int>("b"); Set E(V,V); ElementRef e0 = E.add(v0,v1); ElementRef e1 = E.add(v1,v2); FieldRef<int> a = E.addField<int>("a"); a(e0) = 1; a(e1) = 2; Function func = loadFunction(TEST_FILE_NAME, "main"); if (!func.defined()) FAIL(); func.bind("V", &V); func.bind("E", &E); func.runSafe(); ASSERT_EQ(43, (int)b(v0)); ASSERT_EQ(177, (int)b(v1)); ASSERT_EQ(168, (int)b(v2)); } TEST(assembly, matrix_ve) { Set V; ElementRef v0 = V.add(); ElementRef v1 = V.add(); ElementRef v2 = V.add(); FieldRef<int> c = V.addField<int>("c"); Set E(V,V); ElementRef e0 = E.add(v0, v1); ElementRef e1 = E.add(v1, v2); FieldRef<int> a = E.addField<int>("a"); a(e0) = 1; a(e1) = 2; Function func = loadFunction(TEST_FILE_NAME, "main"); if (!func.defined()) FAIL(); func.bind("V", &V); func.bind("E", &E); func.runSafe(); ASSERT_EQ((int)c(v0), 1); ASSERT_EQ((int)c(v1), 3); ASSERT_EQ((int)c(v2), 2); } TEST(assembly, matrix_ev) { Set V; ElementRef v0 = V.add(); ElementRef v1 = V.add(); ElementRef v2 = V.add(); FieldRef<int> c = V.addField<int>("c"); c(v0) = 1; c(v1) = 2; c(v2) = 3; Set E(V,V); ElementRef e0 = E.add(v0, v1); ElementRef e1 = E.add(v1, v2); FieldRef<int> a = E.addField<int>("a"); Function func = loadFunction(TEST_FILE_NAME, "main"); if (!func.defined()) FAIL(); func.bind("V", &V); func.bind("E", &E); func.runSafe(); ASSERT_EQ((int)a(e0), 3); ASSERT_EQ((int)a(e1), 5); } TEST(assembly, matrix_vv) { Set V; ElementRef v0 = V.add(); ElementRef v1 = V.add(); ElementRef v2 = V.add(); FieldRef<int> a = V.addField<int>("a"); FieldRef<int> b = V.addField<int>("b"); a(v0) = 1; a(v1) = 1; a(v2) = 1; Set E(V,V); E.add(v0,v1); E.add(v1,v2); Function func = loadFunction(TEST_FILE_NAME, "main"); if (!func.defined()) FAIL(); func.bind("V", &V); func.bind("E", &E); func.runSafe(); ASSERT_EQ(2, (int)b(v0)); ASSERT_EQ(4, (int)b(v1)); ASSERT_EQ(2, (int)b(v2)); } TEST(assembly, matrix_ve_heterogeneous) { Set V0; FieldRef<int> b0 = V0.addField<int>("b"); std::vector<ElementRef> v0; v0.reserve(4); for (int i = 0; i < 4; ++i) { v0[i] = V0.add(); } Set V1; FieldRef<int> b1 = V1.addField<int>("b"); std::vector<ElementRef> v1; v1.reserve(9); for (int i = 0; i < 9; ++i) { v1[i] = V1.add(); } Set E(V1,V1,V0,V1,V1); FieldRef<int> a = E.addField<int>("a"); ElementRef e0 = E.add(v1[0],v1[1],v0[0],v1[3],v1[4]); ElementRef e1 = E.add(v1[1],v1[2],v0[1],v1[4],v1[5]); ElementRef e2 = E.add(v1[3],v1[4],v0[2],v1[6],v1[7]); ElementRef e3 = E.add(v1[4],v1[5],v0[3],v1[7],v1[8]); a(e0) = 1; a(e1) = 2; a(e2) = 3; a(e3) = 4; Function func = loadFunction(TEST_FILE_NAME, "main"); if (!func.defined()) FAIL(); func.bind("V0", &V0); func.bind("V1", &V1); func.bind("E", &E); func.runSafe(); for (int i = 0; i < 4; ++i) { ASSERT_EQ(i + 1, (int)b0(v0[i])); } const std::vector<int> b1Expected = {1, 4, 4, 6, 20, 16, 9, 24, 16}; for (int i = 0; i < 9; ++i) { ASSERT_EQ(b1Expected[i], (int)b1(v1[i])); } } TEST(assembly, matrix_ev_heterogeneous) { Set V0; FieldRef<int> a0 = V0.addField<int>("a"); std::vector<ElementRef> v0; v0.reserve(4); for (int i = 0; i < 4; ++i) { v0[i] = V0.add(); a0(v0[i]) = i + 1; } Set V1; FieldRef<int> a1 = V1.addField<int>("a"); std::vector<ElementRef> v1; v1.reserve(9); for (int i = 0; i < 9; ++i) { v1[i] = V1.add(); a1(v1[i]) = i + 1; } Set E(V1,V1,V0,V1,V1); FieldRef<int> b0 = E.addField<int>("b0"); FieldRef<int> b1 = E.addField<int>("b1"); ElementRef e0 = E.add(v1[0],v1[1],v0[0],v1[3],v1[4]); ElementRef e1 = E.add(v1[1],v1[2],v0[1],v1[4],v1[5]); ElementRef e2 = E.add(v1[3],v1[4],v0[2],v1[6],v1[7]); ElementRef e3 = E.add(v1[4],v1[5],v0[3],v1[7],v1[8]); Function func = loadFunction(TEST_FILE_NAME, "main"); if (!func.defined()) FAIL(); func.bind("V0", &V0); func.bind("V1", &V1); func.bind("E", &E); func.runSafe(); ASSERT_EQ(1, (int)b0(e0)); ASSERT_EQ(2, (int)b0(e1)); ASSERT_EQ(3, (int)b0(e2)); ASSERT_EQ(4, (int)b0(e3)); ASSERT_EQ(37, (int)b1(e0)); ASSERT_EQ(47, (int)b1(e1)); ASSERT_EQ(67, (int)b1(e2)); ASSERT_EQ(77, (int)b1(e3)); } TEST(assembly, matrix_vv_heterogeneous) { Set V0; FieldRef<int> a0 = V0.addField<int>("a"); FieldRef<int> b0 = V0.addField<int>("b"); std::vector<ElementRef> v0; v0.reserve(4); for (int i = 0; i < 4; ++i) { v0[i] = V0.add(); a0(v0[i]) = i + 1; } Set V1; FieldRef<int> a1 = V1.addField<int>("a"); FieldRef<int> b1 = V1.addField<int>("b"); std::vector<ElementRef> v1; v1.reserve(9); for (int i = 0; i < 9; ++i) { v1[i] = V1.add(); a1(v1[i]) = i + 1; } Set E(V1,V1,V0,V1,V1); E.add(v1[0],v1[1],v0[0],v1[3],v1[4]); E.add(v1[1],v1[2],v0[1],v1[4],v1[5]); E.add(v1[3],v1[4],v0[2],v1[6],v1[7]); E.add(v1[4],v1[5],v0[3],v1[7],v1[8]); Function func = loadFunction(TEST_FILE_NAME, "main"); if (!func.defined()) FAIL(); func.bind("V0", &V0); func.bind("V1", &V1); func.bind("E", &E); func.runSafe(); const std::vector<int> b0Expected = {37, 47, 67, 77}; for (int i = 0; i < 4; ++i) { ASSERT_EQ(b0Expected[i], (int)b0(v0[i])); } const std::vector<int> b1Expected = {1, 4, 4, 6, 20, 16, 9, 24, 16}; for (int i = 0; i < 9; ++i) { ASSERT_EQ(b1Expected[i], (int)b1(v1[i])); } } TEST(assembly, blocked) { Set V; ElementRef v0 = V.add(); ElementRef v1 = V.add(); ElementRef v2 = V.add(); FieldRef<int> x = V.addField<int>("x"); FieldRef<int> z = V.addField<int>("z"); x(v0) = 1; x(v1) = 2; x(v2) = 3; Function func = loadFunction(TEST_FILE_NAME, "main"); if (!func.defined()) FAIL(); func.bind("V", &V); func.runSafe(); ASSERT_EQ(81, z(v0)); ASSERT_EQ(324, z(v1)); ASSERT_EQ(729, z(v2)); } TEST(assembly, block_component_write) { Set V; ElementRef v0 = V.add(); ElementRef v1 = V.add(); ElementRef v2 = V.add(); FieldRef<int,2> x = V.addField<int,2>("a"); Set E(V,V); E.add(v0,v1); E.add(v1,v2); Function func = loadFunction(TEST_FILE_NAME, "main"); if (!func.defined()) FAIL(); func.bind("V", &V); func.bind("E", &E); func.runSafe(); ASSERT_EQ(1, x(v0)(0)); ASSERT_EQ(0, x(v0)(1)); ASSERT_EQ(1, x(v1)(0)); ASSERT_EQ(0, x(v1)(1)); ASSERT_EQ(0, x(v2)(0)); ASSERT_EQ(0, x(v2)(1)); }
5,371
27,296
import time import platform import subprocess import selenium from selenium.webdriver.common.action_chains import ActionChains import logging import os import sys import shutil import tempfile from subprocess import Popen, PIPE def find_executable(executable, path=None): """Find if 'executable' can be run. Looks for it in 'path' (string that lists directories separated by 'os.pathsep'; defaults to os.environ['PATH']). Checks for all executable extensions. Returns full path or None if no command is found. """ if path is None: path = os.environ['PATH'] paths = path.split(os.pathsep) extlist = [''] if os.name == 'os2': (base, ext) = os.path.splitext(executable) # executable files on OS/2 can have an arbitrary extension, but # .exe is automatically appended if no dot is present in the name if not ext: executable = executable + ".exe" elif sys.platform == 'win32': pathext = os.environ['PATHEXT'].lower().split(os.pathsep) (base, ext) = os.path.splitext(executable) if ext.lower() not in pathext: extlist = pathext for ext in extlist: execname = executable + ext if os.path.isfile(execname): return execname else: for p in paths: f = os.path.join(p, execname) if os.path.isfile(f): return f else: return None def install_native_modules(): nw_dir = os.path.normpath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)) nw_tools = os.path.join(nw_dir, 'tools') sys.path.append(nw_tools) import getnwversion import getnwisrelease header_path = os.path.join(nw_dir, 'tmp', 'node') nw_version = getnwversion.nw_version if getnwisrelease.release == 0: nw_version += getnwisrelease.postfix arch = '' _arch = platform.architecture()[0] if _arch == '64bit': arch = 'x64' elif _arch == '32bit': arch = 'ia32' else: print 'Unsupported arch: ' + _arch exit(-1) target_arch = arch if 'target_arch=ia32' in os.getenv('GYP_DEFINES'): target_arch='ia32' nw_gyp_path = find_executable('nw-gyp') npm_path = find_executable('npm') npm_cmdline = [npm_path, 'install'] if sys.platform in ('win32', 'cygwin'): nw_gyp_path = os.path.join(os.path.dirname(nw_gyp_path), 'node_modules', 'nw-gyp', 'bin', 'nw-gyp.js') npm_cmdline = [npm_path, 'install', '--msvs_version=2017'] print "nw_gyp: ", nw_gyp_path print "npm_path: ", npm_path print "header path: ", header_path print "command line: ", npm_cmdline npm_env = {'npm_config_nodedir': header_path, 'npm_config_target': nw_version, 'npm_config_arch': arch, 'npm_config_target_arch': target_arch, 'npm_config_runtime': 'node-webkit', 'npm_config_build_from_source': "true", 'npm_config_node_gyp': nw_gyp_path, 'PATH': os.getenv('PATH')} os.environ.update(npm_env) proc = Popen(npm_cmdline, stdout=PIPE, stderr=PIPE, env=os.environ) out, err = proc.communicate() print out print err assert(proc.returncode == 0) def wait_for_execute_script(driver, script, timeout=10): ret = None while timeout > 0: try: ret = driver.execute_script(script) break except selenium.common.exceptions.NoSuchElementException: pass except selenium.common.exceptions.WebDriverException: pass time.sleep(1) timeout = timeout - 1 if timeout <= 0: raise Exception('Timeout when execute script: ' + script) return ret def wait_for_element_id(driver, elem_id, timeout=10): ret = '' while timeout > 0: try: ret = driver.find_element_by_id(elem_id).get_attribute('innerHTML') break except selenium.common.exceptions.NoSuchElementException: pass except selenium.common.exceptions.WebDriverException: pass time.sleep(1) timeout = timeout - 1 if timeout <= 0: raise Exception('Timeout when waiting for element' + elem_id) return ret def wait_for_element_class(driver, elem_class, timeout=10): ret = '' while timeout > 0: try: ret = driver.find_element_by_class_name(elem_class).get_attribute('innerHTML') break except selenium.common.exceptions.NoSuchElementException: pass except selenium.common.exceptions.WebDriverException: pass time.sleep(1) timeout = timeout - 1 if timeout <= 0: raise Exception('Timeout when waiting for element' + elem_class) return ret def wait_for_element_tag(driver, elem_tag, timeout=10): ret = '' while timeout > 0: try: ret = driver.find_element_by_tag_name(elem_tag).get_attribute('innerHTML') break except selenium.common.exceptions.NoSuchElementException: pass except selenium.common.exceptions.WebDriverException: pass time.sleep(1) timeout = timeout - 1 if timeout <= 0: raise Exception('Timeout when waiting for element' + elem_tag) return ret def wait_for_element_id_content(driver, elem_id, content, timeout=10): ret = '' while timeout > 0: try: ret = driver.find_element_by_id(elem_id).get_attribute('innerHTML') if content in ret: break except selenium.common.exceptions.NoSuchElementException: pass time.sleep(1) timeout = timeout - 1 if timeout <= 0: raise Exception('Timeout when waiting for element: ' + elem_id + " content: " + content + "; actual: " + ret) return ret # wait for window handles def wait_window_handles(driver, until, timeout=60): if not hasattr(until, '__call__'): cond = lambda handles: len(handles) == until else: cond = until while not cond(driver.window_handles): time.sleep(1) timeout = timeout - 1 if timeout == 0: raise Exception('Timeout when waiting for window handles') def wait_switch_window_name(driver, name, timeout=60): while timeout > 0: try: driver.switch_to_window(name) break except selenium.common.exceptions.NoSuchWindowException: pass time.sleep(1) timeout = timeout - 1 if timeout <= 0: raise Exception('Timeout when waiting for window handles') def switch_to_app(driver, window_handle=None): def is_app_url(url): return (url.startswith('chrome-extension://') or url.startswith('file://') or url.startswith('http://') or url.startswith('https://')) and not url.endswith('/_generated_background_page.html') if window_handle is not None: driver.switch_to_window(window_handle) if is_app_url(driver.current_url): return elif window_handle is not None: # raise exception when given window is a devtools window raise Exception('Provided window handle is not an app window. %s' % driver.current_url) for handle in driver.window_handles: driver.switch_to_window(handle) if is_app_url(driver.current_url): return raise Exception('No app window found.') def switch_to_devtools(driver, devtools_window=None, skip_exception=False): def wait_for_devtools_ready(): # necessary compatible for older alphaN # where devtools is loaded in an iframe inspector_frames = driver.find_elements_by_id('inspector-app-iframe') if inspector_frames: driver.switch_to_frame(inspector_frames[0]) # wait for devtools is completely loaded while driver.execute_script('return document.readyState') != 'complete': time.sleep(1) if devtools_window is not None: driver.switch_to_window(devtools_window) if driver.current_url.startswith('devtools://'): wait_for_devtools_ready() return elif devtools_window is not None: # raise exception when given window is not a devtools raise Exception('Provided window handle is not a devtools window. %s' % driver.current_url) for handle in driver.window_handles: try: driver.switch_to_window(handle) if driver.current_url.startswith('devtools://'): wait_for_devtools_ready() return except selenium.common.exceptions.WebDriverException: if skip_exception: pass raise Exception('No devtools window found.') def devtools_click_tab(driver, tab_name): driver.execute_script('return document.querySelector(".tabbed-pane").shadowRoot.getElementById("tab-%s")' % tab_name).click() def devtools_type_in_console(driver, keys): console_prompt = driver.find_element_by_id('console-prompt') ActionChains(driver).click(console_prompt).perform() ActionChains(driver).send_keys(keys).perform() def no_live_process(driver, print_if_fail=True): if platform.system() == 'Windows': pgrep = subprocess.Popen(['wmic', 'process', 'where', '(ParentProcessId=%s)' % driver.service.process.pid, 'get', 'ProcessId'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, err = pgrep.communicate() ret = ('No Instance(s) Available.' in out) if not ret and print_if_fail: print 'live chrome processes:\n%s' % out # expect "No Instance(s) Available." in output return ret else: pgrep = subprocess.Popen(['pgrep', '-P', str(driver.service.process.pid)], stdout=subprocess.PIPE) out, err = pgrep.communicate() ret = (pgrep.returncode == 1) if not ret and print_if_fail: print 'live chrome processes:\n%s' % out print 'pgrep exit with %s' % pgrep.returncode # expect exit 1 from pgrep, which means no chrome process alive return ret def wait_net_service(server, port, timeout=None): """ Wait for network service to appear @param timeout: in seconds, if None or 0 wait forever @return: True of False, if timeout is None may return only True or throw unhandled network exception """ import socket import errno if timeout: from time import time as now # time module is needed to calc timeout shared between two exceptions end = now() + timeout while True: try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if timeout: next_timeout = end - now() if next_timeout < 0: return False else: s.settimeout(next_timeout) s.connect((server, port)) except socket.timeout, err: # this exception occurs only if timeout is set if timeout: return False except socket.error, err: # catch timeout exception from underlying network library # this one is different from socket.timeout if type(err.args) != tuple or err[0] != errno.ETIMEDOUT and err[0] != errno.ECONNREFUSED: raise else: s.close() return True _LOGGER = logging.getLogger(os.path.basename(__file__)) class ScopedTempDir(object): """A class that creates a scoped temporary directory.""" def __init__(self): self.path_ = None def __enter__(self): """Creates the temporary directory and initializes |path|.""" self.path_ = tempfile.mkdtemp(prefix='kasko_integration_') return self def __exit__(self, *args, **kwargs): """Destroys the temporary directory.""" if self.path_ is None: return shutil.rmtree(self.path_) @property def path(self): return self.path_ def release(self): path = self.path_ self.path_ = None return path class ScopedStartStop(object): """Utility class for calling 'start' and 'stop' within a scope.""" def __init__(self, service, start=None, stop=None): self.service_ = service if start is None: self.start_ = lambda x: x.start() else: self.start_ = start if stop is None: self.stop_ = lambda x: x.stop() else: self.stop_ = stop def __enter__(self): self.start_(self.service_) return self def __exit__(self, *args, **kwargs): if self.service_: self.stop_(self.service_) @property def service(self): """Returns the encapsulated service, retaining ownership.""" return self.service_ def release(self): """Relinquishes ownership of the encapsulated service and returns it.""" service = self.service_ self.service_ = None return service
5,529
335
<gh_stars>100-1000 { "word": "Lek", "definitions": [ "Take part in a communal display on a lek." ], "parts-of-speech": "Verb" }
72
416
<reponame>Zi0P4tch0/sdks<filename>iPhoneOS14.2.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSValueTransformer.h<gh_stars>100-1000 /* NSValueTransformer.h Copyright (c) 2002-2019, Apple Inc. All rights reserved. */ #import <Foundation/NSObject.h> @class NSArray<ObjectType>, NSString; NS_ASSUME_NONNULL_BEGIN typedef NSString *NSValueTransformerName NS_EXTENSIBLE_STRING_ENUM; FOUNDATION_EXPORT NSValueTransformerName const NSNegateBooleanTransformerName API_AVAILABLE(macos(10.3), ios(3.0), watchos(2.0), tvos(9.0)); FOUNDATION_EXPORT NSValueTransformerName const NSIsNilTransformerName API_AVAILABLE(macos(10.3), ios(3.0), watchos(2.0), tvos(9.0)); FOUNDATION_EXPORT NSValueTransformerName const NSIsNotNilTransformerName API_AVAILABLE(macos(10.3), ios(3.0), watchos(2.0), tvos(9.0)); FOUNDATION_EXPORT NSValueTransformerName const NSUnarchiveFromDataTransformerName API_DEPRECATED_WITH_REPLACEMENT("NSSecureUnarchiveFromDataTransformerName", macos(10.3, 10.14), ios(3.0, 12.0), watchos(2.0, 5.0), tvos(9.0, 12.0)); FOUNDATION_EXPORT NSValueTransformerName const NSKeyedUnarchiveFromDataTransformerName API_DEPRECATED_WITH_REPLACEMENT("NSSecureUnarchiveFromDataTransformerName", macos(10.3, 10.14), ios(3.0, 12.0), watchos(2.0, 5.0), tvos(9.0, 12.0)); FOUNDATION_EXPORT NSValueTransformerName const NSSecureUnarchiveFromDataTransformerName API_AVAILABLE(macos(10.14), ios(12.0), watchos(5.0), tvos(12.0)); API_AVAILABLE(macos(10.3), ios(3.0), watchos(2.0), tvos(9.0)) @interface NSValueTransformer : NSObject { } // name-based registry for shared objects (especially used when loading nib files with transformers specified by name in Interface Builder) - also useful for localization (developers can register different kind of transformers or differently configured transformers at application startup and refer to them by name from within nib files or other code) // if valueTransformerForName: does not find a registered transformer instance, it will fall back to looking up a class with the specified name - if one is found, it will instantiate a transformer with the default -init method and automatically register it + (void)setValueTransformer:(nullable NSValueTransformer *)transformer forName:(NSValueTransformerName)name; + (nullable NSValueTransformer *)valueTransformerForName:(NSValueTransformerName)name; + (NSArray<NSValueTransformerName> *)valueTransformerNames; // information that can be used to analyze available transformer instances (especially used inside Interface Builder) + (Class)transformedValueClass; // class of the "output" objects, as returned by transformedValue: + (BOOL)allowsReverseTransformation; // flag indicating whether transformation is read-only or not - (nullable id)transformedValue:(nullable id)value; // by default returns value - (nullable id)reverseTransformedValue:(nullable id)value; // by default raises an exception if +allowsReverseTransformation returns NO and otherwise invokes transformedValue: @end /// A value transformer which transforms values to and from \c NSData by archiving and unarchiving using secure coding. API_AVAILABLE(macos(10.14), ios(12.0), watchos(5.0), tvos(12.0)) @interface NSSecureUnarchiveFromDataTransformer : NSValueTransformer /// The list of allowable classes which the top-level object in the archive must conform to on encoding and decoding. /// /// Returns the result of \c +transformedValueClass if not \c Nil; otherwise, currently returns \c NSArray, \c NSDictionary, \c NSSet, \c NSString, \c NSNumber, \c NSDate, \c NSData, \c NSURL, \c NSUUID, and \c NSNull. /// /// Can be overridden by subclasses to provide an expanded or different set of allowed transformation classes. @property (class, readonly, copy) NSArray<Class> *allowedTopLevelClasses; @end NS_ASSUME_NONNULL_END
1,219
552
<reponame>asheraryam/ETEngine<filename>Engine/source/EtPipeline/Content/EditorAssetDatabase.h #pragma once #include "EditorAsset.h" #include <EtCore/Content/AssetDatabaseInterface.h> #include <EtCore/FileSystem/Package/PackageDescriptor.h> namespace et { namespace core { class Directory; class AssetDatabase; } REGISTRATION_NS(pl) } namespace et { namespace pl { //--------------------------------- // EditorAssetDatabase // class EditorAssetDatabase final : public core::I_AssetDatabase { // Definitions //--------------------- RTTR_ENABLE() REGISTRATION_FRIEND_NS(pl) public: typedef std::vector<EditorAssetBase*> T_AssetList; private: typedef std::vector<T_AssetList> T_CacheList; static std::string const s_AssetContentFileExt; // static functionality //---------------------- static rttr::type GetCacheType(T_AssetList const& cache); static rttr::type GetCacheAssetType(T_AssetList const& cache); public: static void InitDb(EditorAssetDatabase& db, std::string const& path); // construct destruct //-------------------- EditorAssetDatabase() = default; ~EditorAssetDatabase(); private: void Init(core::Directory* const directory); // accessors //----------- public: std::string const& GetAssetPath() const { return m_RootDirectory; } core::Directory const* GetDirectory() const { return m_Directory; } core::Directory* GetDirectory() { return m_Directory; } T_AssetList GetAssetsInPackage(core::HashString const packageId); std::vector<core::PackageDescriptor> const& GetPackages() const { return m_Packages; } T_AssetList GetAssetsMatchingQuery(std::string const& path, bool const recursive, std::string const& searchTerm, std::vector<rttr::type> const& filteredTypes); EditorAssetBase* GetAsset(core::HashString const assetId, bool const reportErrors = true) const; EditorAssetBase* GetAsset(core::HashString const assetId, rttr::type const type, bool const reportErrors = true) const; // faster bool IsRuntimeAsset(core::I_Asset* const asset) const; // Interface //----------- void IterateAllAssets(core::I_AssetDatabase::T_AssetFunc const& func) override; // Functionality //--------------------- void Flush(); void SetupAllRuntimeAssets(); void PopulateAssetDatabase(core::AssetDatabase& db) const; void RegisterNewAsset(EditorAssetBase* const asset); // utility //--------- private: T_CacheList::iterator FindCacheIt(rttr::type const type); T_CacheList::const_iterator FindCacheIt(rttr::type const type) const; T_AssetList& FindOrCreateCache(rttr::type const type); void RecursivePopulateAssets(core::Directory* const directory); void AddAsset(core::File* const configFile); // Data /////// core::Directory* m_Directory = nullptr; T_CacheList m_AssetCaches; // reflected std::string m_RootDirectory; std::vector<core::PackageDescriptor> m_Packages; }; } // namespace pl } // namespace et
892
480
<reponame>weicao/galaxysql /* * Copyright [2013-2021], Alibaba Group Holding Limited * * 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. */ /** * (created at 2011-10-31) */ package com.alibaba.polardbx.util; import com.alibaba.polardbx.server.util.StringUtil; import com.alibaba.polardbx.common.utils.Pair; import junit.framework.TestCase; import org.junit.Assert; /** * @author <NAME> */ public class StringUtilTest extends TestCase { public void testSequenceSlicing() { Assert.assertEquals(new Pair<Integer, Integer>(0, 2), StringUtil.sequenceSlicing("2")); Assert.assertEquals(new Pair<Integer, Integer>(1, 2), StringUtil.sequenceSlicing("1: 2")); Assert.assertEquals(new Pair<Integer, Integer>(1, 0), StringUtil.sequenceSlicing(" 1 :")); Assert.assertEquals(new Pair<Integer, Integer>(-1, 0), StringUtil.sequenceSlicing("-1: ")); Assert.assertEquals(new Pair<Integer, Integer>(-1, 0), StringUtil.sequenceSlicing(" -1:0")); Assert.assertEquals(new Pair<Integer, Integer>(0, 0), StringUtil.sequenceSlicing(" :")); } }
585
2,151
/* Written by Dr <NAME> (<EMAIL>) for the OpenSSL * project 2006. */ /* ==================================================================== * Copyright (c) 2006 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * [email protected]. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This product includes cryptographic software written by <NAME> * (<EMAIL>). This product includes software written by <NAME> (<EMAIL>). */ #include <openssl/evp.h> #include <limits.h> #include <string.h> #include <openssl/bn.h> #include <openssl/buf.h> #include <openssl/bytestring.h> #include <openssl/digest.h> #include <openssl/err.h> #include <openssl/mem.h> #include <openssl/nid.h> #include <openssl/rsa.h> #include "../internal.h" #include "../fipsmodule/rsa/internal.h" #include "internal.h" typedef struct { // Key gen parameters int nbits; BIGNUM *pub_exp; // RSA padding mode int pad_mode; // message digest const EVP_MD *md; // message digest for MGF1 const EVP_MD *mgf1md; // PSS salt length int saltlen; // tbuf is a buffer which is either NULL, or is the size of the RSA modulus. // It's used to store the output of RSA operations. uint8_t *tbuf; // OAEP label uint8_t *oaep_label; size_t oaep_labellen; } RSA_PKEY_CTX; typedef struct { uint8_t *data; size_t len; } RSA_OAEP_LABEL_PARAMS; static int pkey_rsa_init(EVP_PKEY_CTX *ctx) { RSA_PKEY_CTX *rctx; rctx = OPENSSL_malloc(sizeof(RSA_PKEY_CTX)); if (!rctx) { return 0; } OPENSSL_memset(rctx, 0, sizeof(RSA_PKEY_CTX)); rctx->nbits = 2048; rctx->pad_mode = RSA_PKCS1_PADDING; rctx->saltlen = -2; ctx->data = rctx; return 1; } static int pkey_rsa_copy(EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src) { RSA_PKEY_CTX *dctx, *sctx; if (!pkey_rsa_init(dst)) { return 0; } sctx = src->data; dctx = dst->data; dctx->nbits = sctx->nbits; if (sctx->pub_exp) { dctx->pub_exp = BN_dup(sctx->pub_exp); if (!dctx->pub_exp) { return 0; } } dctx->pad_mode = sctx->pad_mode; dctx->md = sctx->md; dctx->mgf1md = sctx->mgf1md; if (sctx->oaep_label) { OPENSSL_free(dctx->oaep_label); dctx->oaep_label = BUF_memdup(sctx->oaep_label, sctx->oaep_labellen); if (!dctx->oaep_label) { return 0; } dctx->oaep_labellen = sctx->oaep_labellen; } return 1; } static void pkey_rsa_cleanup(EVP_PKEY_CTX *ctx) { RSA_PKEY_CTX *rctx = ctx->data; if (rctx == NULL) { return; } BN_free(rctx->pub_exp); OPENSSL_free(rctx->tbuf); OPENSSL_free(rctx->oaep_label); OPENSSL_free(rctx); } static int setup_tbuf(RSA_PKEY_CTX *ctx, EVP_PKEY_CTX *pk) { if (ctx->tbuf) { return 1; } ctx->tbuf = OPENSSL_malloc(EVP_PKEY_size(pk->pkey)); if (!ctx->tbuf) { return 0; } return 1; } static int pkey_rsa_sign(EVP_PKEY_CTX *ctx, uint8_t *sig, size_t *siglen, const uint8_t *tbs, size_t tbslen) { RSA_PKEY_CTX *rctx = ctx->data; RSA *rsa = ctx->pkey->pkey.rsa; const size_t key_len = EVP_PKEY_size(ctx->pkey); if (!sig) { *siglen = key_len; return 1; } if (*siglen < key_len) { OPENSSL_PUT_ERROR(EVP, EVP_R_BUFFER_TOO_SMALL); return 0; } if (rctx->md) { unsigned out_len; switch (rctx->pad_mode) { case RSA_PKCS1_PADDING: if (!RSA_sign(EVP_MD_type(rctx->md), tbs, tbslen, sig, &out_len, rsa)) { return 0; } *siglen = out_len; return 1; case RSA_PKCS1_PSS_PADDING: return RSA_sign_pss_mgf1(rsa, siglen, sig, *siglen, tbs, tbslen, rctx->md, rctx->mgf1md, rctx->saltlen); default: return 0; } } return RSA_sign_raw(rsa, siglen, sig, *siglen, tbs, tbslen, rctx->pad_mode); } static int pkey_rsa_verify(EVP_PKEY_CTX *ctx, const uint8_t *sig, size_t siglen, const uint8_t *tbs, size_t tbslen) { RSA_PKEY_CTX *rctx = ctx->data; RSA *rsa = ctx->pkey->pkey.rsa; if (rctx->md) { switch (rctx->pad_mode) { case RSA_PKCS1_PADDING: return RSA_verify(EVP_MD_type(rctx->md), tbs, tbslen, sig, siglen, rsa); case RSA_PKCS1_PSS_PADDING: return RSA_verify_pss_mgf1(rsa, tbs, tbslen, rctx->md, rctx->mgf1md, rctx->saltlen, sig, siglen); default: return 0; } } size_t rslen; const size_t key_len = EVP_PKEY_size(ctx->pkey); if (!setup_tbuf(rctx, ctx) || !RSA_verify_raw(rsa, &rslen, rctx->tbuf, key_len, sig, siglen, rctx->pad_mode) || rslen != tbslen || CRYPTO_memcmp(tbs, rctx->tbuf, rslen) != 0) { return 0; } return 1; } static int pkey_rsa_verify_recover(EVP_PKEY_CTX *ctx, uint8_t *out, size_t *out_len, const uint8_t *sig, size_t sig_len) { RSA_PKEY_CTX *rctx = ctx->data; RSA *rsa = ctx->pkey->pkey.rsa; const size_t key_len = EVP_PKEY_size(ctx->pkey); if (out == NULL) { *out_len = key_len; return 1; } if (*out_len < key_len) { OPENSSL_PUT_ERROR(EVP, EVP_R_BUFFER_TOO_SMALL); return 0; } if (rctx->md == NULL) { return RSA_verify_raw(rsa, out_len, out, *out_len, sig, sig_len, rctx->pad_mode); } if (rctx->pad_mode != RSA_PKCS1_PADDING) { return 0; } // Assemble the encoded hash, using a placeholder hash value. static const uint8_t kDummyHash[EVP_MAX_MD_SIZE] = {0}; const size_t hash_len = EVP_MD_size(rctx->md); uint8_t *asn1_prefix; size_t asn1_prefix_len; int asn1_prefix_allocated; if (!setup_tbuf(rctx, ctx) || !RSA_add_pkcs1_prefix(&asn1_prefix, &asn1_prefix_len, &asn1_prefix_allocated, EVP_MD_type(rctx->md), kDummyHash, hash_len)) { return 0; } size_t rslen; int ok = 1; if (!RSA_verify_raw(rsa, &rslen, rctx->tbuf, key_len, sig, sig_len, RSA_PKCS1_PADDING) || rslen != asn1_prefix_len || // Compare all but the hash suffix. CRYPTO_memcmp(rctx->tbuf, asn1_prefix, asn1_prefix_len - hash_len) != 0) { ok = 0; } if (asn1_prefix_allocated) { OPENSSL_free(asn1_prefix); } if (!ok) { return 0; } if (out != NULL) { OPENSSL_memcpy(out, rctx->tbuf + rslen - hash_len, hash_len); } *out_len = hash_len; return 1; } static int pkey_rsa_encrypt(EVP_PKEY_CTX *ctx, uint8_t *out, size_t *outlen, const uint8_t *in, size_t inlen) { RSA_PKEY_CTX *rctx = ctx->data; RSA *rsa = ctx->pkey->pkey.rsa; const size_t key_len = EVP_PKEY_size(ctx->pkey); if (!out) { *outlen = key_len; return 1; } if (*outlen < key_len) { OPENSSL_PUT_ERROR(EVP, EVP_R_BUFFER_TOO_SMALL); return 0; } if (rctx->pad_mode == RSA_PKCS1_OAEP_PADDING) { if (!setup_tbuf(rctx, ctx) || !RSA_padding_add_PKCS1_OAEP_mgf1(rctx->tbuf, key_len, in, inlen, rctx->oaep_label, rctx->oaep_labellen, rctx->md, rctx->mgf1md) || !RSA_encrypt(rsa, outlen, out, *outlen, rctx->tbuf, key_len, RSA_NO_PADDING)) { return 0; } return 1; } return RSA_encrypt(rsa, outlen, out, *outlen, in, inlen, rctx->pad_mode); } static int pkey_rsa_decrypt(EVP_PKEY_CTX *ctx, uint8_t *out, size_t *outlen, const uint8_t *in, size_t inlen) { RSA_PKEY_CTX *rctx = ctx->data; RSA *rsa = ctx->pkey->pkey.rsa; const size_t key_len = EVP_PKEY_size(ctx->pkey); if (!out) { *outlen = key_len; return 1; } if (*outlen < key_len) { OPENSSL_PUT_ERROR(EVP, EVP_R_BUFFER_TOO_SMALL); return 0; } if (rctx->pad_mode == RSA_PKCS1_OAEP_PADDING) { size_t padded_len; if (!setup_tbuf(rctx, ctx) || !RSA_decrypt(rsa, &padded_len, rctx->tbuf, key_len, in, inlen, RSA_NO_PADDING) || !RSA_padding_check_PKCS1_OAEP_mgf1( out, outlen, key_len, rctx->tbuf, padded_len, rctx->oaep_label, rctx->oaep_labellen, rctx->md, rctx->mgf1md)) { return 0; } return 1; } return RSA_decrypt(rsa, outlen, out, key_len, in, inlen, rctx->pad_mode); } static int check_padding_md(const EVP_MD *md, int padding) { if (!md) { return 1; } if (padding == RSA_NO_PADDING) { OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_PADDING_MODE); return 0; } return 1; } static int is_known_padding(int padding_mode) { switch (padding_mode) { case RSA_PKCS1_PADDING: case RSA_NO_PADDING: case RSA_PKCS1_OAEP_PADDING: case RSA_PKCS1_PSS_PADDING: return 1; default: return 0; } } static int pkey_rsa_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) { RSA_PKEY_CTX *rctx = ctx->data; switch (type) { case EVP_PKEY_CTRL_RSA_PADDING: if (!is_known_padding(p1) || !check_padding_md(rctx->md, p1) || (p1 == RSA_PKCS1_PSS_PADDING && 0 == (ctx->operation & (EVP_PKEY_OP_SIGN | EVP_PKEY_OP_VERIFY))) || (p1 == RSA_PKCS1_OAEP_PADDING && 0 == (ctx->operation & EVP_PKEY_OP_TYPE_CRYPT))) { OPENSSL_PUT_ERROR(EVP, EVP_R_ILLEGAL_OR_UNSUPPORTED_PADDING_MODE); return 0; } if ((p1 == RSA_PKCS1_PSS_PADDING || p1 == RSA_PKCS1_OAEP_PADDING) && rctx->md == NULL) { rctx->md = EVP_sha1(); } rctx->pad_mode = p1; return 1; case EVP_PKEY_CTRL_GET_RSA_PADDING: *(int *)p2 = rctx->pad_mode; return 1; case EVP_PKEY_CTRL_RSA_PSS_SALTLEN: case EVP_PKEY_CTRL_GET_RSA_PSS_SALTLEN: if (rctx->pad_mode != RSA_PKCS1_PSS_PADDING) { OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_PSS_SALTLEN); return 0; } if (type == EVP_PKEY_CTRL_GET_RSA_PSS_SALTLEN) { *(int *)p2 = rctx->saltlen; } else { if (p1 < -2) { return 0; } rctx->saltlen = p1; } return 1; case EVP_PKEY_CTRL_RSA_KEYGEN_BITS: if (p1 < 256) { OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_KEYBITS); return 0; } rctx->nbits = p1; return 1; case EVP_PKEY_CTRL_RSA_KEYGEN_PUBEXP: if (!p2) { return 0; } BN_free(rctx->pub_exp); rctx->pub_exp = p2; return 1; case EVP_PKEY_CTRL_RSA_OAEP_MD: case EVP_PKEY_CTRL_GET_RSA_OAEP_MD: if (rctx->pad_mode != RSA_PKCS1_OAEP_PADDING) { OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_PADDING_MODE); return 0; } if (type == EVP_PKEY_CTRL_GET_RSA_OAEP_MD) { *(const EVP_MD **)p2 = rctx->md; } else { rctx->md = p2; } return 1; case EVP_PKEY_CTRL_MD: if (!check_padding_md(p2, rctx->pad_mode)) { return 0; } rctx->md = p2; return 1; case EVP_PKEY_CTRL_GET_MD: *(const EVP_MD **)p2 = rctx->md; return 1; case EVP_PKEY_CTRL_RSA_MGF1_MD: case EVP_PKEY_CTRL_GET_RSA_MGF1_MD: if (rctx->pad_mode != RSA_PKCS1_PSS_PADDING && rctx->pad_mode != RSA_PKCS1_OAEP_PADDING) { OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_MGF1_MD); return 0; } if (type == EVP_PKEY_CTRL_GET_RSA_MGF1_MD) { if (rctx->mgf1md) { *(const EVP_MD **)p2 = rctx->mgf1md; } else { *(const EVP_MD **)p2 = rctx->md; } } else { rctx->mgf1md = p2; } return 1; case EVP_PKEY_CTRL_RSA_OAEP_LABEL: { if (rctx->pad_mode != RSA_PKCS1_OAEP_PADDING) { OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_PADDING_MODE); return 0; } OPENSSL_free(rctx->oaep_label); RSA_OAEP_LABEL_PARAMS *params = p2; rctx->oaep_label = params->data; rctx->oaep_labellen = params->len; return 1; } case EVP_PKEY_CTRL_GET_RSA_OAEP_LABEL: if (rctx->pad_mode != RSA_PKCS1_OAEP_PADDING) { OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_PADDING_MODE); return 0; } CBS_init((CBS *)p2, rctx->oaep_label, rctx->oaep_labellen); return 1; default: OPENSSL_PUT_ERROR(EVP, EVP_R_COMMAND_NOT_SUPPORTED); return 0; } } static int pkey_rsa_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) { RSA *rsa = NULL; RSA_PKEY_CTX *rctx = ctx->data; if (!rctx->pub_exp) { rctx->pub_exp = BN_new(); if (!rctx->pub_exp || !BN_set_word(rctx->pub_exp, RSA_F4)) { return 0; } } rsa = RSA_new(); if (!rsa) { return 0; } if (!RSA_generate_key_ex(rsa, rctx->nbits, rctx->pub_exp, NULL)) { RSA_free(rsa); return 0; } EVP_PKEY_assign_RSA(pkey, rsa); return 1; } const EVP_PKEY_METHOD rsa_pkey_meth = { EVP_PKEY_RSA, pkey_rsa_init, pkey_rsa_copy, pkey_rsa_cleanup, pkey_rsa_keygen, pkey_rsa_sign, NULL /* sign_message */, pkey_rsa_verify, NULL /* verify_message */, pkey_rsa_verify_recover, pkey_rsa_encrypt, pkey_rsa_decrypt, 0 /* derive */, pkey_rsa_ctrl, }; int EVP_PKEY_CTX_set_rsa_padding(EVP_PKEY_CTX *ctx, int padding) { return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, -1, EVP_PKEY_CTRL_RSA_PADDING, padding, NULL); } int EVP_PKEY_CTX_get_rsa_padding(EVP_PKEY_CTX *ctx, int *out_padding) { return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, -1, EVP_PKEY_CTRL_GET_RSA_PADDING, 0, out_padding); } int EVP_PKEY_CTX_set_rsa_pss_saltlen(EVP_PKEY_CTX *ctx, int salt_len) { return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, (EVP_PKEY_OP_SIGN | EVP_PKEY_OP_VERIFY), EVP_PKEY_CTRL_RSA_PSS_SALTLEN, salt_len, NULL); } int EVP_PKEY_CTX_get_rsa_pss_saltlen(EVP_PKEY_CTX *ctx, int *out_salt_len) { return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, (EVP_PKEY_OP_SIGN | EVP_PKEY_OP_VERIFY), EVP_PKEY_CTRL_GET_RSA_PSS_SALTLEN, 0, out_salt_len); } int EVP_PKEY_CTX_set_rsa_keygen_bits(EVP_PKEY_CTX *ctx, int bits) { return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, EVP_PKEY_OP_KEYGEN, EVP_PKEY_CTRL_RSA_KEYGEN_BITS, bits, NULL); } int EVP_PKEY_CTX_set_rsa_keygen_pubexp(EVP_PKEY_CTX *ctx, BIGNUM *e) { return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, EVP_PKEY_OP_KEYGEN, EVP_PKEY_CTRL_RSA_KEYGEN_PUBEXP, 0, e); } int EVP_PKEY_CTX_set_rsa_oaep_md(EVP_PKEY_CTX *ctx, const EVP_MD *md) { return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, EVP_PKEY_OP_TYPE_CRYPT, EVP_PKEY_CTRL_RSA_OAEP_MD, 0, (void *)md); } int EVP_PKEY_CTX_get_rsa_oaep_md(EVP_PKEY_CTX *ctx, const EVP_MD **out_md) { return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, EVP_PKEY_OP_TYPE_CRYPT, EVP_PKEY_CTRL_GET_RSA_OAEP_MD, 0, (void*) out_md); } int EVP_PKEY_CTX_set_rsa_mgf1_md(EVP_PKEY_CTX *ctx, const EVP_MD *md) { return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, EVP_PKEY_OP_TYPE_SIG | EVP_PKEY_OP_TYPE_CRYPT, EVP_PKEY_CTRL_RSA_MGF1_MD, 0, (void*) md); } int EVP_PKEY_CTX_get_rsa_mgf1_md(EVP_PKEY_CTX *ctx, const EVP_MD **out_md) { return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, EVP_PKEY_OP_TYPE_SIG | EVP_PKEY_OP_TYPE_CRYPT, EVP_PKEY_CTRL_GET_RSA_MGF1_MD, 0, (void*) out_md); } int EVP_PKEY_CTX_set0_rsa_oaep_label(EVP_PKEY_CTX *ctx, uint8_t *label, size_t label_len) { RSA_OAEP_LABEL_PARAMS params = {label, label_len}; return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, EVP_PKEY_OP_TYPE_CRYPT, EVP_PKEY_CTRL_RSA_OAEP_LABEL, 0, &params); } int EVP_PKEY_CTX_get0_rsa_oaep_label(EVP_PKEY_CTX *ctx, const uint8_t **out_label) { CBS label; if (!EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, EVP_PKEY_OP_TYPE_CRYPT, EVP_PKEY_CTRL_GET_RSA_OAEP_LABEL, 0, &label)) { return -1; } if (CBS_len(&label) > INT_MAX) { OPENSSL_PUT_ERROR(EVP, ERR_R_OVERFLOW); return -1; } *out_label = CBS_data(&label); return (int)CBS_len(&label); }
9,497
13,006
<filename>deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/conf/misc/DummyConfig.java /******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ package org.deeplearning4j.nn.conf.misc; import lombok.AllArgsConstructor; import org.deeplearning4j.nn.api.TrainingConfig; import org.deeplearning4j.nn.conf.GradientNormalization; import org.nd4j.linalg.api.buffer.DataType; import org.nd4j.linalg.learning.config.IUpdater; import org.nd4j.linalg.learning.config.NoOp; import org.nd4j.linalg.learning.regularization.Regularization; import java.util.List; /** * A 'dummy' training configuration for use in frozen layers * * @author <NAME> */ @AllArgsConstructor public class DummyConfig implements TrainingConfig { private final String name; @Override public String getLayerName() { return name; } @Override public List<Regularization> getRegularizationByParam(String paramName) { return null; } @Override public boolean isPretrainParam(String paramName) { return false; } @Override public IUpdater getUpdaterByParam(String paramName) { return new NoOp(); } @Override public GradientNormalization getGradientNormalization() { return GradientNormalization.None; } @Override public double getGradientNormalizationThreshold() { return 1.0; } @Override public void setDataType(DataType dataType) { } }
680
32,544
<reponame>DBatOWL/tutorials<filename>spring-core-2/src/main/java/com/baeldung/bean/injection/Ship.java<gh_stars>1000+ package com.baeldung.bean.injection; import org.springframework.beans.factory.annotation.Autowired; public class Ship { @Autowired private Helm helm; public Ship() { helm = new Helm(); } public Ship(Helm helm) { this.helm = helm; } @Autowired public void setHelm(Helm helm) { this.helm = helm; } public Helm getHelm() { return this.helm; } }
237
848
/* * Copyright 2019 Xilinx 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. */ #pragma once #include <memory> #include "xir/dpu_controller.hpp" namespace { class DpuControllerDnndk : public xir::DpuController { public: DpuControllerDnndk(); virtual ~DpuControllerDnndk(); DpuControllerDnndk(const DpuControllerDnndk& other) = delete; DpuControllerDnndk& operator=(const DpuControllerDnndk& rhs) = delete; private: virtual void run(size_t core_idx, const uint64_t code, const std::vector<uint64_t>& gen_reg) override; virtual size_t get_num_of_dpus() const override; virtual size_t get_device_id(size_t device_core_id) const override; virtual size_t get_core_id(size_t device_core_id) const override; virtual uint64_t get_fingerprint(size_t device_core_id) const override; private: int fd_; size_t num_of_dpus_; uint64_t fingerprint_; }; } // namespace
470
370
/* Copyright <NAME> 2014 Copyright <NAME> 2014 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 MSGPACK_PREDEF_OS_HAIKU_H #define MSGPACK_PREDEF_OS_HAIKU_H #include "../version_number.h" #include "../make.h" /*` [heading `MSGPACK_OS_HAIKU`] [@http://en.wikipedia.org/wiki/Haiku_(operating_system) Haiku] operating system. [table [[__predef_symbol__] [__predef_version__]] [[`__HAIKU__`] [__predef_detection__]] ] */ #define MSGPACK_OS_HAIKU MSGPACK_VERSION_NUMBER_NOT_AVAILABLE #if !defined(MSGPACK_PREDEF_DETAIL_OS_DETECTED) && ( \ defined(__HAIKU__) \ ) # undef MSGPACK_OS_HAIKU # define MSGPACK_OS_HAIKU MSGPACK_VERSION_NUMBER_AVAILABLE #endif #if MSGPACK_OS_HAIKU # define MSGPACK_OS_HAIKU_AVAILABLE #include "../detail/os_detected.h" #endif #define MSGPACK_OS_HAIKU_NAME "Haiku" #include "../detail/test.h" MSGPACK_PREDEF_DECLARE_TEST(MSGPACK_OS_HAIKU,MSGPACK_OS_HAIKU_NAME) #endif
468
1,681
package com.easytoolsoft.easyreport.mybatis.service; import java.util.List; import com.easytoolsoft.easyreport.mybatis.data.SelectRepository; import com.easytoolsoft.easyreport.mybatis.pager.PageInfo; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; /** * @param <Dao> * @param <Po> * @param <Example> * @param <Type> Key字段数据类型(Integer,Long,String等) * @author <NAME> * @date 2017-03-25 */ public abstract class AbstractGetService<Dao extends SelectRepository<Po, Example, Type>, Po, Example, Type> implements GetService<Po, Example, Type> { @Autowired protected Dao dao; @Override public boolean exists(final Example example) { return this.dao.countByExample(example) > 0; } @Override public Po getById(final Type id) { return this.dao.selectById(id); } @Override public List<Po> getByExample(final Example example) { return this.dao.selectByExample(example); } @Override public List<Po> getAll() { return this.dao.selectByExample(null); } @Override public Po getOneByExample(final Example example) { return this.dao.selectOneByExample(example); } @Override public List<Po> getIn(final List<Po> records) { return this.dao.selectIn(records); } @Override public List<Po> getByPage(final PageInfo pageInfo) { return this.getByPage(pageInfo, "", ""); } @Override public List<Po> getByPage(final PageInfo pageInfo, final String fieldName, final String keyword) { if (StringUtils.isBlank(fieldName)) { return this.getByPage(pageInfo, null); } return this.getByPage(pageInfo, this.getPageExample(fieldName, keyword)); } @Override public List<Po> getByPage(final PageInfo pageInfo, final Example example) { pageInfo.setTotals(this.dao.countByPager(pageInfo, example)); return this.dao.selectByPager(pageInfo, example); } protected abstract Example getPageExample(String fieldName, String keyword); }
814
435
<filename>pycon-ar-2013/videos/me-voy-a-hacer-pypy-por-natalia-bidart-pycon-2013-dia-1-auditorio-aep.json { "description": "Help us caption & translate this video!\n\nhttp://amara.org/v/DKoA/", "language": "spa", "recorded": "2013-10-24", "speakers": [ "<NAME>" ], "thumbnail_url": "https://i.ytimg.com/vi/3EgECmkNDOk/hqdefault.jpg", "title": "Me voy a hacer pypy", "videos": [ { "type": "youtube", "url": "https://www.youtube.com/watch?v=3EgECmkNDOk" } ] }
235
312
/******************************************************************************* * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Distribution License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/org/documents/edl-v10.php. *******************************************************************************/ package org.eclipse.rdf4j.rio.helpers; import org.eclipse.rdf4j.rio.RioSetting; /** * WriterSettings for the N-Triples writer features. * * @author <NAME> */ public class NTriplesWriterSettings { /** * Boolean setting for writer to determine if unicode escapes are used. * <p> * Defaults to false. * <p> * Can be overridden by setting system property {@code org.eclipse.rdf4j.rio.ntriples.escape_unicode} */ public static final RioSetting<Boolean> ESCAPE_UNICODE = new BooleanRioSetting( "org.eclipse.rdf4j.rio.ntriples.escape_unicode", "Escape Unicode characters", Boolean.FALSE); /** * Private constructor */ private NTriplesWriterSettings() { } }
333
664
#include "libtorrent/storage.hpp" #include "libtorrent/disk_io_job.hpp" #include "test.hpp" #include <boost/atomic.hpp> using namespace libtorrent; TORRENT_TEST(empty_fence) { libtorrent::disk_job_fence fence; counters cnt; disk_io_job test_job[10]; // issue 5 jobs. None of them should be blocked by a fence int ret = 0; // add a fence job ret = fence.raise_fence(&test_job[5], &test_job[6], cnt); // since we don't have any outstanding jobs // we need to post this job TEST_CHECK(ret == disk_job_fence::fence_post_fence); ret = fence.is_blocked(&test_job[7]); TEST_CHECK(ret == true); ret = fence.is_blocked(&test_job[8]); TEST_CHECK(ret == true); tailqueue<disk_io_job> jobs; // complete the fence job fence.job_complete(&test_job[5], jobs); // now it's fine to post the blocked jobs TEST_CHECK(jobs.size() == 2); TEST_CHECK(jobs.first() == &test_job[7]); // the disk_io_fence has an assert in its destructor // to make sure all outstanding jobs are completed, so we must // complete them before we're done fence.job_complete(&test_job[7], jobs); fence.job_complete(&test_job[8], jobs); } TORRENT_TEST(job_fence) { counters cnt; libtorrent::disk_job_fence fence; disk_io_job test_job[10]; // issue 5 jobs. None of them should be blocked by a fence bool ret = false; TEST_CHECK(fence.num_outstanding_jobs() == 0); ret = fence.is_blocked(&test_job[0]); TEST_CHECK(ret == false); TEST_CHECK(fence.num_outstanding_jobs() == 1); ret = fence.is_blocked(&test_job[1]); TEST_CHECK(ret == false); ret = fence.is_blocked(&test_job[2]); TEST_CHECK(ret == false); ret = fence.is_blocked(&test_job[3]); TEST_CHECK(ret == false); ret = fence.is_blocked(&test_job[4]); TEST_CHECK(ret == false); TEST_CHECK(fence.num_outstanding_jobs() == 5); TEST_CHECK(fence.num_blocked() == 0); // add a fence job ret = fence.raise_fence(&test_job[5], &test_job[6], cnt); // since we have outstanding jobs, no need // to post anything TEST_CHECK(ret == disk_job_fence::fence_post_flush); ret = fence.is_blocked(&test_job[7]); TEST_CHECK(ret == true); ret = fence.is_blocked(&test_job[8]); TEST_CHECK(ret == true); tailqueue<disk_io_job> jobs; fence.job_complete(&test_job[3], jobs); TEST_CHECK(jobs.size() == 0); fence.job_complete(&test_job[2], jobs); TEST_CHECK(jobs.size() == 0); fence.job_complete(&test_job[4], jobs); TEST_CHECK(jobs.size() == 0); fence.job_complete(&test_job[1], jobs); TEST_CHECK(jobs.size() == 0); fence.job_complete(&test_job[0], jobs); TEST_EQUAL(jobs.size(), 0); // the flush job completes fence.job_complete(&test_job[6], jobs); // this was the last job. Now we should be // able to run the fence job TEST_EQUAL(jobs.size(), 1); TEST_CHECK(jobs.first() == &test_job[5]); jobs.pop_front(); // complete the fence job fence.job_complete(&test_job[5], jobs); // now it's fine to post the blocked jobs TEST_EQUAL(jobs.size(), 2); TEST_CHECK(jobs.first() == &test_job[7]); // the disk_io_fence has an assert in its destructor // to make sure all outstanding jobs are completed, so we must // complete them before we're done fence.job_complete(&test_job[7], jobs); fence.job_complete(&test_job[8], jobs); } TORRENT_TEST(double_fence) { counters cnt; libtorrent::disk_job_fence fence; disk_io_job test_job[10]; // issue 5 jobs. None of them should be blocked by a fence int ret = 0; TEST_CHECK(fence.num_outstanding_jobs() == 0); ret = fence.is_blocked(&test_job[0]); TEST_CHECK(ret == false); TEST_CHECK(fence.num_outstanding_jobs() == 1); ret = fence.is_blocked(&test_job[1]); TEST_CHECK(ret == false); ret = fence.is_blocked(&test_job[2]); TEST_CHECK(ret == false); ret = fence.is_blocked(&test_job[3]); TEST_CHECK(ret == false); ret = fence.is_blocked(&test_job[4]); TEST_CHECK(ret == false); TEST_CHECK(fence.num_outstanding_jobs() == 5); TEST_CHECK(fence.num_blocked() == 0); // add two fence jobs ret = fence.raise_fence(&test_job[5], &test_job[6], cnt); // since we have outstanding jobs, no need // to post anything TEST_CHECK(ret == disk_job_fence::fence_post_flush); ret = fence.raise_fence(&test_job[7], &test_job[8], cnt); // since we have outstanding jobs, no need // to post anything TEST_CHECK(ret == disk_job_fence::fence_post_none); fprintf(stderr, "ret: %d\n", ret); ret = fence.is_blocked(&test_job[9]); TEST_CHECK(ret == true); tailqueue<disk_io_job> jobs; fence.job_complete(&test_job[3], jobs); TEST_CHECK(jobs.size() == 0); fence.job_complete(&test_job[2], jobs); TEST_CHECK(jobs.size() == 0); fence.job_complete(&test_job[4], jobs); TEST_CHECK(jobs.size() == 0); fence.job_complete(&test_job[1], jobs); TEST_CHECK(jobs.size() == 0); fence.job_complete(&test_job[0], jobs); TEST_CHECK(jobs.size() == 0); fence.job_complete(&test_job[6], jobs); // this was the last job. Now we should be // able to run the fence job TEST_CHECK(jobs.size() == 1); TEST_CHECK(jobs.first() == &test_job[5]); jobs.pop_front(); // complete the fence job fence.job_complete(&test_job[5], jobs); // now it's fine to run the next fence job // first we get the flush job TEST_CHECK(jobs.size() == 1); TEST_CHECK(jobs.first() == &test_job[8]); jobs.pop_front(); fence.job_complete(&test_job[8], jobs); // then the fence itself TEST_CHECK(jobs.size() == 1); TEST_CHECK(jobs.first() == &test_job[7]); jobs.pop_front(); fence.job_complete(&test_job[7], jobs); // and now we can run the remaining blocked job TEST_CHECK(jobs.size() == 1); TEST_CHECK(jobs.first() == &test_job[9]); // the disk_io_fence has an assert in its destructor // to make sure all outstanding jobs are completed, so we must // complete them before we're done fence.job_complete(&test_job[9], jobs); }
2,251
379
// Copyright © 2012, Université catholique de Louvain // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #ifndef MOZART_MODCOMPACTSTRING_H #define MOZART_MODCOMPACTSTRING_H #include "../mozartcore.hh" #ifndef MOZART_GENERATOR namespace mozart { namespace builtins { ////////////////////////// // CompactString module // ////////////////////////// class ModCompactString : public Module { public: ModCompactString() : Module("CompactString") {} class IsCompactString : public Builtin<IsCompactString> { public: IsCompactString() : Builtin("isCompactString") {} static void call(VM vm, In value, Out result) { result = build(vm, StringLike(value).isString(vm)); } }; class IsCompactByteString : public Builtin<IsCompactByteString> { public: IsCompactByteString() : Builtin("isCompactByteString") {} static void call(VM vm, In value, Out result) { result = build(vm, StringLike(value).isByteString(vm)); } }; class CharAt : public Builtin<CharAt> { public: CharAt() : Builtin("charAt") {} static void call(VM vm, In value, In index, Out result) { result = build(vm, StringLike(value).stringCharAt(vm, index)); } }; class Append : public Builtin<Append> { public: Append() : Builtin("append") {} static void call(VM vm, In left, In right, Out result) { result = StringLike(left).stringAppend(vm, right); } }; class Slice : public Builtin<Slice> { public: Slice() : Builtin("slice") {} static void call(VM vm, In value, In from, In to, Out result) { result = StringLike(value).stringSlice(vm, from, to); } }; class Search : public Builtin<Search> { public: Search() : Builtin("search") {} static void call(VM vm, In value, In from, In needle, Out begin, Out end) { return StringLike(value).stringSearch(vm, from, needle, begin, end); } }; class HasPrefix : public Builtin<HasPrefix> { public: HasPrefix() : Builtin("hasPrefix") {} static void call(VM vm, In string, In prefix, Out result) { result = build(vm, StringLike(string).stringHasPrefix(vm, prefix)); } }; class HasSuffix : public Builtin<HasSuffix> { public: HasSuffix() : Builtin("hasSuffix") {} static void call(VM vm, In string, In suffix, Out result) { result = build(vm, StringLike(string).stringHasSuffix(vm, suffix)); } }; }; } } #endif #endif // MOZART_MODCOMPACTSTRING_H
1,253
3,089
/*! http://www.w3.org/TR/SVG/coords.html#InterfaceSVGTransform // Transform Types const unsigned short SVG_TRANSFORM_UNKNOWN = 0; const unsigned short SVG_TRANSFORM_MATRIX = 1; const unsigned short SVG_TRANSFORM_TRANSLATE = 2; const unsigned short SVG_TRANSFORM_SCALE = 3; const unsigned short SVG_TRANSFORM_ROTATE = 4; const unsigned short SVG_TRANSFORM_SKEWX = 5; const unsigned short SVG_TRANSFORM_SKEWY = 6; readonly attribute unsigned short type; readonly attribute SVGMatrix matrix; readonly attribute float angle; void setMatrix(in SVGMatrix matrix) raises(DOMException); void setTranslate(in float tx, in float ty) raises(DOMException); void setScale(in float sx, in float sy) raises(DOMException); void setRotate(in float angle, in float cx, in float cy) raises(DOMException); void setSkewX(in float angle) raises(DOMException); void setSkewY(in float angle) raises(DOMException); */ #import <Foundation/Foundation.h> #import "SVGMatrix.h" @interface SVGTransform : NSObject /*! Transform Types */ typedef enum SVGKTransformType { SVG_TRANSFORM_UNKNOWN = 0, SVG_TRANSFORM_MATRIX = 1, SVG_TRANSFORM_TRANSLATE = 2, SVG_TRANSFORM_SCALE = 3, SVG_TRANSFORM_ROTATE = 4, SVG_TRANSFORM_SKEWX = 5, SVG_TRANSFORM_SKEWY = 6 } SVGKTransformType; @property(nonatomic) SVGKTransformType type; @property(nonatomic,strong) SVGMatrix* matrix; @property(nonatomic,readonly) float angle; -(void) setMatrix:(SVGMatrix*) matrix; -(void) setTranslate:(float) tx ty:(float) ty; -(void) setScale:(float) sx sy:(float) sy; -(void) setRotate:(float) angle cx:(float) cx cy:(float) cy; -(void) setSkewX:(float) angle; -(void) setSkewY:(float) angle; @end
598
8,865
<filename>atlas-gradle-plugin/atlas-plugin/src/main/java/com/taobao/android/builder/insant/InstantInfo.java package com.taobao.android.builder.insant; /** * InstantInfo * * @author zhayu.ll * @date 18/10/26 */ public class InstantInfo { public String fileName; public String baseVersion; public String patchVersion; public String md5; public long patchSize; }
138
492
#include <THC/THC.h> #include "shift_cuda.h" #include "cuda/shift_kernel_cuda.h" extern THCState *state; void shift_featuremap_cuda_forward(THCudaTensor *data, THCudaIntTensor *shift, THCudaTensor *out) { THArgCheck(THCudaTensor_isContiguous(state, data), 1, "data tensor has to be contiguous"); THArgCheck(THCudaTensor_isContiguous(state, shift), 1, "shift tensor has to be contiguous"); int batch_size = THCudaTensor_size(state, data, 0); int channels = THCudaTensor_size(state, data, 2); int tsize = THCudaTensor_size(state, data, 1); int hwsize = THCudaTensor_size(state, data, 3); int groupsize = THCudaTensor_size(state, shift, 1); ShiftDataCudaForward(THCState_getCurrentStream(state), THCudaTensor_data(state, data), THCudaIntTensor_data(state, shift), batch_size, channels, tsize, hwsize, groupsize, THCudaTensor_data(state, out)); } void shift_featuremap_cuda_backward(THCudaTensor *grad_output, THCudaIntTensor *shift, THCudaTensor *grad_input) { THArgCheck(THCudaTensor_isContiguous(state, grad_output), 1, "data tensor has to be contiguous"); THArgCheck(THCudaTensor_isContiguous(state, shift), 1, "shift tensor has to be contiguous"); int batch_size = THCudaTensor_size(state, grad_output, 0); int channels = THCudaTensor_size(state, grad_output, 2); int tsize = THCudaTensor_size(state, grad_output, 1); int hwsize = THCudaTensor_size(state, grad_output, 3); int groupsize = THCudaTensor_size(state, shift, 1); ShiftDataCudaBackward(THCState_getCurrentStream(state), THCudaTensor_data(state, grad_output), THCudaIntTensor_data(state, shift), batch_size, channels, tsize, hwsize, groupsize, THCudaTensor_data(state, grad_input)); }
1,015
439
<gh_stars>100-1000 #ifndef GyverDimmer_h #define GyverDimmer_h #include <Arduino.h> #include "FastIO.h" // брезенхем одноканальный template < uint8_t _D_PIN > class DimmerBres { public: DimmerBres() { pinMode(_D_PIN, OUTPUT); fastWrite(_D_PIN, LOW); } void write(uint8_t dim) { dimmer = dim; } void tick() { int val = ((uint16_t)++count * dimmer) >> 9; if (lastVal != (val != last)) fastWrite(_D_PIN, val != last); lastVal = (val != last); last = val; } private: uint8_t count = 0, last = 0, lastVal = 0, dimmer = 0; }; // брезенхем многоканальный template < uint8_t _D_AMOUNT > class DimmerBresMulti { public: void attach(uint8_t num, uint8_t pin) { dimPins[num] = pin; pinMode(pin, OUTPUT); } void write(uint8_t pin, uint8_t dim) { dimmer[pin] = dim; } void tick() { count++; for (byte i = 0; i < _D_AMOUNT; i++) { int val = ((uint16_t)count * dimmer[i]) >> 9; if (lastState[i] != (val != last[i])) fastWrite(dimPins[i], val != last[i]); lastState[i] = (val != last[i]); last[i] = val; } } private: uint8_t count, last[_D_AMOUNT], lastState[_D_AMOUNT], dimmer[_D_AMOUNT], dimPins[_D_AMOUNT]; }; // плавный диммер одноканальный template < uint8_t _D_PIN > class Dimmer { public: Dimmer(uint8_t freq = 50) { pinMode(_D_PIN, OUTPUT); fastWrite(_D_PIN, LOW); if (freq == 50) maxVal = 9300; else maxVal = 7600; } void write(uint8_t dim) { dimmer = map(dim, 0, 255, maxVal, 500); } bool tickZero() { fastWrite(_D_PIN, LOW); if (lastDim != dimmer) { lastDim = dimmer; return true; } return false; } void tickTimer() { fastWrite(_D_PIN, HIGH); } int getPeriod() { return dimmer; } private: int dimmer = 0, lastDim = 0; int maxVal = 0; }; // плавный диммер многоканальный template < uint8_t _D_AMOUNT > class DimmerMulti { public: DimmerMulti(uint8_t freq = 50) { if (freq == 50) maxVal = 9300; else maxVal = 7600; } void attach(uint8_t num, uint8_t pin) { dimPins[num] = pin; pinMode(pin, OUTPUT); } void write(uint8_t pin, uint8_t dim) { dimmer[pin] = dim; } bool tickZero() { counter = 255; } void tickTimer() { for (byte i = 0; i < _D_AMOUNT; i++) { if (counter == dimmer[i]) fastWrite(dimPins[i], 1); // на текущем тике включаем else if (counter == dimmer[i] - 1) fastWrite(dimPins[i], 0); // на следующем выключаем } counter--; } int getPeriod() { return (maxVal == 9300) ? 37 : 31; // us } private: uint8_t dimmer[_D_AMOUNT], dimPins[_D_AMOUNT]; int maxVal = 0; volatile int counter = 0; }; #endif
1,285
978
""" Reference: <NAME> et al., "Deep Matrix Factorization Models for Recommender Systems." In IJCAI2017. @author: wubin """ import tensorflow as tf import numpy as np from time import time from util import learner, tool from model.AbstractRecommender import AbstractRecommender from util import timer class DMF(AbstractRecommender): def __init__(self, sess, dataset, conf): super(DMF, self).__init__(dataset, conf) self.learning_rate = conf["learning_rate"] self.learner = conf["learner"] self.num_epochs = conf["epochs"] self.num_negatives = conf["num_negatives"] self.batch_size = conf["batch_size"] self.verbose = conf["verbose"] layers = conf["layers"] self.loss_function = conf["loss_function"] self.fist_layer_size = layers[0] self.last_layer_size = layers[1] self.init_method = conf["init_method"] self.stddev = conf["stddev"] self.neg_sample_size = self.num_negatives self.num_users = dataset.num_users self.num_items = dataset.num_items self.dataset = dataset self.user_matrix = self.dataset.train_matrix self.item_matrix = self.dataset.train_matrix.tocsc() self.trainMatrix = self.dataset.train_matrix.todok() self.sess = sess def _create_placeholders(self): with tf.name_scope("input_data"): self.one_hot_u = tf.placeholder(tf.float32, shape=[None, None], name='user_input') self.one_hot_v = tf.placeholder(tf.float32, shape=[None, None], name='item_input') self.labels = tf.placeholder(tf.float32, shape=[None, ], name="labels") def _create_variables(self): with tf.name_scope("embedding"): # The embedding initialization is unknown now initializer = tool.get_initializer(self.init_method, self.stddev) self.u_w1 = tf.Variable(initializer([self.num_items, self.fist_layer_size]), name="u_w1") self.u_b1 = tf.Variable(initializer([self.fist_layer_size]), name="u_b1") self.u_w2 = tf.Variable(initializer([self.fist_layer_size, self.last_layer_size]), name="u_w2") self.u_b2 = tf.Variable(initializer([self.last_layer_size]), name="u_b2") self.v_w1 = tf.Variable(initializer([self.num_users, self.fist_layer_size]), name="v_w1") self.v_b1 = tf.Variable(initializer([self.fist_layer_size]), name="v_b1") self.v_w2 = tf.Variable(initializer([self.fist_layer_size, self.last_layer_size]), name="v_w2") self.v_b2 = tf.Variable(initializer([self.last_layer_size]), name="v_b2") def _create_inference(self): with tf.name_scope("inference"): net_u_1 = tf.nn.relu(tf.matmul(self.one_hot_u, self.u_w1) + self.u_b1) net_u_2 = tf.matmul(net_u_1, self.u_w2) + self.u_b2 net_v_1 = tf.nn.relu(tf.matmul(self.one_hot_v, self.v_w1) + self.v_b1) net_v_2 = tf.matmul(net_v_1, self.v_w2) + self.v_b2 fen_zhi = tf.reduce_sum(net_u_2 * net_v_2, 1) norm_u = tf.reduce_sum(tf.square(net_u_2), 1) norm_v = tf.reduce_sum(tf.square(net_v_2), 1) fen_mu = norm_u * norm_v self.output = tf.nn.relu(fen_zhi / fen_mu) def _create_loss(self): with tf.name_scope("loss"): self.loss = learner.pointwise_loss(self.loss_function, self.labels, self.output) def _create_optimizer(self): with tf.name_scope("learner"): self.optimizer = learner.optimizer(self.learner, self.loss, self.learning_rate) def build_graph(self): self._create_placeholders() self._create_variables() self._create_inference() self._create_loss() self._create_optimizer() def train_model(self): for epoch in range(self.num_epochs): # Generate training instances user_input, item_input, labels = self._get_input_all_data() total_loss = 0.0 training_start_time = time() num_training_instances = len(user_input) for num_batch in np.arange(int(num_training_instances/self.batch_size)): num_training_instances = len(user_input) id_start = num_batch * self.batch_size id_end = (num_batch + 1) * self.batch_size if id_end > num_training_instances: id_end = num_training_instances bat_users = user_input[id_start:id_end].tolist() bat_items = item_input[id_start:id_end].tolist() bat_labels = np.array(labels[id_start:id_end]) feed_dict = {self.one_hot_u: bat_users, self.one_hot_v: bat_items, self.labels: bat_labels} loss, _ = self.sess.run((self.loss, self.optimizer), feed_dict=feed_dict) total_loss += loss self.logger.info("[iter %d : loss : %f, time: %f]" % (epoch, total_loss/num_training_instances, time()-training_start_time)) if epoch % self.verbose == 0: self.logger.info("epoch %d:\t%s" % (epoch, self.evaluate())) @timer def evaluate(self): return self.evaluator.evaluate(self) def predict(self, user_ids, candidate_items_user_ids): ratings = [] if candidate_items_user_ids is not None: for user_id, candidate_items_user_id in zip(user_ids, candidate_items_user_ids): user_input, item_input = [], [] u_vector = np.reshape(self.user_matrix.getrow(user_id.toarray(), [self.num_items])) for i in candidate_items_user_id: user_input.append(u_vector) i_vector = np.reshape(self.item_matrix.getcol(i).toarray(), [self.num_users]) item_input.append(i_vector) feed_dict = {self.one_hot_u: user_input, self.one_hot_v: item_input} ratings.append(self.sess.run(self.output, feed_dict=feed_dict)) else: user_input, item_input = [], [] u_vector = np.reshape(self.user_matrix.getrow(user_id.toarray(), [self.num_items])) for i in range(self.num_items): user_input.append(u_vector) i_vector = np.reshape(self.item_matrix.getcol(i).toarray(), [self.num_users]) item_input.append(i_vector) feed_dict = {self.one_hot_u: user_input, self.one_hot_v: item_input} ratings.append(self.sess.run(self.output, feed_dict=feed_dict)) return ratings def _get_input_all_data(self): user_input, item_input, labels = [], [], [] for u in range(self.num_users): # positive instance items_by_user = self.user_matrix[u].indices u_vector = np.reshape(self.user_matrix.getrow(u).toarray(), [self.num_items]) for i in items_by_user: i_vector = np.reshape(self.item_matrix.getcol(i).toarray(), [self.num_users]) user_input.append(u_vector) item_input.append(i_vector) labels.append(1) # negative instance for _ in range(self.num_negatives): j = np.random.randint(self.num_items) while (u, j) in self.trainMatrix.keys(): j = np.random.randint(self.num_items) j_vector = np.reshape(self.item_matrix.getcol(i).toarray(), [self.num_users]) user_input.append(u_vector) item_input.append(j_vector) labels.append(0) user_input = np.array(user_input, dtype=np.int32) item_input = np.array(item_input, dtype=np.int32) labels = np.array(labels, dtype=np.float32) num_training_instances = len(user_input) shuffle_index = np.arange(num_training_instances, dtype=np.int32) np.random.shuffle(shuffle_index) user_input = user_input[shuffle_index] item_input = item_input[shuffle_index] labels = labels[shuffle_index] return user_input, item_input, labels
4,219
320
<reponame>pubnative/hybid-ios-mopub-mediation-demo<gh_stars>100-1000 // // MPVASTMediaFile.h // // Copyright 2018-2021 Twitter, Inc. // Licensed under the MoPub SDK License Agreement // http://www.mopub.com/legal/sdk-license-agreement/ // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import "MPVASTModel.h" @interface MPVASTMediaFile : MPVASTModel @property (nonatomic, copy, readonly) NSString *identifier; @property (nonatomic, copy, readonly) NSString *delivery; @property (nonatomic, copy, readonly) NSString *mimeType; @property (nonatomic, readonly) CGFloat bitrate; @property (nonatomic, readonly) CGFloat width; @property (nonatomic, readonly) CGFloat height; @property (nonatomic, copy, readonly) NSURL *URL; @end @interface MPVASTMediaFile (Selection) /** Pick the best media file that fits into the provided container size and scale factor. */ + (MPVASTMediaFile *)bestMediaFileFromCandidates:(NSArray<MPVASTMediaFile *> *)candidates forContainerSize:(CGSize)containerSize containerScaleFactor:(CGFloat)containerScaleFactor; @end @interface MPVASTMediaFile (MimeType) /** The file extension associated with this VAST MIME type. In the event that the VAST MIME type is invalid, this will be @c nil. */ @property (nonatomic, copy, readonly) NSString *fileExtensionForMimeType; @end
497
436
<filename>src/main/java/com/jdon/jivejdon/infrastructure/repository/dao/MessageDaoFacade.java /* * Copyright 2003-2006 the original author or authors. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.jdon.jivejdon.infrastructure.repository.dao; /** * @author banq(http://www.jdon.com) * */ public class MessageDaoFacade { protected MessageDao messageDao; protected MessageQueryDao messageQueryDao; protected SequenceDao sequenceDao; public MessageDaoFacade(MessageDao messageDao, MessageQueryDao messageQueryDao, SequenceDao sequenceDao){ this.messageDao = messageDao; this.messageQueryDao = messageQueryDao; this.sequenceDao = sequenceDao; } /** * @return Returns the messageDao. */ public MessageDao getMessageDao() { return messageDao; } /** * @param messageDao The messageDao to set. */ public void setMessageDao(MessageDao messageDao) { this.messageDao = messageDao; } /** * @return Returns the messageQueryDao. */ public MessageQueryDao getMessageQueryDao() { return messageQueryDao; } /** * @param messageQueryDao The messageQueryDao to set. */ public void setMessageQueryDao(MessageQueryDao messageQueryDao) { this.messageQueryDao = messageQueryDao; } /** * @return Returns the sequenceDao. */ public SequenceDao getSequenceDao() { return sequenceDao; } /** * @param sequenceDao The sequenceDao to set. */ public void setSequenceDao(SequenceDao sequenceDao) { this.sequenceDao = sequenceDao; } }
832
1,244
<reponame>ngzhian/emscripten<filename>system/lib/libc/musl/src/locale/iswalpha_l.c #include <wctype.h> int iswalpha_l(wint_t c, locale_t l) { return iswalpha(c); }
81
1,851
<reponame>yoelhawa/viro // // VROAudioPlayeriOS.h // ViroRenderer // // Created by <NAME> on 11/6/16. // Copyright © 2016 Viro Media. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #ifndef VROAudioPlayeriOS_h #define VROAudioPlayeriOS_h #include "VROAudioPlayer.h" #include "VROSoundDataDelegate.h" #include "VROSoundData.h" #include <AVFoundation/AVFoundation.h> /* Simple object that wraps a VROSoundDelegateInternal object and acts as a delegate for the AVAudioPlayer */ @interface VROAudioPlayerDelegate : NSObject <AVAudioPlayerDelegate> - (id)initWithSoundDelegate:(std::shared_ptr<VROSoundDelegateInternal>)soundDelegate; - (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag; @end class VROAudioPlayeriOS : public VROAudioPlayer, public VROSoundDataDelegate, public std::enable_shared_from_this<VROAudioPlayeriOS> { public: VROAudioPlayeriOS(std::string url, bool isLocalUrl); VROAudioPlayeriOS(std::shared_ptr<VROData> data); VROAudioPlayeriOS(std::shared_ptr<VROSoundData> data); virtual ~VROAudioPlayeriOS(); /* Must be invoke after construction, after setting the delegate. */ void setup(); void setDelegate(std::shared_ptr<VROSoundDelegateInternal> delegate); void setLoop(bool loop); void play(); void pause(); void setVolume(float volume); void setMuted(bool muted); void seekToTime(float seconds); /* Calls Specific to AVAudioPlayer */ void play(double atTime); void setLoop(bool loop, int numberOfLoops); double getAudioDuration(); double getDeviceCurrentTime(); #pragma mark VROSoundDataDelegate Implementation void dataIsReady(); void dataError(std::string error); private: /* Underlying iOS audio player. The delegate is only kept here so that it's retained. */ AVAudioPlayer *_player; VROAudioPlayerDelegate *_audioDelegate; /* Generic settings. */ float _playVolume; bool _muted; bool _paused; bool _loop; bool _isLocal; int _numberOfLoops; /* Source audio. */ std::string _url; std::shared_ptr<VROSoundData> _data; /* Update the underlying iOS player with the various properties set on this player (e.g. muted, loop, volume, etc.) */ void updatePlayerProperties(); }; #endif /* VROAudioPlayeriOS_h */
1,189
4,391
# This sample tests the type checker's "type var scoring" mechanism # whereby it attempts to solve type variables with the simplest # possible solution. from typing import Union, List, TypeVar, Type T = TypeVar("T") def to_list1(obj_type: Type[T], obj: Union[List[T], T]) -> List[T]: return [] def to_list2(obj_type: Type[T], obj: Union[T, List[T]]) -> List[T]: return [] input_list: List[str] = ["string"] # The expression on the RHS can satisfy the type variable T # with either the type str or Union[List[str], str]. It should # pick the simpler of the two. output_list1 = to_list1(str, input_list) verify_type1: List[str] = output_list1 # The resulting type should not depend on the order of the union # elements. output_list2 = to_list2(str, input_list) verify_type2: List[str] = output_list2
271
734
<filename>modules/tracktion_engine/utilities/tracktion_CpuMeasurement.h /* ,--. ,--. ,--. ,--. ,-' '-.,--.--.,--,--.,---.| |,-.,-' '-.`--' ,---. ,--,--, Copyright 2018 '-. .-'| .--' ,-. | .--'| /'-. .-',--.| .-. || \ Tracktion Software | | | | \ '-' \ `--.| \ \ | | | |' '-' '| || | Corporation `---' `--' `--`--'`---'`--'`--' `---' `--' `---' `--''--' www.tracktion.com Tracktion Engine uses a GPL/commercial licence - see LICENCE.md for details. */ namespace tracktion_engine { struct ScopedCpuMeter { ScopedCpuMeter (std::atomic<double>& valueToUpdate_, double filterAmount_) noexcept : valueToUpdate (valueToUpdate_), filterAmount (filterAmount_) { } ~ScopedCpuMeter() noexcept { const double msTaken = juce::Time::getMillisecondCounterHiRes() - callbackStartTime; valueToUpdate.store (filterAmount * (msTaken - valueToUpdate)); } private: std::atomic<double>& valueToUpdate; const double filterAmount, callbackStartTime { juce::Time::getMillisecondCounterHiRes() }; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ScopedCpuMeter) }; //============================================================================== struct StopwatchTimer { StopwatchTimer() noexcept : time (juce::Time::getCurrentTime()) {} juce::RelativeTime getTime() const noexcept { return juce::Time::getCurrentTime() - time; } juce::String getDescription() const { return getTime().getDescription(); } double getSeconds() const noexcept { return getTime().inSeconds(); } private: const juce::Time time; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StopwatchTimer) }; //============================================================================== #if TRACKTION_CHECK_FOR_SLOW_RENDERING struct RealtimeCheck { RealtimeCheck (const char* f, int l, double maxMillisecs) noexcept : start (juce::Time::getMillisecondCounterHiRes()), end (start + maxMillisecs), file (f), line (l) { } ~RealtimeCheck() noexcept { const double now = juce::Time::getMillisecondCounterHiRes(); if (now > end) juce::Logger::outputDebugString (juce::String (now - start) + " " + file + ":" + juce::String (line)); } double start, end; const char* file; int line; }; #define SCOPED_REALTIME_CHECK const RealtimeCheck JUCE_JOIN_MACRO(__realtimeCheck, __LINE__) (__FILE__, __LINE__, 1.5); #define SCOPED_REALTIME_CHECK_LONGER const RealtimeCheck JUCE_JOIN_MACRO(__realtimeCheck, __LINE__) (__FILE__, __LINE__, 200 / 44.1); #else #define SCOPED_REALTIME_CHECK #define SCOPED_REALTIME_CHECK_LONGER #endif } // namespace tracktion_engine
1,138
2,494
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * vim: set ts=8 sts=4 et sw=4 tw=99: */ /* 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/. */ #include "jit/IonAnalysis.h" #include "jit/MIRGenerator.h" #include "jit/MIRGraph.h" #include "jit/ValueNumbering.h" #include "jsapi-tests/testJitMinimalFunc.h" #include "jsapi-tests/tests.h" using namespace js; using namespace js::jit; BEGIN_TEST(testJitDCEinGVN_ins) { MinimalFunc func; MBasicBlock *block = func.createEntryBlock(); // mul0 = p * p // mul1 = mul0 * mul0 // return p MParameter *p = func.createParameter(); block->add(p); MMul *mul0 = MMul::New(func.alloc, p, p, MIRType_Double); block->add(mul0); MMul *mul1 = MMul::New(func.alloc, mul0, mul0, MIRType_Double); block->add(mul1); MReturn *ret = MReturn::New(func.alloc, p); block->end(ret); if (!func.runGVN()) return false; // mul0 and mul1 should be deleted. for (MInstructionIterator ins = block->begin(); ins != block->end(); ins++) { CHECK(!ins->isMul() || (ins->getOperand(0) != p && ins->getOperand(1) != p)); CHECK(!ins->isMul() || (ins->getOperand(0) != mul0 && ins->getOperand(1) != mul0)); } return true; } END_TEST(testJitDCEinGVN_ins) BEGIN_TEST(testJitDCEinGVN_phi) { MinimalFunc func; MBasicBlock *block = func.createEntryBlock(); MBasicBlock *thenBlock1 = func.createBlock(block); MBasicBlock *thenBlock2 = func.createBlock(block); MBasicBlock *elifBlock = func.createBlock(block); MBasicBlock *elseBlock = func.createBlock(block); MBasicBlock *joinBlock = func.createBlock(block); // if (p) { // x = 1.0; // y = 3.0; // } else if (q) { // x = 2.0; // y = 4.0; // } else { // x = 1.0; // y = 5.0; // } // x = phi(1.0, 2.0, 1.0); // y = phi(3.0, 4.0, 5.0); // z = x * y; // return y; MConstant *c1 = MConstant::New(func.alloc, DoubleValue(1.0)); block->add(c1); MPhi *x = MPhi::New(func.alloc); MPhi *y = MPhi::New(func.alloc); // if (p) { MParameter *p = func.createParameter(); block->add(p); block->end(MTest::New(func.alloc, p, thenBlock1, elifBlock)); // x = 1.0 // y = 3.0; x->addInputSlow(c1); MConstant *c3 = MConstant::New(func.alloc, DoubleValue(3.0)); thenBlock1->add(c3); y->addInputSlow(c3); thenBlock1->end(MGoto::New(func.alloc, joinBlock)); joinBlock->addPredecessor(func.alloc, thenBlock1); // } else if (q) { MParameter *q = func.createParameter(); elifBlock->add(q); elifBlock->end(MTest::New(func.alloc, q, thenBlock2, elseBlock)); // x = 2.0 // y = 4.0; MConstant *c2 = MConstant::New(func.alloc, DoubleValue(2.0)); thenBlock2->add(c2); x->addInputSlow(c2); MConstant *c4 = MConstant::New(func.alloc, DoubleValue(4.0)); thenBlock2->add(c4); y->addInputSlow(c4); thenBlock2->end(MGoto::New(func.alloc, joinBlock)); joinBlock->addPredecessor(func.alloc, thenBlock2); // } else { // x = 1.0 // y = 5.0; // } x->addInputSlow(c1); MConstant *c5 = MConstant::New(func.alloc, DoubleValue(5.0)); elseBlock->add(c5); y->addInputSlow(c5); elseBlock->end(MGoto::New(func.alloc, joinBlock)); joinBlock->addPredecessor(func.alloc, elseBlock); // x = phi(1.0, 2.0, 1.0) // y = phi(3.0, 4.0, 5.0) // z = x * y // return y joinBlock->addPhi(x); joinBlock->addPhi(y); MMul *z = MMul::New(func.alloc, x, y, MIRType_Double); joinBlock->add(z); MReturn *ret = MReturn::New(func.alloc, y); joinBlock->end(ret); if (!func.runGVN()) return false; // c1 should be deleted. for (MInstructionIterator ins = block->begin(); ins != block->end(); ins++) { CHECK(!ins->isConstant() || (ins->toConstant()->value().toNumber() != 1.0)); } return true; } END_TEST(testJitDCEinGVN_phi)
1,880
820
<reponame>microsoft/msticpy # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- """Azure Cloud Mappings.""" from msrestazure import azure_cloud from .._version import VERSION from .exceptions import MsticpyAzureConfigError __version__ = VERSION __author__ = "<NAME>" _CLOUD_MAPPING = { "global": azure_cloud.AZURE_PUBLIC_CLOUD, "usgov": azure_cloud.AZURE_US_GOV_CLOUD, "de": azure_cloud.AZURE_GERMAN_CLOUD, "cn": azure_cloud.AZURE_CHINA_CLOUD, } _CLOUD_ALIASES = {"public": "global", "gov": "usgov", "germany": "de", "china": "cn"} def create_cloud_suf_dict(suffix: str) -> dict: """ Get all the suffixes for a specific service in a cloud. Parameters ---------- suffix : str The name of the suffix to get details for. Returns ------- dict A dictionary of cloud names and suffixes. """ return { cloud: getattr(msr_cloud.suffixes, suffix) for cloud, msr_cloud in _CLOUD_MAPPING.items() } def create_cloud_ep_dict(endpoint: str) -> dict: """ Return lookup dict for cloud endpoints. Parameters ---------- endpoint : str The name of the endpoint to retreive for each cloud. Returns ------- dict A dictionary of cloud names and endpoints. """ return { cloud: getattr(msr_cloud.endpoints, endpoint) for cloud, msr_cloud in _CLOUD_MAPPING.items() } def get_all_endpoints(cloud: str) -> azure_cloud.CloudEndpoints: """ Get a list of all the endpoints for an Azure cloud. Parameters ---------- cloud : str The name of the Azure cloud to get endpoints for. Returns ------- dict A dictionary of endpoints for the cloud. Raises ------ MsticpyAzureConfigError If the cloud name is not valid. """ cloud = _CLOUD_ALIASES.get(cloud, cloud) try: endpoints = _CLOUD_MAPPING[cloud].endpoints except KeyError as cloud_err: raise MsticpyAzureConfigError( f"""{cloud} is not a valid Azure cloud name. Valid names are 'global', 'usgov', 'de', 'cn'""" ) from cloud_err return endpoints def get_all_suffixes(cloud: str) -> azure_cloud.CloudSuffixes: """ Get a list of all the suffixes for an Azure cloud. Parameters ---------- cloud : str The name of the Azure cloud to get suffixes for. Returns ------- dict A dictionary of suffixes for the cloud. Raises ------ MsticpyAzureConfigError If the cloud name is not valid. """ cloud = _CLOUD_ALIASES.get(cloud, cloud) try: endpoints = _CLOUD_MAPPING[cloud].suffixes except KeyError as cloud_err: raise MsticpyAzureConfigError( f"""{cloud} is not a valid Azure cloud name. Valid names are 'global', 'usgov', 'de', 'cn'""" ) from cloud_err return endpoints
1,227
2,236
<reponame>jungyoonoh/baekjoon-1 # Authored by : yj2221 # Co-authored by : - # Link : http://boj.kr/18c501c01b3d4d91aa311c9c4d952e67 import sys def input(): return sys.stdin.readline().rstrip() n, k = map(int, input().split()) rocks = list(map(int, input().split())) dp = [99999999] * n dp[0] = 0 for i in range(n-1): if dp[i]>k: continue for j in range(i+1, n): need = (j-i) * (1 + abs(rocks[i]-rocks[j])) dp[j] = min(dp[j], need) if dp[n-1]>k: print('NO') else: print('YES')
278
424
<reponame>tsegismont/vertx-sql-client /* * Copyright (C) 2017 <NAME> * * 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 io.vertx.pgclient.pubsub; import io.vertx.codegen.annotations.Fluent; import io.vertx.codegen.annotations.VertxGen; import io.vertx.core.Handler; import io.vertx.core.streams.ReadStream; /** * A channel to Postgres that tracks the subscription to a given Postgres channel using the {@code LISTEN/UNLISTEN} commands. * <p/> * When paused the channel discards the messages. */ @VertxGen public interface PgChannel extends ReadStream<String> { /** * Set an handler called when the the channel get subscribed. * * @param handler the handler * @return a reference to this, so the API can be used fluently */ @Fluent PgChannel subscribeHandler(Handler<Void> handler); /** * Set or unset an handler to be called when a the channel is notified by Postgres. * <p/> * <ul> * <li>when the handler is set, the subscriber sends a {@code LISTEN} command if needed</li> * <li>when the handler is unset, the subscriber sends a {@code UNLISTEN} command if needed</li> * </ul> * * @param handler the handler * @return a reference to this, so the API can be used fluently */ @Override PgChannel handler(Handler<String> handler); /** * Pause the channel, all notifications are discarded. * * @return a reference to this, so the API can be used fluently */ @Override PgChannel pause(); /** * Resume the channel. * * @return a reference to this, so the API can be used fluently */ @Override PgChannel resume(); /** * Set an handler to be called when no more notifications will be received. * * @param endHandler the handler * @return a reference to this, so the API can be used fluently */ @Override PgChannel endHandler(Handler<Void> endHandler); @Override PgChannel exceptionHandler(Handler<Throwable> handler); }
758
348
{"nom":"Taizé-Aizie","circ":"3ème circonscription","dpt":"Charente","inscrits":447,"abs":229,"votants":218,"blancs":10,"nuls":6,"exp":202,"res":[{"nuance":"SOC","nom":"M. <NAME>","voix":110},{"nuance":"REM","nom":"<NAME>","voix":92}]}
96
387
/* * Stack-less Just-In-Time compiler * * Copyright 2009-2012 <NAME> (<EMAIL>). 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 HOLDER(S) AND CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE COPYRIGHT HOLDER(S) 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. */ /* ppc 32-bit arch dependent functions. */ static int load_immediate(struct sljit_compiler *compiler, int reg, sljit_w imm) { if (imm <= SIMM_MAX && imm >= SIMM_MIN) return push_inst(compiler, ADDI | D(reg) | A(0) | IMM(imm)); if (!(imm & ~0xffff)) return push_inst(compiler, ORI | S(ZERO_REG) | A(reg) | IMM(imm)); FAIL_IF(push_inst(compiler, ADDIS | D(reg) | A(0) | IMM(imm >> 16))); return (imm & 0xffff) ? push_inst(compiler, ORI | S(reg) | A(reg) | IMM(imm)) : SLJIT_SUCCESS; } #define INS_CLEAR_LEFT(dst, src, from) \ (RLWINM | S(src) | A(dst) | ((from) << 6) | (31 << 1)) static SLJIT_INLINE int emit_single_op(struct sljit_compiler *compiler, int op, int flags, int dst, int src1, int src2) { switch (op) { case SLJIT_ADD: if (flags & ALT_FORM1) { /* Flags does not set: BIN_IMM_EXTS unnecessary. */ SLJIT_ASSERT(src2 == TMP_REG2); return push_inst(compiler, ADDI | D(dst) | A(src1) | compiler->imm); } if (flags & ALT_FORM2) { /* Flags does not set: BIN_IMM_EXTS unnecessary. */ SLJIT_ASSERT(src2 == TMP_REG2); return push_inst(compiler, ADDIS | D(dst) | A(src1) | compiler->imm); } if (flags & ALT_FORM3) { SLJIT_ASSERT(src2 == TMP_REG2); return push_inst(compiler, ADDIC | D(dst) | A(src1) | compiler->imm); } if (flags & ALT_FORM4) { /* Flags does not set: BIN_IMM_EXTS unnecessary. */ FAIL_IF(push_inst(compiler, ADDI | D(dst) | A(src1) | (compiler->imm & 0xffff))); return push_inst(compiler, ADDIS | D(dst) | A(dst) | (((compiler->imm >> 16) & 0xffff) + ((compiler->imm >> 15) & 0x1))); } if (!(flags & ALT_SET_FLAGS)) return push_inst(compiler, ADD | D(dst) | A(src1) | B(src2)); return push_inst(compiler, ADDC | OERC(ALT_SET_FLAGS) | D(dst) | A(src1) | B(src2)); case SLJIT_ADDC: if (flags & ALT_FORM1) { FAIL_IF(push_inst(compiler, MFXER | S(0))); FAIL_IF(push_inst(compiler, ADDE | D(dst) | A(src1) | B(src2))); return push_inst(compiler, MTXER | S(0)); } return push_inst(compiler, ADDE | D(dst) | A(src1) | B(src2)); case SLJIT_SUB: if (flags & ALT_FORM1) { /* Flags does not set: BIN_IMM_EXTS unnecessary. */ SLJIT_ASSERT(src2 == TMP_REG2); return push_inst(compiler, SUBFIC | D(dst) | A(src1) | compiler->imm); } if (flags & (ALT_FORM2 | ALT_FORM3)) { SLJIT_ASSERT(src2 == TMP_REG2); if (flags & ALT_FORM2) FAIL_IF(push_inst(compiler, CMPI | CRD(0) | A(src1) | compiler->imm)); if (flags & ALT_FORM3) return push_inst(compiler, CMPLI | CRD(4) | A(src1) | compiler->imm); return SLJIT_SUCCESS; } if (flags & (ALT_FORM4 | ALT_FORM5)) { if (flags & ALT_FORM4) FAIL_IF(push_inst(compiler, CMPL | CRD(4) | A(src1) | B(src2))); if (flags & ALT_FORM5) FAIL_IF(push_inst(compiler, CMP | CRD(0) | A(src1) | B(src2))); return SLJIT_SUCCESS; } if (!(flags & ALT_SET_FLAGS)) return push_inst(compiler, SUBF | D(dst) | A(src2) | B(src1)); if (flags & ALT_FORM6) FAIL_IF(push_inst(compiler, CMPL | CRD(4) | A(src1) | B(src2))); return push_inst(compiler, SUBFC | OERC(ALT_SET_FLAGS) | D(dst) | A(src2) | B(src1)); case SLJIT_SUBC: if (flags & ALT_FORM1) { FAIL_IF(push_inst(compiler, MFXER | S(0))); FAIL_IF(push_inst(compiler, SUBFE | D(dst) | A(src2) | B(src1))); return push_inst(compiler, MTXER | S(0)); } return push_inst(compiler, SUBFE | D(dst) | A(src2) | B(src1)); case SLJIT_MUL: if (flags & ALT_FORM1) { SLJIT_ASSERT(src2 == TMP_REG2); return push_inst(compiler, MULLI | D(dst) | A(src1) | compiler->imm); } return push_inst(compiler, MULLW | OERC(flags) | D(dst) | A(src2) | B(src1)); case SLJIT_AND: if (flags & ALT_FORM1) { SLJIT_ASSERT(src2 == TMP_REG2); return push_inst(compiler, ANDI | S(src1) | A(dst) | compiler->imm); } if (flags & ALT_FORM2) { SLJIT_ASSERT(src2 == TMP_REG2); return push_inst(compiler, ANDIS | S(src1) | A(dst) | compiler->imm); } return push_inst(compiler, AND | RC(flags) | S(src1) | A(dst) | B(src2)); case SLJIT_OR: if (flags & ALT_FORM1) { SLJIT_ASSERT(src2 == TMP_REG2); return push_inst(compiler, ORI | S(src1) | A(dst) | compiler->imm); } if (flags & ALT_FORM2) { SLJIT_ASSERT(src2 == TMP_REG2); return push_inst(compiler, ORIS | S(src1) | A(dst) | compiler->imm); } if (flags & ALT_FORM3) { SLJIT_ASSERT(src2 == TMP_REG2); FAIL_IF(push_inst(compiler, ORI | S(src1) | A(dst) | IMM(compiler->imm))); return push_inst(compiler, ORIS | S(dst) | A(dst) | IMM(compiler->imm >> 16)); } return push_inst(compiler, OR | RC(flags) | S(src1) | A(dst) | B(src2)); case SLJIT_XOR: if (flags & ALT_FORM1) { SLJIT_ASSERT(src2 == TMP_REG2); return push_inst(compiler, XORI | S(src1) | A(dst) | compiler->imm); } if (flags & ALT_FORM2) { SLJIT_ASSERT(src2 == TMP_REG2); return push_inst(compiler, XORIS | S(src1) | A(dst) | compiler->imm); } if (flags & ALT_FORM3) { SLJIT_ASSERT(src2 == TMP_REG2); FAIL_IF(push_inst(compiler, XORI | S(src1) | A(dst) | IMM(compiler->imm))); return push_inst(compiler, XORIS | S(dst) | A(dst) | IMM(compiler->imm >> 16)); } return push_inst(compiler, XOR | RC(flags) | S(src1) | A(dst) | B(src2)); case SLJIT_SHL: if (flags & ALT_FORM1) { SLJIT_ASSERT(src2 == TMP_REG2); compiler->imm &= 0x1f; return push_inst(compiler, RLWINM | RC(flags) | S(src1) | A(dst) | (compiler->imm << 11) | ((31 - compiler->imm) << 1)); } return push_inst(compiler, SLW | RC(flags) | S(src1) | A(dst) | B(src2)); case SLJIT_LSHR: if (flags & ALT_FORM1) { SLJIT_ASSERT(src2 == TMP_REG2); compiler->imm &= 0x1f; return push_inst(compiler, RLWINM | RC(flags) | S(src1) | A(dst) | (((32 - compiler->imm) & 0x1f) << 11) | (compiler->imm << 6) | (31 << 1)); } return push_inst(compiler, SRW | RC(flags) | S(src1) | A(dst) | B(src2)); case SLJIT_ASHR: if (flags & ALT_FORM1) { SLJIT_ASSERT(src2 == TMP_REG2); compiler->imm &= 0x1f; return push_inst(compiler, SRAWI | RC(flags) | S(src1) | A(dst) | (compiler->imm << 11)); } return push_inst(compiler, SRAW | RC(flags) | S(src1) | A(dst) | B(src2)); case SLJIT_MOV: case SLJIT_MOV_UI: case SLJIT_MOV_SI: SLJIT_ASSERT(src1 == TMP_REG1); if (dst != src2) return push_inst(compiler, OR | S(src2) | A(dst) | B(src2)); return SLJIT_SUCCESS; case SLJIT_MOV_UB: case SLJIT_MOV_SB: SLJIT_ASSERT(src1 == TMP_REG1); if ((flags & (REG_DEST | REG2_SOURCE)) == (REG_DEST | REG2_SOURCE)) { if (op == SLJIT_MOV_SB) return push_inst(compiler, EXTSB | S(src2) | A(dst)); return push_inst(compiler, INS_CLEAR_LEFT(dst, src2, 24)); } else if ((flags & REG_DEST) && op == SLJIT_MOV_SB) return push_inst(compiler, EXTSB | S(src2) | A(dst)); else if (dst != src2) SLJIT_ASSERT_STOP(); return SLJIT_SUCCESS; case SLJIT_MOV_UH: case SLJIT_MOV_SH: SLJIT_ASSERT(src1 == TMP_REG1); if ((flags & (REG_DEST | REG2_SOURCE)) == (REG_DEST | REG2_SOURCE)) { if (op == SLJIT_MOV_SH) return push_inst(compiler, EXTSH | S(src2) | A(dst)); return push_inst(compiler, INS_CLEAR_LEFT(dst, src2, 16)); } else if (dst != src2) SLJIT_ASSERT_STOP(); return SLJIT_SUCCESS; case SLJIT_NOT: SLJIT_ASSERT(src1 == TMP_REG1); return push_inst(compiler, NOR | RC(flags) | S(src2) | A(dst) | B(src2)); case SLJIT_NEG: SLJIT_ASSERT(src1 == TMP_REG1); return push_inst(compiler, NEG | OERC(flags) | D(dst) | A(src2)); case SLJIT_CLZ: SLJIT_ASSERT(src1 == TMP_REG1); return push_inst(compiler, CNTLZW | RC(flags) | S(src2) | A(dst)); } SLJIT_ASSERT_STOP(); return SLJIT_SUCCESS; } static SLJIT_INLINE int emit_const(struct sljit_compiler *compiler, int reg, sljit_w init_value) { FAIL_IF(push_inst(compiler, ADDIS | D(reg) | A(0) | IMM(init_value >> 16))); return push_inst(compiler, ORI | S(reg) | A(reg) | IMM(init_value)); } SLJIT_API_FUNC_ATTRIBUTE void sljit_set_jump_addr(sljit_uw addr, sljit_uw new_addr) { sljit_ins *inst = (sljit_ins*)addr; inst[0] = (inst[0] & 0xffff0000) | ((new_addr >> 16) & 0xffff); inst[1] = (inst[1] & 0xffff0000) | (new_addr & 0xffff); SLJIT_CACHE_FLUSH(inst, inst + 2); } SLJIT_API_FUNC_ATTRIBUTE void sljit_set_const(sljit_uw addr, sljit_w new_constant) { sljit_ins *inst = (sljit_ins*)addr; inst[0] = (inst[0] & 0xffff0000) | ((new_constant >> 16) & 0xffff); inst[1] = (inst[1] & 0xffff0000) | (new_constant & 0xffff); SLJIT_CACHE_FLUSH(inst, inst + 2); }
4,537
1,306
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef ART_RUNTIME_GC_ACCOUNTING_MOD_UNION_TABLE_INL_H_ #define ART_RUNTIME_GC_ACCOUNTING_MOD_UNION_TABLE_INL_H_ #include "mod_union_table.h" #include "gc/space/space.h" namespace art { namespace gc { namespace accounting { // A mod-union table to record image references to the Zygote and alloc space. class ModUnionTableToZygoteAllocspace : public ModUnionTableReferenceCache { public: explicit ModUnionTableToZygoteAllocspace(Heap* heap) : ModUnionTableReferenceCache(heap) {} bool AddReference(const mirror::Object* /* obj */, const mirror::Object* ref) { const std::vector<space::ContinuousSpace*>& spaces = GetHeap()->GetContinuousSpaces(); typedef std::vector<space::ContinuousSpace*>::const_iterator It; for (It it = spaces.begin(); it != spaces.end(); ++it) { if ((*it)->Contains(ref)) { return (*it)->IsDlMallocSpace(); } } // Assume it points to a large object. // TODO: Check. return true; } }; // A mod-union table to record Zygote references to the alloc space. class ModUnionTableToAllocspace : public ModUnionTableReferenceCache { public: explicit ModUnionTableToAllocspace(Heap* heap) : ModUnionTableReferenceCache(heap) {} bool AddReference(const mirror::Object* /* obj */, const mirror::Object* ref) { const std::vector<space::ContinuousSpace*>& spaces = GetHeap()->GetContinuousSpaces(); typedef std::vector<space::ContinuousSpace*>::const_iterator It; for (It it = spaces.begin(); it != spaces.end(); ++it) { space::ContinuousSpace* space = *it; if (space->Contains(ref)) { // The allocation space is always considered for collection whereas the Zygote space is // return space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect; } } // Assume it points to a large object. // TODO: Check. return true; } }; } // namespace accounting } // namespace gc } // namespace art #endif // ART_RUNTIME_GC_ACCOUNTING_MOD_UNION_TABLE_INL_H_
877
354
<gh_stars>100-1000 #include <iostream> using namespace std; int main() { int swapNibbles(int n); int n, result; cout << "Enter a number: "; cin >> n; result = swapNibbles(n); cout << result; return 0; } int swapNibbles(int n) { return (((n & 0x0F) << 4) | ((n & 0xF0) >> 4)); }
145
349
<filename>src/base/devices/posix/epiphany/loader.h #pragma once struct team; struct prog; extern int epiphany_load(struct team *team, int start, int count, struct prog *prog, const char *function, int argn, const p_arg_t *args); extern void epiphany_start(struct team *team, int start, int count); extern int epiphany_soft_reset(struct team *team, int start, int count); int epiphany_reset_system(struct epiphany_dev *epiphany); extern bool epiphany_is_core_done (struct team *team, int rank);
209
643
# # Copyright (c) 2020 JinTian. # # This file is part of alfred # (see http://jinfagang.github.io). # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # import os import sys import numpy as np from alfred.vis.image.common import get_unique_color_by_id from alfred.fusion.kitti_fusion import LidarCamCalibData, \ load_pc_from_file, cam3d_to_pixel, lidar_pt_to_cam0_frame from alfred.fusion.common import draw_3d_box, compute_3d_box_cam_coords, center_to_corner_3d import cv2 img_f = os.path.join(os.path.dirname(os.path.abspath(__file__)), './data/000011.png') v_f = os.path.join(os.path.dirname(os.path.abspath(__file__)), './data/000011.bin') calib_f = os.path.join(os.path.dirname(os.path.abspath(__file__)), './data/000011.txt') frame_calib = LidarCamCalibData(calib_f=calib_f) res = [[5.06, 1.43, 12.42, 1.90, 0.42, 1.04, 0.68], [-5.12, 1.85, 4.13, 1.50, 1.46, 3.70, 1.56], [-4.95, 1.83, 26.64, 1.86, 1.57, 3.83, 1.55]] img = cv2.imread(img_f) for p in res: xyz = np.array([p[: 3]]) c2d = cam3d_to_pixel(xyz, frame_calib) if c2d is not None: cv2.circle(img, (int(c2d[0]), int(c2d[1])), 8, (0, 0, 255), -1) # hwl -> lwh lwh = np.array([p[3: 6]])[:, [2, 1, 0]] r_y = p[6] pts3d = compute_3d_box_cam_coords(xyz[0], lwh[0], r_y) pts2d = [] for pt in pts3d: coords = cam3d_to_pixel(pt, frame_calib) if coords is not None: pts2d.append(coords[:2]) pts2d = np.array(pts2d) draw_3d_box(pts2d, img) cv2.imshow('rr', img) cv2.imwrite('result.png', img) cv2.waitKey(0)
974
5,941
<reponame>zouhirzz/FreeRDP /** * FreeRDP: A Remote Desktop Protocol Implementation * Multimedia Redirection Virtual Channel Types * * Copyright 2011 <NAME> * * 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. */ /* DEPRECATION WARNING: * * This channel is unmaintained and not used since windows 7. * Only compile and use it if absolutely necessary, otherwise * deactivate it or use the newer [MS-RDPEVOR] video redirection. */ #ifndef FREERDP_CHANNEL_TSMF_CLIENT_TSMF_H #define FREERDP_CHANNEL_TSMF_CLIENT_TSMF_H #include <freerdp/codec/region.h> #include <freerdp/channels/tsmf.h> /* RDP_VIDEO_FRAME_EVENT.frame_pixfmt */ /* http://www.fourcc.org/yuv.php */ #define RDP_PIXFMT_I420 0x30323449 #define RDP_PIXFMT_YV12 0x32315659 struct _TSMF_VIDEO_FRAME_EVENT { BYTE* frameData; UINT32 frameSize; UINT32 framePixFmt; INT16 frameWidth; INT16 frameHeight; INT16 x; INT16 y; INT16 width; INT16 height; UINT16 numVisibleRects; RECTANGLE_16* visibleRects; }; typedef struct _TSMF_VIDEO_FRAME_EVENT TSMF_VIDEO_FRAME_EVENT; /** * Client Interface */ typedef struct _tsmf_client_context TsmfClientContext; typedef int (*pcTsmfFrameEvent)(TsmfClientContext* context, TSMF_VIDEO_FRAME_EVENT* event); struct _tsmf_client_context { void* handle; void* custom; pcTsmfFrameEvent FrameEvent; }; #endif /* FREERDP_CHANNEL_TSMF_CLIENT_TSMF_H */
665
1,831
/** * Copyright (c) 2020-present, Facebook, Inc. and its affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <string> #include <folly/io/Cursor.h> #include <folly/io/IOBuf.h> #include "logdevice/common/PayloadGroupCodec.h" #include "logdevice/include/types.h" namespace facebook { namespace logdevice { /** Codec for batches of single payloads */ class BufferedWriteSinglePayloadsCodec { public: class Encoder { public: /** * Creates encoder with specified capacity for the encoding buffer * (uncompressed). In addition to capacity, a headroom can be reserved. * encode ensures that returned IOBuf has this headroom available. */ Encoder(size_t capacity, size_t headroom); /** Appends single payload to the batch. */ void append(const folly::IOBuf& payload); /* * Encodes and compressess payloads. If compressing payloads with requested * compresssion doesn't improve required space, then it can be left * uncompressed. compression parameter is updated accordingly. */ void encode(folly::IOBufQueue& out, Compression& compression, int zstd_level = 0); private: /** * Replaces blob with compressed blob if compression saves some space and * returns true. Otherwise leaves blob as is and returns false. */ bool compress(Compression compression, int zstd_level); // Payloads are appended to the blob_ using appender_ */ folly::IOBuf blob_; folly::io::Appender appender_; }; /** Estimator for uncompressed batch size. */ class Estimator { public: /** Appends payload to the batch */ void append(const folly::IOBuf& payload); /** Returns size of current batch in encoded form */ size_t calculateSize() const; private: // Number of bytes required to encode payloads. size_t encoded_payloads_size_ = 0; }; /** * Uncompress and decode payloads stored in batch. * Resulting payloads can optionally share data with input (for example in * case it's uncompressed). * Returns number of bytes consumed, or 0 if decoding fails. */ static size_t decode(const Slice& binary, Compression compression, std::vector<folly::IOBuf>& payloads_out, bool allow_buffer_sharing); }; /** * Codec for encoding/decoding buffered writes. */ class BufferedWriteCodec { public: // Enum values are persisted in storage to identify encoding. enum class Format : uint8_t { SINGLE_PAYLOADS = 0xb1, PAYLOAD_GROUPS = 0xb2 }; /** Supports encoding of the payloads. */ template <typename PayloadsEncoder> class Encoder { public: /** * Creates encoder. Encoder requires number of appends and capacity for * the buffer to be specified beforehand. Capacity must be calculated using * Estimator on the same sequence of appends. */ Encoder(int checksum_bits, size_t appends_count, size_t capacity); /** Appends single payload to the batch. */ void append(folly::IOBuf&& payload); /** Appends payload group to the batch. */ void append(const PayloadGroup& payload_group); /** * Encodes added appends into output specified in constructor. * Output queue will be appended with a single contigous IOBuf containing * encoded payloads. * Encoder must not be re-used after calling this. * zstd_level must be specified if ZSTD compression is used. */ void encode(folly::IOBufQueue& out, Compression compression, int zstd_level = 0); private: /** Writes header (checksum, flags, etc) to the blob's headroom */ void encodeHeader(folly::IOBuf& blob, Compression compression); int checksum_bits_; size_t appends_count_; size_t header_size_; PayloadsEncoder payloads_encoder_; }; /** * Supports estimation of encoded buffered writes batch size. */ class Estimator { public: /** Appends single payload to the batch. */ void append(const folly::IOBuf& payload); /** * Appends payload group to the batch. This can change required format for * the encoding. */ void append(const PayloadGroup& payload_group); /** * Returns resulting encoded uncompressed blob size, including space for * the header. Result of this call can be used to specify capacity for the * Encoder. Passing same sequence of appends to encoder is guaranteed to fit * into a buffer of size calculated by this function. */ size_t calculateSize(int checksum_bits) const; /** * Returns format required for the batch encoding. Format is updated * dynamically based on perormed appends. */ Format getFormat() const { return format_; } private: Format format_ = Format::SINGLE_PAYLOADS; // Appends count is required to calculate header size correctly size_t appends_count_ = 0; BufferedWriteSinglePayloadsCodec::Estimator single_payloads_estimator_; PayloadGroupCodec::Estimator payload_groups_estimator_; }; /** Decodes number of records stored in batch */ FOLLY_NODISCARD static bool decodeBatchSize(Slice binary, size_t* size_out); /** Decodes batch compression in use */ FOLLY_NODISCARD static bool decodeCompression(Slice binary, Compression* compression_out); /** Decodes format in use. Fails is format is unknown. */ FOLLY_NODISCARD static bool decodeFormat(Slice binary, Format* format_out); /** * Decodes payloads stored in batch. * Resulting payloads can optionally share data with input (for example in * case it's uncompressed). * Returns number of bytes consumed, or 0 if decoding fails. */ FOLLY_NODISCARD static size_t decode(Slice binary, std::vector<folly::IOBuf>& payloads_out, bool allow_buffer_sharing); /** * Decodes payloads stored in batch. * Resulting payloads can optionally share data with input (for example in * case it's uncompressed). * Returns number of bytes consumed, or 0 if decoding fails. */ FOLLY_NODISCARD static size_t decode(Slice binary, std::vector<PayloadGroup>& payload_groups_out, bool allow_buffer_sharing); /** * Decodes payload groups without uncompressing them. This requires payloads * to be in PAYLOAD_GROUPS format, otherwise decoding fails. * Returns number of bytes consumed, or 0 if decoding fails. */ FOLLY_NODISCARD static size_t decode(const folly::IOBuf& iobuf, CompressedPayloadGroups& compressed_payload_groups_out, bool allow_buffer_sharing); }; }} // namespace facebook::logdevice
2,367
1,338
<gh_stars>1000+ /* * Copyright 2007-2009 <NAME> <<EMAIL>>. * All rights reserved. Distributed under the terms of the MIT License. */ #include "ImportPLItemsCommand.h" #include <new> #include <stdio.h> #include <Autolock.h> #include <Catalog.h> #include <Locale.h> #include "Playlist.h" #include "PlaylistItem.h" #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "MediaPlayer-ImportPLItemsCmd" using std::nothrow; ImportPLItemsCommand::ImportPLItemsCommand(Playlist* playlist, const BMessage* refsMessage, int32 toIndex, bool sortItems) : PLItemsCommand(), fPlaylist(playlist), fOldItems(NULL), fOldCount(0), fNewItems(NULL), fNewCount(0), fToIndex(toIndex), fPlaylingIndex(0), fItemsAdded(false) { if (!fPlaylist) return; Playlist temp; temp.AppendItems(refsMessage, APPEND_INDEX_REPLACE_PLAYLIST, sortItems); fNewCount = temp.CountItems(); if (fNewCount <= 0) return; fNewItems = new (nothrow) PlaylistItem*[fNewCount]; if (!fNewItems) return; memset(fNewItems, 0, fNewCount * sizeof(PlaylistItem*)); // init new entries int32 added = 0; for (int32 i = 0; i < fNewCount; i++) { if (!Playlist::ExtraMediaExists(playlist, temp.ItemAtFast(i))) { fNewItems[added] = temp.ItemAtFast(i)->Clone(); if (fNewItems[added] == NULL) { // indicate bad object init _CleanUp(fNewItems, fNewCount, true); return; } added++; } } fNewCount = added; fPlaylingIndex = fPlaylist->CurrentItemIndex(); if (fToIndex == APPEND_INDEX_REPLACE_PLAYLIST) { fOldCount = fPlaylist->CountItems(); if (fOldCount > 0) { fOldItems = new (nothrow) PlaylistItem*[fOldCount]; if (!fOldItems) { // indicate bad object init _CleanUp(fNewItems, fNewCount, true); } else memset(fOldItems, 0, fOldCount * sizeof(PlaylistItem*)); } } for (int32 i = 0; i < fOldCount; i++) { fOldItems[i] = fPlaylist->ItemAtFast(i)->Clone(); if (fOldItems[i] == NULL) { // indicate bad object init _CleanUp(fNewItems, fNewCount, true); return; } } } ImportPLItemsCommand::~ImportPLItemsCommand() { _CleanUp(fOldItems, fOldCount, fItemsAdded); _CleanUp(fNewItems, fNewCount, !fItemsAdded); } status_t ImportPLItemsCommand::InitCheck() { if (!fPlaylist || !fNewItems) return B_NO_INIT; return B_OK; } status_t ImportPLItemsCommand::Perform() { BAutolock _(fPlaylist); fItemsAdded = true; if (fToIndex == APPEND_INDEX_APPEND_LAST) fToIndex = fPlaylist->CountItems(); int32 index = fToIndex; if (fToIndex == APPEND_INDEX_REPLACE_PLAYLIST) { fPlaylist->MakeEmpty(false); index = 0; } bool startPlaying = fPlaylist->CountItems() == 0; // add refs to playlist at the insertion index for (int32 i = 0; i < fNewCount; i++) { if (!fPlaylist->AddItem(fNewItems[i], index++)) return B_NO_MEMORY; } if (startPlaying) { // open first file fPlaylist->SetCurrentItemIndex(0); } return B_OK; } status_t ImportPLItemsCommand::Undo() { BAutolock _(fPlaylist); fItemsAdded = false; if (fToIndex == APPEND_INDEX_REPLACE_PLAYLIST) { // remove new items from playlist and restore old refs fPlaylist->MakeEmpty(false); for (int32 i = 0; i < fOldCount; i++) { if (!fPlaylist->AddItem(fOldItems[i], i)) return B_NO_MEMORY; } // Restore previously playing item if (fPlaylingIndex >= 0) fPlaylist->SetCurrentItemIndex(fPlaylingIndex, false); } else { // remove new items from playlist for (int32 i = 0; i < fNewCount; i++) { fPlaylist->RemoveItem(fToIndex); } } return B_OK; } void ImportPLItemsCommand::GetName(BString& name) { if (fNewCount > 1) name << B_TRANSLATE("Import Entries"); else name << B_TRANSLATE("Import Entry"); }
1,494
341
{ "schema": "https://developer.microsoft.com/json-schemas/sp/view-formatting.schema.json", "additionalRowClass": "=if([$DueDate] <= @now, 'sp-field-severity--severeWarning', '')" }
72
977
#ifndef REALM_NOINST_SERVER_LEGACY_MIGRATION_HPP #define REALM_NOINST_SERVER_LEGACY_MIGRATION_HPP #include <string> #include <realm/util/logger.hpp> namespace realm { namespace _impl { /// If not already done, migrate legacy format server-side Realm files. This /// migration step introduces stable identifiers, and discards all /// client-specific state. void ensure_legacy_migration_1(const std::string& realms_dir, const std::string& migration_dir, util::Logger&); } // namespace _impl } // namespace realm #endif // REALM_NOINST_SERVER_LEGACY_MIGRATION_HPP
194
5,813
<filename>server/src/main/java/org/apache/druid/server/initialization/ZkPathsConfig.java /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.druid.server.initialization; import com.fasterxml.jackson.annotation.JsonProperty; import org.apache.curator.utils.ZKPaths; public class ZkPathsConfig { @JsonProperty private String base = "druid"; @JsonProperty private String propertiesPath; @JsonProperty private String announcementsPath; @JsonProperty @Deprecated private String servedSegmentsPath; @JsonProperty private String liveSegmentsPath; @JsonProperty private String coordinatorPath; @JsonProperty private String loadQueuePath; @JsonProperty private String connectorPath; public String getBase() { return base; } public String getPropertiesPath() { return (null == propertiesPath) ? defaultPath("properties") : propertiesPath; } public String getAnnouncementsPath() { return (null == announcementsPath) ? defaultPath("announcements") : announcementsPath; } @Deprecated public String getServedSegmentsPath() { return (null == servedSegmentsPath) ? defaultPath("servedSegments") : servedSegmentsPath; } public String getLiveSegmentsPath() { return (null == liveSegmentsPath) ? defaultPath("segments") : liveSegmentsPath; } public String getCoordinatorPath() { return (null == coordinatorPath) ? defaultPath("coordinator") : coordinatorPath; } public String getOverlordPath() { return defaultPath("overlord"); } public String getLoadQueuePath() { return (null == loadQueuePath) ? defaultPath("loadQueue") : loadQueuePath; } public String getConnectorPath() { return (null == connectorPath) ? defaultPath("connector") : connectorPath; } public String getInternalDiscoveryPath() { return defaultPath("internal-discovery"); } public String defaultPath(final String subPath) { return ZKPaths.makePath(getBase(), subPath); } @Override public boolean equals(Object other) { if (null == other) { return false; } if (this == other) { return true; } if (!(other instanceof ZkPathsConfig)) { return false; } ZkPathsConfig otherConfig = (ZkPathsConfig) other; if (this.getBase().equals(otherConfig.getBase()) && this.getAnnouncementsPath().equals(otherConfig.getAnnouncementsPath()) && this.getConnectorPath().equals(otherConfig.getConnectorPath()) && this.getLiveSegmentsPath().equals(otherConfig.getLiveSegmentsPath()) && this.getCoordinatorPath().equals(otherConfig.getCoordinatorPath()) && this.getLoadQueuePath().equals(otherConfig.getLoadQueuePath()) && this.getPropertiesPath().equals(otherConfig.getPropertiesPath()) && this.getServedSegmentsPath().equals(otherConfig.getServedSegmentsPath())) { return true; } return false; } @Override public int hashCode() { int result = base != null ? base.hashCode() : 0; result = 31 * result + (propertiesPath != null ? propertiesPath.hashCode() : 0); result = 31 * result + (announcementsPath != null ? announcementsPath.hashCode() : 0); result = 31 * result + (servedSegmentsPath != null ? servedSegmentsPath.hashCode() : 0); result = 31 * result + (liveSegmentsPath != null ? liveSegmentsPath.hashCode() : 0); result = 31 * result + (coordinatorPath != null ? coordinatorPath.hashCode() : 0); result = 31 * result + (loadQueuePath != null ? loadQueuePath.hashCode() : 0); result = 31 * result + (connectorPath != null ? connectorPath.hashCode() : 0); return result; } }
1,394
3,227
// Copyright (c) 2013 INRIA Sophia-Antipolis (France). // All rights reserved. // // This file is part of CGAL (www.cgal.org) // // $URL$ // $Id$ // SPDX-License-Identifier: LGPL-3.0-or-later OR LicenseRef-Commercial // // Author(s) : <NAME> // <NAME> #ifndef CGAL_INTERNAL_SCALE_COORDINATES_ADAPTOR_TRAITS_3_H #define CGAL_INTERNAL_SCALE_COORDINATES_ADAPTOR_TRAITS_3_H namespace CGAL { namespace internal { template <int x, int y, int z, int ord> struct Transform_constant_struct; template <> struct Transform_constant_struct<1,1,0,0> { enum {value = 0}; }; template <> struct Transform_constant_struct<-1,1,0,0> { enum {value = 1}; }; template <> struct Transform_constant_struct<1,-1,0,0> { enum {value = 2}; }; template <> struct Transform_constant_struct<-1,-1,0,0> { enum {value = 3}; }; template <> struct Transform_constant_struct<1,1,0,1> { enum {value = 4}; }; template <> struct Transform_constant_struct<-1,1,0,1> { enum {value = 5}; }; template <> struct Transform_constant_struct<1,-1,0,1> { enum {value = 6}; }; template <> struct Transform_constant_struct<-1,-1,0,1> { enum {value = 7}; }; template <> struct Transform_constant_struct<1,0,1,0> { enum {value = 8}; }; template <> struct Transform_constant_struct<-1,0,1,0> { enum {value = 9}; }; template <> struct Transform_constant_struct<1,0,-1,0> { enum {value = 10}; }; template <> struct Transform_constant_struct<-1,0,-1,0> { enum {value = 11}; }; template <> struct Transform_constant_struct<1,0,1,1> { enum {value = 12}; }; template <> struct Transform_constant_struct<-1,0,1,1> { enum {value = 13}; }; template <> struct Transform_constant_struct<1,0,-1,1> { enum {value = 14}; }; template <> struct Transform_constant_struct<-1,0,-1,1> { enum {value = 15}; }; template <> struct Transform_constant_struct<0,1,1,0> { enum {value = 16}; }; template <> struct Transform_constant_struct<0,-1,1,0> { enum {value = 17}; }; template <> struct Transform_constant_struct<0,1,-1,0> { enum {value = 18}; }; template <> struct Transform_constant_struct<0,-1,-1,0> { enum {value = 19}; }; template <> struct Transform_constant_struct<0,1,1,1> { enum {value = 20}; }; template <> struct Transform_constant_struct<0,-1,1,1> { enum {value = 21}; }; template <> struct Transform_constant_struct<0,1,-1,1> { enum {value = 22}; }; template <> struct Transform_constant_struct<0,-1,-1,1> { enum {value = 23}; }; template <class R, int opt> struct Coordinate_value_adaptor; template <class R> struct Coordinate_value_adaptor<R,0> { static typename R::FT x(const typename R::Point_3& p) {return p.x();} static typename R::FT y(const typename R::Point_3& p) {return p.y();} }; template <class R> struct Coordinate_value_adaptor<R,1> { static typename R::FT x(const typename R::Point_3& p) {return -p.x();} static typename R::FT y(const typename R::Point_3& p) {return p.y();} }; template <class R> struct Coordinate_value_adaptor<R,2> { static typename R::FT x(const typename R::Point_3& p) {return p.x();} static typename R::FT y(const typename R::Point_3& p) {return -p.y();} }; template <class R> struct Coordinate_value_adaptor<R,3> { static typename R::FT x(const typename R::Point_3& p) {return -p.x();} static typename R::FT y(const typename R::Point_3& p) {return -p.y();} }; template <class R> struct Coordinate_value_adaptor<R,4> { static typename R::FT x(const typename R::Point_3& p) {return p.y();} static typename R::FT y(const typename R::Point_3& p) {return p.x();} }; template <class R> struct Coordinate_value_adaptor<R,5> { static typename R::FT x(const typename R::Point_3& p) {return -p.y();} static typename R::FT y(const typename R::Point_3& p) {return p.x();} }; template <class R> struct Coordinate_value_adaptor<R,6> { static typename R::FT x(const typename R::Point_3& p) {return p.y();} static typename R::FT y(const typename R::Point_3& p) {return -p.x();} }; template <class R> struct Coordinate_value_adaptor<R,7> { static typename R::FT x(const typename R::Point_3& p) {return -p.y();} static typename R::FT y(const typename R::Point_3& p) {return -p.x();} }; template <class R> struct Coordinate_value_adaptor<R,8> { static typename R::FT x(const typename R::Point_3& p) {return p.x();} static typename R::FT y(const typename R::Point_3& p) {return p.z();} }; template <class R> struct Coordinate_value_adaptor<R,9> { static typename R::FT x(const typename R::Point_3& p) {return -p.x();} static typename R::FT y(const typename R::Point_3& p) {return p.z();} }; template <class R> struct Coordinate_value_adaptor<R,10> { static typename R::FT x(const typename R::Point_3& p) {return p.x();} static typename R::FT y(const typename R::Point_3& p) {return -p.z();} }; template <class R> struct Coordinate_value_adaptor<R,11> { static typename R::FT x(const typename R::Point_3& p) {return -p.x();} static typename R::FT y(const typename R::Point_3& p) {return -p.z();} }; template <class R> struct Coordinate_value_adaptor<R,12> { static typename R::FT x(const typename R::Point_3& p) {return p.z();} static typename R::FT y(const typename R::Point_3& p) {return p.x();} }; template <class R> struct Coordinate_value_adaptor<R,13> { static typename R::FT x(const typename R::Point_3& p) {return -p.z();} static typename R::FT y(const typename R::Point_3& p) {return p.x();} }; template <class R> struct Coordinate_value_adaptor<R,14> { static typename R::FT x(const typename R::Point_3& p) {return p.z();} static typename R::FT y(const typename R::Point_3& p) {return -p.x();} }; template <class R> struct Coordinate_value_adaptor<R,15> { static typename R::FT x(const typename R::Point_3& p) {return -p.z();} static typename R::FT y(const typename R::Point_3& p) {return -p.x();} }; template <class R> struct Coordinate_value_adaptor<R,16> { static typename R::FT x(const typename R::Point_3& p) {return p.y();} static typename R::FT y(const typename R::Point_3& p) {return p.z();} }; template <class R> struct Coordinate_value_adaptor<R,17> { static typename R::FT x(const typename R::Point_3& p) {return -p.y();} static typename R::FT y(const typename R::Point_3& p) {return p.z();} }; template <class R> struct Coordinate_value_adaptor<R,18> { static typename R::FT x(const typename R::Point_3& p) {return p.y();} static typename R::FT y(const typename R::Point_3& p) {return -p.z();} }; template <class R> struct Coordinate_value_adaptor<R,19> { static typename R::FT x(const typename R::Point_3& p) {return -p.y();} static typename R::FT y(const typename R::Point_3& p) {return -p.z();} }; template <class R> struct Coordinate_value_adaptor<R,20> { static typename R::FT x(const typename R::Point_3& p) {return p.z();} static typename R::FT y(const typename R::Point_3& p) {return p.y();} }; template <class R> struct Coordinate_value_adaptor<R,21> { static typename R::FT x(const typename R::Point_3& p) {return -p.z();} static typename R::FT y(const typename R::Point_3& p) {return p.y();} }; template <class R> struct Coordinate_value_adaptor<R,22> { static typename R::FT x(const typename R::Point_3& p) {return p.z();} static typename R::FT y(const typename R::Point_3& p) {return -p.y();} }; template <class R> struct Coordinate_value_adaptor<R,23> { static typename R::FT x(const typename R::Point_3& p) {return -p.z();} static typename R::FT y(const typename R::Point_3& p) {return -p.y();} }; template <class R, int opt> class Compute_x_2 { public: typedef typename R::Point_3 Point; typename R::FT x(const Point &p) const { return Coordinate_value_adaptor<R,opt>::x(p); } typename R::FT operator()(const Point& p) const { return x(p); } }; template <class R, int opt> class Compute_y_2 { public: typedef typename R::Point_3 Point; typename R::FT y(const Point &p) const { return Coordinate_value_adaptor<R,opt>::y(p); } typename R::FT operator()(const Point& p) const { return y(p); } }; template <class R, int opt> class Less_x_2 { public: typedef typename R::Point_3 Point; typename R::FT x(const Point &p) const { return Coordinate_value_adaptor<R,opt>::x(p); } bool operator()(const Point& p, const Point& q) const { return x(p) < x(q); } }; template <class R, int opt> class Less_y_2 { public: typedef typename R::Point_3 Point; typename R::FT y(const Point &p) const { return Coordinate_value_adaptor<R,opt>::y(p); } bool operator()(const Point& p, const Point& q) const { return y(p) < y(q); } }; template <class R, int x, int y, int z, int ord> struct Transform_coordinates_traits_3 { private: enum {opt = Transform_constant_struct<x,y,z,ord>::value}; public: typedef Transform_coordinates_traits_3<R,x,y,z,ord> Traits; typedef R Rp; typedef typename Rp::Point_3 Point_2; typedef Less_x_2<R,opt> Less_x; typedef Less_y_2<R,opt> Less_y; typedef Compute_x_2<R,opt> Compute_x; typedef Compute_y_2<R,opt> Compute_y; Transform_coordinates_traits_3(){} Transform_coordinates_traits_3(const Transform_coordinates_traits_3&){} Less_x less_x_2_object() const { return Less_x(); } Less_y less_y_2_object() const { return Less_y(); } Compute_x compute_x_2_object() const { return Compute_x(); } Compute_y compute_y_2_object() const { return Compute_y(); } }; } } //namespace CGAL::internal #endif // CGAL_INTERNAL_SCALE_COORDINATES_ADAPTOR_TRAITS_3_H
3,811
335
{ "word": "Fab", "definitions": [ "A microchip manufacturing plant.", "A process in a microchip manufacturing plant." ], "parts-of-speech": "Noun" }
75
1,414
<filename>Real-Time Corruptor/BizHawk_RTC/libmupen64plus/mupen64plus-video-rice/src/FrameBuffer.h /* Copyright (C) 2002 Rice1964 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef _FRAME_BUFFER_H_ #define _FRAME_BUFFER_H_ #include "typedefs.h" #include "RenderTexture.h" #include "TextureManager.h" typedef int SURFFORMAT; extern void TexRectToN64FrameBuffer_16b(uint32 x0, uint32 y0, uint32 width, uint32 height, uint32 dwTile); extern void TexRectToFrameBuffer_8b(uint32 dwXL, uint32 dwYL, uint32 dwXH, uint32 dwYH, float t0u0, float t0v0, float t0u1, float t0v1, uint32 dwTile); class FrameBufferManager { friend class CGraphicsContext; friend class CDXGraphicsContext; public: FrameBufferManager(); virtual ~FrameBufferManager(); void Initialize(); void CloseUp(); void Set_CI_addr(SetImgInfo &newCI); void UpdateRecentCIAddr(SetImgInfo &ciinfo); void SetAddrBeDisplayed(uint32 addr); bool HasAddrBeenDisplayed(uint32 addr, uint32 width); int FindRecentCIInfoIndex(uint32 addr); bool IsDIaRenderTexture(); int CheckAddrInRenderTextures(uint32 addr, bool checkcrc = true); uint32 ComputeRenderTextureCRCInRDRAM(int infoIdx); void CheckRenderTextureCRCInRDRAM(void); int CheckRenderTexturesWithNewCI(SetImgInfo &CIinfo, uint32 height, bool byNewTxtrBuf); virtual void ClearN64FrameBufferToBlack(uint32 left=0, uint32 top=0, uint32 width=0, uint32 height=0); virtual int SetBackBufferAsRenderTexture(SetImgInfo &CIinfo, int ciInfoIdx); void LoadTextureFromRenderTexture(TxtrCacheEntry* pEntry, int infoIdx); void UpdateFrameBufferBeforeUpdateFrame(); virtual void RestoreNormalBackBuffer(); // restore the normal back buffer virtual void CopyBackToFrameBufferIfReadByCPU(uint32 addr); virtual void SetRenderTexture(void); virtual void CloseRenderTexture(bool toSave); virtual void ActiveTextureBuffer(void); int IsAddrInRecentFrameBuffers(uint32 addr); int CheckAddrInBackBuffers(uint32 addr, uint32 memsize, bool copyToRDRAM = false); uint8 CIFindIndex(uint16 val); uint32 ComputeCImgHeight(SetImgInfo &info, uint32 &height); int FindASlot(void); bool ProcessFrameWriteRecord(); void FrameBufferWriteByCPU(uint32 addr, uint32 size); void FrameBufferReadByCPU( uint32 addr ); bool FrameBufferInRDRAMCheckCRC(); void StoreRenderTextureToRDRAM(int infoIdx = -1); virtual bool IsRenderingToTexture() {return m_isRenderingToTexture;} // Device dependent functions virtual void SaveBackBuffer(int ciInfoIdx, RECT* pRect=NULL, bool forceToSaveToRDRAM = false); // Copy the current back buffer to temp buffer virtual void CopyBackBufferToRenderTexture(int idx, RecentCIInfo &ciInfo, RECT* pRect=NULL) {} // Copy the current back buffer to temp buffer virtual void CopyBufferToRDRAM(uint32 addr, uint32 fmt, uint32 siz, uint32 width, uint32 height, uint32 bufWidth, uint32 bufHeight, uint32 startaddr, uint32 memsize, uint32 pitch, TextureFmt bufFmt, void *surf, uint32 bufPitch); virtual void StoreBackBufferToRDRAM(uint32 addr, uint32 fmt, uint32 siz, uint32 width, uint32 height, uint32 bufWidth, uint32 bufHeight, uint32 startaddr=0xFFFFFFFF, uint32 memsize=0xFFFFFFFF, uint32 pitch=0, SURFFORMAT surf_fmt=SURFFMT_A8R8G8B8) {} #ifdef DEBUGGER virtual void DisplayRenderTexture(int infoIdx = -1); #endif protected: bool m_isRenderingToTexture; int m_curRenderTextureIndex; int m_lastTextureBufferIndex; }; class DXFrameBufferManager : public FrameBufferManager { virtual ~DXFrameBufferManager() {} public: // Device dependent functions virtual void CopyBackBufferToRenderTexture(int idx, RecentCIInfo &ciInfo, RECT* pRect=NULL); // Copy the current back buffer to temp buffer virtual void StoreBackBufferToRDRAM(uint32 addr, uint32 fmt, uint32 siz, uint32 width, uint32 height, uint32 bufWidth, uint32 bufHeight, uint32 startaddr=0xFFFFFFFF, uint32 memsize=0xFFFFFFFF, uint32 pitch=0, SURFFORMAT surf_fmt=SURFFMT_A8R8G8B8); }; class OGLFrameBufferManager : public FrameBufferManager { virtual ~OGLFrameBufferManager() {} public: // Device dependent functions virtual void CopyBackBufferToRenderTexture(int idx, RecentCIInfo &ciInfo, RECT* pRect=NULL); // Copy the current back buffer to temp buffer virtual void StoreBackBufferToRDRAM(uint32 addr, uint32 fmt, uint32 siz, uint32 width, uint32 height, uint32 bufWidth, uint32 bufHeight, uint32 startaddr=0xFFFFFFFF, uint32 memsize=0xFFFFFFFF, uint32 pitch=0, SURFFORMAT surf_fmt=SURFFMT_A8R8G8B8); }; extern RenderTextureInfo gRenderTextureInfos[]; extern RenderTextureInfo newRenderTextureInfo; #define NEW_TEXTURE_BUFFER extern RenderTextureInfo g_ZI_saves[2]; extern RenderTextureInfo *g_pRenderTextureInfo; extern FrameBufferManager* g_pFrameBufferManager; extern RecentCIInfo g_RecentCIInfo[]; extern RecentViOriginInfo g_RecentVIOriginInfo[]; extern RenderTextureInfo gRenderTextureInfos[]; extern int numOfTxtBufInfos; extern RecentCIInfo *g_uRecentCIInfoPtrs[5]; extern uint8 RevTlutTable[0x10000]; extern uint32 CalculateRDRAMCRC(void *pAddr, uint32 left, uint32 top, uint32 width, uint32 height, uint32 size, uint32 pitchInBytes ); extern uint16 ConvertRGBATo555(uint8 r, uint8 g, uint8 b, uint8 a); extern uint16 ConvertRGBATo555(uint32 color32); extern void InitTlutReverseLookup(void); #endif
2,158
2,670
<reponame>hmarr/dependabot-core { "name": "test", "version": "1.0.0", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "test", "version": "1.0.0", "license": "ISC", "dependencies": { "polling-to-event": "^2.1.0" } }, "node_modules/debug": { "version": "3.2.6", "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz", "integrity": "<KEY> "dependencies": { "ms": "^2.1.1" } }, "node_modules/deep-equal": { "version": "0.2.2", "resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-0.2.2.tgz", "integrity": "sha1-hLdFiW80xoTpjyzg5Cq69Du6AX0=" }, "node_modules/extend": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/extend/-/extend-2.0.0.tgz", "integrity": "<KEY> }, "node_modules/ms": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==" }, "node_modules/pauseable": { "version": "0.1.7", "resolved": "https://registry.npmjs.org/pauseable/-/pauseable-0.1.7.tgz", "integrity": "sha1-hczXeQ5JoTr+O5A7NhYTC8AHTgc=" }, "node_modules/polling-to-event": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/polling-to-event/-/polling-to-event-2.1.0.tgz", "integrity": "sha1-LorKGFZiQz8X/tL0z3RKKZPiJWw=", "dependencies": { "debug": "^3.0.1", "deep-equal": "~0.2.1", "extend": "~2.0.0", "pauseable": "~0.1.5" } } }, "dependencies": { "debug": { "version": "3.2.6", "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz", "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==", "requires": { "ms": "^2.1.1" } }, "deep-equal": { "version": "0.2.2", "resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-0.2.2.tgz", "integrity": "sha1-hLdFiW80xoTpjyzg5Cq69Du6AX0=" }, "extend": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/extend/-/extend-2.0.0.tgz", "integrity": "<KEY> }, "ms": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", "integrity": "<KEY> }, "pauseable": { "version": "0.1.7", "resolved": "https://registry.npmjs.org/pauseable/-/pauseable-0.1.7.tgz", "integrity": "sha1-<KEY> }, "polling-to-event": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/polling-to-event/-/polling-to-event-2.1.0.tgz", "integrity": "sha1-LorKGFZiQz8X/tL0z3RKKZPiJWw=", "requires": { "debug": "^3.0.1", "deep-equal": "~0.2.1", "extend": "~2.0.0", "pauseable": "~0.1.5" } } } }
1,717
5,938
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # 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. import pytest import main # Note: samples that do end-user auth are difficult to test in an automated # way. These tests are basic confidence checks. @pytest.fixture def client(): main.app.testing = True return main.app.test_client() def test_index_wo_credentials(client): r = client.get('/') assert r.status_code == 302 assert r.headers['location'].endswith('/authorize') def test_authorize(client): r = client.get('/authorize') assert r.status_code == 302 assert r.headers['location'].startswith('https://accounts.google.com')
349
609
// keyboard.c // See: // https://www.gnu.org/software/libc/manual/html_node/Canonical-or-Not.html // #include <kernel.h> // quando tem uma interrupção de mouse eu desligo o teclado e espero por ack // mas quando tem uma interrupção de teclado, então eu desligo o mouse mas não espero o ack. __VOID_IRQ irq1_KEYBOARD (void) { //#debug debug_print ("\n"); debug_print ("irq1_KEYBOARD: [TODO]\n"); // Not initialized. // Uma interrupção ocorreu antes mesmo de inicializarmos // o dispositivo e o handler ja estava conectado. // apenas drenamos um byte pra evitar problemas. // Mas antes deveríamos checar se a flag indica que // o buffer está cheio. if ( PS2.keyboard_initialized != TRUE ) { in8(0x60); return; } //printf ("k"); //refresh_screen(); // Disable mouse port. wait_then_write (0x64,0xA7); //mouse_expect_ack(); // See: // ps2kbd.c DeviceInterface_PS2Keyboard(); // #bugbug // Se estivermos usando uma inicialização reduzida, // onde habilitamos somente a porta do teclado, // não podemos habilitar a porta do mouse, sem a // devida inicialização. // Só reabilitaremos se a configuração de ps2 // nos disser que o segundo dispositivo esta em uso. // Reabilitando a porta de um dispositivo que // ja foi devidamente inicializado. // Reenable the mouse port. done: if ( PS2.used == TRUE ) { if ( PS2.mouse_initialized == TRUE ){ wait_then_write (0x64,0xA8); //mouse_expect_ack(); } } }
699
1,091
/* * Copyright 2016-present Open Networking Foundation * * 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.onosproject.cli.net; import java.util.Map; import org.apache.karaf.shell.api.action.Command; import org.apache.karaf.shell.api.action.lifecycle.Service; import org.onosproject.cli.AbstractShellCommand; import org.onosproject.store.service.StorageAdminService; import org.onosproject.store.service.WorkQueueStats; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; /** * Command to list stats for all work queues in the system. */ @Service @Command(scope = "onos", name = "queues", description = "Lists information about work queues in the system") public class QueuesListCommand extends AbstractShellCommand { private static final String FMT = "name=%s pending=%d inProgress=%d, completed=%d"; @Override protected void doExecute() { StorageAdminService storageAdminService = get(StorageAdminService.class); Map<String, WorkQueueStats> queueStats = storageAdminService.getQueueStats(); if (outputJson()) { ObjectMapper mapper = new ObjectMapper(); ObjectNode jsonQueues = mapper.createObjectNode(); queueStats.forEach((k, v) -> { ObjectNode jsonStats = jsonQueues.putObject(k); jsonStats.put("pending", v.totalPending()); jsonStats.put("inProgress", v.totalInProgress()); jsonStats.put("completed", v.totalCompleted()); }); print("%s", jsonQueues); } else { queueStats.forEach((name, stats) -> print(FMT, name, stats.totalPending(), stats.totalInProgress(), stats.totalCompleted())); } } }
797
2,535
<gh_stars>1000+ /** @file pgm.h ** @brief Portable graymap format (PGM) parser ** @author <NAME> **/ /* Copyright (C) 2007-12 <NAME> and <NAME>. All rights reserved. This file is part of the VLFeat library and is made available under the terms of the BSD license (see the COPYING file). */ #ifndef VL_PGM_H #define VL_PGM_H #include "generic.h" #include "mathop.h" #include <stdio.h> /** @name PGM parser error codes ** @{ */ #define VL_ERR_PGM_INV_HEAD 101 /**< Invalid PGM header section. */ #define VL_ERR_PGM_INV_META 102 /**< Invalid PGM meta section. */ #define VL_ERR_PGM_INV_DATA 103 /**< Invalid PGM data section.*/ #define VL_ERR_PGM_IO 104 /**< Generic I/O error. */ /** @} */ /** @brief PGM image meta data ** ** A PGM image is a 2-D array of pixels of width #width and height ** #height. Each pixel is an integer one or two bytes wide, depending ** whether #max_value is smaller than 256. **/ typedef struct _VlPgmImage { vl_size width ; /**< image width. */ vl_size height ; /**< image height. */ vl_size max_value ; /**< pixel maximum value (<= 2^16-1). */ vl_bool is_raw ; /**< is RAW format? */ } VlPgmImage ; /** @name Core operations ** @{ */ VL_EXPORT int vl_pgm_extract_head (FILE *f, VlPgmImage *im) ; VL_EXPORT int vl_pgm_extract_data (FILE *f, VlPgmImage const *im, void *data) ; VL_EXPORT int vl_pgm_insert (FILE *f, VlPgmImage const *im, void const*data ) ; VL_EXPORT vl_size vl_pgm_get_npixels (VlPgmImage const *im) ; VL_EXPORT vl_size vl_pgm_get_bpp (VlPgmImage const *im) ; /** @} */ /** @name Helper functions ** @{ */ VL_EXPORT int vl_pgm_write (char const *name, vl_uint8 const *data, int width, int height) ; VL_EXPORT int vl_pgm_write_f (char const *name, float const *data, int width, int height) ; VL_EXPORT int vl_pgm_read_new (char const *name, VlPgmImage *im, vl_uint8 **data) ; VL_EXPORT int vl_pgm_read_new_f (char const *name, VlPgmImage *im, float **data) ; /** @} */ /* VL_PGM_H */ #endif
1,159
7,931
<filename>zbar/src/main/jni/libiconv-1.15/lib/mac_greek.h /* * Copyright (C) 1999-2001, 2016 Free Software Foundation, Inc. * This file is part of the GNU LIBICONV Library. * * The GNU LIBICONV Library is free software; you can redistribute it * and/or modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * The GNU LIBICONV Library is distributed in the hope that it will be * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with the GNU LIBICONV Library; see the file COPYING.LIB. * If not, see <http://www.gnu.org/licenses/>. */ /* * MacGreek */ static const unsigned short mac_greek_2uni[128] = { /* 0x80 */ 0x00c4, 0x00b9, 0x00b2, 0x00c9, 0x00b3, 0x00d6, 0x00dc, 0x0385, 0x00e0, 0x00e2, 0x00e4, 0x0384, 0x00a8, 0x00e7, 0x00e9, 0x00e8, /* 0x90 */ 0x00ea, 0x00eb, 0x00a3, 0x2122, 0x00ee, 0x00ef, 0x2022, 0x00bd, 0x2030, 0x00f4, 0x00f6, 0x00a6, 0x00ad, 0x00f9, 0x00fb, 0x00fc, /* 0xa0 */ 0x2020, 0x0393, 0x0394, 0x0398, 0x039b, 0x039e, 0x03a0, 0x00df, 0x00ae, 0x00a9, 0x03a3, 0x03aa, 0x00a7, 0x2260, 0x00b0, 0x0387, /* 0xb0 */ 0x0391, 0x00b1, 0x2264, 0x2265, 0x00a5, 0x0392, 0x0395, 0x0396, 0x0397, 0x0399, 0x039a, 0x039c, 0x03a6, 0x03ab, 0x03a8, 0x03a9, /* 0xc0 */ 0x03ac, 0x039d, 0x00ac, 0x039f, 0x03a1, 0x2248, 0x03a4, 0x00ab, 0x00bb, 0x2026, 0x00a0, 0x03a5, 0x03a7, 0x0386, 0x0388, 0x0153, /* 0xd0 */ 0x2013, 0x2015, 0x201c, 0x201d, 0x2018, 0x2019, 0x00f7, 0x0389, 0x038a, 0x038c, 0x038e, 0x03ad, 0x03ae, 0x03af, 0x03cc, 0x038f, /* 0xe0 */ 0x03cd, 0x03b1, 0x03b2, 0x03c8, 0x03b4, 0x03b5, 0x03c6, 0x03b3, 0x03b7, 0x03b9, 0x03be, 0x03ba, 0x03bb, 0x03bc, 0x03bd, 0x03bf, /* 0xf0 */ 0x03c0, 0x03ce, 0x03c1, 0x03c3, 0x03c4, 0x03b8, 0x03c9, 0x03c2, 0x03c7, 0x03c5, 0x03b6, 0x03ca, 0x03cb, 0x0390, 0x03b0, 0xfffd, }; static int mac_greek_mbtowc (conv_t conv, ucs4_t *pwc, const unsigned char *s, size_t n) { unsigned char c = *s; if (c < 0x80) { *pwc = (ucs4_t) c; return 1; } else { unsigned short wc = mac_greek_2uni[c-0x80]; if (wc != 0xfffd) { *pwc = (ucs4_t) wc; return 1; } } return RET_ILSEQ; } static const unsigned char mac_greek_page00[96] = { 0xca, 0x00, 0x00, 0x92, 0x00, 0xb4, 0x9b, 0xac, /* 0xa0-0xa7 */ 0x8c, 0xa9, 0x00, 0xc7, 0xc2, 0x9c, 0xa8, 0x00, /* 0xa8-0xaf */ 0xae, 0xb1, 0x82, 0x84, 0x00, 0x00, 0x00, 0x00, /* 0xb0-0xb7 */ 0x00, 0x81, 0x00, 0xc8, 0x00, 0x97, 0x00, 0x00, /* 0xb8-0xbf */ 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, /* 0xc0-0xc7 */ 0x00, 0x83, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xc8-0xcf */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x85, 0x00, /* 0xd0-0xd7 */ 0x00, 0x00, 0x00, 0x00, 0x86, 0x00, 0x00, 0xa7, /* 0xd8-0xdf */ 0x88, 0x00, 0x89, 0x00, 0x8a, 0x00, 0x00, 0x8d, /* 0xe0-0xe7 */ 0x8f, 0x8e, 0x90, 0x91, 0x00, 0x00, 0x94, 0x95, /* 0xe8-0xef */ 0x00, 0x00, 0x00, 0x00, 0x99, 0x00, 0x9a, 0xd6, /* 0xf0-0xf7 */ 0x00, 0x9d, 0x00, 0x9e, 0x9f, 0x00, 0x00, 0x00, /* 0xf8-0xff */ }; static const unsigned char mac_greek_page03[80] = { 0x00, 0x00, 0x00, 0x00, 0x8b, 0x87, 0xcd, 0xaf, /* 0x80-0x87 */ 0xce, 0xd7, 0xd8, 0x00, 0xd9, 0x00, 0xda, 0xdf, /* 0x88-0x8f */ 0xfd, 0xb0, 0xb5, 0xa1, 0xa2, 0xb6, 0xb7, 0xb8, /* 0x90-0x97 */ 0xa3, 0xb9, 0xba, 0xa4, 0xbb, 0xc1, 0xa5, 0xc3, /* 0x98-0x9f */ 0xa6, 0xc4, 0x00, 0xaa, 0xc6, 0xcb, 0xbc, 0xcc, /* 0xa0-0xa7 */ 0xbe, 0xbf, 0xab, 0xbd, 0xc0, 0xdb, 0xdc, 0xdd, /* 0xa8-0xaf */ 0xfe, 0xe1, 0xe2, 0xe7, 0xe4, 0xe5, 0xfa, 0xe8, /* 0xb0-0xb7 */ 0xf5, 0xe9, 0xeb, 0xec, 0xed, 0xee, 0xea, 0xef, /* 0xb8-0xbf */ 0xf0, 0xf2, 0xf7, 0xf3, 0xf4, 0xf9, 0xe6, 0xf8, /* 0xc0-0xc7 */ 0xe3, 0xf6, 0xfb, 0xfc, 0xde, 0xe0, 0xf1, 0x00, /* 0xc8-0xcf */ }; static const unsigned char mac_greek_page20[40] = { 0x00, 0x00, 0x00, 0xd0, 0x00, 0xd1, 0x00, 0x00, /* 0x10-0x17 */ 0xd4, 0xd5, 0x00, 0x00, 0xd2, 0xd3, 0x00, 0x00, /* 0x18-0x1f */ 0xa0, 0x00, 0x96, 0x00, 0x00, 0x00, 0xc9, 0x00, /* 0x20-0x27 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x28-0x2f */ 0x98, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x30-0x37 */ }; static const unsigned char mac_greek_page22[32] = { 0xc5, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x50-0x57 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x58-0x5f */ 0xad, 0x00, 0x00, 0x00, 0xb2, 0xb3, 0x00, 0x00, /* 0x60-0x67 */ }; static int mac_greek_wctomb (conv_t conv, unsigned char *r, ucs4_t wc, size_t n) { unsigned char c = 0; if (wc < 0x0080) { *r = wc; return 1; } else if (wc >= 0x00a0 && wc < 0x0100) c = mac_greek_page00[wc-0x00a0]; else if (wc == 0x0153) c = 0xcf; else if (wc >= 0x0380 && wc < 0x03d0) c = mac_greek_page03[wc-0x0380]; else if (wc >= 0x2010 && wc < 0x2038) c = mac_greek_page20[wc-0x2010]; else if (wc == 0x2122) c = 0x93; else if (wc >= 0x2248 && wc < 0x2268) c = mac_greek_page22[wc-0x2248]; if (c != 0) { *r = c; return 1; } return RET_ILUNI; }
3,016
1,056
<filename>platform/api.annotations.common/src/org/netbeans/api/annotations/common/NullUnknown.java /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.api.annotations.common; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * The annotated element might be <code>null</code> under certain * <i>defined</i> circumstances. The necessity of the non-null check depends * on situations described in the javadoc (so the non-null check is * not required by default). * <p> * Consider {@link java.util.Map#get(java.lang.Object)} as an example of * such a method - depending on usage of the {@link java.util.Map} * <code>null</code> may be legal or forbidden. * * @author <NAME>, <NAME> */ @Documented @Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.LOCAL_VARIABLE}) @Retention(RetentionPolicy.CLASS) @javax.annotation.Nonnull(when=javax.annotation.meta.When.UNKNOWN) @javax.annotation.meta.TypeQualifierNickname public @interface NullUnknown { }
557
789
import subprocess import os def download_task_model(task): m_path = os.path.join('/home/ubuntu/s3', "model_log_final", task, "logs/model.permanent-ckpt") dirs, fname = os.path.split(m_path) dst_dir = dirs.replace('/home/ubuntu/s3', "s3://taskonomy-unpacked-oregon") tmp_path = "/home/ubuntu/temp/{}".format(task) subprocess.call('mkdir -p {}'.format(tmp_path), shell=True) tmp_fname = os.path.join(tmp_path, fname) aws_cp_command = "aws s3 cp {}.data-00000-of-00001 {}".format(os.path.join(dst_dir, fname), tmp_path) subprocess.call(aws_cp_command, shell=True) aws_cp_command = "aws s3 cp {}.meta {}".format(os.path.join(dst_dir, fname), tmp_path) subprocess.call(aws_cp_command, shell=True) aws_cp_command = "aws s3 cp {}.index {}".format(os.path.join(dst_dir, fname), tmp_path) subprocess.call(aws_cp_command, shell=True) list_of_tasks = 'autoencoder curvature denoise edge2d edge3d \ keypoint2d keypoint3d colorization jigsaw \ reshade rgb2depth rgb2mist rgb2sfnorm \ room_layout segment25d segment2d vanishing_point_well_defined \ segmentsemantic_rb class_1000 class_places impainting_whole' list_of_tasks = 'impainting_whole' list_of_tasks = list_of_tasks.split() for t in list_of_tasks: download_task_model(t)
560
790
from django.contrib.localflavor.sk.forms import (SKRegionSelect, SKPostalCodeField, SKDistrictSelect) from django.test import SimpleTestCase class SKLocalFlavorTests(SimpleTestCase): def test_SKRegionSelect(self): f = SKRegionSelect() out = u'''<select name="regions"> <option value="BB">Banska Bystrica region</option> <option value="BA">Bratislava region</option> <option value="KE">Kosice region</option> <option value="NR">Nitra region</option> <option value="PO">Presov region</option> <option value="TN">Trencin region</option> <option value="TT" selected="selected">Trnava region</option> <option value="ZA">Zilina region</option> </select>''' self.assertHTMLEqual(f.render('regions', 'TT'), out) def test_SKDistrictSelect(self): f = SKDistrictSelect() out = u'''<select name="Districts"> <option value="BB">Banska Bystrica</option> <option value="BS">Banska Stiavnica</option> <option value="BJ">Bardejov</option> <option value="BN">Banovce nad Bebravou</option> <option value="BR">Brezno</option> <option value="BA1">Bratislava I</option> <option value="BA2">Bratislava II</option> <option value="BA3">Bratislava III</option> <option value="BA4">Bratislava IV</option> <option value="BA5">Bratislava V</option> <option value="BY">Bytca</option> <option value="CA">Cadca</option> <option value="DT">Detva</option> <option value="DK">Dolny Kubin</option> <option value="DS">Dunajska Streda</option> <option value="GA">Galanta</option> <option value="GL">Gelnica</option> <option value="HC">Hlohovec</option> <option value="HE">Humenne</option> <option value="IL">Ilava</option> <option value="KK">Kezmarok</option> <option value="KN">Komarno</option> <option value="KE1">Kosice I</option> <option value="KE2">Kosice II</option> <option value="KE3">Kosice III</option> <option value="KE4">Kosice IV</option> <option value="KEO">Kosice - okolie</option> <option value="KA">Krupina</option> <option value="KM">Kysucke Nove Mesto</option> <option value="LV">Levice</option> <option value="LE">Levoca</option> <option value="LM">Liptovsky Mikulas</option> <option value="LC">Lucenec</option> <option value="MA">Malacky</option> <option value="MT">Martin</option> <option value="ML">Medzilaborce</option> <option value="MI">Michalovce</option> <option value="MY">Myjava</option> <option value="NO">Namestovo</option> <option value="NR">Nitra</option> <option value="NM">Nove Mesto nad Vahom</option> <option value="NZ">Nove Zamky</option> <option value="PE">Partizanske</option> <option value="PK">Pezinok</option> <option value="PN">Piestany</option> <option value="PT">Poltar</option> <option value="PP">Poprad</option> <option value="PB">Povazska Bystrica</option> <option value="PO">Presov</option> <option value="PD">Prievidza</option> <option value="PU">Puchov</option> <option value="RA">Revuca</option> <option value="RS">Rimavska Sobota</option> <option value="RV">Roznava</option> <option value="RK" selected="selected">Ruzomberok</option> <option value="SB">Sabinov</option> <option value="SC">Senec</option> <option value="SE">Senica</option> <option value="SI">Skalica</option> <option value="SV">Snina</option> <option value="SO">Sobrance</option> <option value="SN">Spisska Nova Ves</option> <option value="SL">Stara Lubovna</option> <option value="SP">Stropkov</option> <option value="SK">Svidnik</option> <option value="SA">Sala</option> <option value="TO">Topolcany</option> <option value="TV">Trebisov</option> <option value="TN">Trencin</option> <option value="TT">Trnava</option> <option value="TR">Turcianske Teplice</option> <option value="TS">Tvrdosin</option> <option value="VK">Velky Krtis</option> <option value="VT">Vranov nad Toplou</option> <option value="ZM">Zlate Moravce</option> <option value="ZV">Zvolen</option> <option value="ZC">Zarnovica</option> <option value="ZH">Ziar nad Hronom</option> <option value="ZA">Zilina</option> </select>''' self.assertHTMLEqual(f.render('Districts', 'RK'), out) def test_SKPostalCodeField(self): error_format = [u'Enter a postal code in the format XXXXX or XXX XX.'] valid = { '91909': '91909', '917 01': '91701', } invalid = { '84545x': error_format, } self.assertFieldOutput(SKPostalCodeField, valid, invalid)
1,650
1,602
# Check the various features of the GoogleTest format. # # RUN: not %{lit} -j 1 -v %{inputs}/googletest-upstream-format > %t.out # RUN: FileCheck < %t.out %s # # END. # CHECK: -- Testing: # CHECK: PASS: googletest-upstream-format :: {{[Dd]ummy[Ss]ub[Dd]ir}}/OneTest.py/FirstTest.subTestA # CHECK: FAIL: googletest-upstream-format :: {{[Dd]ummy[Ss]ub[Dd]ir}}/OneTest.py/FirstTest.subTestB # CHECK-NEXT: *** TEST 'googletest-upstream-format :: {{[Dd]ummy[Ss]ub[Dd]ir}}/OneTest.py/FirstTest.subTestB' FAILED *** # CHECK-NEXT: Running main() from gtest_main.cc # CHECK-NEXT: I am subTest B, I FAIL # CHECK-NEXT: And I have two lines of output # CHECK: *** # CHECK: PASS: googletest-upstream-format :: {{[Dd]ummy[Ss]ub[Dd]ir}}/OneTest.py/ParameterizedTest/0.subTest # CHECK: PASS: googletest-upstream-format :: {{[Dd]ummy[Ss]ub[Dd]ir}}/OneTest.py/ParameterizedTest/1.subTest # CHECK: Failed Tests (1) # CHECK: Passed: 3 # CHECK: Failed: 1
402
1,350
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.network.generated; import com.azure.core.util.Context; /** Samples for VirtualApplianceSites Get. */ public final class VirtualApplianceSitesGetSamples { /* * x-ms-original-file: specification/network/resource-manager/Microsoft.Network/stable/2021-05-01/examples/NetworkVirtualApplianceSiteGet.json */ /** * Sample code: GetNetwork Virtual Appliance Site. * * @param azure The entry point for accessing resource management APIs in Azure. */ public static void getNetworkVirtualApplianceSite(com.azure.resourcemanager.AzureResourceManager azure) { azure .networks() .manager() .serviceClient() .getVirtualApplianceSites() .getWithResponse("rg1", "nva", "site1", Context.NONE); } }
354
418
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Generated from FHIR 4.0.0-a53ec6ee1b on 2019-05-07. # 2019, SMART Health IT. import os import io import unittest import json from . import familymemberhistory from .fhirdate import FHIRDate class FamilyMemberHistoryTests(unittest.TestCase): def instantiate_from(self, filename): datadir = os.environ.get('FHIR_UNITTEST_DATADIR') or '' with io.open(os.path.join(datadir, filename), 'r', encoding='utf-8') as handle: js = json.load(handle) self.assertEqual("FamilyMemberHistory", js["resourceType"]) return familymemberhistory.FamilyMemberHistory(js) def testFamilyMemberHistory1(self): inst = self.instantiate_from("familymemberhistory-example.json") self.assertIsNotNone(inst, "Must have instantiated a FamilyMemberHistory instance") self.implFamilyMemberHistory1(inst) js = inst.as_json() self.assertEqual("FamilyMemberHistory", js["resourceType"]) inst2 = familymemberhistory.FamilyMemberHistory(js) self.implFamilyMemberHistory1(inst2) def implFamilyMemberHistory1(self, inst): self.assertEqual(inst.condition[0].code.coding[0].code, "315619001") self.assertEqual(inst.condition[0].code.coding[0].display, "Myocardial Infarction") self.assertEqual(inst.condition[0].code.coding[0].system, "http://snomed.info/sct") self.assertEqual(inst.condition[0].code.text, "Heart Attack") self.assertTrue(inst.condition[0].contributedToDeath) self.assertEqual(inst.condition[0].note[0].text, "Was fishing at the time. At least he went doing someting he loved.") self.assertEqual(inst.condition[0].onsetAge.code, "a") self.assertEqual(inst.condition[0].onsetAge.system, "http://unitsofmeasure.org") self.assertEqual(inst.condition[0].onsetAge.unit, "yr") self.assertEqual(inst.condition[0].onsetAge.value, 74) self.assertEqual(inst.date.date, FHIRDate("2011-03-18").date) self.assertEqual(inst.date.as_json(), "2011-03-18") self.assertEqual(inst.id, "father") self.assertEqual(inst.identifier[0].value, "12345") self.assertEqual(inst.instantiatesUri[0], "http://example.org/family-member-history-questionnaire") self.assertEqual(inst.meta.tag[0].code, "HTEST") self.assertEqual(inst.meta.tag[0].display, "test health data") self.assertEqual(inst.meta.tag[0].system, "http://terminology.hl7.org/CodeSystem/v3-ActReason") self.assertEqual(inst.relationship.coding[0].code, "FTH") self.assertEqual(inst.relationship.coding[0].display, "father") self.assertEqual(inst.relationship.coding[0].system, "http://terminology.hl7.org/CodeSystem/v3-RoleCode") self.assertEqual(inst.sex.coding[0].code, "male") self.assertEqual(inst.sex.coding[0].display, "Male") self.assertEqual(inst.sex.coding[0].system, "http://hl7.org/fhir/administrative-gender") self.assertEqual(inst.status, "completed") self.assertEqual(inst.text.div, "<div xmlns=\"http://www.w3.org/1999/xhtml\">Father died of a heart attack aged 74</div>") self.assertEqual(inst.text.status, "generated") def testFamilyMemberHistory2(self): inst = self.instantiate_from("familymemberhistory-example-mother.json") self.assertIsNotNone(inst, "Must have instantiated a FamilyMemberHistory instance") self.implFamilyMemberHistory2(inst) js = inst.as_json() self.assertEqual("FamilyMemberHistory", js["resourceType"]) inst2 = familymemberhistory.FamilyMemberHistory(js) self.implFamilyMemberHistory2(inst2) def implFamilyMemberHistory2(self, inst): self.assertEqual(inst.condition[0].code.coding[0].code, "371041009") self.assertEqual(inst.condition[0].code.coding[0].display, "Embolic Stroke") self.assertEqual(inst.condition[0].code.coding[0].system, "http://snomed.info/sct") self.assertEqual(inst.condition[0].code.text, "Stroke") self.assertEqual(inst.condition[0].onsetAge.code, "a") self.assertEqual(inst.condition[0].onsetAge.system, "http://unitsofmeasure.org") self.assertEqual(inst.condition[0].onsetAge.unit, "yr") self.assertEqual(inst.condition[0].onsetAge.value, 56) self.assertEqual(inst.id, "mother") self.assertEqual(inst.meta.tag[0].code, "HTEST") self.assertEqual(inst.meta.tag[0].display, "test health data") self.assertEqual(inst.meta.tag[0].system, "http://terminology.hl7.org/CodeSystem/v3-ActReason") self.assertEqual(inst.relationship.coding[0].code, "MTH") self.assertEqual(inst.relationship.coding[0].display, "mother") self.assertEqual(inst.relationship.coding[0].system, "http://terminology.hl7.org/CodeSystem/v3-RoleCode") self.assertEqual(inst.status, "completed") self.assertEqual(inst.text.div, "<div xmlns=\"http://www.w3.org/1999/xhtml\">Mother died of a stroke aged 56</div>") self.assertEqual(inst.text.status, "generated")
2,129
1,247
<filename>goodskill-web/src/main/java/org/seckill/web/dto/RoleDto.java package org.seckill.web.dto; import lombok.Data; import java.io.Serializable; @Data public class RoleDto implements Serializable { private Integer roleId; private String roleName; }
97
577
/** * Copyright 2009, Google Inc. All rights reserved. * Licensed to PSF under a Contributor Agreement. */ package org.python.indexer.demos; import org.python.indexer.StyleRun; import java.util.ArrayList; import java.util.List; import java.util.HashSet; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; /** * Turns a list of {@link StyleRun}s into HTML spans. */ class StyleApplier { // Empirically, adding the span tags multiplies length by 6 or more. private static final int SOURCE_BUF_MULTIPLIER = 6; private SortedSet<Tag> tags = new TreeSet<Tag>(); private StringBuilder buffer; // html output buffer private String source; // input source code private String path; // input source path, for logging // Current offset into the source being copied into the html buffer. private int sourceOffset = 0; abstract class Tag implements Comparable<Tag>{ int offset; StyleRun style; public int compareTo(Tag other) { if (this == other) { return 0; } if (this.offset < other.offset) { return -1; } if (other.offset < this.offset) { return 1; } return this.hashCode() - other.hashCode(); } void insert() { // Copy source code up through this tag. if (offset > sourceOffset) { copySource(sourceOffset, offset); } } } class StartTag extends Tag { public StartTag(StyleRun style) { offset = style.start(); this.style = style; } @Override void insert() { super.insert(); switch (style.type) { case ANCHOR: buffer.append("<a name='"); buffer.append(style.url); break; case LINK: buffer.append("<a href='"); buffer.append(style.url); break; default: buffer.append("<span class='"); buffer.append(toCSS(style)); break; } buffer.append("'"); if (style.message != null) { buffer.append(" title='"); buffer.append(style.message); buffer.append("'"); } buffer.append(">"); } } class EndTag extends Tag { public EndTag(StyleRun style) { offset = style.end(); this.style = style; } @Override void insert() { super.insert(); switch (style.type) { case ANCHOR: case LINK: buffer.append("</a>"); break; default: buffer.append("</span>"); break; } } } public StyleApplier(String path, String src, List<StyleRun> runs) { this.path = path; source = src; for (StyleRun run : runs) { tags.add(new StartTag(run)); tags.add(new EndTag(run)); } } /** * @return the html */ public String apply() { buffer = new StringBuilder(source.length() * SOURCE_BUF_MULTIPLIER); int lastStart = -1; for (Tag tag : tags) { tag.insert(); } // Copy in remaining source beyond last tag. if (sourceOffset < source.length()) { copySource(sourceOffset, source.length()); } return buffer.toString(); } /** * Copies code from the input source to the output html. * @param beg the starting source offset * @param end the end offset, or -1 to go to end of file */ private void copySource(int beg, int end) { // Be robust if the analyzer gives us bad offsets. try { String src = escape((end == -1) ? source.substring(beg) : source.substring(beg, end)); buffer.append(src); } catch (RuntimeException x) { System.err.println("Warning: " + x); } sourceOffset = end; } private String escape(String s) { return s.replace("&", "&amp;") .replace("'", "&#39;") .replace("\"", "&quot;") .replace("<", "&lt;") .replace(">", "&gt;"); } private String toCSS(StyleRun style) { return style.type.toString().toLowerCase().replace("_", "-"); } }
2,345
410
<filename>ios/Pods/Google-Mobile-Ads-SDK/Frameworks/frameworks/GoogleMobileAds.framework/Versions/A/Headers/GADCorrelatorAdLoaderOptions.h // // GADCorrelatorAdLoaderOptions.h // Google Mobile Ads SDK // // Copyright 2015 Google Inc. All rights reserved. // #import <GoogleMobileAds/GADAdLoader.h> #import <GoogleMobileAds/GADCorrelator.h> #import <GoogleMobileAds/GoogleMobileAdsDefines.h> GAD_ASSUME_NONNULL_BEGIN /// Ad loader options for adding a correlator to a native ad request. @interface GADCorrelatorAdLoaderOptions : GADAdLoaderOptions /// Correlator object for correlating ads loaded by an ad loader to other ad objects. @property(nonatomic, strong, GAD_NULLABLE) GADCorrelator *correlator; @end GAD_ASSUME_NONNULL_END
249
354
/*********************************************************************************************************************** * OpenStudio(R), Copyright (c) 2008-2021, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. * * (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the distribution. * * (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products * derived from this software without specific prior written permission from the respective party. * * (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works * may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior * written permission from Alliance for Sustainable Energy, LLC. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED * STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, 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 <gtest/gtest.h> #include "EnergyPlusFixture.hpp" #include "../ForwardTranslator.hpp" #include "../ReverseTranslator.hpp" #include "../../model/Model.hpp" #include "../../model/EnvironmentalImpactFactors.hpp" #include "../../model/EnvironmentalImpactFactors_Impl.hpp" #include "../../model/OutputEnvironmentalImpactFactors.hpp" #include "../../model/FuelFactors.hpp" #include "../../utilities/idf/IdfFile.hpp" #include "../../utilities/idf/Workspace.hpp" #include "../../utilities/idf/IdfObject.hpp" #include "../../utilities/idf/WorkspaceObject.hpp" #include <utilities/idd/EnvironmentalImpactFactors_FieldEnums.hxx> #include <utilities/idd/IddEnums.hxx> using namespace openstudio::energyplus; using namespace openstudio::model; using namespace openstudio; TEST_F(EnergyPlusFixture, ForwardTranslator_EnvironmentalImpactFactors) { ForwardTranslator ft; Model m; // Get the unique object auto environmentalImpactFactors = m.getUniqueModelObject<EnvironmentalImpactFactors>(); EXPECT_TRUE(environmentalImpactFactors.setDistrictHeatingEfficiency(0.35)); EXPECT_TRUE(environmentalImpactFactors.setDistrictCoolingCOP(3.3)); EXPECT_TRUE(environmentalImpactFactors.setSteamConversionEfficiency(0.27)); EXPECT_TRUE(environmentalImpactFactors.setTotalCarbonEquivalentEmissionFactorFromN2O(79.2)); EXPECT_TRUE(environmentalImpactFactors.setTotalCarbonEquivalentEmissionFactorFromCH4(6.1)); EXPECT_TRUE(environmentalImpactFactors.setTotalCarbonEquivalentEmissionFactorFromCO2(0.31)); // Without the OutputEnvironmentalImpactFactors: not translated { Workspace w = ft.translateModel(m); WorkspaceObjectVector idfObjs = w.getObjectsByType(IddObjectType::EnvironmentalImpactFactors); EXPECT_EQ(0u, idfObjs.size()); } // Create one OutputEnvironmentalImpactFactors o(m); // It also needs at least one FuelFactor to be translated FuelFactors fuelFactors(m); { Workspace w = ft.translateModel(m); WorkspaceObjectVector idfObjs = w.getObjectsByType(IddObjectType::EnvironmentalImpactFactors); ASSERT_EQ(1u, idfObjs.size()); auto idfObject = idfObjs[0]; EXPECT_EQ(0.35, idfObject.getDouble(EnvironmentalImpactFactorsFields::DistrictHeatingEfficiency).get()); EXPECT_EQ(3.3, idfObject.getDouble(EnvironmentalImpactFactorsFields::DistrictCoolingCOP).get()); EXPECT_EQ(0.27, idfObject.getDouble(EnvironmentalImpactFactorsFields::SteamConversionEfficiency).get()); EXPECT_EQ(79.2, idfObject.getDouble(EnvironmentalImpactFactorsFields::TotalCarbonEquivalentEmissionFactorFromN2O).get()); EXPECT_EQ(6.1, idfObject.getDouble(EnvironmentalImpactFactorsFields::TotalCarbonEquivalentEmissionFactorFromCH4).get()); EXPECT_EQ(0.31, idfObject.getDouble(EnvironmentalImpactFactorsFields::TotalCarbonEquivalentEmissionFactorFromCO2).get()); } } TEST_F(EnergyPlusFixture, ReverseTranslator_EnvironmentalImpactFactors) { ReverseTranslator rt; Workspace w(StrictnessLevel::None, IddFileType::EnergyPlus); // Not there, Model shouldn't have it either { Model m = rt.translateWorkspace(w); EXPECT_FALSE(m.getOptionalUniqueModelObject<EnvironmentalImpactFactors>()); } OptionalWorkspaceObject _i_environmentalImpactFactors = w.addObject(IdfObject(IddObjectType::EnvironmentalImpactFactors)); ASSERT_TRUE(_i_environmentalImpactFactors); EXPECT_TRUE(_i_environmentalImpactFactors->setDouble(EnvironmentalImpactFactorsFields::DistrictHeatingEfficiency, 0.35)); EXPECT_TRUE(_i_environmentalImpactFactors->setDouble(EnvironmentalImpactFactorsFields::DistrictCoolingCOP, 3.3)); EXPECT_TRUE(_i_environmentalImpactFactors->setDouble(EnvironmentalImpactFactorsFields::SteamConversionEfficiency, 0.27)); EXPECT_TRUE(_i_environmentalImpactFactors->setDouble(EnvironmentalImpactFactorsFields::TotalCarbonEquivalentEmissionFactorFromN2O, 79.2)); EXPECT_TRUE(_i_environmentalImpactFactors->setDouble(EnvironmentalImpactFactorsFields::TotalCarbonEquivalentEmissionFactorFromCH4, 6.1)); EXPECT_TRUE(_i_environmentalImpactFactors->setDouble(EnvironmentalImpactFactorsFields::TotalCarbonEquivalentEmissionFactorFromCO2, 0.31)); { Model m = rt.translateWorkspace(w); ASSERT_TRUE(m.getOptionalUniqueModelObject<EnvironmentalImpactFactors>()); auto environmentalImpactFactors = m.getUniqueModelObject<EnvironmentalImpactFactors>(); EXPECT_EQ(0.35, environmentalImpactFactors.districtHeatingEfficiency()); EXPECT_EQ(3.3, environmentalImpactFactors.districtCoolingCOP()); EXPECT_EQ(0.27, environmentalImpactFactors.steamConversionEfficiency()); EXPECT_EQ(79.2, environmentalImpactFactors.totalCarbonEquivalentEmissionFactorFromN2O()); EXPECT_EQ(6.1, environmentalImpactFactors.totalCarbonEquivalentEmissionFactorFromCH4()); EXPECT_EQ(0.31, environmentalImpactFactors.totalCarbonEquivalentEmissionFactorFromCO2()); } }
2,219
16,989
<gh_stars>1000+ // Copyright 2021 The Bazel 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. package com.google.devtools.build.lib.rules.cpp; import static com.google.common.truth.Truth.assertThat; import com.google.devtools.build.lib.analysis.ConfiguredTarget; import com.google.devtools.build.lib.analysis.config.CoreOptions; import com.google.devtools.build.lib.analysis.util.BuildViewTestCase; import com.google.devtools.build.lib.packages.util.MockCcSupport; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Unit tests for {@code CcToolchainInputsTransitionFactory}. */ @RunWith(JUnit4.class) public class CcToolchainInputsTransitionFactoryTest extends BuildViewTestCase { @Test public void testExecTransitionForInputsDisabled_usesTargetPlatform() throws Exception { scratch.file( "a/BUILD", "load(':cc_toolchain_config.bzl', 'cc_toolchain_config')", "filegroup(", " name = 'all_files',", " srcs = ['a.txt'],", ")", "cc_toolchain(", " name = 'toolchain',", " all_files = ':all_files',", " ar_files = ':all_files',", " as_files = ':all_files',", " compiler_files = ':all_files',", " compiler_files_without_includes = ':all_files',", " dwp_files = ':all_files',", " linker_files = ':all_files',", " strip_files = ':all_files',", " objcopy_files = ':all_files',", " toolchain_identifier = 'does-not-matter',", " toolchain_config = ':does-not-matter-config',", " exec_transition_for_inputs = False,", ")", "cc_toolchain_config(name = 'does-not-matter-config')"); scratch.file("a/cc_toolchain_config.bzl", MockCcSupport.EMPTY_CC_TOOLCHAIN); ConfiguredTarget toolchainTarget = getConfiguredTarget("//a:toolchain"); assertThat(toolchainTarget).isNotNull(); ConfiguredTarget allFiles = getDirectPrerequisite(toolchainTarget, "//a:all_files"); assertThat(allFiles).isNotNull(); CoreOptions coreOptions = getConfiguration(allFiles).getOptions().get(CoreOptions.class); assertThat(coreOptions).isNotNull(); assertThat(coreOptions.isHost).isFalse(); assertThat(coreOptions.isExec).isFalse(); // if isHost and isExec are false, then allFiles is building for the target platform } @Test public void testExecTransitionForInputsEnabled_usesExecPlatform() throws Exception { scratch.file( "a/BUILD", "load(':cc_toolchain_config.bzl', 'cc_toolchain_config')", "filegroup(", " name = 'all_files',", " srcs = ['a.txt'],", ")", "cc_toolchain(", " name = 'toolchain',", " all_files = ':all_files',", " ar_files = ':all_files',", " as_files = ':all_files',", " compiler_files = ':all_files',", " compiler_files_without_includes = ':all_files',", " dwp_files = ':all_files',", " linker_files = ':all_files',", " strip_files = ':all_files',", " objcopy_files = ':all_files',", " toolchain_identifier = 'does-not-matter',", " toolchain_config = ':does-not-matter-config',", " exec_transition_for_inputs = True,", ")", "cc_toolchain_config(name = 'does-not-matter-config')"); scratch.file("a/cc_toolchain_config.bzl", MockCcSupport.EMPTY_CC_TOOLCHAIN); ConfiguredTarget toolchainTarget = getConfiguredTarget("//a:toolchain"); assertThat(toolchainTarget).isNotNull(); ConfiguredTarget allFiles = getDirectPrerequisite(toolchainTarget, "//a:all_files"); assertThat(allFiles).isNotNull(); CoreOptions coreOptions = getConfiguration(allFiles).getOptions().get(CoreOptions.class); assertThat(coreOptions).isNotNull(); assertThat(coreOptions.isHost).isFalse(); assertThat(coreOptions.isExec).isTrue(); } @Test public void testExecTransitionForInputsDefault_usesExecPlatform() throws Exception { scratch.file( "a/BUILD", "load(':cc_toolchain_config.bzl', 'cc_toolchain_config')", "filegroup(", " name = 'all_files',", " srcs = ['a.txt'],", ")", "cc_toolchain(", " name = 'toolchain',", " all_files = ':all_files',", " ar_files = ':all_files',", " as_files = ':all_files',", " compiler_files = ':all_files',", " compiler_files_without_includes = ':all_files',", " dwp_files = ':all_files',", " linker_files = ':all_files',", " strip_files = ':all_files',", " objcopy_files = ':all_files',", " toolchain_identifier = 'does-not-matter',", " toolchain_config = ':does-not-matter-config',", ")", "cc_toolchain_config(name = 'does-not-matter-config')"); scratch.file("a/cc_toolchain_config.bzl", MockCcSupport.EMPTY_CC_TOOLCHAIN); ConfiguredTarget toolchainTarget = getConfiguredTarget("//a:toolchain"); assertThat(toolchainTarget).isNotNull(); ConfiguredTarget allFiles = getDirectPrerequisite(toolchainTarget, "//a:all_files"); assertThat(allFiles).isNotNull(); CoreOptions coreOptions = getConfiguration(allFiles).getOptions().get(CoreOptions.class); assertThat(coreOptions).isNotNull(); assertThat(coreOptions.isHost).isFalse(); assertThat(coreOptions.isExec).isTrue(); } }
2,448
382
/// generated by: genswift.java 'java/lang|java/util|java/sql|java/awt|javax/swing' /// /// interface java.awt.event.ComponentListener /// package org.swiftjava.java_awt; @SuppressWarnings("JniMissingFunction") public class ComponentListenerProxy implements java.awt.event.ComponentListener { // address of proxy object long __swiftObject; ComponentListenerProxy( long __swiftObject ) { this.__swiftObject = __swiftObject; } /// public abstract void java.awt.event.ComponentListener.componentHidden(java.awt.event.ComponentEvent) public native void __componentHidden( long __swiftObject, java.awt.event.ComponentEvent e ); public void componentHidden( java.awt.event.ComponentEvent e ) { __componentHidden( __swiftObject, e ); } /// public abstract void java.awt.event.ComponentListener.componentMoved(java.awt.event.ComponentEvent) public native void __componentMoved( long __swiftObject, java.awt.event.ComponentEvent e ); public void componentMoved( java.awt.event.ComponentEvent e ) { __componentMoved( __swiftObject, e ); } /// public abstract void java.awt.event.ComponentListener.componentResized(java.awt.event.ComponentEvent) public native void __componentResized( long __swiftObject, java.awt.event.ComponentEvent e ); public void componentResized( java.awt.event.ComponentEvent e ) { __componentResized( __swiftObject, e ); } /// public abstract void java.awt.event.ComponentListener.componentShown(java.awt.event.ComponentEvent) public native void __componentShown( long __swiftObject, java.awt.event.ComponentEvent e ); public void componentShown( java.awt.event.ComponentEvent e ) { __componentShown( __swiftObject, e ); } public native void __finalize( long __swiftObject ); public void finalize() { __finalize( __swiftObject ); } }
635
5,169
{ "name": "NSColorComponents", "version": "1.0.0", "summary": "A Swift extension to NSColor that provides easy access to its RGB and HSB components.", "homepage": "https://github.com/UsabilityEtc/nscolor-components", "license": "MIT", "authors": { "<NAME>": "<EMAIL>" }, "platforms": { "osx": "10.11" }, "source": { "git": "https://github.com/UsabilityEtc/nscolor-components.git", "tag": "1.0.0" }, "source_files": "Sources/*.swift" }
193
582
#!/usr/bin/env python # -*- coding:utf-8 -*- """ Copyright (c) 2014-2016 pocsuite developers (https://seebug.org) See the file 'docs/COPYING' for copying permission """ from pocsuite_cli import modulePath from .lib.core.consoles import PocsuiteInterpreter from .lib.core.data import kb from .lib.core.data import paths from .lib.core.common import setPaths from .lib.core.option import initializeKb def main(): paths.POCSUITE_ROOT_PATH = modulePath() setPaths() kb.unloadedList = {} initializeKb() pcs = PocsuiteInterpreter() pcs.shell_will_go() if __name__ == "__main__": main()
231
2,542
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #pragma once namespace Data { namespace LogRecordLib { // // Const Serialized buffers that never change in the replicator // These are created once by the loggigngreplicator and are passed into the copy stream for them to use when they need to add the copy stage information // class CopyStageBuffers final : public KObject<CopyStageBuffers> , public KShared<CopyStageBuffers> { K_FORCE_SHARED(CopyStageBuffers) public: static CopyStageBuffers::SPtr Create(__in KAllocator & allocator); __declspec(property(get = get_CopyFalseProgressOperation)) KBuffer::SPtr CopyFalseProgressOperation; KBuffer::SPtr get_CopyFalseProgressOperation() const { return copyFalseProgressOperation_; } __declspec(property(get = get_CopyLogOperation)) KBuffer::SPtr CopyLogOperation; KBuffer::SPtr get_CopyLogOperation() const { return copyLogOperation_; } __declspec(property(get = get_CopyProgressVectorOperation)) KBuffer::SPtr CopyProgressVectorOperation; KBuffer::SPtr get_CopyProgressVectorOperation() const { return copyProgressVectorOperation_; } __declspec(property(get = get_CopyStateOperation)) KBuffer::SPtr CopyStateOperation; KBuffer::SPtr get_CopyStateOperation() const { return copyStateOperation_; } private: CopyStageBuffers(__in KAllocator & allocator); KBuffer::SPtr copyFalseProgressOperation_; KBuffer::SPtr copyLogOperation_; KBuffer::SPtr copyProgressVectorOperation_; KBuffer::SPtr copyStateOperation_; }; } }
867
428
<reponame>cping/LGame package loon.opengl.d3d.materials; public class IntAttribute extends Material.Attribute { public static final String CullFaceAlias = "cullface"; public static final long CullFace = register(CullFaceAlias); public static IntAttribute createCullFace(int value) { return new IntAttribute(CullFace, value); } public int value; public IntAttribute(long type) { super(type); } public IntAttribute(long type, int value) { super(type); this.value = value; } @Override public Material.Attribute cpy () { return new IntAttribute(type, value); } @Override protected boolean equals (Material.Attribute other) { return ((IntAttribute)other).value == value; } }
232
704
"""Base Tests.""" from pathlib import Path from unittest import mock def test_imports(): import muffin assert muffin.Request assert muffin.Response assert muffin.ResponseError assert muffin.ResponseFile assert muffin.ResponseHTML assert muffin.ResponseJSON assert muffin.ResponseRedirect assert muffin.ResponseStream assert muffin.ResponseText assert muffin.ASGINotFound assert muffin.ASGIMethodNotAllowed assert muffin.TestClient def test_app(app): assert app assert app.cfg.name == 'muffin' assert repr(app) == '<muffin.Application: muffin>' def test_app_config(): import muffin import os os.environ['TEST_DEBUG'] = 'true' app = muffin.Application('tests.appcfg', config='unknown', name='test') assert app.cfg assert app.cfg.CONFIG == 'tests.appcfg' assert app.cfg.CONFIG_VARIABLE == 42 assert app.cfg.DEBUG is True assert app.cfg.MANAGE_SHELL assert app.cfg.STATIC_URL_PREFIX == '/static' async def test_routing(app, client): import re @app.route('/simple', re.compile('/simple/(a|b|c)/?$'), methods=['GET']) async def test(request): return 200, 'simple' @app.route(r'/parameters/{param1}/{param2}') async def test(request): return 200, request.path_params res = await client.get('/simple') assert res.status_code == 200 assert await res.text() == 'simple' res = await client.post('/404') assert res.status_code == 404 res = await client.post('/simple') assert res.status_code == 405 res = await client.get('/simple/a') assert res.status_code == 200 assert await res.text() == 'simple' res = await client.get('/simple/b/') assert res.status_code == 200 assert await res.text() == 'simple' res = await client.get('/parameters/42/33') assert res.status_code == 200 assert await res.json() == {'param1': '42', 'param2': '33'} @app.route('/trim/last/slash/') async def test(request): return 'OK' res = await client.get('/trim/last/slash/') assert res.status_code == 200 assert await res.text() == 'OK' @app.route('/sync') def sync(request): return 'Sync OK' res = await client.get('/sync') assert res.status_code == 200 assert await res.text() == 'Sync OK' async def test_responses(app, client): @app.route('/none') async def none(request): return None @app.route('/bool') async def none(request): return False @app.route('/str') async def str(request): return 'str' @app.route('/bytes') async def bytes(request): return b'bytes' @app.route('/json') async def json(request): return {'test': 'passed'} res = await client.get('/none') assert res.status_code == 200 assert res.headers['content-type'] == 'application/json' assert await res.json() is None res = await client.get('/bool') assert res.status_code == 200 assert res.headers['content-type'] == 'application/json' assert await res.json() is False res = await client.get('/str') assert res.status_code == 200 assert res.headers['content-type'] == 'text/html; charset=utf-8' assert await res.text() == 'str' res = await client.get('/bytes') assert res.status_code == 200 assert res.headers['content-type'] == 'text/html; charset=utf-8' assert await res.text() == 'bytes' res = await client.get('/json') assert res.status_code == 200 assert res.headers['content-type'] == 'application/json' assert await res.json() == {'test': 'passed'} async def test_websockets(app, client): from muffin import ResponseWebSocket @app.route('/stream') async def stream(request): ws = ResponseWebSocket(request) await ws.accept() msg = await ws.receive() assert msg == 'ping' await ws.send('pong') await ws.close() async with client.websocket('/stream') as ws: await ws.send('ping') msg = await ws.receive() assert msg == 'pong' async def test_middlewares(app, client): @app.middleware async def simple_middleware(app, request, receive, send): response = await app(request, receive, send) if request.path == '/md/simple': response.headers['x-simple'] = 'passed' return response @app.middleware def classic_middleware(app): async def middleware(scope, receive, send): async def custom_send(msg): if scope['path'] == '/md/classic' and msg['type'] == 'http.response.start': msg['headers'].append((b'x-classic', b'passed')) await send(msg) await app(scope, receive, custom_send) return middleware @app.route('/md/simple') async def simple(request): return 200, @app.route('/md/classic') async def classic(request): return 200, res = await client.get('/') assert res.status_code == 200 assert not res.headers.get('x-simple') assert not res.headers.get('x-classic') res = await client.get('/md/simple') assert res.status_code == 200 assert res.headers['x-simple'] == 'passed' assert not res.headers.get('x-classic') res = await client.get('/md/classic') assert res.status_code == 200 assert not res.headers.get('x-simple') assert res.headers['x-classic'] == 'passed' async def test_lifespan(app): import muffin start, finish = mock.MagicMock(), mock.MagicMock() app.on_startup(start) app.on_shutdown(finish) client = muffin.TestClient(app) async with client.lifespan(): assert start.called assert not finish.called res = await client.get('/') assert res.status_code == 200 assert start.called assert finish.called def test_configure_logging(): import muffin dummy = {'dummy': 'dict', 'version': 1} with mock.patch('logging.config.dictConfig') as mocked: app = muffin.Application('muffin', LOG_CONFIG=dummy) assert app.logger assert app.logger.handlers mocked.assert_called_once_with(dummy) async def test_static_folders(): import muffin app = muffin.Application( static_folders=['tests', Path(__file__).parent.parent], static_url_prefix='/assets') assert app.cfg.STATIC_FOLDERS assert app.cfg.STATIC_URL_PREFIX == '/assets' @app.route('/') async def index(request): return 'OK' client = muffin.TestClient(app) res = await client.get('/') assert res.status_code == 200 res = await client.get('/assets/test_application.py') assert res.status_code == 200 text = await res.text() assert text.startswith('"""Base Tests."""') res = await client.get('/assets/setup.cfg') assert res.status_code == 200 async def test_error_handlers(client, app): import muffin @app.route('/500') async def raise_500(request): raise muffin.ResponseError(500) @app.route('/unhandled') async def raise_unhandled(request): raise Exception() @app.on_error(muffin.ResponseError) async def handler(request, exc): return 'Custom Server Error' @app.on_error(404) async def handler_404(request, exc): return 'Custom 404' @app.on_error(Exception) async def handle_exception(request, exc): return 'Custom Unhandled' assert app.exception_handlers res = await client.get('/unhandled') assert res.status_code == 200 assert await res.text() == 'Custom Unhandled' res = await client.get('/500') assert res.status_code == 200 assert await res.text() == 'Custom Server Error' res = await client.get('/404') assert res.status_code == 200 assert await res.text() == 'Custom 404' del app.exception_handlers[404] del app.exception_handlers[muffin.ResponseError] async def test_nested(client, app): @app.middleware async def mid(app, req, receive, send): response = await app(req, receive, send) response.headers['x-app'] = 'OK' return response from muffin import Application subapp = Application() @subapp.route('/route') def subroute(request): return 'OK from subroute' @subapp.middleware async def mid(app, req, receive, send): response = await app(req, receive, send) response.headers['x-subapp'] = 'OK' return response app.route('/sub')(subapp) res = await client.get('/sub/route') assert res.status_code == 200 assert await res.text() == 'OK from subroute' assert res.headers['x-app'] == 'OK' assert res.headers['x-subapp'] == 'OK'
3,447
348
{"nom":"Villelongue-de-la-Salanque","circ":"2ème circonscription","dpt":"Pyrénées-Orientales","inscrits":2405,"abs":1199,"votants":1206,"blancs":18,"nuls":4,"exp":1184,"res":[{"nuance":"FN","nom":"<NAME>","voix":355},{"nuance":"MDM","nom":"Mme <NAME>","voix":336},{"nuance":"LR","nom":"M. <NAME>","voix":136},{"nuance":"FI","nom":"Mme <NAME>","voix":133},{"nuance":"SOC","nom":"Mme <NAME>","voix":46},{"nuance":"COM","nom":"M. <NAME>","voix":40},{"nuance":"REG","nom":"M. <NAME>","voix":40},{"nuance":"DLF","nom":"Mme <NAME>","voix":21},{"nuance":"EXG","nom":"M. <NAME>","voix":18},{"nuance":"ECO","nom":"M. <NAME>","voix":16},{"nuance":"DIV","nom":"M. <NAME>","voix":16},{"nuance":"REG","nom":"<NAME>","voix":13},{"nuance":"ECO","nom":"Mme <NAME>","voix":8},{"nuance":"DIV","nom":"M. <NAME>","voix":6}]}
330
450
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*------------------------------------------------------------------------- * * gpcheckhdfs.c * * This file mainly provide functionalities to check status of * HDFS cluster when: * 1. doing HAWQ cluster initialization; * 2. monitoring HDFS cluster health manually. * * It uses libhdfs to communicate with HDFS. * *------------------------------------------------------------------------- */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <grp.h> #include <pwd.h> #include <sys/types.h> #include <unistd.h> #include "krb5/krb5.h" #include "hdfs/hdfs.h" /* * Check Error Code */ #define GPCHKHDFS_ERR 1 #define CONNECT_ERR 100 #define OPENFILE_ERR 101 #define WRITEFILE_ERR 102 #define FLUSH_ERR 103 #define DELETE_ERR 104 #define DFSDIR_ERR 105 #define GETTOKEN_ERR 106 #define KRBLOGIN_ERR 107 #define DIRECTORY_ERR 108 #define TRASH_DIRECTORY_NAME ".Trash" char * conncat(const char * dfs_name, const char * dfs_url); void getHostAndPort(const char * dfs_url, char * host, char * port); /* * test whether hdfs can be connected while kerberos is on or not */ int testHdfsConnect(hdfsFS * fs, const char * host, int port, const char * krbstatus, const char * krb_srvname, const char * krb_keytabfile); /* * test whether the filepath which dfs_url defined in hdfs is existed or not. * Note: if tde_keyname is not NULL, create an encryption zone on filepath by this key. */ int testHdfsExisted(hdfsFS fs, const char * filepath, const char * dfscompleteurl, const char * tde_keyname); /* * test whether basic file operation in hdfs is worked well or not */ int testHdfsOperateFile(hdfsFS fs, const char * filepath, const char * dfscompleteurl); int main(int argc, char * argv[]) { /* * argv will read from conf * argv[1]:dfs_name * argv[2]:dfs_url * argv[3]:krb status * argv[4]:krb service name * argv[5]:krb keytab file * argv[6]:--with-tde * argv[7]:tde encryption zone key name */ if (argc < 3 || argc > 8 || ((argc == 4 || argc == 5) && 0 != strcasecmp(argv[3], "off") && 0 != strcasecmp(argv[3], "false"))) { fprintf(stderr, "ERROR: gpcheckhdfs parameter error, Please check your config file\n" "\tDFS_NAME and DFS_URL are required, KERBEROS_SERVICENAME, KERBEROS_KEYFILE " "ENABLE_SECURE_FILESYSTEM and TDE_KeyName are optional\n"); return GPCHKHDFS_ERR; } char * dfs_name = argv[1]; char * dfs_url = argv[2]; char * krbstatus = NULL; char * krb_srvname = NULL; char * krb_keytabfile = NULL; char * tde_keyname = NULL; if (argc >= 4) { krbstatus = argv[3]; } if (argc >= 6) { krb_srvname = argv[4]; krb_keytabfile = argv[5]; } //get tde key name param //to avoid the empty param's influences before it, use loop find for (int i = 1; i < argc; i++) { if (strcmp(argv[i], "--with-tde") == 0 && i+1 < argc) tde_keyname = argv[i+1]; } char * host = (char *)malloc(255 * sizeof(char)); char * port = (char *)malloc(5 * sizeof(char)); getHostAndPort(dfs_url, host, port); int iPort = atoi(port); if (iPort < 0) { fprintf(stderr, "ERROR: Invalid NameNode Port, Please Check\n"); return CONNECT_ERR; } hdfsFS fs; int connErrCode = testHdfsConnect(&fs, host, iPort, krbstatus, krb_srvname, krb_keytabfile); if (connErrCode) { return connErrCode; } char * filename = "/testFile"; char * dfscompleteurl = conncat(dfs_name, dfs_url); char * filepath = strchr(dfs_url, '/'); if (!filepath) { fprintf(stderr,"ERROR: argv[2] does not contain '/'"); return DIRECTORY_ERR; } /* * check hdfs's directory configured in dfs_url * such as sdw2:8020/gpsql/,the filepath is /gpsql * */ int checkdirErrCode = testHdfsExisted(fs, filepath, dfscompleteurl, tde_keyname); if (checkdirErrCode) { return checkdirErrCode; } // hawq init should not wait until datanode is ready //strcat(filepath, filename); //int operateErrCode = testHdfsOperateFile(fs, filepath, dfscompleteurl); //if (operateErrCode) { // return operateErrCode; //} free(host); free(port); return 0; } int testHdfsOperateFile(hdfsFS fs, const char * filepath, const char * dfscompleteurl) { hdfsFile testFile = hdfsOpenFile(fs, filepath, O_CREAT, 0, 0, 0); if (NULL == testFile) { fprintf(stderr, "ERROR:'hdfsOpenFile' failed to create file %s\n", dfscompleteurl); return OPENFILE_ERR; } char * testbuff = "Test file...."; int ts = hdfsWrite(fs, testFile, testbuff, strlen(testbuff)); if (ts < 0) { fprintf(stderr, "ERROR:'hdfsWrite' failed to write to file %s\n", dfscompleteurl); return WRITEFILE_ERR; } int rv = hdfsHFlush(fs, testFile); if (rv < 0) { fprintf(stderr, "ERROR:'hdfsHFlush' failed to flush file\n"); return FLUSH_ERR; } rv = hdfsCloseFile(fs, testFile); if (rv < 0) { fprintf(stderr, "ERROR:'hdfsClose' failed to close file\n"); return FLUSH_ERR; } rv = hdfsDelete(fs, filepath, 0); if (rv < 0) { fprintf(stderr, "ERROR:'hdfsDelete' failed to delete %s\n", dfscompleteurl); return DELETE_ERR; } return 0; } int testHdfsConnect(hdfsFS * fsptr, const char * host, int iPort, const char * krbstatus, const char * krb_srvname, const char * krb_keytabfile) { struct hdfsBuilder * builder = hdfsNewBuilder(); hdfsBuilderSetNameNode(builder, host); if (iPort > 0) hdfsBuilderSetNameNodePort(builder, iPort); if (NULL != krbstatus && NULL != krb_keytabfile && (!strcasecmp(krbstatus, "on") || !strcasecmp(krbstatus, "true"))) { //Kerberos if On char * krb5_ccname = "/tmp/postgres.ccname"; char cmd[1024]; snprintf(cmd, sizeof(cmd), "kinit -k -t %s -c %s %s", krb_keytabfile, krb5_ccname, krb_srvname); if (system(cmd)) { fprintf(stderr, "ERROR: Failed to login to Kerberos, command line: '%s'\n", cmd); return KRBLOGIN_ERR; } hdfsBuilderSetKerbTicketCachePath(builder, krb5_ccname); *fsptr = hdfsBuilderConnect(builder); if (NULL == (*fsptr)) { if (iPort > 0) fprintf(stderr, "ERROR: (None HA) Can not connect to 'hdfs://%s:%d'\n", host, iPort); else fprintf(stderr, "ERROR: (HA) Can not connect to 'hdfs://%s'\n", host); fprintf(stderr, "Please check your HDFS or hdfs-client.xml in ${GPHOME}/etc\n"); return CONNECT_ERR; } hdfsFreeBuilder(builder); char * token = hdfsGetDelegationToken((*fsptr), krb_srvname); if (NULL == token) { fprintf(stderr, "ERROR: Get Delegation Token Error\n"); return GETTOKEN_ERR; } builder = hdfsNewBuilder(); hdfsBuilderSetNameNode(builder, host); if (iPort > 0) hdfsBuilderSetNameNodePort(builder, iPort); hdfsBuilderSetToken(builder, token); } *fsptr = hdfsBuilderConnect(builder); if (NULL == (*fsptr)) { fprintf(stderr, "ERROR: Can not connect to 'hdfs://%s:%d'\n", host, iPort); return CONNECT_ERR; } hdfsFreeBuilder(builder); return 0; } /* * check path is a trash directory * path, e.g: /hawq_default/.Trash */ static int isTrashDirectory(const char *path) { if (path == NULL) return 0; size_t len = strlen(TRASH_DIRECTORY_NAME); size_t path_len = strlen(path); if (path_len <= len) return 0; return strncmp(path+path_len-len, TRASH_DIRECTORY_NAME, len+1) == 0; } int testHdfsExisted(hdfsFS fs, const char * filepath, const char * dfscompleteurl, const char * tde_keyname) { int notExisted = hdfsExists(fs, filepath); if (notExisted) { fprintf(stderr, "WARNING:'%s' does not exist, create it ...\n", dfscompleteurl); int rv = hdfsCreateDirectory(fs, filepath); if (rv < 0) { fprintf(stderr, "ERROR: failed to create directory %s\n", dfscompleteurl); return DFSDIR_ERR; } } else { int num = 0; hdfsFileInfo * fi = hdfsListDirectory(fs, filepath, &num); if (NULL == fi || num > 1 || (num == 1 && !isTrashDirectory(fi[0].mName)) /* skip Trash directory */ ) { fprintf(stderr, "ERROR: failed to list directory %s or it is not empty\n" "Please Check your filepath before doing HAWQ cluster initialization.\n", dfscompleteurl); return DFSDIR_ERR; } } if (tde_keyname != NULL && strlen(tde_keyname) > 0) { int ret = hdfsCreateEncryptionZone(fs, filepath, tde_keyname); if (ret != 0) { fprintf(stderr, "ERROR: create encryption zone on directory %s failed, key_name:%s.\n", dfscompleteurl, tde_keyname); return DFSDIR_ERR; } } return 0; } char * conncat(const char * dfs_name, const char * dfs_url) { const char * colon = "://"; int strlength = strlen(dfs_name) + strlen(dfs_url) + strlen(colon) + 1; char * dfsurl = (char *)malloc(strlength * sizeof(char)); strcpy(dfsurl, dfs_name); strcat(dfsurl, colon); strcat(dfsurl, dfs_url); return dfsurl; } void getHostAndPort(const char * dfs_url, char * host, char * port) { char * colonPos = strchr(dfs_url , ':'); char * spritPos = NULL; if (colonPos != NULL) { //None HA url case int hostlength = colonPos - dfs_url; strncpy(host , dfs_url , hostlength); *(host + hostlength) = '\0'; char * remainPtr = colonPos + 1; spritPos = strchr(remainPtr , '/'); int portlength = spritPos - remainPtr; strncpy(port , remainPtr , portlength); *(port + portlength) = '\0'; } else { // HA url case spritPos = strchr(dfs_url , '/'); int nServicelength = spritPos - dfs_url; strncpy(host, dfs_url, nServicelength); *(host + nServicelength) = '\0'; *port = '\0'; } }
4,891
640
#ifndef __MICROC_H__ #define __MICROC_H__ /* * <NAME> Systems Micro C compatibility lib */ #include <stdlib.h> #include <fcntl.h> #include <ctype.h> #include <setjmp.h> #include <string.h> #include <time.h> #include <sound.h> #include <math.h> #undef abort #define abort(a) exit(puts_cons(a)&0) #define getstr(s,l) fgets_cons(s,l) #define putstr(s) puts_cons(s) #define fget(buf,size,fd) read(fd, buf, size); #define fput(buf,size,fd) write(fd, buf, size); #define atox(ptr) stroul(ptr,NULL,16) #define beep(freq, duration) bit_frequency(duration, frequency) #define RAND_SEED std_seed #define random(a) rand()%a #define get_time(a,b,c) *a=(clock()/CLOCKS_PER_SEC*3600); *b=(clock()/CLOCKS_PER_SEC*60); *c=(clock()/CLOCKS_PER_SEC) #endif
358
336
from pythonforandroid.recipe import PythonRecipe class PycryptodomeXRecipe(PythonRecipe): version = '3.6.3' url = ('https://files.pythonhosted.org/packages/e6/5a/' 'cf2bd33574f8f8711bad12baee7ef5c9c53a09c338cec241abfc0ba0cf63/' 'pycryptodomex-3.6.3.tar.gz') md5sum = 'ed1dc06ca4ba6a058ef47db56462234f' depends = ['setuptools', 'cffi'] recipe = PycryptodomeXRecipe()
197
537
<reponame>wangxuan-cn/SMSGate // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2012.08.30 at 11:39:15 AM CEST // package es.rickyepoderi.wbxml.bind.syncml; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "target", "source", "meta", "data", "moreData" }) @XmlRootElement(name = "Item", namespace="SYNCML:SYNCML1.1") public class Item { @XmlElement(name = "Target", namespace="SYNCML:SYNCML1.1") protected Target target; @XmlElement(name = "Source", namespace="SYNCML:SYNCML1.1") protected Source source; @XmlElement(name = "Meta", namespace="SYNCML:SYNCML1.1") protected Meta meta; @XmlElement(name = "Data", namespace="SYNCML:SYNCML1.1") protected String data; @XmlElement(name = "MoreData", namespace="SYNCML:SYNCML1.1") protected MoreData moreData; /** * Gets the value of the target property. * * @return * possible object is * {@link Target } * */ public Target getTarget() { return target; } /** * Sets the value of the target property. * * @param value * allowed object is * {@link Target } * */ public void setTarget(Target value) { this.target = value; } /** * Gets the value of the source property. * * @return * possible object is * {@link Source } * */ public Source getSource() { return source; } /** * Sets the value of the source property. * * @param value * allowed object is * {@link Source } * */ public void setSource(Source value) { this.source = value; } /** * Gets the value of the meta property. * * @return * possible object is * {@link Meta } * */ public Meta getMeta() { return meta; } /** * Sets the value of the meta property. * * @param value * allowed object is * {@link Meta } * */ public void setMeta(Meta value) { this.meta = value; } /** * Gets the value of the data property. * * @return * possible object is * {@link String } * */ public String getData() { return data; } /** * Sets the value of the data property. * * @param value * allowed object is * {@link String } * */ public void setData(String value) { this.data = value; } /** * Gets the value of the moreData property. * * @return * possible object is * {@link MoreData } * */ public MoreData getMoreData() { return moreData; } /** * Sets the value of the moreData property. * * @param value * allowed object is * {@link MoreData } * */ public void setMoreData(MoreData value) { this.moreData = value; } }
1,619
335
<gh_stars>100-1000 { "word": "Microscopic", "definitions": [ "So small as to be visible only with a microscope.", "Extremely small.", "Concerned with minute detail.", "Relating to a microscope." ], "parts-of-speech": "Adjective" }
117
1,682
/* Copyright (c) 2012 LinkedIn Corp. 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. */ /** * $Id: $ */ package com.linkedin.restli.common; /** * @author <NAME> * @version $Revision: $ */ public enum HttpMethod { GET (true, true), PUT (false, true), POST (false, false), DELETE (false, true), OPTIONS (true, true), HEAD (true, true), TRACE (true, true); HttpMethod(boolean safe, boolean idempotent) { _safe = safe; _idempotent = idempotent; } /** * Determine whether this HTTP method is safe, as defined in RFC 2616 * * 9.1.1 Safe Methods * Implementors should be aware that the software represents the user in their interactions over the Internet, and * should be careful to allow the user to be aware of any actions they might take which may have an unexpected * significance to themselves or others. * * In particular, the convention has been established that the GET and HEAD methods SHOULD NOT have the significance * of taking an action other than retrieval. These methods ought to be considered "safe". This allows user agents to * represent other methods, such as POST, PUT and DELETE, in a special way, so that the user is made aware of the * fact that a possibly unsafe action is being requested. * * Naturally, it is not possible to ensure that the server does not generate side-effects as a result of performing * a GET request; in fact, some dynamic resources consider that a feature. The important distinction here is that * the user did not request the side-effects, so therefore cannot be held accountable for them. * * @return a boolean */ public boolean isSafe() { return _safe; } /** * Determine whether this HTTP method is idempotent, as defined in RFC 2616 * * 9.1.2 Idempotent Methods * * Methods can also have the property of "idempotence" in that (aside from error or expiration issues) the * side-effects of N > 0 identical requests is the same as for a single request. The methods GET, HEAD, PUT and * DELETE share this property. Also, the methods OPTIONS and TRACE SHOULD NOT have side effects, and so are * inherently idempotent. * * However, it is possible that a sequence of several requests is non- idempotent, even if all of the methods executed * in that sequence are idempotent. (A sequence is idempotent if a single execution of the entire sequence always * yields a result that is not changed by a reexecution of all, or part, of that sequence.) For example, a sequence is * non-idempotent if its result depends on a value that is later modified in the same sequence. * * A sequence that never has side effects is idempotent, by definition (provided that no concurrent operations are * being executed on the same set of resources). * * @return a boolean */ public boolean isIdempotent() { return _idempotent; } private boolean _safe; private boolean _idempotent; }
1,020
1,007
<reponame>cjztool/btrace /* * Copyright (C) 2021 ByteDance 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. */ #include "utils/timers.h" #include <time.h> #if defined(__linux__) nsecs_t systemTime(int clock) { static const clockid_t clocks[] = { CLOCK_REALTIME, CLOCK_MONOTONIC, CLOCK_PROCESS_CPUTIME_ID, CLOCK_THREAD_CPUTIME_ID, CLOCK_BOOTTIME }; struct timespec t; t.tv_sec = t.tv_nsec = 0; clock_gettime(clocks[clock], &t); return nsecs_t(t.tv_sec)*1000000000LL + t.tv_nsec; } #else nsecs_t systemTime(int /*clock*/) { // Clock support varies widely across hosts. Mac OS doesn't support // CLOCK_BOOTTIME, and Windows is windows. struct timeval t; t.tv_sec = t.tv_usec = 0; gettimeofday(&t, nullptr); return nsecs_t(t.tv_sec)*1000000000LL + nsecs_t(t.tv_usec)*1000LL; } #endif /* * native public static long uptimeMillis(); */ int64_t uptimeMillis() { int64_t when = systemTime(SYSTEM_TIME_MONOTONIC); return (int64_t) nanoseconds_to_milliseconds(when); } /* * native public static long elapsedRealtimeMillis(); */ int64_t elapsedRealtimeMillis() { int64_t when = systemTime(SYSTEM_TIME_BOOTTIME); return (int64_t) nanoseconds_to_milliseconds(when); } /* * native public static long elapsedRealtimeMillis(); */ int64_t elapsedRealtimeMicros() { int64_t when = systemTime(SYSTEM_TIME_BOOTTIME); return (int64_t) nanoseconds_to_microseconds(when); }
711
14,668
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_PASSWORDS_MANAGE_PASSWORDS_TEST_H_ #define CHROME_BROWSER_UI_PASSWORDS_MANAGE_PASSWORDS_TEST_H_ #include <memory> #include <vector> #include "base/metrics/histogram_samples.h" #include "base/test/metrics/histogram_tester.h" #include "chrome/test/base/in_process_browser_test.h" #include "components/autofill/core/common/form_data.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "components/password_manager/core/browser/fake_form_fetcher.h" #include "components/password_manager/core/browser/password_form.h" #include "components/password_manager/core/browser/stub_password_manager_client.h" #include "components/password_manager/core/browser/stub_password_manager_driver.h" #include "components/password_manager/core/common/credential_manager_types.h" #include "testing/gmock/include/gmock/gmock.h" class ManagePasswordsUIController; // Test class for the various password management view bits and pieces. Provides // some helper methods to poke at the bubble, icon, and controller's state. class ManagePasswordsTest : public InProcessBrowserTest { public: ManagePasswordsTest(); ManagePasswordsTest(const ManagePasswordsTest&) = delete; ManagePasswordsTest& operator=(const ManagePasswordsTest&) = delete; ~ManagePasswordsTest() override; // InProcessBrowserTest: void SetUpOnMainThread() override; void SetUpInProcessBrowserTestFixture() override; // Execute the browser command to open the manage passwords bubble. void ExecuteManagePasswordsCommand(); // Put the controller, icon, and bubble into a managing-password state. void SetupManagingPasswords(); // Put the controller, icon, and bubble into the confirmation state. void SetupAutomaticPassword(); // Put the controller, icon, and bubble into a pending-password state. void SetupPendingPassword(); // Put the controller, icon, and bubble into an auto sign-in state. void SetupAutoSignin( std::vector<std::unique_ptr<password_manager::PasswordForm>> local_credentials); // Put the controller, icon, and bubble into the state with 0 compromised // passwords saved. void SetupSafeState(); // Put the controller, icon, and bubble into the "More problems to fix" state. void SetupMoreToFixState(); // Put the controller, icon, and bubble into a moving-password state. void SetupMovingPasswords(); // Get samples for |histogram|. std::unique_ptr<base::HistogramSamples> GetSamples(const char* histogram); password_manager::PasswordForm* test_form() { return &password_form_; } // Get the UI controller for the current WebContents. ManagePasswordsUIController* GetController(); MOCK_METHOD1(OnChooseCredential, void(const password_manager::CredentialInfo&)); private: std::unique_ptr<password_manager::PasswordFormManager> CreateFormManager(); password_manager::PasswordForm password_form_; password_manager::PasswordForm federated_form_; autofill::FormData observed_form_; autofill::FormData submitted_form_; base::HistogramTester histogram_tester_; password_manager::StubPasswordManagerClient client_; password_manager::StubPasswordManagerDriver driver_; password_manager::FakeFormFetcher fetcher_; base::CallbackListSubscription create_services_subscription_; }; #endif // CHROME_BROWSER_UI_PASSWORDS_MANAGE_PASSWORDS_TEST_H_
1,077
575
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/arc/bluetooth/bluetooth_mojom_traits.h" #include <initializer_list> #include <map> #include <string> #include <utility> #include <vector> #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "device/bluetooth/bluetooth_advertisement.h" #include "device/bluetooth/public/cpp/bluetooth_uuid.h" namespace { // BluetoothUUID helpers. constexpr size_t kUUIDSize = 16; // BluetoothAdvertisement helpers. struct AdvertisementEntry { virtual ~AdvertisementEntry() {} virtual void AddTo(device::BluetoothAdvertisement::Data* data) {} }; struct ServiceUUID16Entry : public AdvertisementEntry { std::vector<uint16_t> service_uuids_16; ~ServiceUUID16Entry() override {} void AddTo(device::BluetoothAdvertisement::Data* data) override { auto string_uuids = data->service_uuids(); if (string_uuids == nullptr) string_uuids = std::make_unique<std::vector<std::string>>(); for (const auto& uuid : service_uuids_16) { string_uuids->emplace_back(base::StringPrintf("%04x", uuid)); } data->set_service_uuids(std::move(string_uuids)); } }; struct ServiceUUIDEntry : public AdvertisementEntry { std::vector<device::BluetoothUUID> service_uuids; ~ServiceUUIDEntry() override {} void AddTo(device::BluetoothAdvertisement::Data* data) override { auto string_uuids = data->service_uuids(); if (string_uuids == nullptr) string_uuids = std::make_unique<std::vector<std::string>>(); for (const auto& uuid : service_uuids) { string_uuids->emplace_back(uuid.value()); } data->set_service_uuids(std::move(string_uuids)); } }; struct ServiceDataEntry : public AdvertisementEntry { uint16_t service_uuid; std::vector<uint8_t> service_data; ~ServiceDataEntry() override {} void AddTo(device::BluetoothAdvertisement::Data* data) override { std::string string_uuid = base::StringPrintf("%04x", service_uuid); using MapType = std::map<std::string, std::vector<uint8_t>>; data->set_service_data( std::make_unique<MapType, std::initializer_list<MapType::value_type>>( {{string_uuid, service_data}})); } }; struct ManufacturerDataEntry : public AdvertisementEntry { uint16_t company_id_code; std::vector<uint8_t> blob; ~ManufacturerDataEntry() override {} void AddTo(device::BluetoothAdvertisement::Data* data) override { using MapType = std::map<uint16_t, std::vector<uint8_t>>; data->set_manufacturer_data( std::make_unique<MapType, std::initializer_list<MapType::value_type>>( {{company_id_code, blob}})); } }; uint16_t ExtractCompanyIdentifierCode(std::vector<uint8_t>* blob) { // The company identifier code is in little-endian. uint16_t company_id_code = (*blob)[1] << 8 | (*blob)[0]; blob->erase(blob->begin(), blob->begin() + sizeof(uint16_t)); return company_id_code; } } // namespace namespace mojo { // static std::vector<uint8_t> StructTraits<arc::mojom::BluetoothUUIDDataView, device::BluetoothUUID>::uuid( const device::BluetoothUUID& input) { // TODO(dcheng): Figure out what to do here, this is called twice on // serialization. Building a vector is a little inefficient. return input.GetBytes(); } // static bool StructTraits<arc::mojom::BluetoothUUIDDataView, device::BluetoothUUID>::Read(arc::mojom::BluetoothUUIDDataView data, device::BluetoothUUID* output) { std::vector<uint8_t> address_bytes; if (!data.ReadUuid(&address_bytes)) return false; if (address_bytes.size() != kUUIDSize) return false; // BluetoothUUID expects the format below with the dashes inserted. // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx std::string uuid_str = base::HexEncode(address_bytes.data(), address_bytes.size()); constexpr size_t kUuidDashPos[] = {8, 13, 18, 23}; for (auto pos : kUuidDashPos) uuid_str = uuid_str.insert(pos, "-"); device::BluetoothUUID result(uuid_str); DCHECK(result.IsValid()); *output = result; return true; } template <> struct EnumTraits<arc::mojom::BluetoothAdvertisementType, device::BluetoothAdvertisement::AdvertisementType> { static bool FromMojom( arc::mojom::BluetoothAdvertisementType mojom_type, device::BluetoothAdvertisement::AdvertisementType* type) { switch (mojom_type) { case arc::mojom::BluetoothAdvertisementType::ADV_TYPE_CONNECTABLE: case arc::mojom::BluetoothAdvertisementType::ADV_TYPE_SCANNABLE: *type = device::BluetoothAdvertisement::ADVERTISEMENT_TYPE_PERIPHERAL; return true; case arc::mojom::BluetoothAdvertisementType::ADV_TYPE_NON_CONNECTABLE: *type = device::BluetoothAdvertisement::ADVERTISEMENT_TYPE_BROADCAST; return true; } NOTREACHED() << "Invalid type: " << static_cast<uint32_t>(mojom_type); return false; } }; template <> struct StructTraits<arc::mojom::BluetoothServiceDataDataView, ServiceDataEntry> { static bool Read(arc::mojom::BluetoothServiceDataDataView data, ServiceDataEntry* output) { output->service_uuid = data.uuid_16bit(); return data.ReadData(&output->service_data); } }; template <> struct UnionTraits<arc::mojom::BluetoothAdvertisingDataDataView, std::unique_ptr<AdvertisementEntry>> { static bool Read(arc::mojom::BluetoothAdvertisingDataDataView data, std::unique_ptr<AdvertisementEntry>* output) { switch (data.tag()) { case arc::mojom::BluetoothAdvertisingDataDataView::Tag:: SERVICE_UUIDS_16: { std::unique_ptr<ServiceUUID16Entry> service_uuids_16 = std::make_unique<ServiceUUID16Entry>(); if (!data.ReadServiceUuids16(&service_uuids_16->service_uuids_16)) return false; *output = std::move(service_uuids_16); break; } case arc::mojom::BluetoothAdvertisingDataDataView::Tag::SERVICE_UUIDS: { std::unique_ptr<ServiceUUIDEntry> service_uuids = std::make_unique<ServiceUUIDEntry>(); if (!data.ReadServiceUuids(&service_uuids->service_uuids)) return false; *output = std::move(service_uuids); break; } case arc::mojom::BluetoothAdvertisingDataDataView::Tag::SERVICE_DATA: { std::unique_ptr<ServiceDataEntry> service_data = std::make_unique<ServiceDataEntry>(); if (!data.ReadServiceData(service_data.get())) return false; *output = std::move(service_data); break; } case arc::mojom::BluetoothAdvertisingDataDataView::Tag:: MANUFACTURER_DATA: { std::unique_ptr<ManufacturerDataEntry> manufacturer_data = std::make_unique<ManufacturerDataEntry>(); // We get manufacturer data as a big blob. The first two bytes // should be a company identifier code and the rest is manufacturer- // specific. std::vector<uint8_t> blob; if (!data.ReadManufacturerData(&blob)) return false; if (blob.size() < sizeof(uint16_t)) { LOG(WARNING) << "Advertisement had malformed manufacturer data"; return false; } manufacturer_data->company_id_code = ExtractCompanyIdentifierCode(&blob); manufacturer_data->blob = std::move(blob); *output = std::move(manufacturer_data); break; } default: { LOG(WARNING) << "Bluetooth advertising data case not implemented"; // Default AdvertisementEntry does nothing when added to the // device::BluetoothAdvertisement::AdvertisementData, so data we // don't know how to handle yet will be dropped but won't cause a // failure to deserialize. *output = std::make_unique<AdvertisementEntry>(); break; } } return true; } }; // static bool StructTraits<arc::mojom::BluetoothAdvertisementDataView, std::unique_ptr<device::BluetoothAdvertisement::Data>>:: Read(arc::mojom::BluetoothAdvertisementDataView advertisement, std::unique_ptr<device::BluetoothAdvertisement::Data>* output) { device::BluetoothAdvertisement::AdvertisementType adv_type; if (!advertisement.ReadType(&adv_type)) return false; auto data = std::make_unique<device::BluetoothAdvertisement::Data>(adv_type); std::vector<std::unique_ptr<AdvertisementEntry>> adv_entries; if (!advertisement.ReadData(&adv_entries)) return false; for (const auto& adv_entry : adv_entries) adv_entry->AddTo(data.get()); data->set_include_tx_power(advertisement.include_tx_power()); *output = std::move(data); return true; } } // namespace mojo
3,448
1,511
/*************************************************************** * Project: * CPLD SlaveSerial Configuration via embedded microprocessor. * * Copyright info: * * This is free software; you can redistribute it and/or modify * it as you like. * * 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. * ****************************************************************/
122
313
<reponame>gabrielfougeron/SuiteSparse //------------------------------------------------------------------------------ // GB_AxB_saxpy3_symbolic: symbolic analysis for GB_AxB_saxpy3 //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, <NAME>, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // Symbolic analysis for C=A*B, C<M>=A*B or C<!M>=A*B, via GB_AxB_saxpy3. // Coarse tasks compute nnz (C (:,j)) for each of their vectors j. Fine tasks // just scatter the mask M into the hash table. This phase does not depend on // the semiring, nor does it depend on the type of C, A, or B. It does access // the values of M, if the mask matrix M is present and not structural. // If B is hypersparse, C must also be hypersparse. // Otherwise, C must be sparse. // If both A and B are bitmap/full for C=A*B or C<!M>=A*B, then saxpy3 is // not used. C is selected as bitmap instead. #include "GB_AxB_saxpy3.h" void GB_AxB_saxpy3_symbolic ( GrB_Matrix C, // Cp is computed for coarse tasks const GrB_Matrix M, // mask matrix M const bool Mask_comp, // M complemented, or not const bool Mask_struct, // M structural, or not const bool M_in_place, const GrB_Matrix A, // A matrix; only the pattern is accessed const GrB_Matrix B, // B matrix; only the pattern is accessed GB_saxpy3task_struct *SaxpyTasks, // list of tasks, and workspace const int ntasks, // total number of tasks const int nfine, // number of fine tasks const int nthreads // number of threads ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- ASSERT (!GB_ZOMBIES (M)) ; ASSERT (GB_JUMBLED_OK (M)) ; ASSERT (!GB_PENDING (M)) ; ASSERT (!GB_ZOMBIES (A)) ; ASSERT (GB_JUMBLED_OK (A)) ; ASSERT (!GB_PENDING (A)) ; ASSERT (!GB_ZOMBIES (B)) ; ASSERT (GB_JUMBLED_OK (B)) ; ASSERT (!GB_PENDING (B)) ; const bool A_is_sparse = GB_IS_SPARSE (A) ; const bool A_is_hyper = GB_IS_HYPERSPARSE (A) ; const bool A_is_bitmap = GB_IS_BITMAP (A) ; const bool B_is_sparse = GB_IS_SPARSE (B) ; const bool B_is_hyper = GB_IS_HYPERSPARSE (B) ; const bool B_is_bitmap = GB_IS_BITMAP (B) ; //========================================================================== // phase1: count nnz(C(:,j)) for coarse tasks, scatter M for fine tasks //========================================================================== if (M == NULL) { //---------------------------------------------------------------------- // C = A*B //---------------------------------------------------------------------- if (A_is_sparse) { if (B_is_sparse) { // both A and B are sparse GB_AxB_saxpy3_sym_ss (C, A, B, SaxpyTasks, ntasks, nfine, nthreads) ; } else if (B_is_hyper) { // A is sparse and B is hyper GB_AxB_saxpy3_sym_sh (C, A, B, SaxpyTasks, ntasks, nfine, nthreads) ; } else if (B_is_bitmap) { // A is sparse and B is bitmap GB_AxB_saxpy3_sym_sb (C, A, B, SaxpyTasks, ntasks, nfine, nthreads) ; } else { // A is sparse and B is full GB_AxB_saxpy3_sym_sf (C, A, B, SaxpyTasks, ntasks, nfine, nthreads) ; } } else if (A_is_hyper) { if (B_is_sparse) { // A is hyper and B is sparse GB_AxB_saxpy3_sym_hs (C, A, B, SaxpyTasks, ntasks, nfine, nthreads) ; } else if (B_is_hyper) { // both A and B are hyper GB_AxB_saxpy3_sym_hh (C, A, B, SaxpyTasks, ntasks, nfine, nthreads) ; } else if (B_is_bitmap) { // A is hyper and B is bitmap GB_AxB_saxpy3_sym_hb (C, A, B, SaxpyTasks, ntasks, nfine, nthreads) ; } else { // A is hyper and B is full GB_AxB_saxpy3_sym_hf (C, A, B, SaxpyTasks, ntasks, nfine, nthreads) ; } } else if (A_is_bitmap) { // C=A*B where A is bitmap; B must be sparse/hyper if (B_is_sparse) { // A is bitmap and B is sparse GB_AxB_saxpy3_sym_bs (C, A, B, SaxpyTasks, ntasks, nfine, nthreads) ; } else { // A is bitmap and B is hyper ASSERT (B_is_hyper) ; GB_AxB_saxpy3_sym_bh (C, A, B, SaxpyTasks, ntasks, nfine, nthreads) ; } } else { // C=A*B where A is full; B must be sparse/hyper if (B_is_sparse) { // A is full and B is sparse GB_AxB_saxpy3_sym_fs (C, A, B, SaxpyTasks, ntasks, nfine, nthreads) ; } else { // A is full and B is hyper ASSERT (B_is_hyper) ; GB_AxB_saxpy3_sym_fh (C, A, B, SaxpyTasks, ntasks, nfine, nthreads) ; } } } else if (!Mask_comp) { //---------------------------------------------------------------------- // C<M> = A*B //---------------------------------------------------------------------- if (A_is_sparse) { if (B_is_sparse) { // both A and B are sparse GB_AxB_saxpy3_sym_mss (C, M, Mask_struct, M_in_place, A, B, SaxpyTasks, ntasks, nfine, nthreads) ; } else if (B_is_hyper) { // A is sparse and B is hyper GB_AxB_saxpy3_sym_msh (C, M, Mask_struct, M_in_place, A, B, SaxpyTasks, ntasks, nfine, nthreads) ; } else if (B_is_bitmap) { // A is sparse and B is bitmap GB_AxB_saxpy3_sym_msb (C, M, Mask_struct, M_in_place, A, B, SaxpyTasks, ntasks, nfine, nthreads) ; } else { // A is sparse and B is full GB_AxB_saxpy3_sym_msf (C, M, Mask_struct, M_in_place, A, B, SaxpyTasks, ntasks, nfine, nthreads) ; } } else if (A_is_hyper) { if (B_is_sparse) { // A is hyper and B is sparse GB_AxB_saxpy3_sym_mhs (C, M, Mask_struct, M_in_place, A, B, SaxpyTasks, ntasks, nfine, nthreads) ; } else if (B_is_hyper) { // both A and B are hyper GB_AxB_saxpy3_sym_mhh (C, M, Mask_struct, M_in_place, A, B, SaxpyTasks, ntasks, nfine, nthreads) ; } else if (B_is_bitmap) { // A is hyper and B is bitmap GB_AxB_saxpy3_sym_mhb (C, M, Mask_struct, M_in_place, A, B, SaxpyTasks, ntasks, nfine, nthreads) ; } else { // A is hyper and B is full GB_AxB_saxpy3_sym_mhf (C, M, Mask_struct, M_in_place, A, B, SaxpyTasks, ntasks, nfine, nthreads) ; } } else if (A_is_bitmap) { if (B_is_sparse) { // A is bitmap and B is sparse GB_AxB_saxpy3_sym_mbs (C, M, Mask_struct, M_in_place, A, B, SaxpyTasks, ntasks, nfine, nthreads) ; } else if (B_is_hyper) { // A is bitmap and B is hyper GB_AxB_saxpy3_sym_mbh (C, M, Mask_struct, M_in_place, A, B, SaxpyTasks, ntasks, nfine, nthreads) ; } else if (B_is_bitmap) { // both A and B are bitmap GB_AxB_saxpy3_sym_mbb (C, M, Mask_struct, M_in_place, A, B, SaxpyTasks, ntasks, nfine, nthreads) ; } else { // A is bitmap and B is full GB_AxB_saxpy3_sym_mbf (C, M, Mask_struct, M_in_place, A, B, SaxpyTasks, ntasks, nfine, nthreads) ; } } else { if (B_is_sparse) { // A is full and B is sparse GB_AxB_saxpy3_sym_mfs (C, M, Mask_struct, M_in_place, A, B, SaxpyTasks, ntasks, nfine, nthreads) ; } else if (B_is_hyper) { // A is full and B is hyper GB_AxB_saxpy3_sym_mfh (C, M, Mask_struct, M_in_place, A, B, SaxpyTasks, ntasks, nfine, nthreads) ; } else if (B_is_bitmap) { // A is full and B is bitmap GB_AxB_saxpy3_sym_mfb (C, M, Mask_struct, M_in_place, A, B, SaxpyTasks, ntasks, nfine, nthreads) ; } else { // both A and B are full GB_AxB_saxpy3_sym_mff (C, M, Mask_struct, M_in_place, A, B, SaxpyTasks, ntasks, nfine, nthreads) ; } } } else { //---------------------------------------------------------------------- // C<!M> = A*B //---------------------------------------------------------------------- if (A_is_sparse) { if (B_is_sparse) { // both A and B are sparse GB_AxB_saxpy3_sym_nss (C, M, Mask_struct, M_in_place, A, B, SaxpyTasks, ntasks, nfine, nthreads) ; } else if (B_is_hyper) { // A is sparse and B is hyper GB_AxB_saxpy3_sym_nsh (C, M, Mask_struct, M_in_place, A, B, SaxpyTasks, ntasks, nfine, nthreads) ; } else if (B_is_bitmap) { // A is sparse and B is bitmap GB_AxB_saxpy3_sym_nsb (C, M, Mask_struct, M_in_place, A, B, SaxpyTasks, ntasks, nfine, nthreads) ; } else { // A is sparse and B is full GB_AxB_saxpy3_sym_nsf (C, M, Mask_struct, M_in_place, A, B, SaxpyTasks, ntasks, nfine, nthreads) ; } } else if (A_is_hyper) { if (B_is_sparse) { // A is hyper and B is sparse GB_AxB_saxpy3_sym_nhs (C, M, Mask_struct, M_in_place, A, B, SaxpyTasks, ntasks, nfine, nthreads) ; } else if (B_is_hyper) { // both A and B are hyper GB_AxB_saxpy3_sym_nhh (C, M, Mask_struct, M_in_place, A, B, SaxpyTasks, ntasks, nfine, nthreads) ; } else if (B_is_bitmap) { // A is hyper and B is bitmap GB_AxB_saxpy3_sym_nhb (C, M, Mask_struct, M_in_place, A, B, SaxpyTasks, ntasks, nfine, nthreads) ; } else { // A is hyper and B is full GB_AxB_saxpy3_sym_nhf (C, M, Mask_struct, M_in_place, A, B, SaxpyTasks, ntasks, nfine, nthreads) ; } } else if (A_is_bitmap) { // C<!M>=A*B where A is bitmap; B must be sparse/hyper if (B_is_sparse) { // A is bitmap and B is sparse GB_AxB_saxpy3_sym_nbs (C, M, Mask_struct, M_in_place, A, B, SaxpyTasks, ntasks, nfine, nthreads) ; } else { // A is bitmap and B is hyper ASSERT (B_is_hyper) ; GB_AxB_saxpy3_sym_nbh (C, M, Mask_struct, M_in_place, A, B, SaxpyTasks, ntasks, nfine, nthreads) ; } } else { // C<!M>=A*B where A is full; B must be sparse/hyper if (B_is_sparse) { // A is full and B is sparse GB_AxB_saxpy3_sym_nfs (C, M, Mask_struct, M_in_place, A, B, SaxpyTasks, ntasks, nfine, nthreads) ; } else { // A is full and B is hyper ASSERT (B_is_hyper) ; GB_AxB_saxpy3_sym_nfh (C, M, Mask_struct, M_in_place, A, B, SaxpyTasks, ntasks, nfine, nthreads) ; } } } }
7,875
2,338
#ifdef __APPLE__ // ucontext.h is deprecated on macOS, so tests that include it may stop working // someday. We define _XOPEN_SOURCE to keep using ucontext.h for now. #ifdef _STRUCT_UCONTEXT #error incomplete ucontext_t already defined, change #include order #endif #define _XOPEN_SOURCE 700 #pragma clang diagnostic ignored "-Wdeprecated-declarations" #endif #include <ucontext.h>
117
2,460
<gh_stars>1000+ /** * Copyright (C) 2015 Red Hat, 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 io.fabric8.servicecatalog.client; import io.fabric8.kubernetes.client.Client; import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.NonNamespaceOperation; import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.servicecatalog.api.model.ClusterServiceBroker; import io.fabric8.servicecatalog.api.model.ClusterServiceBrokerList; import io.fabric8.servicecatalog.api.model.ClusterServiceClass; import io.fabric8.servicecatalog.api.model.ClusterServiceClassList; import io.fabric8.servicecatalog.api.model.ClusterServicePlan; import io.fabric8.servicecatalog.api.model.ClusterServicePlanList; import io.fabric8.servicecatalog.api.model.ServiceBinding; import io.fabric8.servicecatalog.api.model.ServiceBindingList; import io.fabric8.servicecatalog.api.model.ServiceBroker; import io.fabric8.servicecatalog.api.model.ServiceBrokerList; import io.fabric8.servicecatalog.api.model.ServiceClass; import io.fabric8.servicecatalog.api.model.ServiceClassList; import io.fabric8.servicecatalog.api.model.ServiceInstance; import io.fabric8.servicecatalog.api.model.ServiceInstanceList; import io.fabric8.servicecatalog.api.model.ServicePlan; import io.fabric8.servicecatalog.api.model.ServicePlanList; import io.fabric8.servicecatalog.client.internal.ClusterServiceBrokerResource; import io.fabric8.servicecatalog.client.internal.ClusterServiceClassResource; import io.fabric8.servicecatalog.client.internal.ClusterServicePlanResource; import io.fabric8.servicecatalog.client.internal.ServiceBindingResource; import io.fabric8.servicecatalog.client.internal.ServiceInstanceResource; /** * Main interface for Service Catalog Client. */ public interface ServiceCatalogClient extends Client { /** * API entrypoint for ClusterServiceBroker(servicecatalog.k8s.io/v1beta1) * * @return NonNamespaceOperation for ClusterServiceBroker class */ NonNamespaceOperation<ClusterServiceBroker, ClusterServiceBrokerList, ClusterServiceBrokerResource> clusterServiceBrokers(); /** * API entrypoint for ClusterServiceClass(servicecatalog.k8s.io/v1beta1) * * @return NonNamespaceOperation for ClusterServiceClass class */ NonNamespaceOperation<ClusterServiceClass, ClusterServiceClassList, ClusterServiceClassResource> clusterServiceClasses(); /** * API entrypoint for ClusterServicePlan(servicecatalog.k8s.io/v1beta1) * * @return NonNamespaceOperation for ClusterServicePlan class */ NonNamespaceOperation<ClusterServicePlan, ClusterServicePlanList, ClusterServicePlanResource> clusterServicePlans(); /** * API entrypoint for ServiceInstance(servicecatalog.k8s.io/v1beta1) * * @return MixedOperation for ServiceInstance class */ MixedOperation<ServiceInstance, ServiceInstanceList, ServiceInstanceResource> serviceInstances(); /** * API entrypoint for ServiceBinding(servicecatalog.k8s.io/v1beta1) * * @return MixedOperation for ServiceBinding class */ MixedOperation<ServiceBinding, ServiceBindingList, ServiceBindingResource> serviceBindings(); /** * API entrypoint for ServiceBroker(servicecatalog.k8s.io/v1beta1) * * @return MixedOperation for ServiceBroker class */ MixedOperation<ServiceBroker, ServiceBrokerList, Resource<ServiceBroker>> serviceBrokers(); /** * API entrypoint for ServiceClass(servicecatalog.k8s.io/v1beta1) * * @return MixedOperation for ServiceClass class */ MixedOperation<ServiceClass, ServiceClassList, Resource<ServiceClass>> serviceClasses(); /** * API entrypoint for ServicePlan(servicecatalog.k8s.io/v1beta1) * * @return MixedOperation for ServicePlan class */ MixedOperation<ServicePlan, ServicePlanList, Resource<ServicePlan>> servicePlans(); }
1,334
3,151
# Copyright (c) 2019-present, HuggingFace 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. import json import logging import os import socket import tarfile import tempfile from datetime import datetime from multiprocessing import Pool import torch from tqdm.auto import tqdm from transformers import cached_path PERSONACHAT_URL = "https://s3.amazonaws.com/datasets.huggingface.co/personachat/personachat_self_original.json" HF_FINETUNED_MODEL = "https://s3.amazonaws.com/models.huggingface.co/transfer-learning-chatbot/gpt_personachat_cache.tar.gz" # noqa logger = logging.getLogger(__file__) def download_pretrained_model(): """Download and extract finetuned model from S3""" resolved_archive_file = cached_path(HF_FINETUNED_MODEL) tempdir = tempfile.mkdtemp() logger.info( "extracting archive file {} to temp dir {}".format( resolved_archive_file, tempdir ) ) with tarfile.open(resolved_archive_file, "r:gz") as archive: archive.extractall(tempdir) return tempdir def tokenize_multi(data): obj, tokenizer = data if isinstance(obj, str): return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(obj)) if isinstance(obj, dict): return dict((n, tokenize_multi((o, tokenizer))) for n, o in obj.items()) return list(tokenize_multi((o, tokenizer)) for o in obj) def get_dataset( tokenizer, dataset_path, dataset_cache, process_count, proxies, evaluate=False, interact=False, no_cache=False, args=None, ): """Get tokenized PERSONACHAT dataset from S3 or cache.""" dataset_path = dataset_path or PERSONACHAT_URL mode = "eval" if evaluate else "train" if interact: mode = "interact" dataset_cache = ( dataset_cache + "_" + type(tokenizer).__name__ + "_" + mode ) # To avoid using GPT cache for GPT-2 and vice-versa if dataset_cache and os.path.isfile(dataset_cache) and not no_cache: logger.info("Load tokenized dataset from cache at %s", dataset_cache) dataset = torch.load(dataset_cache) else: logger.info("Download dataset from %s", dataset_path) personachat_file = cached_path(dataset_path, proxies=proxies) with open(personachat_file, "r", encoding="utf-8") as f: dataset = json.loads(f.read()) logger.info("Tokenize and encode the dataset") def tokenize(obj): if isinstance(obj, str): return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(obj)) if isinstance(obj, dict): return dict((n, tokenize(o)) for n, o in obj.items()) data = [(d, tokenizer) for d in obj] if args.multiprocessing_chunksize == -1: chunksize = max(len(data) // (args.process_count * 2), 500) else: chunksize = args.multiprocessing_chunksize with Pool(process_count) as p: tokenized_data = list( tqdm( p.imap(tokenize_multi, data, chunksize=chunksize), total=len(data), ) ) return tokenized_data if not interact and dataset_path == PERSONACHAT_URL: if not evaluate: dataset = dataset["train"] else: dataset = dataset["valid"] dataset = tokenize(dataset) torch.save(dataset, dataset_cache) return dataset class AttrDict(dict): def __init__(self, *args, **kwargs): super(AttrDict, self).__init__(*args, **kwargs) self.__dict__ = self
1,613
1,686
<reponame>p0tr3c-terraform/driftctl { "Typ": "<KEY>", "Val": "<KEY>", "Err": null }
44
11,719
// Copyright (C) 2003 <NAME> (<EMAIL>) // License: Boost Software License See LICENSE.txt for the full license. #undef DLIB_SEQUENCE_COMPARe_ABSTRACT_ #ifdef DLIB_SEQUENCE_COMPARe_ABSTRACT_ #include "sequence_kernel_abstract.h" #include "../algs.h" namespace dlib { template < typename seq_base > class sequence_compare : public seq_base { /*! REQUIREMENTS ON T T must implement operator< for its type and T must implement operator== for its type REQUIREMENTS ON SEQUENCE_BASE must be an implementation of sequence/sequence_kernel_abstract.h POINTERS AND REFERENCES TO INTERNAL DATA operator== and operator< do not invalidate pointers or references to data members WHAT THIS EXTENSION DOES FOR sequence This gives a sequence the ability to compare itself to other sequences using the < and == operators. !*/ public: bool operator< ( const sequence_compare& rhs ) const; /*! ensures - returns true if there exists an integer j such that 0 <= j < size() and for all integers i such that 0 <= i < j where it is true that (*this)[i] <= rhs[i] and (*this)[j] < rhs[j] - returns false if there is no j that will satisfy the above conditions !*/ bool operator== ( const sequence_compare& rhs ) const; /*! ensures - returns true if for all i: (*this)[i] == rhs[i] else returns false !*/ }; template < typename seq_base > inline void swap ( sequence_compare<seq_base>& a, sequence_compare<seq_base>& b ) { a.swap(b); } /*! provides a global swap function !*/ } #endif // DLIB_SEQUENCE_COMPARe_ABSTRACT_
939
7,892
<gh_stars>1000+ /********************************************************************** Audacity: A Digital Audio Editor AVCodecID.h <NAME> **********************************************************************/ #pragma once enum AudacityAVCodecIDValue { AUDACITY_AV_CODEC_ID_NONE, AUDACITY_AV_CODEC_ID_MPEG1VIDEO, AUDACITY_AV_CODEC_ID_MPEG2VIDEO, AUDACITY_AV_CODEC_ID_MPEG2VIDEO_XVMC, AUDACITY_AV_CODEC_ID_H261, AUDACITY_AV_CODEC_ID_H263, AUDACITY_AV_CODEC_ID_RV10, AUDACITY_AV_CODEC_ID_RV20, AUDACITY_AV_CODEC_ID_MJPEG, AUDACITY_AV_CODEC_ID_MJPEGB, AUDACITY_AV_CODEC_ID_LJPEG, AUDACITY_AV_CODEC_ID_SP5X, AUDACITY_AV_CODEC_ID_JPEGLS, AUDACITY_AV_CODEC_ID_MPEG4, AUDACITY_AV_CODEC_ID_RAWVIDEO, AUDACITY_AV_CODEC_ID_MSMPEG4V1, AUDACITY_AV_CODEC_ID_MSMPEG4V2, AUDACITY_AV_CODEC_ID_MSMPEG4V3, AUDACITY_AV_CODEC_ID_WMV1, AUDACITY_AV_CODEC_ID_WMV2, AUDACITY_AV_CODEC_ID_H263P, AUDACITY_AV_CODEC_ID_H263I, AUDACITY_AV_CODEC_ID_FLV1, AUDACITY_AV_CODEC_ID_SVQ1, AUDACITY_AV_CODEC_ID_SVQ3, AUDACITY_AV_CODEC_ID_DVVIDEO, AUDACITY_AV_CODEC_ID_HUFFYUV, AUDACITY_AV_CODEC_ID_CYUV, AUDACITY_AV_CODEC_ID_H264, AUDACITY_AV_CODEC_ID_INDEO3, AUDACITY_AV_CODEC_ID_VP3, AUDACITY_AV_CODEC_ID_THEORA, AUDACITY_AV_CODEC_ID_ASV1, AUDACITY_AV_CODEC_ID_ASV2, AUDACITY_AV_CODEC_ID_FFV1, AUDACITY_AV_CODEC_ID_4XM, AUDACITY_AV_CODEC_ID_VCR1, AUDACITY_AV_CODEC_ID_CLJR, AUDACITY_AV_CODEC_ID_MDEC, AUDACITY_AV_CODEC_ID_ROQ, AUDACITY_AV_CODEC_ID_INTERPLAY_VIDEO, AUDACITY_AV_CODEC_ID_XAN_WC3, AUDACITY_AV_CODEC_ID_XAN_WC4, AUDACITY_AV_CODEC_ID_RPZA, AUDACITY_AV_CODEC_ID_CINEPAK, AUDACITY_AV_CODEC_ID_WS_VQA, AUDACITY_AV_CODEC_ID_MSRLE, AUDACITY_AV_CODEC_ID_MSVIDEO1, AUDACITY_AV_CODEC_ID_IDCIN, AUDACITY_AV_CODEC_ID_8BPS, AUDACITY_AV_CODEC_ID_SMC, AUDACITY_AV_CODEC_ID_FLIC, AUDACITY_AV_CODEC_ID_TRUEMOTION1, AUDACITY_AV_CODEC_ID_VMDVIDEO, AUDACITY_AV_CODEC_ID_MSZH, AUDACITY_AV_CODEC_ID_ZLIB, AUDACITY_AV_CODEC_ID_QTRLE, AUDACITY_AV_CODEC_ID_TSCC, AUDACITY_AV_CODEC_ID_ULTI, AUDACITY_AV_CODEC_ID_QDRAW, AUDACITY_AV_CODEC_ID_VIXL, AUDACITY_AV_CODEC_ID_QPEG, AUDACITY_AV_CODEC_ID_PNG, AUDACITY_AV_CODEC_ID_PPM, AUDACITY_AV_CODEC_ID_PBM, AUDACITY_AV_CODEC_ID_PGM, AUDACITY_AV_CODEC_ID_PGMYUV, AUDACITY_AV_CODEC_ID_PAM, AUDACITY_AV_CODEC_ID_FFVHUFF, AUDACITY_AV_CODEC_ID_RV30, AUDACITY_AV_CODEC_ID_RV40, AUDACITY_AV_CODEC_ID_VC1, AUDACITY_AV_CODEC_ID_WMV3, AUDACITY_AV_CODEC_ID_LOCO, AUDACITY_AV_CODEC_ID_WNV1, AUDACITY_AV_CODEC_ID_AASC, AUDACITY_AV_CODEC_ID_INDEO2, AUDACITY_AV_CODEC_ID_FRAPS, AUDACITY_AV_CODEC_ID_TRUEMOTION2, AUDACITY_AV_CODEC_ID_BMP, AUDACITY_AV_CODEC_ID_CSCD, AUDACITY_AV_CODEC_ID_MMVIDEO, AUDACITY_AV_CODEC_ID_ZMBV, AUDACITY_AV_CODEC_ID_AVS, AUDACITY_AV_CODEC_ID_SMACKVIDEO, AUDACITY_AV_CODEC_ID_NUV, AUDACITY_AV_CODEC_ID_KMVC, AUDACITY_AV_CODEC_ID_FLASHSV, AUDACITY_AV_CODEC_ID_CAVS, AUDACITY_AV_CODEC_ID_JPEG2000, AUDACITY_AV_CODEC_ID_VMNC, AUDACITY_AV_CODEC_ID_VP5, AUDACITY_AV_CODEC_ID_VP6, AUDACITY_AV_CODEC_ID_VP6F, AUDACITY_AV_CODEC_ID_TARGA, AUDACITY_AV_CODEC_ID_DSICINVIDEO, AUDACITY_AV_CODEC_ID_TIERTEXSEQVIDEO, AUDACITY_AV_CODEC_ID_TIFF, AUDACITY_AV_CODEC_ID_GIF, AUDACITY_AV_CODEC_ID_DXA, AUDACITY_AV_CODEC_ID_DNXHD, AUDACITY_AV_CODEC_ID_THP, AUDACITY_AV_CODEC_ID_SGI, AUDACITY_AV_CODEC_ID_C93, AUDACITY_AV_CODEC_ID_BETHSOFTVID, AUDACITY_AV_CODEC_ID_PTX, AUDACITY_AV_CODEC_ID_TXD, AUDACITY_AV_CODEC_ID_VP6A, AUDACITY_AV_CODEC_ID_AMV, AUDACITY_AV_CODEC_ID_VB, AUDACITY_AV_CODEC_ID_PCX, AUDACITY_AV_CODEC_ID_SUNRAST, AUDACITY_AV_CODEC_ID_INDEO4, AUDACITY_AV_CODEC_ID_INDEO5, AUDACITY_AV_CODEC_ID_MIMIC, AUDACITY_AV_CODEC_ID_RL2, AUDACITY_AV_CODEC_ID_ESCAPE124, AUDACITY_AV_CODEC_ID_DIRAC, AUDACITY_AV_CODEC_ID_BFI, AUDACITY_AV_CODEC_ID_CMV, AUDACITY_AV_CODEC_ID_MOTIONPIXELS, AUDACITY_AV_CODEC_ID_TGV, AUDACITY_AV_CODEC_ID_TGQ, AUDACITY_AV_CODEC_ID_TQI, AUDACITY_AV_CODEC_ID_AURA, AUDACITY_AV_CODEC_ID_AURA2, AUDACITY_AV_CODEC_ID_V210X, AUDACITY_AV_CODEC_ID_TMV, AUDACITY_AV_CODEC_ID_V210, AUDACITY_AV_CODEC_ID_DPX, AUDACITY_AV_CODEC_ID_MAD, AUDACITY_AV_CODEC_ID_FRWU, AUDACITY_AV_CODEC_ID_FLASHSV2, AUDACITY_AV_CODEC_ID_CDGRAPHICS, AUDACITY_AV_CODEC_ID_R210, AUDACITY_AV_CODEC_ID_ANM, AUDACITY_AV_CODEC_ID_BINKVIDEO, AUDACITY_AV_CODEC_ID_IFF_ILBM, AUDACITY_AV_CODEC_ID_IFF_BYTERUN1, AUDACITY_AV_CODEC_ID_KGV1, AUDACITY_AV_CODEC_ID_YOP, AUDACITY_AV_CODEC_ID_VP8, AUDACITY_AV_CODEC_ID_PICTOR, AUDACITY_AV_CODEC_ID_ANSI, AUDACITY_AV_CODEC_ID_A64_MULTI, AUDACITY_AV_CODEC_ID_A64_MULTI5, AUDACITY_AV_CODEC_ID_R10K, AUDACITY_AV_CODEC_ID_MXPEG, AUDACITY_AV_CODEC_ID_LAGARITH, AUDACITY_AV_CODEC_ID_PRORES, AUDACITY_AV_CODEC_ID_JV, AUDACITY_AV_CODEC_ID_DFA, AUDACITY_AV_CODEC_ID_WMV3IMAGE, AUDACITY_AV_CODEC_ID_VC1IMAGE, AUDACITY_AV_CODEC_ID_UTVIDEO, AUDACITY_AV_CODEC_ID_BMV_VIDEO, AUDACITY_AV_CODEC_ID_VBLE, AUDACITY_AV_CODEC_ID_DXTORY, AUDACITY_AV_CODEC_ID_V410, AUDACITY_AV_CODEC_ID_XWD, AUDACITY_AV_CODEC_ID_CDXL, AUDACITY_AV_CODEC_ID_XBM, AUDACITY_AV_CODEC_ID_ZEROCODEC, AUDACITY_AV_CODEC_ID_MSS1, AUDACITY_AV_CODEC_ID_MSA1, AUDACITY_AV_CODEC_ID_TSCC2, AUDACITY_AV_CODEC_ID_MTS2, AUDACITY_AV_CODEC_ID_CLLC, AUDACITY_AV_CODEC_ID_MSS2, AUDACITY_AV_CODEC_ID_VP9, AUDACITY_AV_CODEC_ID_AIC, AUDACITY_AV_CODEC_ID_ESCAPE130_DEPRECATED, AUDACITY_AV_CODEC_ID_G2M_DEPRECATED, AUDACITY_AV_CODEC_ID_WEBP_DEPRECATED, AUDACITY_AV_CODEC_ID_HNM4_VIDEO, AUDACITY_AV_CODEC_ID_HEVC_DEPRECATED, AUDACITY_AV_CODEC_ID_FIC, AUDACITY_AV_CODEC_ID_BRENDER_PIX, AUDACITY_AV_CODEC_ID_Y41P, AUDACITY_AV_CODEC_ID_ESCAPE130, AUDACITY_AV_CODEC_ID_EXR, AUDACITY_AV_CODEC_ID_AVRP, AUDACITY_AV_CODEC_ID_012V, AUDACITY_AV_CODEC_ID_G2M, AUDACITY_AV_CODEC_ID_AVUI, AUDACITY_AV_CODEC_ID_AYUV, AUDACITY_AV_CODEC_ID_TARGA_Y216, AUDACITY_AV_CODEC_ID_V308, AUDACITY_AV_CODEC_ID_V408, AUDACITY_AV_CODEC_ID_YUV4, AUDACITY_AV_CODEC_ID_SANM, AUDACITY_AV_CODEC_ID_PAF_VIDEO, AUDACITY_AV_CODEC_ID_AVRN, AUDACITY_AV_CODEC_ID_CPIA, AUDACITY_AV_CODEC_ID_XFACE, AUDACITY_AV_CODEC_ID_SGIRLE, AUDACITY_AV_CODEC_ID_MVC1, AUDACITY_AV_CODEC_ID_MVC2, AUDACITY_AV_CODEC_ID_SNOW, AUDACITY_AV_CODEC_ID_WEBP, AUDACITY_AV_CODEC_ID_SMVJPEG, AUDACITY_AV_CODEC_ID_HEVC, AUDACITY_AV_CODEC_ID_FIRST_AUDIO, AUDACITY_AV_CODEC_ID_PCM_S16LE, AUDACITY_AV_CODEC_ID_PCM_S16BE, AUDACITY_AV_CODEC_ID_PCM_U16LE, AUDACITY_AV_CODEC_ID_PCM_U16BE, AUDACITY_AV_CODEC_ID_PCM_S8, AUDACITY_AV_CODEC_ID_PCM_U8, AUDACITY_AV_CODEC_ID_PCM_MULAW, AUDACITY_AV_CODEC_ID_PCM_ALAW, AUDACITY_AV_CODEC_ID_PCM_S32LE, AUDACITY_AV_CODEC_ID_PCM_S32BE, AUDACITY_AV_CODEC_ID_PCM_U32LE, AUDACITY_AV_CODEC_ID_PCM_U32BE, AUDACITY_AV_CODEC_ID_PCM_S24LE, AUDACITY_AV_CODEC_ID_PCM_S24BE, AUDACITY_AV_CODEC_ID_PCM_U24LE, AUDACITY_AV_CODEC_ID_PCM_U24BE, AUDACITY_AV_CODEC_ID_PCM_S24DAUD, AUDACITY_AV_CODEC_ID_PCM_ZORK, AUDACITY_AV_CODEC_ID_PCM_S16LE_PLANAR, AUDACITY_AV_CODEC_ID_PCM_DVD, AUDACITY_AV_CODEC_ID_PCM_F32BE, AUDACITY_AV_CODEC_ID_PCM_F32LE, AUDACITY_AV_CODEC_ID_PCM_F64BE, AUDACITY_AV_CODEC_ID_PCM_F64LE, AUDACITY_AV_CODEC_ID_PCM_BLURAY, AUDACITY_AV_CODEC_ID_PCM_LXF, AUDACITY_AV_CODEC_ID_S302M, AUDACITY_AV_CODEC_ID_PCM_S8_PLANAR, AUDACITY_AV_CODEC_ID_PCM_S24LE_PLANAR_DEPRECATED, AUDACITY_AV_CODEC_ID_PCM_S32LE_PLANAR_DEPRECATED, AUDACITY_AV_CODEC_ID_PCM_S24LE_PLANAR, AUDACITY_AV_CODEC_ID_PCM_S32LE_PLANAR, AUDACITY_AV_CODEC_ID_PCM_S16BE_PLANAR, AUDACITY_AV_CODEC_ID_ADPCM_IMA_QT, AUDACITY_AV_CODEC_ID_ADPCM_IMA_WAV, AUDACITY_AV_CODEC_ID_ADPCM_IMA_DK3, AUDACITY_AV_CODEC_ID_ADPCM_IMA_DK4, AUDACITY_AV_CODEC_ID_ADPCM_IMA_WS, AUDACITY_AV_CODEC_ID_ADPCM_IMA_SMJPEG, AUDACITY_AV_CODEC_ID_ADPCM_MS, AUDACITY_AV_CODEC_ID_ADPCM_4XM, AUDACITY_AV_CODEC_ID_ADPCM_XA, AUDACITY_AV_CODEC_ID_ADPCM_ADX, AUDACITY_AV_CODEC_ID_ADPCM_EA, AUDACITY_AV_CODEC_ID_ADPCM_G726, AUDACITY_AV_CODEC_ID_ADPCM_CT, AUDACITY_AV_CODEC_ID_ADPCM_SWF, AUDACITY_AV_CODEC_ID_ADPCM_YAMAHA, AUDACITY_AV_CODEC_ID_ADPCM_SBPRO_4, AUDACITY_AV_CODEC_ID_ADPCM_SBPRO_3, AUDACITY_AV_CODEC_ID_ADPCM_SBPRO_2, AUDACITY_AV_CODEC_ID_ADPCM_THP, AUDACITY_AV_CODEC_ID_ADPCM_IMA_AMV, AUDACITY_AV_CODEC_ID_ADPCM_EA_R1, AUDACITY_AV_CODEC_ID_ADPCM_EA_R3, AUDACITY_AV_CODEC_ID_ADPCM_EA_R2, AUDACITY_AV_CODEC_ID_ADPCM_IMA_EA_SEAD, AUDACITY_AV_CODEC_ID_ADPCM_IMA_EA_EACS, AUDACITY_AV_CODEC_ID_ADPCM_EA_XAS, AUDACITY_AV_CODEC_ID_ADPCM_EA_MAXIS_XA, AUDACITY_AV_CODEC_ID_ADPCM_IMA_ISS, AUDACITY_AV_CODEC_ID_ADPCM_G722, AUDACITY_AV_CODEC_ID_ADPCM_IMA_APC, AUDACITY_AV_CODEC_ID_VIMA, AUDACITY_AV_CODEC_ID_ADPCM_AFC, AUDACITY_AV_CODEC_ID_ADPCM_IMA_OKI, AUDACITY_AV_CODEC_ID_ADPCM_DTK, AUDACITY_AV_CODEC_ID_ADPCM_IMA_RAD, AUDACITY_AV_CODEC_ID_ADPCM_G726LE, AUDACITY_AV_CODEC_ID_AMR_NB, AUDACITY_AV_CODEC_ID_AMR_WB, AUDACITY_AV_CODEC_ID_RA_144, AUDACITY_AV_CODEC_ID_RA_288, AUDACITY_AV_CODEC_ID_ROQ_DPCM, AUDACITY_AV_CODEC_ID_INTERPLAY_DPCM, AUDACITY_AV_CODEC_ID_XAN_DPCM, AUDACITY_AV_CODEC_ID_SOL_DPCM, AUDACITY_AV_CODEC_ID_MP2, AUDACITY_AV_CODEC_ID_MP3, AUDACITY_AV_CODEC_ID_AAC, AUDACITY_AV_CODEC_ID_AC3, AUDACITY_AV_CODEC_ID_DTS, AUDACITY_AV_CODEC_ID_VORBIS, AUDACITY_AV_CODEC_ID_DVAUDIO, AUDACITY_AV_CODEC_ID_WMAV1, AUDACITY_AV_CODEC_ID_WMAV2, AUDACITY_AV_CODEC_ID_MACE3, AUDACITY_AV_CODEC_ID_MACE6, AUDACITY_AV_CODEC_ID_VMDAUDIO, AUDACITY_AV_CODEC_ID_FLAC, AUDACITY_AV_CODEC_ID_MP3ADU, AUDACITY_AV_CODEC_ID_MP3ON4, AUDACITY_AV_CODEC_ID_SHORTEN, AUDACITY_AV_CODEC_ID_ALAC, AUDACITY_AV_CODEC_ID_WESTWOOD_SND1, AUDACITY_AV_CODEC_ID_GSM, AUDACITY_AV_CODEC_ID_QDM2, AUDACITY_AV_CODEC_ID_COOK, AUDACITY_AV_CODEC_ID_TRUESPEECH, AUDACITY_AV_CODEC_ID_TTA, AUDACITY_AV_CODEC_ID_SMACKAUDIO, AUDACITY_AV_CODEC_ID_QCELP, AUDACITY_AV_CODEC_ID_WAVPACK, AUDACITY_AV_CODEC_ID_DSICINAUDIO, AUDACITY_AV_CODEC_ID_IMC, AUDACITY_AV_CODEC_ID_MUSEPACK7, AUDACITY_AV_CODEC_ID_MLP, AUDACITY_AV_CODEC_ID_GSM_MS, AUDACITY_AV_CODEC_ID_ATRAC3, AUDACITY_AV_CODEC_ID_VOXWARE, AUDACITY_AV_CODEC_ID_APE, AUDACITY_AV_CODEC_ID_NELLYMOSER, AUDACITY_AV_CODEC_ID_MUSEPACK8, AUDACITY_AV_CODEC_ID_SPEEX, AUDACITY_AV_CODEC_ID_WMAVOICE, AUDACITY_AV_CODEC_ID_WMAPRO, AUDACITY_AV_CODEC_ID_WMALOSSLESS, AUDACITY_AV_CODEC_ID_ATRAC3P, AUDACITY_AV_CODEC_ID_EAC3, AUDACITY_AV_CODEC_ID_SIPR, AUDACITY_AV_CODEC_ID_MP1, AUDACITY_AV_CODEC_ID_TWINVQ, AUDACITY_AV_CODEC_ID_TRUEHD, AUDACITY_AV_CODEC_ID_MP4ALS, AUDACITY_AV_CODEC_ID_ATRAC1, AUDACITY_AV_CODEC_ID_BINKAUDIO_RDFT, AUDACITY_AV_CODEC_ID_BINKAUDIO_DCT, AUDACITY_AV_CODEC_ID_AAC_LATM, AUDACITY_AV_CODEC_ID_QDMC, AUDACITY_AV_CODEC_ID_CELT, AUDACITY_AV_CODEC_ID_G723_1, AUDACITY_AV_CODEC_ID_G729, AUDACITY_AV_CODEC_ID_8SVX_EXP, AUDACITY_AV_CODEC_ID_8SVX_FIB, AUDACITY_AV_CODEC_ID_BMV_AUDIO, AUDACITY_AV_CODEC_ID_RALF, AUDACITY_AV_CODEC_ID_IAC, AUDACITY_AV_CODEC_ID_ILBC, AUDACITY_AV_CODEC_ID_OPUS_DEPRECATED, AUDACITY_AV_CODEC_ID_COMFORT_NOISE, AUDACITY_AV_CODEC_ID_TAK_DEPRECATED, AUDACITY_AV_CODEC_ID_METASOUND, AUDACITY_AV_CODEC_ID_FFWAVESYNTH, AUDACITY_AV_CODEC_ID_SONIC, AUDACITY_AV_CODEC_ID_SONIC_LS, AUDACITY_AV_CODEC_ID_PAF_AUDIO, AUDACITY_AV_CODEC_ID_OPUS, AUDACITY_AV_CODEC_ID_TAK, AUDACITY_AV_CODEC_ID_EVRC, AUDACITY_AV_CODEC_ID_SMV, AUDACITY_AV_CODEC_ID_FIRST_SUBTITLE, AUDACITY_AV_CODEC_ID_DVD_SUBTITLE, AUDACITY_AV_CODEC_ID_DVB_SUBTITLE, AUDACITY_AV_CODEC_ID_TEXT, AUDACITY_AV_CODEC_ID_XSUB, AUDACITY_AV_CODEC_ID_SSA, AUDACITY_AV_CODEC_ID_MOV_TEXT, AUDACITY_AV_CODEC_ID_HDMV_PGS_SUBTITLE, AUDACITY_AV_CODEC_ID_DVB_TELETEXT, AUDACITY_AV_CODEC_ID_SRT, AUDACITY_AV_CODEC_ID_MICRODVD, AUDACITY_AV_CODEC_ID_EIA_608, AUDACITY_AV_CODEC_ID_JACOSUB, AUDACITY_AV_CODEC_ID_SAMI, AUDACITY_AV_CODEC_ID_REALTEXT, AUDACITY_AV_CODEC_ID_SUBVIEWER1, AUDACITY_AV_CODEC_ID_SUBVIEWER, AUDACITY_AV_CODEC_ID_SUBRIP, AUDACITY_AV_CODEC_ID_WEBVTT, AUDACITY_AV_CODEC_ID_MPL2, AUDACITY_AV_CODEC_ID_VPLAYER, AUDACITY_AV_CODEC_ID_PJS, AUDACITY_AV_CODEC_ID_ASS, AUDACITY_AV_CODEC_ID_FIRST_UNKNOWN, AUDACITY_AV_CODEC_ID_TTF, AUDACITY_AV_CODEC_ID_BINTEXT, AUDACITY_AV_CODEC_ID_XBIN, AUDACITY_AV_CODEC_ID_IDF, AUDACITY_AV_CODEC_ID_OTF, AUDACITY_AV_CODEC_ID_SMPTE_KLV, AUDACITY_AV_CODEC_ID_DVD_NAV, AUDACITY_AV_CODEC_ID_TIMED_ID3, AUDACITY_AV_CODEC_ID_PROBE, AUDACITY_AV_CODEC_ID_MPEG2TS, AUDACITY_AV_CODEC_ID_MPEG4SYSTEMS, AUDACITY_AV_CODEC_ID_FFMETADATA, AUDACITY_AV_CODEC_ID_LAST }; using AVCodecIDFwd = int; //! Define a wrapper struct so that implicit conversion to and from int won't //! mistakenly happen struct AudacityAVCodecID { AudacityAVCodecID(AVCodecIDFwd) = delete; AudacityAVCodecID( AudacityAVCodecIDValue value ) : value{value} {} AudacityAVCodecIDValue value; }; inline bool operator == ( AudacityAVCodecID x, AudacityAVCodecID y ) { return x.value == y.value; } inline bool operator != ( AudacityAVCodecID x, AudacityAVCodecID y ) { return !(x == y); }
8,430
2,151
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.commands.uiautomator; import android.app.UiAutomation.OnAccessibilityEventListener; import android.view.accessibility.AccessibilityEvent; import com.android.commands.uiautomator.Launcher.Command; import com.android.uiautomator.core.UiAutomationShellWrapper; import java.text.SimpleDateFormat; import java.util.Date; /** * Implementation of the events subcommand * * Prints out accessibility events until process is stopped. */ public class EventsCommand extends Command { private Object mQuitLock = new Object(); public EventsCommand() { super("events"); } @Override public String shortHelp() { return "prints out accessibility events until terminated"; } @Override public String detailedOptions() { return null; } @Override public void run(String[] args) { UiAutomationShellWrapper automationWrapper = new UiAutomationShellWrapper(); automationWrapper.connect(); automationWrapper.getUiAutomation().setOnAccessibilityEventListener( new OnAccessibilityEventListener() { @Override public void onAccessibilityEvent(AccessibilityEvent event) { SimpleDateFormat formatter = new SimpleDateFormat("MM-dd HH:mm:ss.SSS"); System.out.println(String.format("%s %s", formatter.format(new Date()), event.toString())); } }); // there's really no way to stop, essentially we just block indefinitely here and wait // for user to press Ctrl+C synchronized (mQuitLock) { try { mQuitLock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } automationWrapper.disconnect(); } }
875
399
<gh_stars>100-1000 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.wgzhao.addax.plugin.reader.hbase20xreader; import com.wgzhao.addax.common.base.HBaseKey; import com.wgzhao.addax.common.util.Configuration; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.util.Bytes; import java.util.List; public class MultiVersionDynamicColumnTask extends MultiVersionTask { private List<String> columnFamilies = null; public MultiVersionDynamicColumnTask(Configuration configuration) { super(configuration); this.columnFamilies = configuration.getList(HBaseKey.COLUMN_FAMILY, String.class); } @Override public void initScan(Scan scan) { for (String columnFamily : columnFamilies) { scan.addFamily(Bytes.toBytes(columnFamily.trim())); } super.setMaxVersions(scan); } }
523
2,151
<filename>content/common/ax_content_node_data.h // Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_COMMON_AX_CONTENT_NODE_DATA_H_ #define CONTENT_COMMON_AX_CONTENT_NODE_DATA_H_ #include <stdint.h> #include "content/common/content_export.h" #include "ui/accessibility/ax_node_data.h" #include "ui/accessibility/ax_tree_data.h" #include "ui/accessibility/ax_tree_update.h" namespace content { enum AXContentIntAttribute { // The routing ID of this node's child tree. AX_CONTENT_ATTR_CHILD_ROUTING_ID, // The browser plugin instance ID of this node's child tree. AX_CONTENT_ATTR_CHILD_BROWSER_PLUGIN_INSTANCE_ID, AX_CONTENT_INT_ATTRIBUTE_LAST }; // A subclass of AXNodeData that contains extra fields for // content-layer-specific AX attributes. struct CONTENT_EXPORT AXContentNodeData : public ui::AXNodeData { AXContentNodeData(); AXContentNodeData(const AXNodeData& other); AXContentNodeData(const AXContentNodeData& other); ~AXContentNodeData() override; bool HasContentIntAttribute(AXContentIntAttribute attribute) const; int GetContentIntAttribute(AXContentIntAttribute attribute) const; bool GetContentIntAttribute(AXContentIntAttribute attribute, int* value) const; void AddContentIntAttribute(AXContentIntAttribute attribute, int value); // Return a string representation of this data, for debugging. std::string ToString() const override; // This is a simple serializable struct. All member variables should be // public and copyable. std::vector<std::pair<AXContentIntAttribute, int32_t>> content_int_attributes; }; // A subclass of AXTreeData that contains extra fields for // content-layer-specific AX attributes. struct CONTENT_EXPORT AXContentTreeData : public ui::AXTreeData { AXContentTreeData(); ~AXContentTreeData() override; // Return a string representation of this data, for debugging. std::string ToString() const override; // The routing ID of this frame. int routing_id; // The routing ID of the parent frame. int parent_routing_id; }; typedef ui::AXTreeUpdateBase<content::AXContentNodeData, content::AXContentTreeData> AXContentTreeUpdate; } // namespace content #endif // CONTENT_COMMON_AX_CONTENT_NODE_DATA_H_
772
6,989
<reponame>HeyLey/catboost<filename>catboost/cuda/targets/pointwise_target_impl.cpp #include "pointwise_target_impl.h" namespace NCatboostCuda { }
58
445
package pl.allegro.tech.build.axion.release.domain; import com.github.zafarkhaja.semver.Version; import pl.allegro.tech.build.axion.release.domain.properties.NextVersionProperties; import pl.allegro.tech.build.axion.release.domain.properties.TagProperties; import pl.allegro.tech.build.axion.release.domain.properties.VersionProperties; import pl.allegro.tech.build.axion.release.domain.scm.ScmPosition; import pl.allegro.tech.build.axion.release.domain.scm.ScmRepository; import pl.allegro.tech.build.axion.release.domain.scm.TaggedCommits; import java.util.regex.Pattern; /** * Returned structure is: * * previousVersion: version read from last release tag * * version: either: * * forced version * * version read from last next version tag * * version read from last release tag and incremented when not on tag * * version read from last release tag when on tag */ public class VersionResolver { private final ScmRepository repository; private final VersionSorter sorter; /** * This is the path of the project relative to the Git root. * If this path is not empty then it means that the project is running as a submodule of a parent project. */ private final String projectRootRelativePath; public VersionResolver(ScmRepository repository, String projectRootRelativePath) { this.repository = repository; this.projectRootRelativePath = projectRootRelativePath; this.sorter = new VersionSorter(); } public VersionContext resolveVersion(VersionProperties versionProperties, TagProperties tagProperties, NextVersionProperties nextVersionProperties) { ScmPosition latestChangePosition = repository.positionOfLastChangeIn( projectRootRelativePath, versionProperties.getMonorepoProperties().getDirsToExclude() ); VersionFactory versionFactory = new VersionFactory(versionProperties, tagProperties, nextVersionProperties, latestChangePosition, repository.isLegacyDefTagnameRepo()); VersionInfo versions = readVersions(versionFactory, tagProperties, nextVersionProperties, versionProperties, latestChangePosition, versionProperties.isUseHighestVersion()); ScmState scmState = new ScmState( versions.onReleaseTag, versions.onNextVersionTag, versions.noTagsFound, repository.checkUncommittedChanges() ); VersionFactory.FinalVersion finalVersion = versionFactory.createFinalVersion(scmState, versions.current); return new VersionContext(finalVersion.version, finalVersion.snapshot, versions.previous, latestChangePosition); } private VersionInfo readVersions( VersionFactory versionFactory, TagProperties tagProperties, NextVersionProperties nextVersionProperties, VersionProperties versionProperties, ScmPosition latestChangePosition, Boolean useHighestVersions ) { String releaseTagPatternString = tagProperties.getPrefix(); if (!releaseTagPatternString.isEmpty()) { releaseTagPatternString += tagProperties.getVersionSeparator(); } Pattern releaseTagPattern = Pattern.compile("^" + releaseTagPatternString + ".*"); Pattern nextVersionTagPattern = Pattern.compile(".*" + nextVersionProperties.getSuffix() + "$"); boolean forceSnapshot = versionProperties.isForceSnapshot(); TaggedCommits latestTaggedCommit; TaggedCommits previousTaggedCommit; if (useHighestVersions) { TaggedCommits allTaggedCommits = TaggedCommits.fromAllCommits(repository, releaseTagPattern, latestChangePosition); latestTaggedCommit = allTaggedCommits; previousTaggedCommit = allTaggedCommits; } else { latestTaggedCommit = TaggedCommits.fromLatestCommit(repository, releaseTagPattern, latestChangePosition); previousTaggedCommit = TaggedCommits.fromLatestCommitBeforeNextVersion(repository, releaseTagPattern, nextVersionTagPattern, latestChangePosition); } VersionSorter.Result currentVersionInfo = versionFromTaggedCommits(latestTaggedCommit, false, nextVersionTagPattern, versionFactory, forceSnapshot); VersionSorter.Result previousVersionInfo = versionFromTaggedCommits(previousTaggedCommit, true, nextVersionTagPattern, versionFactory, forceSnapshot); Version currentVersion = currentVersionInfo.version; Version previousVersion = previousVersionInfo.version; boolean onLatestVersion; if (projectRootRelativePath.isEmpty()) { // Regular case, enough to test if its the same commit onLatestVersion = currentVersionInfo.isSameCommit(latestChangePosition.getRevision()); } else { // Here we must check if there are git differences for the path example case path subProj1: // A(last changes in subProj1) -> B -> C(tag 1.3.0) -> D -> E(head) // Now if we test for anywhere from C to E we should get 1.3.0 String tagCommitRevision = currentVersionInfo.commit != null ? currentVersionInfo.commit : ""; onLatestVersion = repository.isIdenticalForPath(projectRootRelativePath, latestChangePosition.getRevision(),tagCommitRevision); } return new VersionInfo( currentVersion, previousVersion, (onLatestVersion && !currentVersionInfo.isNextVersion), currentVersionInfo.isNextVersion, currentVersionInfo.noTagsFound ); } private VersionSorter.Result versionFromTaggedCommits(TaggedCommits taggedCommits, boolean ignoreNextVersionTags, Pattern nextVersionTagPattern, VersionFactory versionFactory, boolean forceSnapshot) { return sorter.pickTaggedCommit(taggedCommits, ignoreNextVersionTags, forceSnapshot, nextVersionTagPattern, versionFactory); } private static final class VersionInfo { final Version current; final Version previous; final boolean onReleaseTag; final boolean onNextVersionTag; final boolean noTagsFound; VersionInfo(Version current, Version previous, boolean onReleaseTag, boolean onNextVersionTag, boolean noTagsFound) { this.current = current; this.previous = previous; this.onReleaseTag = onReleaseTag; this.onNextVersionTag = onNextVersionTag; this.noTagsFound = noTagsFound; } } }
2,220
372
/* Editor Settings: expandtabs and use 4 spaces for indentation * ex: set softtabstop=4 tabstop=8 expandtab shiftwidth=4: * */ /* * Copyright © BeyondTrust Software 2004 - 2019 * 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. * * BEYONDTRUST MAKES THIS SOFTWARE AVAILABLE UNDER OTHER LICENSING TERMS AS * WELL. IF YOU HAVE ENTERED INTO A SEPARATE LICENSE AGREEMENT WITH * BEYONDTRUST, THEN YOU MAY ELECT TO USE THE SOFTWARE UNDER THE TERMS OF THAT * SOFTWARE LICENSE AGREEMENT INSTEAD OF THE TERMS OF THE APACHE LICENSE, * NOTWITHSTANDING THE ABOVE NOTICE. IF YOU HAVE QUESTIONS, OR WISH TO REQUEST * A COPY OF THE ALTERNATE LICENSING TERMS OFFERED BY BEYONDTRUST, PLEASE CONTACT * BEYONDTRUST AT beyondtrust.com/contact */ /* * Copyright (C) BeyondTrust Software. All rights reserved. * * Module Name: * * keytab.c * * Abstract: * * Kerberos 5 keytab functions * * Public libkeytab API * * Authors: <NAME> (<EMAIL>) * */ #include "includes.h" #include "ktldap.h" #define RDONLY_FILE "FILE" #define RDWR_FILE "WRFILE" #define BAIL_ON_KRB5_ERROR(ctx, krb5_err, winerr) \ if ((krb5_err)) { \ switch ((krb5_err)) \ { \ case ENOENT: \ winerr = krb5_err; \ break; \ \ case KRB5_LIBOS_BADPWDMATCH: \ winerr = ERROR_WRONG_PASSWORD; \ break; \ \ case KRB5KDC_ERR_KEY_EXP: \ winerr = ERROR_PASSWORD_EXPIRED; \ break; \ \ case KRB5KRB_AP_ERR_SKEW: \ winerr = ERROR_TIME_SKEW; \ break; \ \ default: \ winerr = LwTranslateKrb5Error( \ (ctx), \ (krb5_err), \ __FUNCTION__, \ __FILE__, \ __LINE__); \ break; \ } \ goto error; \ } static VOID KtKrb5FreeKeytabEntries( krb5_context ctx, krb5_keytab_entry *pEntries, DWORD dwCount ); static DWORD KtKrb5GetDefaultKeytab( PSTR* ppszKtFile ) { PSTR pszDefName = NULL; PSTR pszDefNameNew = NULL; const DWORD dwMaxSize = 1024; // Do not free PSTR pszKtFilename = NULL; DWORD dwError = 0; krb5_error_code ret = 0; DWORD dwSize = 32; krb5_context ctx = NULL; ret = krb5_init_context(&ctx); BAIL_ON_KRB5_ERROR(ctx, ret, dwError); do { dwSize += dwSize; dwError = LwReallocMemory( (PVOID)pszDefName, (PVOID*)&pszDefNameNew, dwSize); BAIL_ON_LW_ERROR(dwError); pszDefName = pszDefNameNew; pszDefNameNew = NULL; ret = krb5_kt_default_name(ctx, pszDefName, dwSize); if (ret == 0) { LwStrChr(pszDefName, ':', &pszKtFilename); if (!pszKtFilename) { pszKtFilename = pszDefName; } else { pszKtFilename++; } } else if (ret != KRB5_CONFIG_NOTENUFSPACE) { BAIL_ON_KRB5_ERROR(ctx, ret, dwError); } } while (ret == KRB5_CONFIG_NOTENUFSPACE && dwSize < dwMaxSize); dwError = LwAllocateString(pszKtFilename, ppszKtFile); BAIL_ON_LW_ERROR(dwError); cleanup: if (ctx) { krb5_free_context(ctx); } LW_SAFE_FREE_STRING(pszDefName); LW_SAFE_FREE_STRING(pszDefNameNew); return dwError; error: *ppszKtFile = NULL; goto cleanup; } static DWORD KtKrb5KeytabOpen( PCSTR pszPrefix, PCSTR pszKtFile, krb5_context *pCtx, krb5_keytab *pId ) { DWORD dwError = ERROR_SUCCESS; krb5_error_code ret = 0; krb5_context ctx = NULL; krb5_keytab id = 0; PSTR pszKtName = NULL; PSTR pszKtFilename = NULL; ret = krb5_init_context(&ctx); BAIL_ON_KRB5_ERROR(ctx, ret, dwError); if (!pszKtFile) { dwError = KtKrb5GetDefaultKeytab(&pszKtFilename); BAIL_ON_LW_ERROR(dwError); } dwError = LwAllocateStringPrintf( &pszKtName, "%s:%s", pszPrefix, pszKtFile ? pszKtFile : pszKtFilename); BAIL_ON_LW_ERROR(dwError); ret = krb5_kt_resolve(ctx, pszKtName, &id); BAIL_ON_KRB5_ERROR(ctx, ret, dwError); *pId = id; *pCtx = ctx; error: if (dwError && ctx) { krb5_free_context(ctx); ctx = NULL; } LW_SAFE_FREE_MEMORY(pszKtFilename); LW_SAFE_FREE_MEMORY(pszKtName); return dwError; } static DWORD KtKrb5SearchKeys( krb5_context ctx, krb5_keytab ktid, PCSTR pszSrvPrincipal, krb5_keytab_entry **ppEntries, PDWORD pdwCount ) { DWORD dwError = ERROR_SUCCESS; krb5_error_code ret = 0; krb5_principal server = NULL; krb5_kt_cursor ktcursor = NULL; krb5_keytab_entry entry = {0}; krb5_keytab_entry *entries = NULL; DWORD dwCount = 0; ret = krb5_parse_name(ctx, pszSrvPrincipal, &server); BAIL_ON_KRB5_ERROR(ctx, ret, dwError); ret = krb5_kt_start_seq_get(ctx, ktid, &ktcursor); BAIL_ON_KRB5_ERROR(ctx, ret, dwError); do { ret = krb5_kt_next_entry(ctx, ktid, &entry, &ktcursor); if (ret == 0 && krb5_principal_compare(ctx, entry.principal, server)) { dwError = LwReallocMemory((PVOID)entries, (PVOID*)&entries, (dwCount + 1) * sizeof(krb5_keytab_entry)); BAIL_ON_LW_ERROR(dwError); memset(&entries[dwCount], 0, sizeof(krb5_keytab_entry)); dwCount++; entries[dwCount - 1].magic = entry.magic; entries[dwCount - 1].timestamp = entry.timestamp; entries[dwCount - 1].vno = entry.vno; ret = krb5_copy_principal(ctx, entry.principal, &entries[dwCount - 1].principal); BAIL_ON_KRB5_ERROR(ctx, ret, dwError); entries[dwCount - 1].key = entry.key; ret = krb5_copy_keyblock_contents(ctx, &entry.key, &entries[dwCount - 1].key); BAIL_ON_KRB5_ERROR(ctx, ret, dwError); } if (ret == 0) { krb5_free_keytab_entry_contents(ctx, &entry); } } while (ret != KRB5_KT_END); ret = krb5_kt_end_seq_get(ctx, ktid, &ktcursor); BAIL_ON_KRB5_ERROR(ctx, ret, dwError); if (dwCount == 0) { dwError = ERROR_FILE_NOT_FOUND; } cleanup: if (server) { krb5_free_principal(ctx, server); } *ppEntries = entries; *pdwCount = dwCount; return dwError; error: if (entries) { KtKrb5FreeKeytabEntries(ctx, entries, dwCount); } entries = NULL; dwCount = 0; goto cleanup; } static DWORD KtKrb5AddKeyA( PCSTR pszPrincipal, PVOID pKey, DWORD dwKeyLen, PCSTR pszSalt, PCSTR pszKtPath, PCSTR pszDcName, DWORD dwKeyVer ) { const krb5_enctype enc[] = { ENCTYPE_AES256_CTS_HMAC_SHA1_96, ENCTYPE_AES128_CTS_HMAC_SHA1_96, ENCTYPE_ARCFOUR_HMAC, ENCTYPE_DES_CBC_MD5, ENCTYPE_DES_CBC_CRC }; DWORD dwError = ERROR_SUCCESS; PSTR pszBaseDn = NULL; krb5_error_code ret = 0; krb5_context ctx = NULL; krb5_keytab kt = NULL; krb5_principal client = NULL; krb5_principal salt_principal = NULL; krb5_keytab_entry entry = {0}; krb5_keytab_entry *entries = NULL; krb5_kvno kvno = 0; krb5_octet search_kvno = 0; krb5_data password = {0}; krb5_data salt = {0}; krb5_keyblock key = {0}; krb5_encrypt_block key_encrypted = {0}; DWORD dwKvno = 0; DWORD dwCount = 0; DWORD i = 0; struct stat statbuf = { 0 }; PSTR pszKtPathLocal = NULL; int dwKeytabFd = -1; memset(&statbuf, 0, sizeof(struct stat)); if (!pszKtPath) { dwError = KtKrb5GetDefaultKeytab(&pszKtPathLocal); BAIL_ON_LW_ERROR(dwError); pszKtPath = pszKtPathLocal; } if (stat(pszKtPath, &statbuf) == 0 && statbuf.st_size == 0) { // The file is empty. Add the version number to the file so kerberos // will accept it. char byte = 0x05; dwKeytabFd = open(pszKtPath, O_WRONLY, 0); if (dwKeytabFd < 0) { dwError = LwMapErrnoToLwError(errno); BAIL_ON_LW_ERROR(dwError); } while (write(dwKeytabFd, &byte, 1) < 0) { if (errno != EINTR) { dwError = LwMapErrnoToLwError(errno); BAIL_ON_LW_ERROR(dwError); } } byte = 0x02; while (write(dwKeytabFd, &byte, 1) < 0) { if (errno != EINTR) { dwError = LwMapErrnoToLwError(errno); BAIL_ON_LW_ERROR(dwError); } } while (close(dwKeytabFd) < 0) { if (errno != EINTR) { dwKeytabFd = -1; dwError = LwMapErrnoToLwError(errno); BAIL_ON_LW_ERROR(dwError); } } dwKeytabFd = -1; } dwError = KtKrb5KeytabOpen(RDWR_FILE, pszKtPath, &ctx, &kt); BAIL_ON_LW_ERROR(dwError); /* * Try to find kvno by querying ldap directory, if no kvno was passed */ if (dwKeyVer == (unsigned int)(-1)) { dwError = KtLdapGetBaseDnA(pszDcName, &pszBaseDn); BAIL_ON_LW_ERROR(dwError); if (pszBaseDn) { dwError = KtLdapGetKeyVersionA(pszDcName, pszBaseDn, pszPrincipal, &dwKvno); BAIL_ON_LW_ERROR(dwError); kvno = dwKvno; } } else { kvno = dwKeyVer; } /* * Search for existing versions of this principal's keys */ dwError = KtKrb5SearchKeys(ctx, kt, pszPrincipal, &entries, &dwCount); if (dwError == ERROR_SUCCESS) { /* * Find the latest version of this key and remove old ones. * Key versions are stored as a single byte. */ search_kvno = (krb5_octet)(kvno - 1); for (i = 0; i < dwCount; i++) { if (search_kvno == entries[i].vno) { /* Don't remove the keys with just one version number older */ continue; } else { ret = krb5_kt_remove_entry(ctx, kt, &(entries[i])); BAIL_ON_KRB5_ERROR(ctx, ret, dwError); } } } else if (dwError == ERROR_FILE_NOT_FOUND || dwError == ENOENT) { /* * No key has been found or the file doesn't exist so * ignore the error and start adding the new keys */ dwError = ERROR_SUCCESS; } else { BAIL_ON_LW_ERROR(dwError); } /* * Prepare new key for this principal */ ret = krb5_parse_name(ctx, pszPrincipal, &client); BAIL_ON_KRB5_ERROR(ctx, ret, dwError); if (pszSalt) { ret = krb5_parse_name(ctx, pszSalt, &salt_principal); BAIL_ON_KRB5_ERROR(ctx, ret, dwError); ret = krb5_principal2salt(ctx, salt_principal, &salt); BAIL_ON_KRB5_ERROR(ctx, ret, dwError); } password.data = pKey; password.length = dwKeyLen; /* * Add key entry for each encryption type */ for (i = 0; i < sizeof(enc)/sizeof(krb5_enctype); i++) { krb5_data *pass_salt = NULL; memset(&key, 0, sizeof(key)); memset(&key_encrypted, 0, sizeof(key_encrypted)); memset(&entry, 0, sizeof(entry)); if (salt.data && salt.length) { pass_salt = &salt; } krb5_use_enctype(ctx, &key_encrypted, enc[i]); ret = krb5_string_to_key(ctx, &key_encrypted, &key, &password, pass_salt); BAIL_ON_KRB5_ERROR(ctx, ret, dwError); entry.principal = client; entry.vno = kvno; entry.key = key; ret = krb5_kt_add_entry(ctx, kt, &entry); BAIL_ON_KRB5_ERROR(ctx, ret, dwError); krb5_free_keyblock_contents(ctx, &key); } cleanup: if (ctx && entries) { KtKrb5FreeKeytabEntries(ctx, entries, dwCount); } LW_SAFE_FREE_MEMORY(pszBaseDn); LW_SAFE_FREE_MEMORY(salt.data); LW_SAFE_FREE_STRING(pszKtPathLocal); if (dwKeytabFd != -1) { close(dwKeytabFd); } if (ctx) { if (client) { krb5_free_principal(ctx, client); } if (salt_principal) { krb5_free_principal(ctx, salt_principal); } if (kt) { krb5_kt_close(ctx, kt); } if (key.length) { krb5_free_keyblock_contents(ctx, &key); } krb5_free_context(ctx); } return dwError; error: goto cleanup; } static VOID KtKrb5FreeKeytabEntries( krb5_context ctx, krb5_keytab_entry *pEntries, DWORD dwCount ) { DWORD i = 0; for (i = 0; i < dwCount; i++) { krb5_free_keytab_entry_contents(ctx, &pEntries[i]); } LW_SAFE_FREE_MEMORY(pEntries); return; } DWORD KtKrb5AddKeyW( PCWSTR pwszPrincipal, PVOID pKey, DWORD dwKeyLen, PCWSTR pwszKtPath, PCWSTR pwszSalt, PCWSTR pwszDcName, DWORD dwKeyVersion) { DWORD dwError = ERROR_SUCCESS; PSTR pszPrincipal = NULL; PSTR pszKey = NULL; PSTR pszKtPath = NULL; PSTR pszSalt = NULL; PSTR pszDcName = NULL; dwError = LwWc16sToMbs(pwszPrincipal, &pszPrincipal); BAIL_ON_LW_ERROR(dwError); dwError = LwWc16snToMbs((PWSTR)pKey, &pszKey, dwKeyLen + 1); BAIL_ON_LW_ERROR(dwError); if (pwszKtPath) { dwError = LwWc16sToMbs(pwszKtPath, &pszKtPath); BAIL_ON_LW_ERROR(dwError); } dwError = LwWc16sToMbs(pwszSalt, &pszSalt); BAIL_ON_LW_ERROR(dwError); dwError = LwWc16sToMbs(pwszDcName, &pszDcName); BAIL_ON_LW_ERROR(dwError); dwError = KtKrb5AddKeyA(pszPrincipal, (PVOID)pszKey, dwKeyLen, pszSalt, pszKtPath, pszDcName, dwKeyVersion); BAIL_ON_LW_ERROR(dwError); cleanup: LW_SAFE_FREE_MEMORY(pszPrincipal); LW_SAFE_FREE_MEMORY(pszKey); LW_SAFE_FREE_MEMORY(pszKtPath); LW_SAFE_FREE_MEMORY(pszSalt); LW_SAFE_FREE_MEMORY(pszDcName); return dwError; error: goto cleanup; } DWORD KtKrb5GetKey( PCSTR pszPrincipal, PCSTR pszKtPath, DWORD dwEncType, PVOID *ppKey, PDWORD pdwKeyLen ) { DWORD dwError = ERROR_SUCCESS; krb5_error_code ret = 0; krb5_context ctx = NULL; krb5_keytab ktid = 0; krb5_principal client = NULL; krb5_kvno vno = 0; krb5_enctype enctype = 0; krb5_keytab_entry entry = {0}; PVOID pKey = NULL; dwError = KtKrb5KeytabOpen(RDONLY_FILE, pszKtPath, &ctx, &ktid); BAIL_ON_LW_ERROR(dwError); ret = krb5_parse_name(ctx, pszPrincipal, &client); BAIL_ON_KRB5_ERROR(ctx, ret, dwError); enctype = (krb5_enctype)dwEncType; ret = krb5_kt_get_entry(ctx, ktid, client, vno, enctype, &entry); BAIL_ON_KRB5_ERROR(ctx, ret, dwError); dwError = LwAllocateMemory((DWORD)entry.key.length, OUT_PPVOID(&pKey)); BAIL_ON_LW_ERROR(dwError); memcpy(pKey, entry.key.contents, entry.key.length); *ppKey = pKey; *pdwKeyLen = entry.key.length; cleanup: if (ctx) { if (client) { krb5_free_principal(ctx, client); } if (ktid) { krb5_kt_close(ctx, ktid); } krb5_free_context(ctx); } return dwError; error: LW_SAFE_FREE_MEMORY(pKey); *ppKey = NULL; *pdwKeyLen = 0; goto cleanup; } DWORD KtKrb5RemoveKey( PSTR pszPrincipal, DWORD dwVer, PSTR pszKtPath ) { DWORD dwError = ERROR_SUCCESS; krb5_error_code ret = 0; krb5_context ctx = NULL; krb5_keytab ktid = 0; krb5_keytab_entry *entries = NULL; DWORD dwCount = 0; DWORD i = 0; dwError = KtKrb5KeytabOpen(RDWR_FILE, pszKtPath, &ctx, &ktid); BAIL_ON_LW_ERROR(dwError); /* Should enctypes be added to conditions ? */ dwError = KtKrb5SearchKeys(ctx, ktid, pszPrincipal, &entries, &dwCount); BAIL_ON_LW_ERROR(dwError); for (i = 0; i < dwCount; i++) { /* if dwVer is non-zero skip entries with different kvno */ if (dwVer > 0 && dwVer != entries[i].vno) { continue; } ret = krb5_kt_remove_entry(ctx, ktid, &(entries[i])); BAIL_ON_KRB5_ERROR(ctx, ret, dwError); } error: if (ctx) { if (entries) { for (i = 0; i < dwCount; i++) { krb5_free_principal(ctx, entries[i].principal); } LW_SAFE_FREE_MEMORY(entries); } if (ktid) { krb5_kt_close(ctx, ktid); } krb5_free_context(ctx); } return dwError; } DWORD KtKrb5FormatPrincipalA( PCSTR pszAccount, PCSTR pszRealmName, PSTR *ppszPrincipal ) { DWORD dwError = ERROR_SUCCESS; PSTR pszRealm = NULL; krb5_error_code ret = 0; krb5_context ctx = NULL; PSTR pszPrincipal = NULL; ret = krb5_init_context(&ctx); BAIL_ON_KRB5_ERROR(ctx, ret, dwError); if (pszRealmName) { dwError = LwAllocateString(pszRealmName, &pszRealm); BAIL_ON_LW_ERROR(dwError); } else { ret = krb5_get_default_realm(ctx, &pszRealm); BAIL_ON_KRB5_ERROR(ctx, ret, dwError); } LwStrToUpper(pszRealm); dwError = LwAllocateStringPrintf(&pszPrincipal, "%s@%s", pszAccount, pszRealm); BAIL_ON_LW_ERROR(dwError); *ppszPrincipal = pszPrincipal; cleanup: if (pszRealmName) { LW_SAFE_FREE_MEMORY(pszRealm); } if (ctx) { if (pszRealm && !pszRealmName) { krb5_free_default_realm(ctx, pszRealm); } krb5_free_context(ctx); } return dwError; error: LW_SAFE_FREE_MEMORY(pszPrincipal); *ppszPrincipal = NULL; goto cleanup; } DWORD KtKrb5FormatPrincipalW( PCWSTR pwszAccount, PCWSTR pwszRealm, PWSTR *ppwszPrincipal ) { DWORD dwError = ERROR_SUCCESS; PSTR pszAccount = NULL; PSTR pszRealm = NULL; PSTR pszPrincipal = NULL; PWSTR pwszPrincipal = NULL; dwError = LwWc16sToMbs(pwszAccount, &pszAccount); BAIL_ON_LW_ERROR(dwError); /* NULL realm is a valid argument of KtKrb5FormatPrincpal */ if (pwszRealm) { dwError = LwWc16sToMbs(pwszRealm, &pszRealm); BAIL_ON_LW_ERROR(dwError); } dwError = KtKrb5FormatPrincipalA(pszAccount, pszRealm, &pszPrincipal); BAIL_ON_LW_ERROR(dwError); dwError = LwMbsToWc16s(pszPrincipal, &pwszPrincipal); BAIL_ON_LW_ERROR(dwError); *ppwszPrincipal = pwszPrincipal; cleanup: LW_SAFE_FREE_MEMORY(pszAccount); LW_SAFE_FREE_MEMORY(pszRealm); LW_SAFE_FREE_MEMORY(pszPrincipal); return dwError; error: LW_SAFE_FREE_MEMORY(pwszPrincipal); *ppwszPrincipal = NULL; goto cleanup; } DWORD KtKrb5GetSaltingPrincipalA( PCSTR pszMachineName, PCSTR pszMachAcctName, PCSTR pszDnsDomainName, PCSTR pszRealmName, PCSTR pszDcName, PCSTR pszBaseDn, PSTR *pszSalt) { DWORD dwError = ERROR_SUCCESS; krb5_error_code ret = 0; PSTR pszSaltOut = NULL; PSTR pszRealm = NULL; PSTR pszMachine = NULL; PSTR pszDnsRealm = NULL; krb5_context ctx = NULL; /* Try to query for userPrincipalName attribute first */ dwError = KtLdapGetSaltingPrincipalA(pszDcName, pszBaseDn, pszMachAcctName, &pszSaltOut); BAIL_ON_LW_ERROR(dwError); if (pszSaltOut) { *pszSalt = pszSaltOut; goto cleanup; } if (pszRealmName) { /* Use passed realm name */ dwError = LwAllocateString(pszRealmName, &pszRealm); BAIL_ON_LW_ERROR(dwError); } else { /* No realm name was passed so get the default */ ret = krb5_init_context(&ctx); BAIL_ON_KRB5_ERROR(ctx, ret, dwError); ret = krb5_get_default_realm(ctx, &pszRealm); BAIL_ON_KRB5_ERROR(ctx, ret, dwError); } /* Ensure realm name uppercased */ LwStrToUpper(pszRealm); /* Ensure host name lowercased */ dwError = LwAllocateString(pszMachAcctName, &pszMachine); BAIL_ON_LW_ERROR(dwError); LwStrToLower(pszMachine); /* DNS name of the Realm and lowercased */ dwError = LwAllocateString(pszRealm, &pszDnsRealm); BAIL_ON_LW_ERROR(dwError); LwStrToLower(pszDnsRealm); if (pszMachine[strlen(pszMachine)-1] == '$') pszMachine[strlen(pszMachine)-1] = '\0'; dwError = LwAllocateStringPrintf(&pszSaltOut, "host/%s.%s@%s", pszMachine, pszDnsRealm, pszRealm); BAIL_ON_LW_ERROR(dwError); *pszSalt = pszSaltOut; cleanup: if (ctx) { krb5_free_context(ctx); } LW_SAFE_FREE_MEMORY(pszRealm); LW_SAFE_FREE_MEMORY(pszMachine); LW_SAFE_FREE_MEMORY(pszDnsRealm); return dwError; error: *pszSalt = NULL; goto cleanup; } DWORD KtKrb5GetSaltingPrincipalW( PCWSTR pwszMachineName, PCWSTR pwszMachAcctName, PCWSTR pwszDnsDomainName, PCWSTR pwszRealmName, PCWSTR pwszDcName, PCWSTR pwszBaseDn, PWSTR *ppwszSalt ) { DWORD dwError = ERROR_SUCCESS; PSTR pszMachineName = NULL; PSTR pszMachAcctName = NULL; PSTR pszDnsDomainName = NULL; PSTR pszRealmName = NULL; PSTR pszDcName = NULL; PSTR pszBaseDn = NULL; PSTR pszSalt = NULL; PWSTR pwszSalt = NULL; dwError = LwWc16sToMbs(pwszMachineName, &pszMachineName); BAIL_ON_LW_ERROR(dwError); dwError = LwWc16sToMbs(pwszMachAcctName, &pszMachAcctName); BAIL_ON_LW_ERROR(dwError); dwError = LwWc16sToMbs(pwszDnsDomainName, &pszDnsDomainName); BAIL_ON_LW_ERROR(dwError); dwError = LwWc16sToMbs(pwszDcName, &pszDcName); BAIL_ON_LW_ERROR(dwError); dwError = LwWc16sToMbs(pwszBaseDn, &pszBaseDn); BAIL_ON_LW_ERROR(dwError); if (pwszRealmName) { dwError = LwWc16sToMbs(pwszRealmName, &pszRealmName); BAIL_ON_LW_ERROR(dwError); } dwError = KtKrb5GetSaltingPrincipalA(pszMachineName, pszMachAcctName, pszDnsDomainName, pszRealmName, pszDcName, pszBaseDn, &pszSalt); BAIL_ON_LW_ERROR(dwError); if (pszSalt) { dwError = LwMbsToWc16s(pszSalt, &pwszSalt); BAIL_ON_LW_ERROR(dwError); } *ppwszSalt = pwszSalt; cleanup: LW_SAFE_FREE_MEMORY(pszMachineName); LW_SAFE_FREE_MEMORY(pszMachAcctName); LW_SAFE_FREE_MEMORY(pszDnsDomainName); LW_SAFE_FREE_MEMORY(pszRealmName); LW_SAFE_FREE_MEMORY(pszDcName); LW_SAFE_FREE_MEMORY(pszBaseDn); LW_SAFE_FREE_MEMORY(pszSalt); return dwError; error: pwszSalt = NULL; goto cleanup; } DWORD KtKrb5GetUserSaltingPrincipalA( PCSTR pszUserName, PCSTR pszRealmName, PCSTR pszDcName, PCSTR pszBaseDn, PSTR *pszSalt) { DWORD dwError = ERROR_SUCCESS; krb5_error_code ret = 0; PSTR pszSaltOut = NULL; PSTR pszRealm = NULL; krb5_context ctx = NULL; /* Try to query for userPrincipalName attribute first */ dwError = KtLdapGetSaltingPrincipalA(pszDcName, pszBaseDn, pszUserName, &pszSaltOut); BAIL_ON_LW_ERROR(dwError); if (pszSaltOut) { *pszSalt = pszSaltOut; goto cleanup; } if (pszRealmName) { /* Use passed realm name */ dwError = LwAllocateString(pszRealmName, &pszRealm); BAIL_ON_LW_ERROR(dwError); } else { /* No realm name was passed so get the default */ ret = krb5_init_context(&ctx); BAIL_ON_KRB5_ERROR(ctx, ret, dwError); ret = krb5_get_default_realm(ctx, &pszRealm); BAIL_ON_KRB5_ERROR(ctx, ret, dwError); } /* Ensure realm name uppercased */ LwStrToUpper(pszRealm); // Create salt as outlined here: https://msdn.microsoft.com/en-us/library/cc233883.aspx // Salt User accounts: < DNS of the realm, converted to upper case> | <user name> dwError = LwAllocateStringPrintf(&pszSaltOut, "%s%s", pszRealm, pszUserName); BAIL_ON_LW_ERROR(dwError); *pszSalt = pszSaltOut; cleanup: if (ctx) { krb5_free_context(ctx); } LW_SAFE_FREE_MEMORY(pszRealm); return dwError; error: *pszSalt = NULL; goto cleanup; } /* local variables: mode: c c-basic-offset: 4 indent-tabs-mode: nil tab-width: 4 end: */
16,769
605
<filename>mq-cloud/src/main/java/com/sohu/tv/mq/cloud/dao/ConsumerStatDao.java<gh_stars>100-1000 package com.sohu.tv.mq.cloud.dao; import java.util.List; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Options; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import com.sohu.tv.mq.cloud.bo.ConsumerBlock; import com.sohu.tv.mq.cloud.bo.ConsumerStat; /** * 消费者状态 * @author yongfeigao * */ public interface ConsumerStatDao { /** * 保存消费状态 * @param consumerGroup * @param topic * @param undoneMsgCount * @param undone1qMsgCount * @param undoneDelay * @return */ @Insert("insert into consumer_stat(consumer_group,topic,undone_msg_count,undone_1q_msg_count,undone_delay) " + "values(#{consumerGroup},#{topic},#{undoneMsgCount},#{undone1qMsgCount},#{undoneDelay})" + "on duplicate key update undone_msg_count=values(undone_msg_count)," + "undone_1q_msg_count=values(undone_1q_msg_count)," + "undone_delay=values(undone_delay)") public Integer saveConsumerStat(@Param("consumerGroup") String consumerGroup, @Param("topic")String topic, @Param("undoneMsgCount") int undoneMsgCount, @Param("undone1qMsgCount")int undone1qMsgCount, @Param("undoneDelay") long undoneDelay); /** * 保存简单的消费状态 * @param consumerGroup * @param topic * @return */ @Options(useGeneratedKeys = true, keyProperty = "cs.id") @Insert("<script>insert into consumer_stat(consumer_group" + "<if test=\"cs.topic != null\">,topic</if> " + "<if test=\"cs.sbscription != null\">,sbscription</if> " + ") values(#{cs.consumerGroup}" + "<if test=\"cs.topic != null\">,#{cs.topic}</if> " + "<if test=\"cs.sbscription != null\">,#{cs.sbscription}</if> " + ")" + " on duplicate key update updatetime=CURRENT_TIMESTAMP" + "<if test=\"cs.topic != null\">,topic=values(topic)</if> " + "<if test=\"cs.sbscription != null\">,sbscription=values(sbscription)</if> " + "</script>") public Integer saveSimpleConsumerStat(@Param("cs") ConsumerStat consumerStat); /** * 保存阻塞状态 * @param csid * @param instance * @param broker * @param qid * @param blockTime * @return */ @Insert("insert into consumer_block(csid,instance,broker,qid,block_time) " + "values(#{csid},#{instance},#{broker},#{qid},#{blockTime})" + "on duplicate key update instance=values(instance)," + "block_time=values(block_time)") public Integer saveConsumerBlock(@Param("csid")int csid, @Param("instance") String instance, @Param("broker")String broker, @Param("qid") int qid, @Param("blockTime")long blockTime); /** * 保存阻塞状态 * @param csid * @param broker * @param qid * @param offsetMovedTime * @return */ @Insert("insert into consumer_block(csid,broker,qid,offset_moved_time,offset_moved_times) " + "values(#{csid},#{broker},#{qid},#{offsetMovedTime},1) " + "on duplicate key update offset_moved_time=values(offset_moved_time),offset_moved_times=offset_moved_times+1") public Integer saveSomeConsumerBlock(@Param("csid") int csid, @Param("broker") String broker, @Param("qid") int qid, @Param("offsetMovedTime")long offsetMovedTime); @Select("select id,consumer_group consumerGroup,topic,undone_msg_count undoneMsgCount," + "undone_1q_msg_count undone1qMsgCount," + "undone_delay undoneDelay,sbscription,updatetime" + " FROM consumer_stat ORDER BY updatetime desc") public List<ConsumerStat> getConsumerStat(); @Select("select csid,instance,broker,qid,block_time blockTime,updatetime," + "offset_moved_time offsetMovedTime, offset_moved_times offsetMovedTimes " + "FROM consumer_block " + "ORDER BY updatetime desc") public List<ConsumerBlock> getConsumerBlock(); @Select("select count(1) FROM consumer_block where csid = #{csid} and updatetime > DATE_SUB(NOW(), INTERVAL 60 MINUTE)") public Integer getConsumerBlockByCsid(@Param("csid") int csid); }
1,742
428
// pure_api.cpp : Defines the entry point for the application. // #include "stdafx.h" #include "resource.h" #include "agg_scanline_p.h" #include "agg_renderer_scanline.h" #include "agg_pixfmt_rgba.h" #include "agg_rasterizer_scanline_aa.h" #define MAX_LOADSTRING 100 // Global Variables: HINSTANCE hInst; // current instance TCHAR szTitle[MAX_LOADSTRING]; // The title bar text TCHAR szWindowClass[MAX_LOADSTRING]; // The title bar text // Foward declarations of functions included in this code module: ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); LRESULT CALLBACK About(HWND, UINT, WPARAM, LPARAM); int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { // TODO: Place code here. MSG msg; HACCEL hAccelTable; // Initialize global strings LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadString(hInstance, IDC_PURE_API, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); // Perform application initialization: if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } hAccelTable = LoadAccelerators(hInstance, (LPCTSTR)IDC_PURE_API); // Main message loop: while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return msg.wParam; } // // FUNCTION: MyRegisterClass() // // PURPOSE: Registers the window class. // // COMMENTS: // // This function and its usage is only necessary if you want this code // to be compatible with Win32 systems prior to the 'RegisterClassEx' // function that was added to Windows 95. It is important to call this function // so that the application will get 'well formed' small icons associated // with it. // ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = (WNDPROC)WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, (LPCTSTR)IDI_PURE_API); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = (LPCSTR)IDC_PURE_API; wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, (LPCTSTR)IDI_SMALL); return RegisterClassEx(&wcex); } // // FUNCTION: InitInstance(HANDLE, int) // // PURPOSE: Saves instance handle and creates main window // // COMMENTS: // // In this function, we save the instance handle in a global variable and // create and display the main program window. // BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { HWND hWnd; hInst = hInstance; // Store instance handle in our global variable hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL); if (!hWnd) { return FALSE; } ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); return TRUE; } // // FUNCTION: WndProc(HWND, unsigned, WORD, LONG) // // PURPOSE: Processes messages for the main window. // // WM_COMMAND - process the application menu // WM_PAINT - Paint the main window // WM_DESTROY - post a quit message and return // // LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; PAINTSTRUCT ps; HDC hdc; TCHAR szHello[MAX_LOADSTRING]; LoadString(hInst, IDS_HELLO, szHello, MAX_LOADSTRING); switch (message) { case WM_COMMAND: wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); // Parse the menu selections: switch (wmId) { case IDM_ABOUT: DialogBox(hInst, (LPCTSTR)IDD_ABOUTBOX, hWnd, (DLGPROC)About); break; case IDM_EXIT: DestroyWindow(hWnd); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } break; case WM_PAINT: { hdc = BeginPaint(hWnd, &ps); RECT rt; GetClientRect(hWnd, &rt); int width = rt.right - rt.left; int height = rt.bottom - rt.top; //============================================================ //Creating compatible DC and a bitmap to render the image BITMAPINFO bmp_info; bmp_info.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bmp_info.bmiHeader.biWidth = width; bmp_info.bmiHeader.biHeight = height; bmp_info.bmiHeader.biPlanes = 1; bmp_info.bmiHeader.biBitCount = 32; bmp_info.bmiHeader.biCompression = BI_RGB; bmp_info.bmiHeader.biSizeImage = 0; bmp_info.bmiHeader.biXPelsPerMeter = 0; bmp_info.bmiHeader.biYPelsPerMeter = 0; bmp_info.bmiHeader.biClrUsed = 0; bmp_info.bmiHeader.biClrImportant = 0; HDC mem_dc = ::CreateCompatibleDC(hdc); void* buf = 0; HBITMAP bmp = ::CreateDIBSection( mem_dc, &bmp_info, DIB_RGB_COLORS, &buf, 0, 0 ); // Selecting the object before doing anything allows you // to use AGG together with native Windows GDI. HBITMAP temp = (HBITMAP)::SelectObject(mem_dc, bmp); //============================================================ // AGG lowest level code. agg::rendering_buffer rbuf; rbuf.attach((unsigned char*)buf, width, height, -width*4); // Use negative stride in order // to keep Y-axis consistent with // WinGDI, i.e., going down. // Pixel format and basic primitives renderer agg::pixfmt_bgra32 pixf(rbuf); agg::renderer_base<agg::pixfmt_bgra32> renb(pixf); renb.clear(agg::rgba8(255, 255, 255, 255)); // Scanline renderer for solid filling. agg::renderer_scanline_aa_solid<agg::renderer_base<agg::pixfmt_bgra32> > ren(renb); // Rasterizer & scanline agg::rasterizer_scanline_aa<> ras; agg::scanline_p8 sl; // Polygon (triangle) ras.move_to_d(20.7, 34.15); ras.line_to_d(398.23, 123.43); ras.line_to_d(165.45, 401.87); // Setting the attrribute (color) & Rendering ren.color(agg::rgba8(80, 90, 60)); agg::render_scanlines(ras, sl, ren); //============================================================ //------------------------------------------------------------ // Display the image. If the image is B-G-R-A (32-bits per pixel) // one can use AlphaBlend instead of BitBlt. In case of AlphaBlend // one also should clear the image with zero alpha, i.e. rgba8(0,0,0,0) ::BitBlt( hdc, rt.left, rt.top, width, height, mem_dc, 0, 0, SRCCOPY ); // Free resources ::SelectObject(mem_dc, temp); ::DeleteObject(bmp); ::DeleteObject(mem_dc); EndPaint(hWnd, &ps); } break; case WM_ERASEBKGND: // Don't forget to do nothing on Erase Background event :-) break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } // Mesage handler for about box. LRESULT CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_INITDIALOG: return TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); return TRUE; } break; } return FALSE; }
4,777
338
from .sklearn_registration import *
11