max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
461
<gh_stars>100-1000 /*- * Copyright (c) 2002 <NAME>. * 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 AUTHOR 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 AUTHOR 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. */ /* FUNCTION <<getwchar>>, <<getwchar_unlocked>>---read a wide character from standard input INDEX getwchar INDEX getwchar_unlocked INDEX _getwchar_r INDEX _getwchar_unlocked_r SYNOPSIS #include <wchar.h> wint_t getwchar(void); #define _GNU_SOURCE #include <wchar.h> wint_t getwchar_unlocked(void); #include <wchar.h> wint_t _getwchar_r(struct _reent *<[reent]>); #include <wchar.h> wint_t _getwchar_unlocked_r(struct _reent *<[reent]>); DESCRIPTION <<getwchar>> function or macro is the wide character equivalent of the <<getchar>> function. You can use <<getwchar>> to get the next wide character from the standard input stream. As a side effect, <<getwchar>> advances the standard input's current position indicator. <<getwchar_unlocked>> is a non-thread-safe version of <<getwchar>>. <<getwchar_unlocked>> may only safely be used within a scope protected by flockfile() (or ftrylockfile()) and funlockfile(). This function may safely be used in a multi-threaded program if and only if they are called while the invoking thread owns the (FILE *) object, as is the case after a successful call to the flockfile() or ftrylockfile() functions. If threads are disabled, then <<getwchar_unlocked>> is equivalent to <<getwchar>>. The alternate functions <<_getwchar_r>> and <<_getwchar_unlocked_r>> are reentrant versions of the above. The extra argument <[reent]> is a pointer to a reentrancy structure. RETURNS The next wide character cast to <<wint_t>>, unless there is no more data, or the host system reports a read error; in either of these situations, <<getwchar>> returns <<WEOF>>. You can distinguish the two situations that cause an <<WEOF>> result by using `<<ferror(stdin)>>' and `<<feof(stdin)>>'. PORTABILITY <<getwchar>> is required by C99. <<getwchar_unlocked>> is a GNU extension. */ #include <_ansi.h> #include <reent.h> #include <stdio.h> #include <wchar.h> #include "local.h" #undef getwchar wint_t _getwchar_r (struct _reent *ptr) { return _fgetwc_r (ptr, stdin); } /* * Synonym for fgetwc(stdin). */ wint_t getwchar (void) { _REENT_SMALL_CHECK_INIT (_REENT); return fgetwc (stdin); }
1,156
331
<reponame>greenlion/SIMDCompressionAndIntersection<gh_stars>100-1000 /** * This code is released under the * Apache License Version 2.0 http://www.apache.org/licenses/. * */ #include <unistd.h> #include "synthetic.h" #include "timer.h" #include "intersection.h" // https://code.google.com/p/likwid/wiki/LikwidPerfCtr#Using_the_marker_API #ifdef LIKWID_MARKERS // see 'make likwidintersection' for compiler flags #include <likwid.h> #endif using namespace SIMDCompressionLib; /** * Goal: have the largest array count about 4M terms (this * matches our experiments), and vary the size of the * smallest array vary from 1*4M to 1/1000*4M (or so). * * Set the size of the intersection to 30% of the lesser * array. (Again, this matches our real data...) * * To match our clueweb, we use a range of values in [0,2**26). */ template <class generator> pair<vector<uint32_t>, vector<uint32_t>> getNaivePair(generator gen, uint32_t minlength, uint32_t Max, float sizeratio, float intersectionratio) { if (sizeratio < 1) throw runtime_error("sizeratio should be larger or equal to 1"); if (intersectionratio < 0) throw runtime_error("intersectionratio should be positive"); if (intersectionratio > 1) throw runtime_error("intersectionratio cannot be larger than 1"); const uint32_t maxlenth = static_cast<uint32_t>(round(static_cast<float>(minlength) * sizeratio)); if (maxlenth > Max) throw runtime_error( "I can't generate an array so large in such a small range."); if (maxlenth < minlength) throw runtime_error("something went wrong, possibly an overflow."); // we basically assume that, if we do nothing, intersections are very small const uint32_t intersize = static_cast<uint32_t>( round(static_cast<float>(minlength) * intersectionratio)); vector<uint32_t> inter = gen.generate(intersize, Max); vector<uint32_t> smallest = unite(gen.generate(static_cast<uint32_t>(minlength - inter.size()), Max), inter); vector<uint32_t> largest = unite( gen.generate(static_cast<uint32_t>(maxlenth - inter.size()), Max), inter); vector<uint32_t> intersection = intersect(smallest, largest); if (largest.size() > smallest.size()) return pair<vector<uint32_t>, vector<uint32_t>>(smallest, largest); return pair<vector<uint32_t>, vector<uint32_t>>(largest, smallest); } /** * Silly function. */ uint16_t _high16(uint32_t x) { return static_cast<uint16_t>(x >> 16); } /** * Another function. */ uint16_t _low16(uint32_t x) { return static_cast<uint16_t>(x); } /** * From Schlegel et al., Fast Sorted-Set Intersection using SIMD Instructions */ // A - sorted array // s_a - size of A // R - partitioned sorted array size_t partition(const uint32_t *A, const size_t s_a, uint16_t *R, const size_t /*Rlength*/) { uint16_t high = 0; int partition_length = 0; size_t partition_size_position = 1; size_t counter = 0; size_t p = 0; if (p < s_a) { uint16_t chigh = _high16(A[p]); // upper dword uint16_t clow = _low16(A[p]); // lower dword if (chigh == 0) { R[counter++] = chigh; // partition prefix R[counter++] = 0; // reserve place for partition size R[counter++] = clow; // write the first element partition_length = 1; // reset counters high = chigh; ++p; } } for (; p < s_a; p++) { uint16_t chigh = _high16(A[p]); // upper dword uint16_t clow = _low16(A[p]); // lower dword if (chigh == high && p != 0) { // add element to the current partition R[counter++] = clow; partition_length++; } else { // start new partition R[counter++] = chigh; // partition prefix R[counter++] = 0; // reserve place for partition size R[counter++] = clow; // write the first element R[partition_size_position] = static_cast<uint16_t>(partition_length - 1); // store "-1" partition_length = 1; // reset counters partition_size_position = counter - 2; high = chigh; } } R[partition_size_position] = static_cast<uint16_t>(partition_length - 1); return counter; } const static __m128i shuffle_mask16[256] = { _mm_setr_epi8(-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(4, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 4, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 4, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 4, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(6, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 6, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 6, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 6, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(4, 5, 6, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 4, 5, 6, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 4, 5, 6, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 4, 5, 6, 7, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(4, 5, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 4, 5, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 4, 5, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 4, 5, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(6, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(10, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 10, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 10, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 10, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(4, 5, 10, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 4, 5, 10, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 4, 5, 10, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 4, 5, 10, 11, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(6, 7, 10, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 6, 7, 10, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 6, 7, 10, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 6, 7, 10, 11, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(4, 5, 6, 7, 10, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 4, 5, 6, 7, 10, 11, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 4, 5, 6, 7, 10, 11, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 4, 5, 6, 7, 10, 11, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(8, 9, 10, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 8, 9, 10, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 8, 9, 10, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 8, 9, 10, 11, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(4, 5, 8, 9, 10, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 4, 5, 8, 9, 10, 11, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 4, 5, 8, 9, 10, 11, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 4, 5, 8, 9, 10, 11, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(6, 7, 8, 9, 10, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 6, 7, 8, 9, 10, 11, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 6, 7, 8, 9, 10, 11, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 6, 7, 8, 9, 10, 11, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(4, 5, 6, 7, 8, 9, 10, 11, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 4, 5, 6, 7, 8, 9, 10, 11, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, -1, -1, -1, -1), _mm_setr_epi8(12, 13, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(4, 5, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 4, 5, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 4, 5, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 4, 5, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(6, 7, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 6, 7, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 6, 7, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 6, 7, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(4, 5, 6, 7, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 4, 5, 6, 7, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 4, 5, 6, 7, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 4, 5, 6, 7, 12, 13, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(8, 9, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 8, 9, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 8, 9, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 8, 9, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(4, 5, 8, 9, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 4, 5, 8, 9, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 4, 5, 8, 9, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 4, 5, 8, 9, 12, 13, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(6, 7, 8, 9, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 6, 7, 8, 9, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 6, 7, 8, 9, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 6, 7, 8, 9, 12, 13, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(4, 5, 6, 7, 8, 9, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 4, 5, 6, 7, 8, 9, 12, 13, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 4, 5, 6, 7, 8, 9, 12, 13, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 13, -1, -1, -1, -1), _mm_setr_epi8(10, 11, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 10, 11, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 10, 11, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 10, 11, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(4, 5, 10, 11, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 4, 5, 10, 11, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 4, 5, 10, 11, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 4, 5, 10, 11, 12, 13, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(6, 7, 10, 11, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 6, 7, 10, 11, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 6, 7, 10, 11, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 6, 7, 10, 11, 12, 13, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(4, 5, 6, 7, 10, 11, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 4, 5, 6, 7, 10, 11, 12, 13, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 4, 5, 6, 7, 10, 11, 12, 13, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 4, 5, 6, 7, 10, 11, 12, 13, -1, -1, -1, -1), _mm_setr_epi8(8, 9, 10, 11, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 8, 9, 10, 11, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 8, 9, 10, 11, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 8, 9, 10, 11, 12, 13, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(4, 5, 8, 9, 10, 11, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 4, 5, 8, 9, 10, 11, 12, 13, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 4, 5, 8, 9, 10, 11, 12, 13, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 4, 5, 8, 9, 10, 11, 12, 13, -1, -1, -1, -1), _mm_setr_epi8(6, 7, 8, 9, 10, 11, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 6, 7, 8, 9, 10, 11, 12, 13, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 6, 7, 8, 9, 10, 11, 12, 13, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 6, 7, 8, 9, 10, 11, 12, 13, -1, -1, -1, -1), _mm_setr_epi8(4, 5, 6, 7, 8, 9, 10, 11, 12, 13, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, -1, -1), _mm_setr_epi8(14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(4, 5, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 4, 5, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 4, 5, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 4, 5, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(6, 7, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 6, 7, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 6, 7, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 6, 7, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(4, 5, 6, 7, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 4, 5, 6, 7, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 4, 5, 6, 7, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 4, 5, 6, 7, 14, 15, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(8, 9, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 8, 9, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 8, 9, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 8, 9, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(4, 5, 8, 9, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 4, 5, 8, 9, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 4, 5, 8, 9, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 4, 5, 8, 9, 14, 15, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(6, 7, 8, 9, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 6, 7, 8, 9, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 6, 7, 8, 9, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 6, 7, 8, 9, 14, 15, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(4, 5, 6, 7, 8, 9, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 4, 5, 6, 7, 8, 9, 14, 15, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 4, 5, 6, 7, 8, 9, 14, 15, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 14, 15, -1, -1, -1, -1), _mm_setr_epi8(10, 11, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 10, 11, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 10, 11, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 10, 11, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(4, 5, 10, 11, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 4, 5, 10, 11, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 4, 5, 10, 11, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 4, 5, 10, 11, 14, 15, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(6, 7, 10, 11, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 6, 7, 10, 11, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 6, 7, 10, 11, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 6, 7, 10, 11, 14, 15, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(4, 5, 6, 7, 10, 11, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 4, 5, 6, 7, 10, 11, 14, 15, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 4, 5, 6, 7, 10, 11, 14, 15, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 4, 5, 6, 7, 10, 11, 14, 15, -1, -1, -1, -1), _mm_setr_epi8(8, 9, 10, 11, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 8, 9, 10, 11, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 8, 9, 10, 11, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 8, 9, 10, 11, 14, 15, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(4, 5, 8, 9, 10, 11, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 4, 5, 8, 9, 10, 11, 14, 15, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 4, 5, 8, 9, 10, 11, 14, 15, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 4, 5, 8, 9, 10, 11, 14, 15, -1, -1, -1, -1), _mm_setr_epi8(6, 7, 8, 9, 10, 11, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 6, 7, 8, 9, 10, 11, 14, 15, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 6, 7, 8, 9, 10, 11, 14, 15, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 6, 7, 8, 9, 10, 11, 14, 15, -1, -1, -1, -1), _mm_setr_epi8(4, 5, 6, 7, 8, 9, 10, 11, 14, 15, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 4, 5, 6, 7, 8, 9, 10, 11, 14, 15, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 14, 15, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 14, 15, -1, -1), _mm_setr_epi8(12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(4, 5, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 4, 5, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 4, 5, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 4, 5, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(6, 7, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 6, 7, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 6, 7, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 6, 7, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(4, 5, 6, 7, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 4, 5, 6, 7, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 4, 5, 6, 7, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 4, 5, 6, 7, 12, 13, 14, 15, -1, -1, -1, -1), _mm_setr_epi8(8, 9, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 8, 9, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 8, 9, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 8, 9, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(4, 5, 8, 9, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 4, 5, 8, 9, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 4, 5, 8, 9, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 4, 5, 8, 9, 12, 13, 14, 15, -1, -1, -1, -1), _mm_setr_epi8(6, 7, 8, 9, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 6, 7, 8, 9, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 6, 7, 8, 9, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 6, 7, 8, 9, 12, 13, 14, 15, -1, -1, -1, -1), _mm_setr_epi8(4, 5, 6, 7, 8, 9, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 4, 5, 6, 7, 8, 9, 12, 13, 14, 15, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 4, 5, 6, 7, 8, 9, 12, 13, 14, 15, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 13, 14, 15, -1, -1), _mm_setr_epi8(10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(4, 5, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 4, 5, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 4, 5, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1), _mm_setr_epi8(6, 7, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 6, 7, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 6, 7, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 6, 7, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1), _mm_setr_epi8(4, 5, 6, 7, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 4, 5, 6, 7, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 4, 5, 6, 7, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 4, 5, 6, 7, 10, 11, 12, 13, 14, 15, -1, -1), _mm_setr_epi8(8, 9, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 8, 9, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 8, 9, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 8, 9, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1), _mm_setr_epi8(4, 5, 8, 9, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 4, 5, 8, 9, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 4, 5, 8, 9, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 4, 5, 8, 9, 10, 11, 12, 13, 14, 15, -1, -1), _mm_setr_epi8(6, 7, 8, 9, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1), _mm_setr_epi8(2, 3, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, -1, -1), _mm_setr_epi8(4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1), _mm_setr_epi8(0, 1, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, -1, -1), _mm_setr_epi8(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, -1, -1), _mm_setr_epi8(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)}; /** * From Schlegel et al., Fast Sorted-Set Intersection using SIMD Instructions * * Close to the original */ static size_t _original_intersect_vector16(const uint16_t *A, const uint16_t *B, const size_t s_a, const size_t s_b, uint16_t *C) { size_t count = 0; size_t i_a = 0, i_b = 0; const size_t st_a = (s_a / 8) * 8; const size_t st_b = (s_b / 8) * 8; __m128i v_a, v_b; if ((i_a < st_a) and (i_b < st_b)) { v_a = _mm_loadu_si128((const __m128i *)&A[i_a]); v_b = _mm_loadu_si128((const __m128i *)&B[i_b]); while (true) { const __m128i res_v = _mm_cmpestrm( v_b, 16, v_a, 16, _SIDD_UWORD_OPS | _SIDD_CMP_EQUAL_ANY | _SIDD_BIT_MASK); const int r = _mm_extract_epi32(res_v, 0); __m128i p = _mm_shuffle_epi8(v_a, shuffle_mask16[r]); _mm_storeu_si128((__m128i *)&C[count], p); count += _mm_popcnt_u32(r); const uint16_t a_max = A[i_a + 7]; const uint16_t b_max = B[i_b + 7]; if (a_max <= b_max) { i_a += 8; if (i_a == st_a) break; v_a = _mm_loadu_si128((const __m128i *)&A[i_a]); } if (b_max <= a_max) { i_b += 8; if (i_b == st_b) break; v_b = _mm_loadu_si128((const __m128i *)&B[i_b]); } } } // intersect the tail using scalar intersection while (i_a < s_a && i_b < s_b) { if (A[i_a] < B[i_b]) { i_a++; } else if (B[i_b] < A[i_a]) { i_b++; } else { C[count] = A[i_a]; count++; i_a++; i_b++; } } return count; } /** * From Schlegel et al., Fast Sorted-Set Intersection using SIMD Instructions * * Optimized by <NAME> on May 3rd 2013 */ static size_t _intersect_vector16(const uint16_t *A, const uint16_t *B, const size_t s_a, const size_t s_b, uint16_t *C) { size_t count = 0; size_t i_a = 0, i_b = 0; const size_t st_a = (s_a / 8) * 8; const size_t st_b = (s_b / 8) * 8; __m128i v_a, v_b; if ((i_a < st_a) and (i_b < st_b)) { v_a = _mm_loadu_si128((const __m128i *)&A[i_a]); v_b = _mm_loadu_si128((const __m128i *)&B[i_b]); while ((A[i_a] == 0) or (B[i_b] == 0)) { const __m128i res_v = _mm_cmpestrm(v_b, 8, v_a, 8, _SIDD_UWORD_OPS | _SIDD_CMP_EQUAL_ANY | _SIDD_BIT_MASK); const int r = _mm_extract_epi32(res_v, 0); __m128i p = _mm_shuffle_epi8(v_a, shuffle_mask16[r]); _mm_storeu_si128((__m128i *)&C[count], p); count += _mm_popcnt_u32(r); const uint16_t a_max = A[i_a + 7]; const uint16_t b_max = B[i_b + 7]; if (a_max <= b_max) { i_a += 8; if (i_a == st_a) break; v_a = _mm_loadu_si128((const __m128i *)&A[i_a]); } if (b_max <= a_max) { i_b += 8; if (i_b == st_b) break; v_b = _mm_loadu_si128((const __m128i *)&B[i_b]); } } if ((i_a < st_a) and (i_b < st_b)) while (true) { const __m128i res_v = _mm_cmpistrm( v_b, v_a, _SIDD_UWORD_OPS | _SIDD_CMP_EQUAL_ANY | _SIDD_BIT_MASK); const int r = _mm_extract_epi32(res_v, 0); __m128i p = _mm_shuffle_epi8(v_a, shuffle_mask16[r]); _mm_storeu_si128((__m128i *)&C[count], p); count += _mm_popcnt_u32(r); const uint16_t a_max = A[i_a + 7]; const uint16_t b_max = B[i_b + 7]; if (a_max <= b_max) { i_a += 8; if (i_a == st_a) break; v_a = _mm_loadu_si128((const __m128i *)&A[i_a]); } if (b_max <= a_max) { i_b += 8; if (i_b == st_b) break; v_b = _mm_loadu_si128((const __m128i *)&B[i_b]); } } } // intersect the tail using scalar intersection while (i_a < s_a && i_b < s_b) { if (A[i_a] < B[i_b]) { i_a++; } else if (B[i_b] < A[i_a]) { i_b++; } else { C[count] = A[i_a]; count++; i_a++; i_b++; } } return count; } static size_t _intersectV1_vector16(const uint16_t *A, const uint16_t *B, const size_t s_a, const size_t s_b, uint16_t *C) { if (s_a > s_b) return _intersectV1_vector16(B, A, s_b, s_a, C); size_t count = 0; size_t i_a = 0, i_b = 0; const size_t st_a = s_a; const size_t st_b = (s_b / 8) * 8; __m128i v_b; if ((i_a < st_a) and (i_b < st_b)) { v_b = _mm_loadu_si128((const __m128i *)&B[i_b]); while (true) { const __m128i v_a = _mm_set1_epi16(A[i_a]); const __m128i F0 = _mm_cmpeq_epi16(v_a, v_b); #ifdef __SSE4_1__ if (_mm_testz_si128(F0, F0)) { #else if (!_mm_movemask_epi8(F0)) { #endif } else { C[count] = A[i_a]; count++; } ++i_a; if (i_a == st_a) goto FINISH_SCALAR; if (B[i_b + 7] < A[i_a]) { i_b += 8; if (i_b == st_b) goto FINISH_SCALAR; v_b = _mm_loadu_si128((const __m128i *)&B[i_b]); } } } FINISH_SCALAR: // intersect the tail using scalar intersection while (i_a < s_a && i_b < s_b) { if (A[i_a] < B[i_b]) { i_a++; } else if (B[i_b] < A[i_a]) { i_b++; } else { C[count] = A[i_a]; count++; i_a++; i_b++; } } return count; } static size_t _intersectscalar_vector16(const uint16_t *A, const uint16_t *B, const size_t s_a, const size_t s_b, uint16_t *C) { // intersect the tail using scalar intersection size_t count = 0, i_a = 0, i_b = 0; while (i_a < s_a && i_b < s_b) { if (A[i_a] < B[i_b]) { i_a++; } else if (B[i_b] < A[i_a]) { i_b++; } else { C[count] = A[i_a]; count++; i_a++; i_b++; } } return count; } size_t intersect_partitionedV1(const uint16_t *A, const size_t s_a, const uint16_t *B, const size_t s_b, uint16_t *C) { size_t i_a = 0, i_b = 0; size_t counter = 0; while (i_a < s_a && i_b < s_b) { if (A[i_a] < B[i_b]) { do { i_a += static_cast<size_t>(A[i_a + 1]) + 2 + 1; if (i_a >= s_a) goto end; } while (A[i_a] < B[i_b]); } if (B[i_b] < A[i_a]) { do { i_b += static_cast<size_t>(B[i_b + 1]) + 2 + 1; if (i_b >= s_b) goto end; } while (B[i_b] < A[i_a]); } else { size_t partition_size = _intersectV1_vector16( &A[i_a + 2], &B[i_b + 2], static_cast<size_t>(A[i_a + 1]) + 1, static_cast<size_t>(B[i_b + 1]) + 1, &C[counter + 1]); C[counter++] = (uint16_t) partition_size; // write partition size counter += partition_size; i_a += static_cast<size_t>(A[i_a + 1]) + 2 + 1; i_b += static_cast<size_t>(B[i_b + 1]) + 2 + 1; } } end: return counter; } size_t intersect_partitionedscalar(const uint16_t *A, const size_t s_a, const uint16_t *B, const size_t s_b, uint16_t *C) { size_t i_a = 0, i_b = 0; size_t counter = 0; while (i_a < s_a && i_b < s_b) { if (A[i_a] < B[i_b]) { do { i_a += static_cast<size_t>(A[i_a + 1]) + 2 + 1; if (i_a >= s_a) goto end; } while (A[i_a] < B[i_b]); } if (B[i_b] < A[i_a]) { do { i_b += static_cast<size_t>(B[i_b + 1]) + 2 + 1; if (i_b >= s_b) goto end; } while (B[i_b] < A[i_a]); } else { size_t partition_size = _intersectscalar_vector16( &A[i_a + 2], &B[i_b + 2], static_cast<size_t>(A[i_a + 1]) + 1, static_cast<size_t>(B[i_b + 1]) + 1, &C[counter + 1]); C[counter++] = (uint16_t) partition_size; // write partition size counter += partition_size; i_a += static_cast<size_t>(A[i_a + 1]) + 2 + 1; i_b += static_cast<size_t>(B[i_b + 1]) + 2 + 1; } } end: return counter; } /** * Version optimized by <NAME> of * From Schlegel et al., Fast Sorted-Set Intersection using SIMD Instructions */ size_t intersect_partitioned(const uint16_t *A, const size_t s_a, const uint16_t *B, const size_t s_b, uint16_t *C) { size_t i_a = 0, i_b = 0; size_t counter = 0; while (i_a < s_a && i_b < s_b) { if (A[i_a] < B[i_b]) { do { i_a += static_cast<size_t>(A[i_a + 1]) + 2 + 1; if (i_a >= s_a) goto end; } while (A[i_a] < B[i_b]); } if (B[i_b] < A[i_a]) { do { i_b += static_cast<size_t>(B[i_b + 1]) + 2 + 1; if (i_b >= s_b) goto end; } while (B[i_b] < A[i_a]); } else { size_t partition_size = _intersect_vector16( &A[i_a + 2], &B[i_b + 2], static_cast<size_t>(A[i_a + 1]) + 1, static_cast<size_t>(B[i_b + 1]) + 1, &C[counter + 1]); C[counter++] = (uint16_t) partition_size; // write partition size counter += partition_size; i_a += static_cast<size_t>(A[i_a + 1]) + 2 + 1; i_b += static_cast<size_t>(B[i_b + 1]) + 2 + 1; } } end: return counter; } size_t original_intersect_partitioned(const uint16_t *A, const size_t s_a, const uint16_t *B, const size_t s_b, uint16_t *C) { size_t i_a = 0, i_b = 0; size_t counter = 0; while (i_a < s_a && i_b < s_b) { if (A[i_a] < B[i_b]) { do { i_a += static_cast<size_t>(A[i_a + 1]) + 2 + 1; if (i_a >= s_a) goto end; } while (A[i_a] < B[i_b]); } if (B[i_b] < A[i_a]) { do { i_b += static_cast<size_t>(B[i_b + 1]) + 2 + 1; if (i_b >= s_b) goto end; } while (B[i_b] < A[i_a]); } else { size_t partition_size = _original_intersect_vector16( &A[i_a + 2], &B[i_b + 2], static_cast<size_t>(A[i_a + 1]) + 1, static_cast<size_t>(B[i_b + 1]) + 1, &C[counter + 1]); C[counter++] = (uint16_t) partition_size; // write partition size counter += partition_size; i_a += static_cast<size_t>(A[i_a + 1]) + 2 + 1; i_b += static_cast<size_t>(B[i_b + 1]) + 2 + 1; } } end: return counter; } void printusage() { #ifdef LIKWID_MARKERS cout << "example: likwid -m -C 1 -g BRANCH ./likwidintersection -u > " "uniform.out" << endl; #else cout << " -u switches to uniform distribution" << endl; #endif } int main(int argc, char **argv) { size_t howmany = 0; size_t loop = 3; bool uniform = false; uint32_t Big = 22; float intersectionratio = 0.3f; uint32_t MaxBit = 26; int c; while ((c = getopt(argc, argv, "uns:m:R:M:S:l:h")) != -1) switch (c) { case 'h': printusage(); return 0; case 'S': Big = atoi(optarg); break; case 'R': intersectionratio = (float)atof(optarg); break; case 'M': MaxBit = atoi(optarg); if (MaxBit < 1) { printusage(); return -1; } break; case 'm': howmany = atoi(optarg); if (howmany < 1) { printusage(); return -1; } break; case 'l': loop = atoi(optarg); if (loop < 1) { printusage(); return -1; } break; case 'u': uniform = true; break; default: abort(); } if (howmany == 0) { howmany = 5; } cout << "# howmany : " << howmany << endl; cout << "# loop : " << loop << endl; cout << "# distribution : " << (uniform ? "uniform" : "clustered") << endl; cout << "# Big : " << Big << endl; cout << "# intersectionratio : " << intersectionratio << endl; cout << "# MaxBit : " << MaxBit << endl; UniformDataGenerator udg; ClusteredDataGenerator cdg; WallClockTimer z; size_t bogus = 0; vector<uint32_t> buffer(2 * (1U << Big)); #ifdef LIKWID_MARKERS char currentMarker[64]; likwid_markerInit(); #endif cout << "# size-ratio\t"; for (string intername : IntersectionFactory::allNames()) { cout << intername << "\t"; } cout << " partioned (Schlegel et al.: improved, original) 16-bitV1 " "16-bitscalar "; cout << "relative-intersection-size " << endl; for (double ir = 1.001; ir <= 10000; ir = ir * sqrt(1.9)) { vector<pair<vector<uint32_t>, vector<uint32_t>>> data(howmany); uint32_t smallsize = static_cast<uint32_t>(round(static_cast<float>(1 << Big) / ir)); cout << "#generating data..."; cout.flush(); for (size_t k = 0; k < howmany; ++k) { data[k] = uniform ? getNaivePair(udg, smallsize, 1U << MaxBit, (float)ir, intersectionratio) : getNaivePair(cdg, smallsize, 1U << MaxBit, (float)ir, intersectionratio); } cout << "ok." << endl; cout << "#partitions..."; vector<pair<vector<uint16_t>, vector<uint16_t>>> datapart(howmany); for (size_t k = 0; k < howmany; ++k) { vector<uint16_t> part1(data[k].first.size() * 4); size_t p1length = partition(data[k].first.data(), data[k].first.size(), part1.data(), part1.size()); part1.resize(p1length); part1.shrink_to_fit(); vector<uint16_t> part2(data[k].second.size() * 4); size_t p2length = partition(data[k].second.data(), data[k].second.size(), part2.data(), part2.size()); part2.resize(p2length); part2.shrink_to_fit(); datapart[k] = make_pair(part1, part2); } cout << "ok." << endl; cout << ir << "\t"; float aratio = 0.0f; for (string intername : IntersectionFactory::allNames()) { intersectionfunction interfnc = IntersectionFactory::getFromName(intername); size_t volume = 0; #ifdef LIKWID_MARKERS snprintf(currentMarker, sizeof(currentMarker), "%s %.2f", intername.c_str(), ir); likwid_markerStartRegion(currentMarker); #endif z.reset(); for (size_t k = 0; k < data.size(); ++k) { volume += (data[k].first.size() + data[k].second.size()) * loop; for (size_t L = 0; L < loop; ++L) { aratio = interfnc(data[k].first.data(), (data[k].first).size(), data[k].second.data(), (data[k].second).size(), buffer.data()); bogus += size_t(aratio); } } cout << setw(10) << setprecision(5) << (volume / (static_cast<double>(z.split()))) << "\t"; #ifdef LIKWID_MARKERS likwid_markerStopRegion(currentMarker); #endif } z.reset(); size_t volume = 0; for (size_t k = 0; k < data.size(); ++k) { volume += (data[k].first.size() + data[k].second.size()) * loop; for (size_t L = 0; L < loop; ++L) { aratio = intersect_partitioned( datapart[k].first.data(), (datapart[k].first).size(), datapart[k].second.data(), (datapart[k].second).size(), (uint16_t *)buffer.data()); bogus += size_t(aratio); } } cout << setw(10) << setprecision(5) << (volume / (static_cast<double>(z.split()))) << "\t"; z.reset(); volume = 0; for (size_t k = 0; k < data.size(); ++k) { volume += (data[k].first.size() + data[k].second.size()) * loop; for (size_t L = 0; L < loop; ++L) { aratio = original_intersect_partitioned( datapart[k].first.data(), (datapart[k].first).size(), datapart[k].second.data(), (datapart[k].second).size(), (uint16_t *)buffer.data()); bogus += size_t(aratio); } } cout << setw(10) << setprecision(5) << (volume / (static_cast<double>(z.split()))) << "\t"; z.reset(); volume = 0; for (size_t k = 0; k < data.size(); ++k) { volume += (data[k].first.size() + data[k].second.size()) * loop; for (size_t L = 0; L < loop; ++L) { aratio = intersect_partitionedV1( datapart[k].first.data(), (datapart[k].first).size(), datapart[k].second.data(), (datapart[k].second).size(), (uint16_t *)buffer.data()); bogus += size_t(aratio); } } cout << setw(10) << setprecision(5) << (volume / (static_cast<double>(z.split()))) << "\t"; z.reset(); volume = 0; for (size_t k = 0; k < data.size(); ++k) { volume += (data[k].first.size() + data[k].second.size()) * loop; for (size_t L = 0; L < loop; ++L) { aratio = intersect_partitionedscalar( datapart[k].first.data(), (datapart[k].first).size(), datapart[k].second.data(), (datapart[k].second).size(), (uint16_t *)buffer.data()); bogus += size_t(aratio); } } cout << setw(10) << setprecision(5) << (volume / (static_cast<double>(z.split()))) << "\t"; cout << "\t\t" << aratio / smallsize; cout << endl; } #ifdef LIKWID_MARKERS likwid_markerClose(); #endif cout << "# bogus = " << bogus << endl; }
24,965
1,465
{ "type": "Row", "category": "widget", "description": "A composite with the `layout` property initialized with a `RowLayout`. All children are automatically arranged in one horizontal row, starting from the left.", "extends": "Composite", "constructor": { "access": "public", "parameters": [ { "name": "properties", "type": { "interface": "Properties", "generics": ["Row"] }, "optional": true, "description": "Sets all key-value pairs in the properties object as widget properties." } ] }, "properties": { "layout": { "type": "RowLayout", "default": "RowLayout", "const": true, "description": "The row layout manager responsible for interpreting the [`layoutData`](./Widget.md#layoutdata) of the child widgets of this Composite." }, "spacing": { "type": "number", "default": 0, "const": true, "description": "The space between the children in device independent pixel." }, "alignment": { "type": {"union": ["'top'", "'centerY'", "'stretchY'", "'bottom'", "'baseline'"]}, "const": true, "default": "'top'", "description": "Determines the vertical placement of the children.\n\n For `stretchY` to work correctly the `Row` needs to be given a height either by setting `height` or by setting `top` and `bottom`.\n\nIf `baseline` is set the first widget in the row will determine where that baseline is. By setting `top`, `bottom` or `centerY` on that widget the baseline can be shifted." } }, "links": [ { "title": "Creating a simple `Row`", "snippet": "row.jsx" }, { "title": "Creating a `Row` with vertical alignment", "snippet": "row-alignment.jsx" }, { "title": "Creating a `Row` with horizontal alignment", "snippet": "row-halign.jsx" } ] }
723
672
// // RNSketch.h // RNSketch // // Created by <NAME> on 28/04/2016. // Copyright © 2016 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> #if __has_include(<React/RCTViewManager.h>) // React Native >= 0.40 #import <React/UIView+React.h> #else // React Native <= 0.39 #import "UIView+React.h" #endif @interface RNSketch : UIView - (void)clear; - (NSString *)base64Code; // Events @property (nonatomic, copy) RCTBubblingEventBlock onChange; @property (nonatomic, copy) RCTBubblingEventBlock onClear; // Properties @property (nonatomic, strong) UIColor *fillColor; @property (nonatomic, strong) NSString *imageType; @property (nonatomic, strong) UIColor *strokeColor; @property (nonatomic, assign) NSInteger strokeThickness; @end
276
1,909
<gh_stars>1000+ package org.knowm.xchange.coincheck.dto; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.PropertyNamingStrategies; import com.fasterxml.jackson.databind.annotation.JsonNaming; import lombok.Getter; import si.mazi.rescu.HttpStatusExceptionSupport; @JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class) @Getter public class CoincheckException extends HttpStatusExceptionSupport { @JsonProperty private final boolean success; @JsonProperty private final String error; @JsonCreator public CoincheckException( @JsonProperty("success") boolean success, @JsonProperty("error") String error) { super(error); this.success = success; this.error = error; } }
272
335
{ "word": "Approximate", "definitions": [ "Come close or be similar to something in quality, nature, or quantity.", "Estimate or calculate (a quantity) fairly accurately." ], "parts-of-speech": "Verb" }
88
1,367
<gh_stars>1000+ # -*- coding: UTF-8 -*- """ Module with tests for Strings """ #----------------------------------------------------------------------------- # Copyright (c) 2013, the IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- import os import re from ...tests.base import TestsBase from ..strings import (wrap_text, html2text, add_anchor, strip_dollars, strip_files_prefix, get_lines, comment_lines, ipython2python, posix_path, add_prompts, prevent_list_blocks,ascii_only ) #----------------------------------------------------------------------------- # Class #----------------------------------------------------------------------------- class TestStrings(TestsBase): def test_wrap_text(self): """wrap_text test""" test_text = """ Tush! never tell me; I take it much unkindly That thou, Iago, who hast had my purse As if the strings were thine, shouldst know of this. """ for length in [30,5,1]: self._confirm_wrap_text(test_text, length) def _confirm_wrap_text(self, text, length): for line in wrap_text(text, length).split('\n'): assert len(line) <= length def test_html2text(self): """html2text test""" #TODO: More tests self.assertEqual(html2text('<name>joe</name>'), 'joe') def test_add_anchor(self): """add_anchor test""" #TODO: More tests results = add_anchor('<b>Hello World!</b>') assert 'Hello World!' in results assert 'id="' in results assert 'class="anchor-link"' in results assert '<b' in results assert '</b>' in results def test_add_anchor_fail(self): """add_anchor does nothing when it fails""" html = '<h1>Hello <br>World!</h1>' results = add_anchor(html) self.assertEqual(html, results) def test_add_anchor_valid_url_fragment(self): """add_anchor creates a valid URL fragment""" results = add_anchor(r'<h1>$\pi$ with #s and unicode 中</h1>') match = re.search(r'href="#(.*?)"', results) assert match assert len(match.groups()) == 1 href = match.groups()[0] assert len(href) > 0 # No invalid characters should be present assert '\\' not in href assert '#' not in href assert '中' not in href def test_strip_dollars(self): """strip_dollars test""" tests = [ ('', ''), (' ', ' '), ('$$', ''), ('$H$', 'H'), ('$He', 'He'), ('H$el', 'H$el'), ('Hell$', 'Hell'), ('Hello', 'Hello'), ('W$o$rld', 'W$o$rld')] for test in tests: self._try_strip_dollars(test[0], test[1]) def _try_strip_dollars(self, test, result): self.assertEqual(strip_dollars(test), result) def test_strip_files_prefix(self): """strip_files_prefix test""" tests = [ ('', ''), ('/files', '/files'), ('test="/files"', 'test="/files"'), ('My files are in `files/`', 'My files are in `files/`'), ('<a href="files/test.html">files/test.html</a>', '<a href="test.html">files/test.html</a>'), ('<a href="/files/test.html">files/test.html</a>', '<a href="test.html">files/test.html</a>'), ("<a href='files/test.html'>files/test.html</a>", "<a href='test.html'>files/test.html</a>"), ('<img src="files/url/location.gif">', '<img src="url/location.gif">'), ('<img src="/files/url/location.gif">', '<img src="url/location.gif">'), ('hello![caption]', 'hello![caption]'), ('hello![caption](/url/location.gif)', 'hello![caption](/url/location.gif)'), ('hello![caption](url/location.gif)', 'hello![caption](url/location.gif)'), ('hello![caption](url/location.gif)', 'hello![caption](url/location.gif)'), ('hello![caption](files/url/location.gif)', 'hello![caption](url/location.gif)'), ('hello![caption](/files/url/location.gif)', 'hello![caption](url/location.gif)'), ('hello [text](/files/url/location.gif)', 'hello [text](url/location.gif)'), ('hello [text space](files/url/location.gif)', 'hello [text space](url/location.gif)'), ] for test in tests: self._try_files_prefix(test[0], test[1]) def _try_files_prefix(self, test, result): self.assertEqual(strip_files_prefix(test), result) def test_comment_lines(self): """comment_lines test""" for line in comment_lines('hello\nworld\n!').split('\n'): assert line.startswith('# ') for line in comment_lines('hello\nworld\n!', 'beep').split('\n'): assert line.startswith('beep') def test_get_lines(self): """get_lines test""" text = "hello\nworld\n!" self.assertEqual(get_lines(text, start=1), "world\n!") self.assertEqual(get_lines(text, end=2), "hello\nworld") self.assertEqual(get_lines(text, start=2, end=5), "!") self.assertEqual(get_lines(text, start=-2), "world\n!") def test_ipython2python(self): """ipython2python test""" #TODO: More tests results = ipython2python(u'%%pylab\nprint("Hello-World")').replace("u'", "'") self.fuzzy_compare(results, u"get_ipython().run_cell_magic('pylab', '', 'print(\"Hello-World\")')", ignore_spaces=True, ignore_newlines=True) def test_posix_path(self): """posix_path test""" path_list = ['foo', 'bar'] expected = '/'.join(path_list) native = os.path.join(*path_list) filtered = posix_path(native) self.assertEqual(filtered, expected) def test_add_prompts(self): """add_prompts test""" text1 = """for i in range(10):\n i += 1\n print i""" text2 = """>>> for i in range(10):\n... i += 1\n... print i""" self.assertEqual(text2, add_prompts(text1)) def test_prevent_list_blocks(self): """prevent_list_blocks test""" tests = [ ('1. arabic point', '1\\. arabic point'), ('* bullet asterisk', '\\* bullet asterisk'), ('+ bullet Plus Sign', '\\+ bullet Plus Sign'), ('- bullet Hyphen-Minus', '\\- bullet Hyphen-Minus'), (' 1. spaces + arabic point', ' 1\\. spaces + arabic point'), ] for test in tests: self.assertEqual(prevent_list_blocks(test[0]), test[1]) def test_ascii_only(self): """ascii only test""" tests = [ ('', ''), (' ', ' '), ('Hello', 'Hello'), ('Hello 中文', 'Hello ??'), ] for test in tests: self.assertEqual(test[1], ascii_only(test[0]))
3,250
419
<filename>Resources/Services/Export/Dialog/ActionRendering/ScribanRenderingEngine/RenderingObjects/ScribanSpawnObjectActionData.en.json<gh_stars>100-1000 { "PlaceholderDesc_Object": "The object that is being spawned.", "PlaceholderDesc_TargetMarkerName": "The name of the marker at which the object is being spawned.", "PlaceholderDesc_UnescapedTargetMarkerName": "The name of the marker at which the object is being spawned without using the escape settings.", "PlaceholderDesc_Pitch": "Rotation around the X-Axis when spawning.", "PlaceholderDesc_Yaw": "Rotation around the X-Axis when spawning.", "PlaceholderDesc_Roll": "Rotation around the Z-Axis when spawning." }
215
13,885
/* * Copyright (C) 2021 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. */ #include <jni.h> #include <functional> #include <stdlib.h> #include <string.h> #include <filament/SkinningBuffer.h> #include "common/CallbackUtils.h" #include "common/NioUtils.h" using namespace filament; using namespace backend; extern "C" JNIEXPORT jlong JNICALL Java_com_google_android_filament_SkinningBuffer_nCreateBuilder(JNIEnv*, jclass) { return (jlong) new SkinningBuffer::Builder(); } extern "C" JNIEXPORT void JNICALL Java_com_google_android_filament_SkinningBuffer_nDestroyBuilder(JNIEnv*, jclass, jlong nativeBuilder) { SkinningBuffer::Builder* builder = (SkinningBuffer::Builder *) nativeBuilder; delete builder; } extern "C" JNIEXPORT void JNICALL Java_com_google_android_filament_SkinningBuffer_nBuilderBoneCount(JNIEnv*, jclass, jlong nativeBuilder, jint boneCount) { SkinningBuffer::Builder* builder = (SkinningBuffer::Builder *) nativeBuilder; builder->boneCount((uint32_t)boneCount); } extern "C" JNIEXPORT void JNICALL Java_com_google_android_filament_SkinningBuffer_nBuilderInitialize(JNIEnv*, jclass, jlong nativeBuilder, jboolean initialize) { SkinningBuffer::Builder* builder = (SkinningBuffer::Builder *) nativeBuilder; builder->initialize((bool)initialize); } extern "C" JNIEXPORT jlong JNICALL Java_com_google_android_filament_SkinningBuffer_nBuilderBuild(JNIEnv*, jclass, jlong nativeBuilder, jlong nativeEngine) { SkinningBuffer::Builder* builder = (SkinningBuffer::Builder *) nativeBuilder; Engine *engine = (Engine *) nativeEngine; return (jlong) builder->build(*engine); } // ------------------------------------------------------------------------------------------------ extern "C" JNIEXPORT jint JNICALL Java_com_google_android_filament_SkinningBuffer_nSetBonesAsMatrices(JNIEnv* env, jclass, jlong nativeSkinningBuffer, jlong nativeEngine, jobject matrices, jint remaining, jint boneCount, jint offset) { SkinningBuffer *skinningBuffer = (SkinningBuffer *) nativeSkinningBuffer; Engine *engine = (Engine *) nativeEngine; AutoBuffer nioBuffer(env, matrices, boneCount * 16); void* data = nioBuffer.getData(); size_t sizeInBytes = nioBuffer.getSize(); if (sizeInBytes > (remaining << nioBuffer.getShift())) { // BufferOverflowException return -1; } skinningBuffer->setBones(*engine, static_cast<filament::math::mat4f const *>(data), (size_t)boneCount, (size_t)offset); return 0; } extern "C" JNIEXPORT jint JNICALL Java_com_google_android_filament_SkinningBuffer_nSetBonesAsQuaternions(JNIEnv* env, jclass, jlong nativeSkinningBuffer, jlong nativeEngine, jobject quaternions, jint remaining, jint boneCount, jint offset) { SkinningBuffer *skinningBuffer = (SkinningBuffer *) nativeSkinningBuffer; Engine *engine = (Engine *) nativeEngine; AutoBuffer nioBuffer(env, quaternions, boneCount * 8); void* data = nioBuffer.getData(); size_t sizeInBytes = nioBuffer.getSize(); if (sizeInBytes > (remaining << nioBuffer.getShift())) { // BufferOverflowException return -1; } skinningBuffer->setBones(*engine, static_cast<RenderableManager::Bone const *>(data), (size_t)boneCount, (size_t)offset); return 0; } extern "C" JNIEXPORT jint JNICALL Java_com_google_android_filament_SkinningBuffer_nGetBoneCount(JNIEnv*, jclass, jlong nativeSkinningBuffer) { SkinningBuffer *skinningBuffer = (SkinningBuffer *) nativeSkinningBuffer; return (jint)skinningBuffer->getBoneCount(); }
1,451
778
//--------------------------------------------------------------------------------------------------------------------// // // // Tuplex: Blazing Fast Python Data Science // // // // // // (c) 2017 - 2021, Tuplex team // // Created by <NAME> first on 1/1/2021 // // License: Apache 2.0 // //--------------------------------------------------------------------------------------------------------------------// #ifndef TUPLEX_JSONUTILS_H #define TUPLEX_JSONUTILS_H #ifdef BUILD_WITH_AWS #include <aws/core/external/cjson/cJSON.h> #else #include <cJSON.h> #endif #include <vector> #include "Base.h" #include "Utils.h" #include <nlohmann/json.hpp> namespace tuplex { /*! * converts an array of strings to a string in JSON representation * @param array * @return JSON string containing the string array */ inline std::string stringArrayToJSON(const std::vector<std::string>& array) { // special case: empty if(array.empty()) return "[]"; nlohmann::json j; for(auto s: array) { j.push_back(s); } return j.dump(); } /*! * convert string to vector of strings * @param s * @return */ inline std::vector<std::string> jsonToStringArray(const std::string& s) { auto j = nlohmann::json::parse(s); if(!j.is_array()) throw std::runtime_error("json object is not an array!"); std::vector<std::string> v; for(auto it = j.begin(); it != j.end(); ++it) { if(!it->is_string()) { throw std::runtime_error("array element is not string"); } v.push_back(it->get<std::string>()); } return v; } inline std::unordered_map<std::string, std::string> jsonToMap(const std::string &s) { std::unordered_map<std::string, std::string> m; // empty string? return empty map! if(s.empty()) return m; auto j = nlohmann::json::parse(s); for (auto &el : j.items()) { if(el.value().is_null()) m[el.key()] = "null"; else if(el.value().is_string()) m[el.key()] = el.value().get<std::string>(); else if(el.value().is_boolean()) m[el.key()] = boolToString(el.value().get<bool>()); else if(el.value().is_number_integer()) m[el.key()] = std::to_string(el.value().get<int64_t>()); else if(el.value().is_number_float()) m[el.key()] = std::to_string(el.value().get<double>()); else { m[el.key()] = el.value().dump(); } } return m; } } #endif //TUPLEX_JSONUTILS_H
1,889
892
<reponame>github/advisory-database { "schema_version": "1.2.0", "id": "GHSA-5297-pw47-52pg", "modified": "2022-05-13T01:31:18Z", "published": "2022-05-13T01:31:18Z", "aliases": [ "CVE-2019-1835" ], "details": "A vulnerability in the CLI of Cisco Aironet Access Points (APs) could allow an authenticated, local attacker to access sensitive information stored in an AP. The vulnerability is due to improper sanitization of user-supplied input in specific CLI commands. An attacker could exploit this vulnerability by accessing the CLI of an affected AP with administrator privileges and issuing crafted commands that result in directory traversal. A successful exploit could allow the attacker to view system files on the affected device, which could contain sensitive information. Software versions 8.8 and 8.9 are affected.", "severity": [ { "type": "CVSS_V3", "score": "CVSS:3.0/AV:L/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N" } ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2019-1835" }, { "type": "WEB", "url": "https://tools.cisco.com/security/center/content/CiscoSecurityAdvisory/cisco-sa-20190417-air-ap-traversal" }, { "type": "WEB", "url": "http://www.securityfocus.com/bid/108001" } ], "database_specific": { "cwe_ids": [ "CWE-22" ], "severity": "MODERATE", "github_reviewed": false } }
573
348
{"nom":"Landudec","circ":"7ème circonscription","dpt":"Finistère","inscrits":1088,"abs":616,"votants":472,"blancs":49,"nuls":15,"exp":408,"res":[{"nuance":"REM","nom":"<NAME>","voix":251},{"nuance":"LR","nom":"<NAME>","voix":157}]}
90
335
<reponame>Safal08/Hacktoberfest-1 { "word": "Level", "definitions": [ "A horizontal plane or line with respect to the distance above or below a given point.", "A height or distance from the ground or another stated or understood base.", "A floor within a multistorey building.", "A position on a scale of amount, quantity, extent, or quality.", "An intellectual, social, or moral standard.", "A position in a hierarchy.", "(in a video game) each of a series of stages of increasing difficulty through which a player may progress, completing one stage in order to reach the next.", "(especially in a role-playing game) each of a number of steps in the development of a character, who progressively acquires enhanced skills and abilities within the game as the player advances by completing tasks and earning points.", "An instrument marked with a line parallel to the plane of the horizon for testing whether things are horizontal.", "An instrument for giving a horizontal line of sight.", "A flat tract of land." ], "parts-of-speech": "Noun" }
339
1,529
<reponame>IgiArdiyanto/PINTO_model_zoo ### tensorflow==2.3.1 import tensorflow as tf # Weight Quantization - Input/Output=float32 height = 480 width = 640 converter = tf.lite.TFLiteConverter.from_saved_model('saved_model_nyu_{}x{}'.format(height, width)) converter.optimizations = [tf.lite.Optimize.OPTIMIZE_FOR_SIZE] tflite_model = converter.convert() with open('dense_depth_nyu_{}x{}_weight_quant.tflite'.format(height, width), 'wb') as w: w.write(tflite_model) print('Weight Quantization complete! - dense_depth_nyu_{}x{}_weight_quant.tflite'.format(height, width)) ''' signature_def['serving_default']: The given SavedModel SignatureDef contains the following input(s): inputs['input_1'] tensor_info: dtype: DT_FLOAT shape: (-1, 480, 640, 3) name: serving_default_input_1:0 The given SavedModel SignatureDef contains the following output(s): outputs['output_1'] tensor_info: dtype: DT_FLOAT shape: (-1, 240, 320, 1) name: StatefulPartitionedCall:0 Method name is: tensorflow/serving/predict '''
426
1,072
<reponame>THUDM/cogdl import argparse import numpy as np import torch from sklearn.metrics import auc, f1_score, precision_recall_curve, roc_auc_score from cogdl.data import Graph from .. import register_model_wrapper, EmbeddingModelWrapper def get_score(embs, node1, node2): vector1 = embs[int(node1)] vector2 = embs[int(node2)] return np.dot(vector1, vector2) / (np.linalg.norm(vector1) * np.linalg.norm(vector2)) def evaluate(embs, true_edges, false_edges): true_list = list() prediction_list = list() for edge in true_edges: true_list.append(1) prediction_list.append(get_score(embs, edge[0], edge[1])) for edge in false_edges: true_list.append(0) prediction_list.append(get_score(embs, edge[0], edge[1])) sorted_pred = prediction_list[:] sorted_pred.sort() threshold = sorted_pred[-len(true_edges)] y_pred = np.zeros(len(prediction_list), dtype=np.int32) for i in range(len(prediction_list)): if prediction_list[i] >= threshold: y_pred[i] = 1 y_true = np.array(true_list) y_scores = np.array(prediction_list) ps, rs, _ = precision_recall_curve(y_true, y_scores) return roc_auc_score(y_true, y_scores), f1_score(y_true, y_pred), auc(rs, ps) def evaluate_multiplex(all_embs, test_data): total_roc_auc, total_f1_score, total_pr_auc = [], [], [] for key in test_data.keys(): embs = all_embs[key] roc_auc, f1_score, pr_auc = evaluate(embs, test_data[key][0], test_data[key][1]) total_roc_auc.append(roc_auc) total_f1_score.append(f1_score) total_pr_auc.append(pr_auc) assert len(total_roc_auc) > 0 roc_auc, f1_score, pr_auc = ( np.mean(total_roc_auc), np.mean(total_f1_score), np.mean(total_pr_auc), ) print(f"Test ROC-AUC = {roc_auc:.4f}, F1 = {f1_score:.4f}, PR-AUC = {pr_auc:.4f}") return dict(ROC_AUC=roc_auc, PR_AUC=pr_auc, F1=f1_score) @register_model_wrapper("multiplex_embedding_mw") class MultiplexEmbeddingModelWrapper(EmbeddingModelWrapper): @staticmethod def add_args(parser: argparse.ArgumentParser): """Add task-specific arguments to the parser.""" # fmt: off parser.add_argument("--hidden-size", type=int, default=200) parser.add_argument("--eval-type", type=str, default='all', nargs='+') # fmt: on def __init__(self, model, hidden_size=200, eval_type="all"): super(MultiplexEmbeddingModelWrapper, self).__init__() self.model = model self.hidden_size = hidden_size self.eval_type = eval_type def train_step(self, batch): if hasattr(self.model, "multiplicity"): all_embs = self.model(batch) else: all_embs = dict() for key in batch.keys(): if self.eval_type == "all" or key in self.eval_type: G = Graph(edge_index=torch.LongTensor(batch[key]).transpose(0, 1)) embs = self.model(G, return_dict=True) all_embs[key] = embs return all_embs def test_step(self, batch): all_embs, test_data = batch return evaluate_multiplex(all_embs, test_data)
1,483
2,151
<filename>media/mca/filterfw/java/android/filterfw/core/NativeBuffer.java /* * Copyright (C) 2011 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 android.filterfw.core; import android.filterfw.core.Frame; /** * @hide */ public class NativeBuffer { // These are set by the native layer private long mDataPointer = 0; private int mSize = 0; private Frame mAttachedFrame; private boolean mOwnsData = false; private int mRefCount = 1; public NativeBuffer() { } public NativeBuffer(int count) { allocate(count * getElementSize()); mOwnsData = true; } public NativeBuffer mutableCopy() { NativeBuffer result = null; try { Class myClass = getClass(); result = (NativeBuffer)myClass.newInstance(); } catch (Exception e) { throw new RuntimeException("Unable to allocate a copy of " + getClass() + "! Make " + "sure the class has a default constructor!"); } if (mSize > 0 && !nativeCopyTo(result)) { throw new RuntimeException("Failed to copy NativeBuffer to mutable instance!"); } return result; } public int size() { return mSize; } public int count() { return (mDataPointer != 0) ? mSize / getElementSize() : 0; } public int getElementSize() { return 1; } public NativeBuffer retain() { if (mAttachedFrame != null) { mAttachedFrame.retain(); } else if (mOwnsData) { ++mRefCount; } return this; } public NativeBuffer release() { // Decrement refcount boolean doDealloc = false; if (mAttachedFrame != null) { doDealloc = (mAttachedFrame.release() == null); } else if (mOwnsData) { --mRefCount; doDealloc = (mRefCount == 0); } // Deallocate if necessary if (doDealloc) { deallocate(mOwnsData); return null; } else { return this; } } public boolean isReadOnly() { return (mAttachedFrame != null) ? mAttachedFrame.isReadOnly() : false; } static { System.loadLibrary("filterfw"); } void attachToFrame(Frame frame) { // We do not auto-retain. We expect the user to call retain() if they want to hold on to // the frame. mAttachedFrame = frame; } protected void assertReadable() { if (mDataPointer == 0 || mSize == 0 || (mAttachedFrame != null && !mAttachedFrame.hasNativeAllocation())) { throw new NullPointerException("Attempting to read from null data frame!"); } } protected void assertWritable() { if (isReadOnly()) { throw new RuntimeException("Attempting to modify read-only native (structured) data!"); } } private native boolean allocate(int size); private native boolean deallocate(boolean ownsData); private native boolean nativeCopyTo(NativeBuffer buffer); }
1,449
3,372
<filename>aws-java-sdk-sqs/src/main/java/com/amazonaws/services/sqs/buffered/AmazonSQSBufferedAsyncClient.java /* * Copyright 2012-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.sqs.buffered; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Future; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.AmazonWebServiceRequest; import com.amazonaws.ResponseMetadata; import com.amazonaws.handlers.AsyncHandler; import com.amazonaws.regions.Region; import com.amazonaws.services.sqs.AmazonSQSAsync; import com.amazonaws.services.sqs.model.AddPermissionRequest; import com.amazonaws.services.sqs.model.AddPermissionResult; import com.amazonaws.services.sqs.model.ChangeMessageVisibilityBatchRequest; import com.amazonaws.services.sqs.model.ChangeMessageVisibilityBatchRequestEntry; import com.amazonaws.services.sqs.model.ChangeMessageVisibilityBatchResult; import com.amazonaws.services.sqs.model.ChangeMessageVisibilityRequest; import com.amazonaws.services.sqs.model.ChangeMessageVisibilityResult; import com.amazonaws.services.sqs.model.CreateQueueRequest; import com.amazonaws.services.sqs.model.CreateQueueResult; import com.amazonaws.services.sqs.model.DeleteMessageBatchRequest; import com.amazonaws.services.sqs.model.DeleteMessageBatchRequestEntry; import com.amazonaws.services.sqs.model.DeleteMessageBatchResult; import com.amazonaws.services.sqs.model.DeleteMessageRequest; import com.amazonaws.services.sqs.model.DeleteMessageResult; import com.amazonaws.services.sqs.model.DeleteQueueRequest; import com.amazonaws.services.sqs.model.DeleteQueueResult; import com.amazonaws.services.sqs.model.GetQueueAttributesRequest; import com.amazonaws.services.sqs.model.GetQueueAttributesResult; import com.amazonaws.services.sqs.model.GetQueueUrlRequest; import com.amazonaws.services.sqs.model.GetQueueUrlResult; import com.amazonaws.services.sqs.model.ListDeadLetterSourceQueuesRequest; import com.amazonaws.services.sqs.model.ListDeadLetterSourceQueuesResult; import com.amazonaws.services.sqs.model.ListQueueTagsRequest; import com.amazonaws.services.sqs.model.ListQueueTagsResult; import com.amazonaws.services.sqs.model.ListQueuesRequest; import com.amazonaws.services.sqs.model.ListQueuesResult; import com.amazonaws.services.sqs.model.PurgeQueueRequest; import com.amazonaws.services.sqs.model.PurgeQueueResult; import com.amazonaws.services.sqs.model.ReceiveMessageRequest; import com.amazonaws.services.sqs.model.ReceiveMessageResult; import com.amazonaws.services.sqs.model.RemovePermissionRequest; import com.amazonaws.services.sqs.model.RemovePermissionResult; import com.amazonaws.services.sqs.model.SendMessageBatchRequest; import com.amazonaws.services.sqs.model.SendMessageBatchRequestEntry; import com.amazonaws.services.sqs.model.SendMessageBatchResult; import com.amazonaws.services.sqs.model.SendMessageRequest; import com.amazonaws.services.sqs.model.SendMessageResult; import com.amazonaws.services.sqs.model.SetQueueAttributesRequest; import com.amazonaws.services.sqs.model.SetQueueAttributesResult; import com.amazonaws.services.sqs.model.TagQueueRequest; import com.amazonaws.services.sqs.model.TagQueueResult; import com.amazonaws.services.sqs.model.UntagQueueRequest; import com.amazonaws.services.sqs.model.UntagQueueResult; import com.amazonaws.util.VersionInfoUtils; /** * AmazonSQSBufferedAsyncClient provides client-side batching of outgoing sendMessage, deleteMessage * and changeMessageVisibility calls. <br> * After receiving a call, rather than executing it right away, this client waits for a configurable * period of time ( default=200ms) for other calls of the same type to come in; if such calls do * come in, they are also not executed immediately, but instead are added to the batch. When the * batch becomes full or the timeout period expires, the entire batch is executed at once and the * results are returned to the callers. This method of operation leads to reduced operating costs * (since SQS charges per call and fewer calls are made) and increased overall throughput (since * more work is performed per call, and all fixed costs of making a call are amortized over a * greater amount of work). The cost of this method is increased latency for individual calls, since * calls spend some time waiting on the client side for the potential batch-mates to appear before * they are actually executed. <br> * This client also performs pre-fetching of messages from SQS. After the first receiveMessage call * is made, the client attempts not only to satisfy that call, but also pre-fetch extra messages to * store in a temporary buffer. Future receiveMessage calls will be satisfied from the buffer, and * only if the buffer is empty will the calling thread have to wait for the messages to be fetched. * The size of the buffer and the maximum number of threads used for prefetching are configurable. <br> * AmazonSQSBufferedAsyncClient is thread-safe.<br> */ public class AmazonSQSBufferedAsyncClient implements AmazonSQSAsync { public static final String USER_AGENT = AmazonSQSBufferedAsyncClient.class.getSimpleName() + "/" + VersionInfoUtils.getVersion(); private final CachingMap buffers = new CachingMap(16, (float) 0.75, true); private final AmazonSQSAsync realSQS; private final QueueBufferConfig bufferConfigExemplar; public AmazonSQSBufferedAsyncClient(AmazonSQSAsync paramRealSQS) { this(paramRealSQS, new QueueBufferConfig()); } // route all future constructors to the most general one, because validation // happens here public AmazonSQSBufferedAsyncClient(AmazonSQSAsync paramRealSQS, QueueBufferConfig config) { config.validate(); realSQS = paramRealSQS; bufferConfigExemplar = config; } /* * (non-Javadoc) * @see com.amazonaws.services.sqs.AmazonSQS#setRegion(com.amazonaws.regions.Region) */ @Override public void setRegion(Region region) throws IllegalArgumentException { realSQS.setRegion(region); } public SetQueueAttributesResult setQueueAttributes(SetQueueAttributesRequest setQueueAttributesRequest) throws AmazonServiceException, AmazonClientException { ResultConverter.appendUserAgent(setQueueAttributesRequest, USER_AGENT); return realSQS.setQueueAttributes(setQueueAttributesRequest); } public ChangeMessageVisibilityBatchResult changeMessageVisibilityBatch(ChangeMessageVisibilityBatchRequest changeMessageVisibilityBatchRequest) throws AmazonServiceException, AmazonClientException { ResultConverter.appendUserAgent(changeMessageVisibilityBatchRequest, USER_AGENT); return realSQS.changeMessageVisibilityBatch(changeMessageVisibilityBatchRequest); } public ChangeMessageVisibilityResult changeMessageVisibility(ChangeMessageVisibilityRequest changeMessageVisibilityRequest) throws AmazonServiceException, AmazonClientException { ResultConverter.appendUserAgent(changeMessageVisibilityRequest, USER_AGENT); QueueBuffer buffer = getQBuffer(changeMessageVisibilityRequest.getQueueUrl()); return buffer.changeMessageVisibilitySync(changeMessageVisibilityRequest); } public SendMessageBatchResult sendMessageBatch(SendMessageBatchRequest sendMessageBatchRequest) throws AmazonServiceException, AmazonClientException { ResultConverter.appendUserAgent(sendMessageBatchRequest, USER_AGENT); return realSQS.sendMessageBatch(sendMessageBatchRequest); } public SendMessageResult sendMessage(SendMessageRequest sendMessageRequest) throws AmazonServiceException, AmazonClientException { QueueBuffer buffer = getQBuffer(sendMessageRequest.getQueueUrl()); ResultConverter.appendUserAgent(sendMessageRequest, USER_AGENT); return buffer.sendMessageSync(sendMessageRequest); } public ReceiveMessageResult receiveMessage(ReceiveMessageRequest receiveMessageRequest) throws AmazonServiceException, AmazonClientException { ResultConverter.appendUserAgent(receiveMessageRequest, USER_AGENT); QueueBuffer buffer = getQBuffer(receiveMessageRequest.getQueueUrl()); return buffer.receiveMessageSync(receiveMessageRequest); } public DeleteMessageBatchResult deleteMessageBatch(DeleteMessageBatchRequest deleteMessageBatchRequest) throws AmazonServiceException, AmazonClientException { ResultConverter.appendUserAgent(deleteMessageBatchRequest, USER_AGENT); QueueBuffer buffer = getQBuffer(deleteMessageBatchRequest.getQueueUrl()); return buffer.deleteMessageBatchSync(deleteMessageBatchRequest); } public DeleteMessageResult deleteMessage(DeleteMessageRequest deleteMessageRequest) throws AmazonServiceException, AmazonClientException { ResultConverter.appendUserAgent(deleteMessageRequest, USER_AGENT); QueueBuffer buffer = getQBuffer(deleteMessageRequest.getQueueUrl()); return buffer.deleteMessageSync(deleteMessageRequest); } public void shutdown() { for (QueueBuffer buffer : buffers.values()) { buffer.shutdown(); } realSQS.shutdown(); } /** * Flushes all outstanding outbound requests. Calling this method will wait for * the pending outbound tasks in the {@link QueueBuffer} to finish. */ public void flush() { for (QueueBuffer buffer : buffers.values()) { buffer.flush(); } } public Future<ChangeMessageVisibilityBatchResult> changeMessageVisibilityBatchAsync(ChangeMessageVisibilityBatchRequest changeMessageVisibilityBatchRequest) throws AmazonServiceException, AmazonClientException { ResultConverter.appendUserAgent(changeMessageVisibilityBatchRequest, USER_AGENT); return realSQS.changeMessageVisibilityBatchAsync(changeMessageVisibilityBatchRequest); } public Future<ChangeMessageVisibilityResult> changeMessageVisibilityAsync(ChangeMessageVisibilityRequest changeMessageVisibilityRequest) throws AmazonServiceException, AmazonClientException { ResultConverter.appendUserAgent(changeMessageVisibilityRequest, USER_AGENT); QueueBuffer buffer = getQBuffer(changeMessageVisibilityRequest.getQueueUrl()); return buffer.changeMessageVisibility(changeMessageVisibilityRequest, null); } public Future<SendMessageBatchResult> sendMessageBatchAsync(SendMessageBatchRequest sendMessageBatchRequest) throws AmazonServiceException, AmazonClientException { ResultConverter.appendUserAgent(sendMessageBatchRequest, USER_AGENT); return realSQS.sendMessageBatchAsync(sendMessageBatchRequest); } public Future<SendMessageResult> sendMessageAsync(SendMessageRequest sendMessageRequest) throws AmazonServiceException, AmazonClientException { ResultConverter.appendUserAgent(sendMessageRequest, USER_AGENT); QueueBuffer buffer = getQBuffer(sendMessageRequest.getQueueUrl()); return buffer.sendMessage(sendMessageRequest, null); } public Future<ReceiveMessageResult> receiveMessageAsync(ReceiveMessageRequest receiveMessageRequest) throws AmazonServiceException, AmazonClientException { ResultConverter.appendUserAgent(receiveMessageRequest, USER_AGENT); QueueBuffer buffer = getQBuffer(receiveMessageRequest.getQueueUrl()); return buffer.receiveMessage(receiveMessageRequest, null); } public Future<DeleteMessageBatchResult> deleteMessageBatchAsync(DeleteMessageBatchRequest deleteMessageBatchRequest) throws AmazonServiceException, AmazonClientException { ResultConverter.appendUserAgent(deleteMessageBatchRequest, USER_AGENT); return realSQS.deleteMessageBatchAsync(deleteMessageBatchRequest); } public void setEndpoint(String endpoint) throws IllegalArgumentException { realSQS.setEndpoint(endpoint); } public Future<SetQueueAttributesResult> setQueueAttributesAsync(SetQueueAttributesRequest setQueueAttributesRequest) throws AmazonServiceException, AmazonClientException { ResultConverter.appendUserAgent(setQueueAttributesRequest, USER_AGENT); return realSQS.setQueueAttributesAsync(setQueueAttributesRequest); } public Future<GetQueueUrlResult> getQueueUrlAsync(GetQueueUrlRequest getQueueUrlRequest) throws AmazonServiceException, AmazonClientException { ResultConverter.appendUserAgent(getQueueUrlRequest, USER_AGENT); return realSQS.getQueueUrlAsync(getQueueUrlRequest); } public Future<RemovePermissionResult> removePermissionAsync(RemovePermissionRequest removePermissionRequest) throws AmazonServiceException, AmazonClientException { ResultConverter.appendUserAgent(removePermissionRequest, USER_AGENT); return realSQS.removePermissionAsync(removePermissionRequest); } public GetQueueUrlResult getQueueUrl(GetQueueUrlRequest getQueueUrlRequest) throws AmazonServiceException, AmazonClientException { ResultConverter.appendUserAgent(getQueueUrlRequest, USER_AGENT); return realSQS.getQueueUrl(getQueueUrlRequest); } public RemovePermissionResult removePermission(RemovePermissionRequest removePermissionRequest) throws AmazonServiceException, AmazonClientException { ResultConverter.appendUserAgent(removePermissionRequest, USER_AGENT); return realSQS.removePermission(removePermissionRequest); } public Future<GetQueueAttributesResult> getQueueAttributesAsync(GetQueueAttributesRequest getQueueAttributesRequest) throws AmazonServiceException, AmazonClientException { ResultConverter.appendUserAgent(getQueueAttributesRequest, USER_AGENT); return realSQS.getQueueAttributesAsync(getQueueAttributesRequest); } public GetQueueAttributesResult getQueueAttributes(GetQueueAttributesRequest getQueueAttributesRequest) throws AmazonServiceException, AmazonClientException { ResultConverter.appendUserAgent(getQueueAttributesRequest, USER_AGENT); return realSQS.getQueueAttributes(getQueueAttributesRequest); } public Future<PurgeQueueResult> purgeQueueAsync(PurgeQueueRequest purgeQueueRequest) throws AmazonServiceException, AmazonClientException { ResultConverter.appendUserAgent(purgeQueueRequest, USER_AGENT); return realSQS.purgeQueueAsync(purgeQueueRequest); } public PurgeQueueResult purgeQueue(PurgeQueueRequest purgeQueueRequest) throws AmazonServiceException, AmazonClientException { ResultConverter.appendUserAgent(purgeQueueRequest, USER_AGENT); return realSQS.purgeQueue(purgeQueueRequest); } public Future<DeleteQueueResult> deleteQueueAsync(DeleteQueueRequest deleteQueueRequest) throws AmazonServiceException, AmazonClientException { ResultConverter.appendUserAgent(deleteQueueRequest, USER_AGENT); return realSQS.deleteQueueAsync(deleteQueueRequest); } public DeleteQueueResult deleteQueue(DeleteQueueRequest deleteQueueRequest) throws AmazonServiceException, AmazonClientException { ResultConverter.appendUserAgent(deleteQueueRequest, USER_AGENT); return realSQS.deleteQueue(deleteQueueRequest); } public Future<ListQueuesResult> listQueuesAsync(ListQueuesRequest listQueuesRequest) throws AmazonServiceException, AmazonClientException { ResultConverter.appendUserAgent(listQueuesRequest, USER_AGENT); return realSQS.listQueuesAsync(listQueuesRequest); } public ListQueuesResult listQueues(ListQueuesRequest listQueuesRequest) throws AmazonServiceException, AmazonClientException { ResultConverter.appendUserAgent(listQueuesRequest, USER_AGENT); return realSQS.listQueues(listQueuesRequest); } public Future<CreateQueueResult> createQueueAsync(CreateQueueRequest createQueueRequest) throws AmazonServiceException, AmazonClientException { ResultConverter.appendUserAgent(createQueueRequest, USER_AGENT); return realSQS.createQueueAsync(createQueueRequest); } public CreateQueueResult createQueue(CreateQueueRequest createQueueRequest) throws AmazonServiceException, AmazonClientException { ResultConverter.appendUserAgent(createQueueRequest, USER_AGENT); return realSQS.createQueue(createQueueRequest); } public Future<AddPermissionResult> addPermissionAsync(AddPermissionRequest addPermissionRequest) throws AmazonServiceException, AmazonClientException { ResultConverter.appendUserAgent(addPermissionRequest, USER_AGENT); return realSQS.addPermissionAsync(addPermissionRequest); } @Override public Future<AddPermissionResult> addPermissionAsync(String queueUrl, String label, List<String> aWSAccountIds, List<String> actions) { return addPermissionAsync(new AddPermissionRequest(queueUrl, label, aWSAccountIds, actions)); } @Override public Future<AddPermissionResult> addPermissionAsync(String queueUrl, String label, List<String> aWSAccountIds, List<String> actions, AsyncHandler<AddPermissionRequest, AddPermissionResult> asyncHandler) { return addPermissionAsync(new AddPermissionRequest(queueUrl, label, aWSAccountIds, actions), asyncHandler); } public AddPermissionResult addPermission(AddPermissionRequest addPermissionRequest) throws AmazonServiceException, AmazonClientException { ResultConverter.appendUserAgent(addPermissionRequest, USER_AGENT); return realSQS.addPermission(addPermissionRequest); } public ListQueuesResult listQueues() throws AmazonServiceException, AmazonClientException { return realSQS.listQueues(); } public ResponseMetadata getCachedResponseMetadata(AmazonWebServiceRequest request) { ResultConverter.appendUserAgent(request, USER_AGENT); return realSQS.getCachedResponseMetadata(request); } public Future<DeleteMessageResult> deleteMessageAsync(DeleteMessageRequest deleteMessageRequest) throws AmazonServiceException, AmazonClientException { ResultConverter.appendUserAgent(deleteMessageRequest, USER_AGENT); QueueBuffer buffer = getQBuffer(deleteMessageRequest.getQueueUrl()); return buffer.deleteMessage(deleteMessageRequest, null); } /** * Returns (creating it if necessary) a queue buffer for a particular queue Since we are only * storing a limited number of queue buffers, it is possible that as a result of calling this * method the least recently used queue buffer will be removed from our queue buffer cache * * @return a queue buffer associated with the provided queue URL. Never null */ private synchronized QueueBuffer getQBuffer(String qUrl) { QueueBuffer toReturn = buffers.get(qUrl); if (null == toReturn) { QueueBufferConfig config = new QueueBufferConfig(bufferConfigExemplar); toReturn = new QueueBuffer(config, qUrl, realSQS); buffers.put(qUrl, toReturn); } return toReturn; } class CachingMap extends LinkedHashMap<String, QueueBuffer> { private static final long serialVersionUID = 1; private static final int MAX_ENTRIES = 100; public CachingMap(int initial, float loadFactor, boolean accessOrder) { super(initial, loadFactor, accessOrder); } protected boolean removeEldestEntry(java.util.Map.Entry<String, QueueBuffer> eldest) { return size() > MAX_ENTRIES; } } public Future<ChangeMessageVisibilityResult> changeMessageVisibilityAsync(ChangeMessageVisibilityRequest changeMessageVisibilityRequest, AsyncHandler<ChangeMessageVisibilityRequest, ChangeMessageVisibilityResult> asyncHandler) throws AmazonServiceException, AmazonClientException { ResultConverter.appendUserAgent(changeMessageVisibilityRequest, USER_AGENT); QueueBuffer buffer = getQBuffer(changeMessageVisibilityRequest.getQueueUrl()); return buffer.changeMessageVisibility(changeMessageVisibilityRequest, asyncHandler); } @Override public Future<ChangeMessageVisibilityResult> changeMessageVisibilityAsync(String queueUrl, String receiptHandle, Integer visibilityTimeout) { return changeMessageVisibilityAsync(new ChangeMessageVisibilityRequest( queueUrl, receiptHandle, visibilityTimeout)); } @Override public Future<ChangeMessageVisibilityResult> changeMessageVisibilityAsync(String queueUrl, String receiptHandle, Integer visibilityTimeout, AsyncHandler<ChangeMessageVisibilityRequest, ChangeMessageVisibilityResult> asyncHandler) { return changeMessageVisibilityAsync(new ChangeMessageVisibilityRequest( queueUrl, receiptHandle, visibilityTimeout), asyncHandler); } public Future<SendMessageResult> sendMessageAsync(SendMessageRequest sendMessageRequest, AsyncHandler<SendMessageRequest, SendMessageResult> asyncHandler) throws AmazonServiceException, AmazonClientException { ResultConverter.appendUserAgent(sendMessageRequest, USER_AGENT); QueueBuffer buffer = getQBuffer(sendMessageRequest.getQueueUrl()); return buffer.sendMessage(sendMessageRequest, asyncHandler); } @Override public Future<SendMessageResult> sendMessageAsync(String queueUrl, String messageBody) { return sendMessageAsync(new SendMessageRequest(queueUrl, messageBody)); } @Override public Future<SendMessageResult> sendMessageAsync(String queueUrl, String messageBody, AsyncHandler<SendMessageRequest, SendMessageResult> asyncHandler) { return sendMessageAsync(new SendMessageRequest(queueUrl, messageBody), asyncHandler); } public Future<ReceiveMessageResult> receiveMessageAsync(ReceiveMessageRequest receiveMessageRequest, AsyncHandler<ReceiveMessageRequest, ReceiveMessageResult> asyncHandler) throws AmazonServiceException, AmazonClientException { ResultConverter.appendUserAgent(receiveMessageRequest, USER_AGENT); QueueBuffer buffer = getQBuffer(receiveMessageRequest.getQueueUrl()); return buffer.receiveMessage(receiveMessageRequest, asyncHandler); } @Override public Future<ReceiveMessageResult> receiveMessageAsync(String queueUrl) { return receiveMessageAsync(new ReceiveMessageRequest(queueUrl)); } @Override public Future<ReceiveMessageResult> receiveMessageAsync( String queueUrl, AsyncHandler<ReceiveMessageRequest, ReceiveMessageResult> asyncHandler) { return receiveMessageAsync(new ReceiveMessageRequest(queueUrl), asyncHandler); } public Future<DeleteMessageResult> deleteMessageAsync(DeleteMessageRequest deleteMessageRequest, AsyncHandler<DeleteMessageRequest, DeleteMessageResult> asyncHandler) throws AmazonServiceException, AmazonClientException { ResultConverter.appendUserAgent(deleteMessageRequest, USER_AGENT); QueueBuffer buffer = getQBuffer(deleteMessageRequest.getQueueUrl()); return buffer.deleteMessage(deleteMessageRequest, asyncHandler); } @Override public Future<DeleteMessageResult> deleteMessageAsync(String queueUrl, String receiptHandle) { return deleteMessageAsync(new DeleteMessageRequest(queueUrl, receiptHandle)); } @Override public Future<DeleteMessageResult> deleteMessageAsync(String queueUrl, String receiptHandle, AsyncHandler<DeleteMessageRequest, DeleteMessageResult> asyncHandler) { return deleteMessageAsync(new DeleteMessageRequest(queueUrl, receiptHandle), asyncHandler); } public Future<SetQueueAttributesResult> setQueueAttributesAsync(SetQueueAttributesRequest setQueueAttributesRequest, AsyncHandler<SetQueueAttributesRequest, SetQueueAttributesResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return realSQS.setQueueAttributesAsync(setQueueAttributesRequest, asyncHandler); } public Future<SetQueueAttributesResult> setQueueAttributesAsync(String queueUrl, java.util.Map<String, String> attributes) throws AmazonServiceException, AmazonClientException { return realSQS.setQueueAttributesAsync(queueUrl, attributes); } public Future<SetQueueAttributesResult> setQueueAttributesAsync(String queueUrl, java.util.Map<String, String> attributes, com.amazonaws.handlers.AsyncHandler<SetQueueAttributesRequest, SetQueueAttributesResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return realSQS.setQueueAttributesAsync(queueUrl, attributes, asyncHandler); } public Future<ChangeMessageVisibilityBatchResult> changeMessageVisibilityBatchAsync(ChangeMessageVisibilityBatchRequest changeMessageVisibilityBatchRequest, AsyncHandler<ChangeMessageVisibilityBatchRequest, ChangeMessageVisibilityBatchResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return realSQS.changeMessageVisibilityBatchAsync(changeMessageVisibilityBatchRequest, asyncHandler); } @Override public Future<ChangeMessageVisibilityBatchResult> changeMessageVisibilityBatchAsync( String queueUrl, List<ChangeMessageVisibilityBatchRequestEntry> entries) { return changeMessageVisibilityBatchAsync(new ChangeMessageVisibilityBatchRequest( queueUrl, entries)); } @Override public Future<ChangeMessageVisibilityBatchResult> changeMessageVisibilityBatchAsync( String queueUrl, List<ChangeMessageVisibilityBatchRequestEntry> entries, AsyncHandler<ChangeMessageVisibilityBatchRequest, ChangeMessageVisibilityBatchResult> asyncHandler) { return changeMessageVisibilityBatchAsync(new ChangeMessageVisibilityBatchRequest( queueUrl, entries), asyncHandler); } public Future<GetQueueUrlResult> getQueueUrlAsync(GetQueueUrlRequest getQueueUrlRequest, AsyncHandler<GetQueueUrlRequest, GetQueueUrlResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return realSQS.getQueueUrlAsync(getQueueUrlRequest, asyncHandler); } @Override public Future<GetQueueUrlResult> getQueueUrlAsync(String queueName) { return getQueueUrlAsync(new GetQueueUrlRequest(queueName)); } @Override public Future<GetQueueUrlResult> getQueueUrlAsync(String queueName, AsyncHandler<GetQueueUrlRequest, GetQueueUrlResult> asyncHandler) { return getQueueUrlAsync(new GetQueueUrlRequest(queueName), asyncHandler); } public Future<RemovePermissionResult> removePermissionAsync(RemovePermissionRequest removePermissionRequest, AsyncHandler<RemovePermissionRequest, RemovePermissionResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return realSQS.removePermissionAsync(removePermissionRequest, asyncHandler); } @Override public Future<RemovePermissionResult> removePermissionAsync(String queueUrl, String label) { return removePermissionAsync(new RemovePermissionRequest(queueUrl, label)); } @Override public Future<RemovePermissionResult> removePermissionAsync(String queueUrl, String label, AsyncHandler<RemovePermissionRequest, RemovePermissionResult> asyncHandler) { return removePermissionAsync(new RemovePermissionRequest(queueUrl, label), asyncHandler); } public Future<GetQueueAttributesResult> getQueueAttributesAsync(GetQueueAttributesRequest getQueueAttributesRequest, AsyncHandler<GetQueueAttributesRequest, GetQueueAttributesResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return realSQS.getQueueAttributesAsync(getQueueAttributesRequest, asyncHandler); } @Override public Future<GetQueueAttributesResult> getQueueAttributesAsync( String queueUrl, List<String> attributeNames) { return getQueueAttributesAsync(new GetQueueAttributesRequest(queueUrl, attributeNames)); } @Override public Future<GetQueueAttributesResult> getQueueAttributesAsync( String queueUrl, List<String> attributeNames, AsyncHandler<GetQueueAttributesRequest, GetQueueAttributesResult> asyncHandler) { return getQueueAttributesAsync(new GetQueueAttributesRequest(queueUrl, attributeNames), asyncHandler); } public Future<SendMessageBatchResult> sendMessageBatchAsync(SendMessageBatchRequest sendMessageBatchRequest, AsyncHandler<SendMessageBatchRequest, SendMessageBatchResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return realSQS.sendMessageBatchAsync(sendMessageBatchRequest, asyncHandler); } @Override public Future<SendMessageBatchResult> sendMessageBatchAsync( String queueUrl, List<SendMessageBatchRequestEntry> entries) { return sendMessageBatchAsync(new SendMessageBatchRequest(queueUrl, entries)); } @Override public Future<SendMessageBatchResult> sendMessageBatchAsync( String queueUrl, List<SendMessageBatchRequestEntry> entries, AsyncHandler<SendMessageBatchRequest, SendMessageBatchResult> asyncHandler) { return sendMessageBatchAsync(new SendMessageBatchRequest(queueUrl, entries), asyncHandler); } public Future<PurgeQueueResult> purgeQueueAsync(PurgeQueueRequest purgeQueueRequest, AsyncHandler<PurgeQueueRequest, PurgeQueueResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return realSQS.purgeQueueAsync(purgeQueueRequest, asyncHandler); } public Future<DeleteQueueResult> deleteQueueAsync(DeleteQueueRequest deleteQueueRequest, AsyncHandler<DeleteQueueRequest, DeleteQueueResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return realSQS.deleteQueueAsync(deleteQueueRequest, asyncHandler); } @Override public Future<DeleteQueueResult> deleteQueueAsync(String queueUrl) { return deleteQueueAsync(new DeleteQueueRequest(queueUrl)); } @Override public Future<DeleteQueueResult> deleteQueueAsync(String queueUrl, AsyncHandler<DeleteQueueRequest, DeleteQueueResult> asyncHandler) { return deleteQueueAsync(new DeleteQueueRequest(queueUrl), asyncHandler); } public Future<ListQueuesResult> listQueuesAsync(ListQueuesRequest listQueuesRequest, AsyncHandler<ListQueuesRequest, ListQueuesResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return realSQS.listQueuesAsync(listQueuesRequest, asyncHandler); } @Override public Future<ListQueuesResult> listQueuesAsync() { return listQueuesAsync(new ListQueuesRequest()); } @Override public Future<ListQueuesResult> listQueuesAsync( AsyncHandler<ListQueuesRequest, ListQueuesResult> asyncHandler) { return listQueuesAsync(new ListQueuesRequest(), asyncHandler); } @Override public Future<ListQueuesResult> listQueuesAsync(String queueNamePrefix) { return listQueuesAsync(new ListQueuesRequest(queueNamePrefix)); } @Override public Future<ListQueuesResult> listQueuesAsync(String queueNamePrefix, AsyncHandler<ListQueuesRequest, ListQueuesResult> asyncHandler) { return listQueuesAsync(new ListQueuesRequest(queueNamePrefix), asyncHandler); } public Future<DeleteMessageBatchResult> deleteMessageBatchAsync(DeleteMessageBatchRequest deleteMessageBatchRequest, AsyncHandler<DeleteMessageBatchRequest, DeleteMessageBatchResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return realSQS.deleteMessageBatchAsync(deleteMessageBatchRequest, asyncHandler); } @Override public Future<DeleteMessageBatchResult> deleteMessageBatchAsync( String queueUrl, List<DeleteMessageBatchRequestEntry> entries) { return deleteMessageBatchAsync(new DeleteMessageBatchRequest(queueUrl, entries)); } @Override public Future<DeleteMessageBatchResult> deleteMessageBatchAsync( String queueUrl, List<DeleteMessageBatchRequestEntry> entries, AsyncHandler<DeleteMessageBatchRequest, DeleteMessageBatchResult> asyncHandler) { return deleteMessageBatchAsync(new DeleteMessageBatchRequest(queueUrl, entries), asyncHandler); } public Future<CreateQueueResult> createQueueAsync(CreateQueueRequest createQueueRequest, AsyncHandler<CreateQueueRequest, CreateQueueResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return realSQS.createQueueAsync(createQueueRequest, asyncHandler); } @Override public Future<CreateQueueResult> createQueueAsync(String queueName) { return createQueueAsync(new CreateQueueRequest(queueName)); } @Override public Future<CreateQueueResult> createQueueAsync(String queueName, AsyncHandler<CreateQueueRequest, CreateQueueResult> asyncHandler) { return createQueueAsync(new CreateQueueRequest(queueName), asyncHandler); } public Future<AddPermissionResult> addPermissionAsync(AddPermissionRequest addPermissionRequest, AsyncHandler<AddPermissionRequest, AddPermissionResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return realSQS.addPermissionAsync(addPermissionRequest, asyncHandler); } @Override public ListDeadLetterSourceQueuesResult listDeadLetterSourceQueues(ListDeadLetterSourceQueuesRequest listDeadLetterSourceQueuesRequest) throws AmazonServiceException, AmazonClientException { ResultConverter.appendUserAgent(listDeadLetterSourceQueuesRequest, USER_AGENT); return realSQS.listDeadLetterSourceQueues(listDeadLetterSourceQueuesRequest); } @Override public Future<ListDeadLetterSourceQueuesResult> listDeadLetterSourceQueuesAsync(ListDeadLetterSourceQueuesRequest listDeadLetterSourceQueuesRequest) throws AmazonServiceException, AmazonClientException { ResultConverter.appendUserAgent(listDeadLetterSourceQueuesRequest, USER_AGENT); return realSQS.listDeadLetterSourceQueuesAsync(listDeadLetterSourceQueuesRequest); } @Override public Future<ListDeadLetterSourceQueuesResult> listDeadLetterSourceQueuesAsync(ListDeadLetterSourceQueuesRequest listDeadLetterSourceQueuesRequest, AsyncHandler<ListDeadLetterSourceQueuesRequest, ListDeadLetterSourceQueuesResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return realSQS.listDeadLetterSourceQueuesAsync(listDeadLetterSourceQueuesRequest, asyncHandler); } @Override public SetQueueAttributesResult setQueueAttributes(String queueUrl, Map<String, String> attributes) throws AmazonServiceException, AmazonClientException { return setQueueAttributes(new SetQueueAttributesRequest(queueUrl, attributes)); } @Override public ChangeMessageVisibilityBatchResult changeMessageVisibilityBatch(String queueUrl, List<ChangeMessageVisibilityBatchRequestEntry> entries) throws AmazonServiceException, AmazonClientException { return changeMessageVisibilityBatch(new ChangeMessageVisibilityBatchRequest(queueUrl, entries)); } @Override public ChangeMessageVisibilityResult changeMessageVisibility(String queueUrl, String receiptHandle, Integer visibilityTimeout) throws AmazonServiceException, AmazonClientException { return changeMessageVisibility(new ChangeMessageVisibilityRequest(queueUrl, receiptHandle, visibilityTimeout)); } @Override public GetQueueUrlResult getQueueUrl(String queueName) throws AmazonServiceException, AmazonClientException { return getQueueUrl(new GetQueueUrlRequest(queueName)); } @Override public RemovePermissionResult removePermission(String queueUrl, String label) throws AmazonServiceException, AmazonClientException { return removePermission(new RemovePermissionRequest(queueUrl, label)); } @Override public SendMessageBatchResult sendMessageBatch(String queueUrl, List<SendMessageBatchRequestEntry> entries) throws AmazonServiceException, AmazonClientException { return sendMessageBatch(new SendMessageBatchRequest(queueUrl, entries)); } @Override public DeleteQueueResult deleteQueue(String queueUrl) throws AmazonServiceException, AmazonClientException { return deleteQueue(new DeleteQueueRequest(queueUrl)); } @Override public SendMessageResult sendMessage(String queueUrl, String messageBody) throws AmazonServiceException, AmazonClientException { return sendMessage(new SendMessageRequest(queueUrl, messageBody)); } @Override public ReceiveMessageResult receiveMessage(String queueUrl) throws AmazonServiceException, AmazonClientException { return receiveMessage(new ReceiveMessageRequest(queueUrl)); } @Override public ListQueuesResult listQueues(String queueNamePrefix) throws AmazonServiceException, AmazonClientException { return listQueues(new ListQueuesRequest(queueNamePrefix)); } @Override public DeleteMessageBatchResult deleteMessageBatch(String queueUrl, List<DeleteMessageBatchRequestEntry> entries) throws AmazonServiceException, AmazonClientException { return deleteMessageBatch(new DeleteMessageBatchRequest(queueUrl, entries)); } @Override public CreateQueueResult createQueue(String queueName) throws AmazonServiceException, AmazonClientException { return createQueue(new CreateQueueRequest(queueName)); } @Override public AddPermissionResult addPermission(String queueUrl, String label, List<String> aWSAccountIds, List<String> actions) throws AmazonServiceException, AmazonClientException { return addPermission(new AddPermissionRequest(queueUrl, label, aWSAccountIds, actions)); } @Override public DeleteMessageResult deleteMessage(String queueUrl, String receiptHandle) throws AmazonServiceException, AmazonClientException { return deleteMessage(new DeleteMessageRequest(queueUrl, receiptHandle)); } @Override public GetQueueAttributesResult getQueueAttributes(String queueUrl, List<String> attributeNames) { return getQueueAttributes(new GetQueueAttributesRequest(queueUrl, attributeNames)); } public TagQueueResult tagQueue(TagQueueRequest tagQueueRequest) { ResultConverter.appendUserAgent(tagQueueRequest, USER_AGENT); return realSQS.tagQueue(tagQueueRequest); } public TagQueueResult tagQueue(String queueUrl, Map<String, String> tags) { return tagQueue(new TagQueueRequest(queueUrl, tags)); } @Override public Future<TagQueueResult> tagQueueAsync(TagQueueRequest tagQueueRequest) { ResultConverter.appendUserAgent(tagQueueRequest, USER_AGENT); return realSQS.tagQueueAsync(tagQueueRequest); } @Override public Future<TagQueueResult> tagQueueAsync(TagQueueRequest tagQueueRequest, AsyncHandler<TagQueueRequest, TagQueueResult> asyncHandler) { ResultConverter.appendUserAgent(tagQueueRequest, USER_AGENT); return realSQS.tagQueueAsync(tagQueueRequest, asyncHandler); } @Override public Future<TagQueueResult> tagQueueAsync(String queueUrl, Map<String, String> tags) { return tagQueueAsync(new TagQueueRequest(queueUrl, tags)); } @Override public Future<TagQueueResult> tagQueueAsync(String queueUrl, Map<String, String> tags, AsyncHandler<TagQueueRequest, TagQueueResult> asyncHandler) { return tagQueueAsync(new TagQueueRequest(queueUrl, tags), asyncHandler); } public UntagQueueResult untagQueue(UntagQueueRequest untagQueueRequest) { ResultConverter.appendUserAgent(untagQueueRequest, USER_AGENT); return realSQS.untagQueue(untagQueueRequest); } public UntagQueueResult untagQueue(String queueUrl, List<String> tagKeys) { return untagQueue(new UntagQueueRequest(queueUrl, tagKeys)); } @Override public Future<UntagQueueResult> untagQueueAsync(UntagQueueRequest untagQueueRequest) { ResultConverter.appendUserAgent(untagQueueRequest, USER_AGENT); return realSQS.untagQueueAsync(untagQueueRequest); } @Override public Future<UntagQueueResult> untagQueueAsync(UntagQueueRequest untagQueueRequest, AsyncHandler<UntagQueueRequest, UntagQueueResult> asyncHandler) { ResultConverter.appendUserAgent(untagQueueRequest, USER_AGENT); return realSQS.untagQueueAsync(untagQueueRequest, asyncHandler); } @Override public Future<UntagQueueResult> untagQueueAsync(String queueUrl, List<String> tagKeys) { return untagQueueAsync(new UntagQueueRequest(queueUrl, tagKeys)); } @Override public Future<UntagQueueResult> untagQueueAsync(String queueUrl, List<String> tagKeys, AsyncHandler<UntagQueueRequest, UntagQueueResult> asyncHandler) { return untagQueueAsync(new UntagQueueRequest(queueUrl, tagKeys), asyncHandler); } public ListQueueTagsResult listQueueTags(ListQueueTagsRequest listQueueTagsRequest) { ResultConverter.appendUserAgent(listQueueTagsRequest, USER_AGENT); return realSQS.listQueueTags(listQueueTagsRequest); } public ListQueueTagsResult listQueueTags(String queueUrl) { return listQueueTags(new ListQueueTagsRequest(queueUrl)); } @Override public Future<ListQueueTagsResult> listQueueTagsAsync(ListQueueTagsRequest listQueueTagsRequest) { ResultConverter.appendUserAgent(listQueueTagsRequest, USER_AGENT); return realSQS.listQueueTagsAsync(listQueueTagsRequest); } @Override public Future<ListQueueTagsResult> listQueueTagsAsync(ListQueueTagsRequest listQueueTagsRequest, AsyncHandler<ListQueueTagsRequest, ListQueueTagsResult> asyncHandler) { return realSQS.listQueueTagsAsync(listQueueTagsRequest, asyncHandler); } @Override public Future<ListQueueTagsResult> listQueueTagsAsync(String queueUrl) { return listQueueTagsAsync(new ListQueueTagsRequest(queueUrl)); } @Override public Future<ListQueueTagsResult> listQueueTagsAsync(String queueUrl, AsyncHandler<ListQueueTagsRequest, ListQueueTagsResult> asyncHandler) { return listQueueTagsAsync(new ListQueueTagsRequest(queueUrl), asyncHandler); } }
15,038
1,043
<reponame>triceo/simple-java-mail<gh_stars>1000+ package org.simplejavamail.internal.authenticatedsockssupport.socks5server.io; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.Socket; /** * The class <code>SocketPipe</code> represents pipe that can transfer data from one socket to another socket. The tow socket should be * connected sockets. If any of the them occurred error the pipe will close all of them. */ public class SocketPipe { private static final Logger LOGGER = LoggerFactory.getLogger(SocketPipe.class); private static final String INPUT_PIPE_NAME = "INPUT_PIPE"; private static final String OUTPUT_PIPE_NAME = "OUTPUT_PIPE"; private final StreamPipe pipe1; private final StreamPipe pipe2; private final Socket socket1; private final Socket socket2; private String name; private boolean running = false; private final PipeListener listener = new PipeListener(); /** * Constructs SocketPipe instance by tow connected sockets. */ public SocketPipe(final Socket socket1, final Socket socket2) throws IOException { this.socket1 = socket1; this.socket2 = socket2; pipe1 = new StreamPipe(socket1.getInputStream(), socket2.getOutputStream(), OUTPUT_PIPE_NAME); pipe2 = new StreamPipe(socket2.getInputStream(), socket1.getOutputStream(), INPUT_PIPE_NAME); pipe1.addPipeListener(listener); pipe2.addPipeListener(listener); } public void start() { running = pipe1.start() && pipe2.start(); } public void stop() { if (running) { pipe1.stop(); pipe2.stop(); if (pipe1.isStopped() && pipe2.isStopped()) { running = false; } } } private void close() { pipe2.removePipeListener(listener); pipe1.removePipeListener(listener); stop(); try { if (socket1 != null && !socket1.isClosed()) { socket1.close(); } if (socket2 != null && !socket2.isClosed()) { socket2.close(); } } catch (final IOException e) { LOGGER.error(e.getMessage(), e); } } public boolean isRunning() { return running; } public void setName(final String name) { this.name = name; } public class PipeListener { public String getName() { return name; } public void onStop(final StreamPipe streamPipe) { LOGGER.trace("Pipe[{}] stopped", streamPipe.getName()); close(); } } }
831
14,668
// Copyright (c) 2013 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_POLICY_PROFILE_POLICY_CONNECTOR_BUILDER_H_ #define CHROME_BROWSER_POLICY_PROFILE_POLICY_CONNECTOR_BUILDER_H_ #include <memory> namespace user_manager { class User; } namespace content { class BrowserContext; } namespace policy { class ChromeBrowserPolicyConnector; class CloudPolicyStore; class ConfigurationPolicyProvider; class ProfilePolicyConnector; class SchemaRegistry; class UserCloudPolicyManager; // Factory method that creates and initializes a new instance of // ProfilePolicyConnector for the given |context|. std::unique_ptr<ProfilePolicyConnector> CreateProfilePolicyConnectorForBrowserContext( SchemaRegistry* schema_registry, UserCloudPolicyManager* user_cloud_policy_manager, ConfigurationPolicyProvider* user_policy_provider, policy::ChromeBrowserPolicyConnector* browser_policy_connector, bool force_immediate_load, content::BrowserContext* context); // Factory method that creates and initializes a ProfilePolicyConnector. std::unique_ptr<ProfilePolicyConnector> CreateAndInitProfilePolicyConnector( SchemaRegistry* schema_registry, policy::ChromeBrowserPolicyConnector* browser_policy_connector, ConfigurationPolicyProvider* policy_provider, const CloudPolicyStore* policy_store, bool force_immediate_load, const user_manager::User* user = nullptr); // The next caller to create a ProfilePolicyConnector will get a PolicyService // with |provider| as its sole policy provider. This can be called multiple // times to override the policy providers for more than one Profile. void PushProfilePolicyConnectorProviderForTesting( ConfigurationPolicyProvider* provider); } // namespace policy #endif // CHROME_BROWSER_POLICY_PROFILE_POLICY_CONNECTOR_BUILDER_H_
552
1,602
// assign to all the variables #define lvar(name, type, init) name = init; #include "var-types.h" #undef lvar
40
469
/******************************************************************************* * Copyright 2019 See AUTHORS file * * 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.mini2Dx.core.collections; import org.junit.Test; import java.util.Iterator; import static org.junit.Assert.*; public class ShortQueueTest { @Test public void addFirstAndLastTest() { ShortQueue queue = new ShortQueue(); queue.addFirst((short) 1); queue.addLast((short) 2); queue.addFirst((short) 3); queue.addLast((short) 4); assertEquals(0, queue.indexOf((short) 3)); assertEquals(1, queue.indexOf((short) 1)); assertEquals(2, queue.indexOf((short) 2)); assertEquals(3, queue.indexOf((short) 4)); } @Test public void removeLastTest() { ShortQueue queue = new ShortQueue(); queue.addLast((short) 1); queue.addLast((short) 2); queue.addLast((short) 3); queue.addLast((short) 4); assertEquals(4, queue.size); assertEquals(3, queue.indexOf((short) 4)); assertEquals(4, queue.removeLast()); assertEquals(3, queue.size); assertEquals(2, queue.indexOf((short) 3)); assertEquals(3, queue.removeLast()); assertEquals(2, queue.size); assertEquals(1, queue.indexOf((short) 2)); assertEquals(2, queue.removeLast()); assertEquals(1, queue.size); assertEquals(0, queue.indexOf((short) 1)); assertEquals(1, queue.removeLast()); assertEquals(0, queue.size); } @Test public void removeFirstTest() { ShortQueue queue = new ShortQueue(); queue.addLast((short) 1); queue.addLast((short) 2); queue.addLast((short) 3); queue.addLast((short) 4); assertEquals(4, queue.size); assertEquals(0, queue.indexOf((short) 1)); assertEquals(1, queue.removeFirst()); assertEquals(3, queue.size); assertEquals(0, queue.indexOf((short) 2)); assertEquals(2, queue.removeFirst()); assertEquals(2, queue.size); assertEquals(0, queue.indexOf((short) 3)); assertEquals(3, queue.removeFirst()); assertEquals(1, queue.size); assertEquals(0, queue.indexOf((short) 4)); assertEquals(4, queue.removeFirst()); assertEquals(0, queue.size); } @Test public void resizableQueueTest () { final ShortQueue q = new ShortQueue(8); assertEquals("New queue is not empty!", 0, q.size); for (int i = 0; i < 100; i++) { for (int j = 0; j < i; j++) { try { q.addLast((short) j); } catch (IllegalStateException e) { fail("Failed to add element " + j + " (" + i + ")"); } final short peeked = q.last(); assertEquals("peekLast shows " + peeked + ", should be " + j + " (" + i + ")", peeked, j); final int size = q.size; assertEquals("Size should be " + (j + 1) + " but is " + size + " (" + i + ")", size, j + 1); } if (i != 0) { final short peek = q.first(); assertEquals("First thing is not zero but " + peek + " (" + i + ")", 0, peek); } for (int j = 0; j < i; j++) { final short pop = q.removeFirst(); assertEquals("Popped should be " + j + " but is " + pop + " (" + i + ")", pop, j); final int size = q.size; assertEquals("Size should be " + (i - 1 - j) + " but is " + size + " (" + i + ")", size, i - 1 - j); } assertEquals("Not empty after cycle " + i, 0, q.size); } for (int i = 0; i < 56; i++) { q.addLast((short) 42); } q.clear(); assertEquals("Clear did not clear properly", 0, q.size); } /** Same as resizableQueueTest, but in reverse */ @Test public void resizableDequeTest () { final ShortQueue q = new ShortQueue(8); assertEquals("New deque is not empty!", 0, q.size); for (int i = 0; i < 100; i++) { for (int j = 0; j < i; j++) { try { q.addFirst((short) j); } catch (IllegalStateException e) { fail("Failed to add element " + j + " (" + i + ")"); } final short peeked = q.first(); assertEquals("peek shows " + peeked + ", should be " + j + " (" + i + ")", peeked, j); final int size = q.size; assertEquals("Size should be " + (j + 1) + " but is " + size + " (" + i + ")", size, j + 1); } if (i != 0) { final short peek = q.last(); assertEquals("Last thing is not zero but " + peek + " (" + i + ")", 0, peek); } for (int j = 0; j < i; j++) { final short pop = q.removeLast(); assertEquals("Popped should be " + j + " but is " + pop + " (" + i + ")", pop, j); final int size = q.size; assertEquals("Size should be " + (i - 1 - j) + " but is " + size + " (" + i + ")", size, i - 1 - j); } assertEquals("Not empty after cycle " + i, 0, q.size); } for (int i = 0; i < 56; i++) { q.addFirst((short) 42); } q.clear(); assertEquals("Clear did not clear properly", 0, q.size); } @Test public void getTest () { final ShortQueue q = new ShortQueue(7); for (int i = 0; i < 5; i++) { for (int j = 0; j < 4; j++) { q.addLast((short) j); } assertEquals("get(0) is not equal to peek (" + i + ")", q.get(0), q.first()); assertEquals("get(size-1) is not equal to peekLast (" + i + ")", q.get(q.size - 1), q.last()); for (int j = 0; j < 4; j++) { assertEquals(q.get(j), j); } for (int j = 0; j < 4 - 1; j++) { q.removeFirst(); assertEquals("get(0) is not equal to peek (" + i + ")", q.get(0), q.first()); } q.removeFirst(); assert q.size == 0; // Failing this means broken test try { q.get(0); fail("get() on empty queue did not throw"); } catch (IndexOutOfBoundsException ignore) { // Expected } } } @Test public void removeTest () { final ShortQueue q = new ShortQueue(); // Test head < tail. for (int j = 0; j <= 6; j++) q.addLast((short) j); assertValues(q, 0, 1, 2, 3, 4, 5, 6); q.removeIndex(0); assertValues(q, 1, 2, 3, 4, 5, 6); q.removeIndex(1); assertValues(q, 1, 3, 4, 5, 6); q.removeIndex(4); assertValues(q, 1, 3, 4, 5); q.removeIndex(2); assertValues(q, 1, 3, 5); // Test head >= tail and index >= head. q.clear(); for (int j = 2; j >= 0; j--) q.addFirst((short) j); for (int j = 3; j <= 6; j++) q.addLast((short) j); assertValues(q, 0, 1, 2, 3, 4, 5, 6); q.removeIndex(1); assertValues(q, 0, 2, 3, 4, 5, 6); q.removeIndex(0); assertValues(q, 2, 3, 4, 5, 6); // Test head >= tail and index < tail. q.clear(); for (int j = 2; j >= 0; j--) q.addFirst((short) j); for (int j = 3; j <= 6; j++) q.addLast((short) j); assertValues(q, 0, 1, 2, 3, 4, 5, 6); q.removeIndex(5); assertValues(q, 0, 1, 2, 3, 4, 6); q.removeIndex(5); assertValues(q, 0, 1, 2, 3, 4); } @Test public void indexOfTest () { final ShortQueue q = new ShortQueue(); // Test head < tail. for (int j = 0; j <= 6; j++) q.addLast((short) j); for (int j = 0; j <= 6; j++) assertEquals(q.indexOf((short) j), j); // Test head >= tail. q.clear(); for (int j = 2; j >= 0; j--) q.addFirst((short) j); for (int j = 3; j <= 6; j++) q.addLast((short) j); for (int j = 0; j <= 6; j++) assertEquals(q.indexOf((short) j), j); } @Test public void iteratorTest () { final ShortQueue q = new ShortQueue(); // Test head < tail. for (int j = 0; j <= 6; j++) q.addLast((short) j); Iterator<Short> iter = q.iterator(); for (int j = 0; j <= 6; j++) assertEquals(iter.next().intValue(), j); iter = q.iterator(); iter.next(); iter.remove(); assertValues(q, 1, 2, 3, 4, 5, 6); iter.next(); iter.remove(); assertValues(q, 2, 3, 4, 5, 6); iter.next(); iter.next(); iter.remove(); assertValues(q, 2, 4, 5, 6); iter.next(); iter.next(); iter.next(); iter.remove(); assertValues(q, 2, 4, 5); // Test head >= tail. q.clear(); for (int j = 2; j >= 0; j--) q.addFirst((short) j); for (int j = 3; j <= 6; j++) q.addLast((short) j); iter = q.iterator(); for (int j = 0; j <= 6; j++) assertEquals(iter.next().intValue(), j); iter = q.iterator(); iter.next(); iter.remove(); assertValues(q, 1, 2, 3, 4, 5, 6); iter.next(); iter.remove(); assertValues(q, 2, 3, 4, 5, 6); iter.next(); iter.next(); iter.remove(); assertValues(q, 2, 4, 5, 6); iter.next(); iter.next(); iter.next(); iter.remove(); assertValues(q, 2, 4, 5); } @Test public void iteratorRemoveEdgeCaseTest() {//See #4300 ShortQueue queue = new ShortQueue(); //Simulate normal usage for(int i = 0; i < 100; i++) { queue.addLast((short) i); if(i > 50) queue.removeFirst(); } Iterator<Short> it = queue.iterator(); while(it.hasNext()) { it.next(); it.remove(); } queue.addLast((short) 1337); short i = queue.first(); assertEquals((short) 1337, i); } @Test public void toStringTest () { ShortQueue q = new ShortQueue(1); assertEquals("[]", q.toString()); q.addLast((short) 4); assertEquals("[4]", q.toString()); q.addLast((short) 5); q.addLast((short) 6); q.addLast((short) 7); assertEquals("[4, 5, 6, 7]", q.toString()); } @Test public void hashEqualsTest () { ShortQueue q1 = new ShortQueue(); ShortQueue q2 = new ShortQueue(); assertEqualsAndHash(q1, q2); q1.addFirst((short) 1); assertNotEquals(q1, q2); q2.addFirst((short) 1); assertEqualsAndHash(q1, q2); q1.clear(); q1.addLast((short) 1); q1.addLast((short) 2); q2.addLast((short) 2); assertEqualsAndHash(q1, q2); for (int i = 0; i < 100; i++) { q1.addLast((short) i); q1.addLast((short) i); q1.removeFirst(); assertNotEquals(q1, q2); q2.addLast((short) i); q2.addLast((short) i); q2.removeFirst(); assertEqualsAndHash(q1, q2); } } private void assertEqualsAndHash (ShortQueue q1, ShortQueue q2) { assertEquals(q1, q2); assertEquals("Hash codes are not equal", q1.hashCode(), q2.hashCode()); } private void assertValues (ShortQueue q, int... values) { for (int i = 0, n = values.length; i < n; i++) { assertEquals((short) values[i], q.get(i)); } } }
6,221
399
#pragma once #include "CompositeObj.hpp" #include "system/System.hpp" #include "Common.hpp" /** \brief Helpers to export a Rendu scene. \ingroup ObjToScene */ namespace SceneExport { /** \brief Contain exported texture infos for a given material. */ struct Material { std::string colorName; ///< Color texture name. std::string normalName; ///< Normal map name. std::string roughMetAoName; ///< Roughness-metalness-ambient occlusion texture name. std::string depthName; ///< Optional depth map. bool hasAlpha = false; ///< Alpha mask. }; /** Save a small colored texture. \param outputPath the output image file path \param color the color to store in the texture \return an error code or 0 */ int saveColor(const std::string & outputPath, const glm::vec3 & color); /** Save a material parameters as a series of textures. \param baseName material base name \param material the material to export \param outputDirPath the output directory \return the exported material information */ Material saveMaterial(const std::string & baseName, const CompositeObj::Material & material, const std::string & outputDirPath); /** Save a scene description, listing all objects with materials. The file can then be decoded by Codable objects. \param objects the scene objects \param materials the scene materials \param outputPath the destination file \return an error code or 0 */ int saveDescription(const std::vector<CompositeObj::Object> & objects, const std::unordered_map<std::string, Material> & materials, const std::string & outputPath); }
445
4,879
<gh_stars>1000+ // Copyright 2019 Google // // 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 <stdbool.h> #include <stdint.h> #include <sys/types.h> #include "FIRCLSDwarfUnwindRegisters.h" #include "FIRCLSThreadState.h" #if CLS_DWARF_UNWINDING_SUPPORTED #pragma mark Structures typedef struct { uint32_t length; const void* data; } DWARFInstructions; typedef struct { uint64_t length; uint8_t version; uintptr_t ehData; // 8 bytes for 64-bit architectures, 4 bytes for 32 const char* augmentation; uint8_t pointerEncoding; uint8_t lsdaEncoding; uint8_t personalityEncoding; uintptr_t personalityFunction; uint64_t codeAlignFactor; int64_t dataAlignFactor; uint64_t returnAddressRegister; // is 64 bits enough for this value? bool signalFrame; DWARFInstructions instructions; } DWARFCIERecord; typedef struct { uint64_t length; uint64_t cieOffset; // also an arch-specific size uintptr_t startAddress; uintptr_t rangeSize; DWARFInstructions instructions; } DWARFFDERecord; typedef struct { DWARFCIERecord cie; DWARFFDERecord fde; } FIRCLSDwarfCFIRecord; typedef enum { FIRCLSDwarfRegisterUnused = 0, FIRCLSDwarfRegisterInCFA, FIRCLSDwarfRegisterOffsetFromCFA, FIRCLSDwarfRegisterInRegister, FIRCLSDwarfRegisterAtExpression, FIRCLSDwarfRegisterIsExpression } FIRCLSDwarfRegisterLocation; typedef struct { FIRCLSDwarfRegisterLocation location; uint64_t value; } FIRCLSDwarfRegister; typedef struct { uint64_t cfaRegister; int64_t cfaRegisterOffset; const void* cfaExpression; uint32_t spArgSize; FIRCLSDwarfRegister registers[CLS_DWARF_MAX_REGISTER_NUM + 1]; } FIRCLSDwarfState; __BEGIN_DECLS #pragma mark - Parsing bool FIRCLSDwarfParseCIERecord(DWARFCIERecord* cie, const void* ptr); bool FIRCLSDwarfParseFDERecord(DWARFFDERecord* fdeRecord, bool parseCIE, DWARFCIERecord* cieRecord, const void* ptr); bool FIRCLSDwarfParseCFIFromFDERecord(FIRCLSDwarfCFIRecord* record, const void* ptr); bool FIRCLSDwarfParseCFIFromFDERecordOffset(FIRCLSDwarfCFIRecord* record, const void* ehFrame, uintptr_t fdeOffset); #pragma mark - Properties bool FIRCLSDwarfCIEIsValid(DWARFCIERecord* cie); bool FIRCLSDwarfCIEHasAugmentationData(DWARFCIERecord* cie); #pragma mark - Execution bool FIRCLSDwarfInstructionsEnumerate(DWARFInstructions* instructions, DWARFCIERecord* cieRecord, FIRCLSDwarfState* state, intptr_t pcOffset); bool FIRCLSDwarfUnwindComputeRegisters(FIRCLSDwarfCFIRecord* record, FIRCLSThreadContext* registers); bool FIRCLSDwarfUnwindAssignRegisters(const FIRCLSDwarfState* state, const FIRCLSThreadContext* registers, uintptr_t cfaRegister, FIRCLSThreadContext* outputRegisters); #pragma mark - Register Operations bool FIRCLSDwarfCompareRegisters(const FIRCLSThreadContext* a, const FIRCLSThreadContext* b, uint64_t registerNum); bool FIRCLSDwarfGetCFA(FIRCLSDwarfState* state, const FIRCLSThreadContext* registers, uintptr_t* cfa); uintptr_t FIRCLSDwarfGetSavedRegister(const FIRCLSThreadContext* registers, uintptr_t cfaRegister, FIRCLSDwarfRegister dRegister); #if DEBUG #pragma mark - Debugging void FIRCLSCFIRecordShow(FIRCLSDwarfCFIRecord* record); void FIRCLSCIERecordShow(DWARFCIERecord* record); void FIRCLSFDERecordShow(DWARFFDERecord* record, DWARFCIERecord* cie); void FIRCLSDwarfPointerEncodingShow(const char* leadString, uint8_t encoding); void FIRCLSDwarfInstructionsShow(DWARFInstructions* instructions, DWARFCIERecord* cie); #endif __END_DECLS #endif
2,035
338
package fr.lteconsulting.pomexplorer.graph; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; import fr.lteconsulting.pomexplorer.graph.relation.*; import org.jgrapht.graph.DirectedMultigraph; import fr.lteconsulting.pomexplorer.model.Gav; public class PomGraph { private PomGraphReadTransaction readTransaction = null; private final AtomicReference<DirectedMultigraph<Gav, Relation>> graphReference = new AtomicReference<>( createGraph() ); public PomGraphWriteTransaction write() { return new PomGraphWriteTransaction(); } public PomGraphReadTransaction read() { if( readTransaction == null ) readTransaction = new PomGraphReadTransaction( graphReference.get() ); return readTransaction; } private DirectedMultigraph<Gav, Relation> copyGraph( DirectedMultigraph<Gav, Relation> graph ) { DirectedMultigraph<Gav, Relation> newGraph = createGraph(); for( Gav gav : graph.vertexSet() ) newGraph.addVertex( gav ); for( Relation edge : graph.edgeSet() ) newGraph.addEdge( graph.getEdgeSource( edge ), graph.getEdgeTarget( edge ), edge ); return newGraph; } private DirectedMultigraph<Gav, Relation> createGraph() { @SuppressWarnings( "unchecked" ) Class<? extends Relation> edgeClass = Relation.class; return new DirectedMultigraph<>(edgeClass); } public static class PomGraphReadTransaction { protected final DirectedMultigraph<Gav, Relation> txGraph; public PomGraphReadTransaction( DirectedMultigraph<Gav, Relation> txGraph ) { this.txGraph = txGraph; } public Set<Gav> gavs() { return txGraph.vertexSet(); } public Set<Relation> relations() { return txGraph.edgeSet(); } public boolean hasArtifact( Gav gav ) { return txGraph.containsVertex( gav ); } /** * For read only purpose only ! */ public DirectedMultigraph<Gav, Relation> internalGraph() { return txGraph; } public Gav sourceOf( Relation relation ) { return relation.getSource(); } public Gav targetOf( Relation relation ) { return relation.getTarget(); } public Gav parent( Gav gav ) { Set<ParentRelation> relations = filterParentRelations( relations( gav ) ); if( relations == null || relations.size() != 1 ) return null; return txGraph.getEdgeTarget( relations.iterator().next() ); } public Set<Gav> children( Gav gav ) { Set<Gav> res = new HashSet<>(); Set<ParentRelation> relations = filterParentRelations( relationsReverse( gav ) ); for( ParentRelation relation : relations ) res.add( txGraph.getEdgeSource( relation ) ); return res; } /** * Gets the outgoing relations of a GAV */ public Set<Relation> relations( Gav gav ) { Set<Relation> res = new HashSet<>(); relations( gav, res ); return res; } /** * Recursively gets the outgoing relations of a GAV */ public Set<Relation> relationsRec( Gav gav ) { Set<Relation> res = new HashSet<>(); relationsRec( gav, res, new HashSet<>() ); return res; } /** * Gets the ingoing relations of a GAV */ public Set<Relation> relationsReverse( Gav gav ) { if( !txGraph.containsVertex( gav ) ) return null; return txGraph.incomingEdgesOf( gav ); } /** * Recursively gets the ingoing relations of a GAV */ public Set<Relation> relationsReverseRec( Gav gav ) { Set<Relation> res = new HashSet<>(); relationsReverseRec( gav, res, new HashSet<>() ); return res; } public Set<DependencyManagementRelation> dependenciesManagement( Gav gav ) { return filterDependencyManagementRelations( relations( gav ) ); } public Set<DependencyManagementRelation> dependenciesManagementRec( Gav gav ) { return filterDependencyManagementRelations( relationsRec( gav ) ); } public Set<DependencyRelation> dependencies( Gav gav ) { return filterDependencyRelations( relations( gav ) ); } public Set<DependencyRelation> dependenciesRec( Gav gav ) { return filterDependencyRelations( relationsRec( gav ) ); } public Set<BuildDependencyRelation> buildDependencies( Gav gav ) { return filterBuildDependencyRelations( relations( gav ) ); } public Set<BuildDependencyRelation> buildDependenciesRec( Gav gav ) { return filterBuildDependencyRelations( relationsRec( gav ) ); } /** * Returns the set of GAVs which depend directly on the one passed by parameter */ public Set<DependencyRelation> dependents( Gav gav ) { return filterDependencyRelations( relationsReverse( gav ) ); } public Set<DependencyRelation> dependentsRec( Gav gav ) { return filterDependencyRelations( relationsReverseRec( gav ) ); } public Set<DependencyManagementRelation> dependentsManagement( Gav gav ) { return filterDependencyManagementRelations( relationsReverse( gav ) ); } public Set<DependencyManagementRelation> dependentsManagementRec( Gav gav ) { return filterDependencyManagementRelations( relationsReverseRec( gav ) ); } public Set<BuildDependencyRelation> buildDependents( Gav gav ) { return filterBuildDependencyRelations( relationsReverse( gav ) ); } public Set<BuildDependencyRelation> buildDependentsRec( Gav gav ) { return filterBuildDependencyRelations( relationsReverseRec( gav ) ); } private static Set<ParentRelation> filterParentRelations( Set<Relation> relations ) { return filterRelations(relations, ParentRelation.class); } private static Set<DependencyRelation> filterDependencyRelations( Set<Relation> relations ) { return filterRelations(relations, DependencyRelation.class); } private static Set<DependencyManagementRelation> filterDependencyManagementRelations( Set<Relation> relations ) { return filterRelations(relations, DependencyManagementRelation.class); } private static Set<BuildDependencyRelation> filterBuildDependencyRelations( Set<Relation> relations ) { return filterRelations(relations, BuildDependencyRelation.class); } private static <T> Set<T> filterRelations(Set<Relation> relations, Class<T> clazz) { return relations.stream() .filter(clazz::isInstance) .map(clazz::cast) .collect(Collectors.toSet()); } private void relations( Gav gav, Set<Relation> set ) { if( !txGraph.containsVertex( gav ) ) return; set.addAll( txGraph.outgoingEdgesOf( gav ) ); } private void relationsRec( Gav gav, Set<Relation> set, Set<Gav> visitedGavs ) { if( !txGraph.containsVertex( gav ) ) return; if( visitedGavs.contains( gav ) ) return; visitedGavs.add( gav ); Set<Relation> relations = txGraph.outgoingEdgesOf( gav ); set.addAll( relations ); for( Relation r : relations ) { Gav target = txGraph.getEdgeTarget( r ); relationsRec( target, set, visitedGavs ); } } private void relationsReverseRec( Gav gav, Set<Relation> set, Set<Gav> visitedGavs ) { if( visitedGavs.contains( gav ) ) return; visitedGavs.add( gav ); Set<Relation> relations = txGraph.incomingEdgesOf( gav ); for( Relation r : relations ) { Gav source = txGraph.getEdgeSource( r ); set.add( r ); relationsReverseRec( source, set, visitedGavs ); } } } public class PomGraphWriteTransaction extends PomGraphReadTransaction { private PomGraphWriteTransaction() { super( copyGraph( graphReference.get() ) ); } public void commit() { graphReference.set( txGraph ); readTransaction = null; } public boolean addGav( Gav gav ) { return txGraph.addVertex( gav ); } public boolean addRelation( Relation relation ) { return txGraph.addEdge( relation.getSource(), relation.getTarget(), relation ); } public void removeRelations( Collection<Relation> relations ) { txGraph.removeAllEdges( relations ); } } }
2,957
1,444
package mage.client.dialog; import mage.client.MageFrame; import mage.client.util.SettingsManager; import mage.client.util.gui.GuiDisplayUtil; import org.apache.log4j.Logger; import javax.swing.*; import java.awt.*; import java.awt.event.InvocationEvent; import java.awt.event.MouseEvent; import java.beans.PropertyVetoException; import java.lang.reflect.InvocationTargetException; /** * @author <EMAIL>, JayDi85 */ public class MageDialog extends javax.swing.JInternalFrame { private static final Logger LOGGER = Logger.getLogger(MageDialog.class); protected boolean modal = false; /** * Creates new form MageDialog */ public MageDialog() { initComponents(); } public void changeGUISize() { } public static boolean isModalDialogActivated() { for (JInternalFrame frame : MageFrame.getDesktop().getAllFrames()) { if (frame instanceof MageDialog) { MageDialog md = (MageDialog) frame; if (md.isVisible() && md.isModal()) { return true; } } } return false; } public static void printFramesOrder(String name) { ///* JInternalFrame[] frames = MageFrame.getDesktop().getAllFrames(); System.out.println("--- " + name + " ---"); int order = 0; for (JInternalFrame frame : frames) { order++; int zorder = -1; if (frame.getParent() != null) { zorder = frame.getParent().getComponentZOrder(frame); } System.out.println(order + ". " + frame.getClass() + " (" + frame.getTitle() + ") : layer = " + frame.getLayer() + ", zorder = " + zorder); } //*/ } @Override public void show() { super.show(); // frames desktop ordering // more info https://docs.oracle.com/javase/7/docs/api/javax/swing/JLayeredPane.html // WARNING, use // - JLayeredPane.DEFAULT_LAYER: tables and games (tabs) // - JLayeredPane.PALETTE_LAYER: toolbars and info windows like cards list, not modal dialogs (not required user actions) // - JLayeredPane.MODAL_LAYER: all modal dialogs (user required actions - select cards in game, new game window, error windows) // - JLayeredPane.POPUP_LAYER: hints and other top level graphics // - JLayeredPane.DRAG_LAYER: top most layer for critical actions and user controls if (modal) { this.setClosable(false); } this.toFront(); if (modal) { startModal(); } } @Override public void setVisible(boolean value) { super.setVisible(value); if (value) { this.toFront(); try { this.setSelected(true); } catch (PropertyVetoException e) { // } } if (modal) { this.setClosable(false); if (value) { startModal(); } else if (SwingUtilities.isEventDispatchThread()) { stopModal(); } else { try { SwingUtilities.invokeAndWait(() -> stopModal()); } catch (InterruptedException ex) { LOGGER.fatal("MageDialog error", ex); Thread.currentThread().interrupt(); } catch (InvocationTargetException ex) { LOGGER.fatal("MageDialog error", ex); } } } } private synchronized void startModal() { // modal loop -- all mouse events must be ignored by other windows try { if (SwingUtilities.isEventDispatchThread()) { EventQueue theQueue = getToolkit().getSystemEventQueue(); while (isVisible()) { AWTEvent event = theQueue.getNextEvent(); Object source = event.getSource(); boolean dispatch = true; // https://github.com/magefree/mage/issues/584 - Let's hope this will fix the Linux window problem if (event.getSource() != null && event.getSource() instanceof TrayIcon && !(event instanceof InvocationEvent)) { dispatch = false; //return; // JayDi85: users can move mouse over try icon to disable modal mode (it's a bug but can be used in the future) } // ignore mouse events outside from panel, only drag and move allowed -- as example: // combobox's popup will be selectable outside // cards and button hints will be works Component popupComponent = null; MouseEvent popupEvent = null; if (event instanceof MouseEvent && event.getSource() instanceof Component) { MouseEvent e = (MouseEvent) event; MouseEvent m = SwingUtilities.convertMouseEvent((Component) e.getSource(), e, this); // disable all outer events (except some actions) if (!this.contains(m.getPoint())) { boolean allowedEvent = false; // need any mouse move (for hints) if (e.getID() == MouseEvent.MOUSE_DRAGGED || e.getID() == MouseEvent.MOUSE_MOVED) { allowedEvent = true; } // need popup clicks and mouse wheel (for out of bound actions) if (!allowedEvent) { popupComponent = SwingUtilities.getDeepestComponentAt(e.getComponent(), e.getX(), e.getY()); // show root component (popups creates at root) if (popupComponent != null && (popupComponent.getClass().getName().contains("BasicComboPopup") || popupComponent.getClass().getName().contains("JMenuItem"))) { popupEvent = SwingUtilities.convertMouseEvent((Component) e.getSource(), e, popupComponent); allowedEvent = true; } } dispatch = allowedEvent; } } if (dispatch) { if (popupEvent != null) { // process outer popup events, it's must be FIRST check popupComponent.dispatchEvent(popupEvent); } else if (event instanceof ActiveEvent) { ((ActiveEvent) event).dispatch(); } else if (source instanceof Component) { ((Component) source).dispatchEvent(event); } else if (source instanceof MenuComponent) { ((MenuComponent) source).dispatchEvent(event); } else { LOGGER.warn("Unable to dispatch: " + event); } } } } else { while (isVisible()) { wait(); } } } catch (InterruptedException e) { LOGGER.fatal("MageDialog error", e); Thread.currentThread().interrupt(); } } private synchronized void stopModal() { notifyAll(); } public void setModal(boolean modal) { this.modal = modal; } public boolean isModal() { return this.modal; } public void hideDialog() { this.setVisible(false); } public void removeDialog() { // avoid memory leak of javax.swing.plaf.nimbus.NimbusStyle$CacheKey KeyboardFocusManager.getCurrentKeyboardFocusManager().clearGlobalFocusOwner(); //this.setVisible(false); // important to set close before removing the JInternalFrame to avoid memory leaks (http://bugs.java.com/view_bug.do?bug_id=7163808) try { this.setClosed(true); } catch (PropertyVetoException ex) { LOGGER.error("setClosed(false) failed", ex); } MageFrame.getDesktop().remove(this); } public void makeWindowCentered() { makeWindowCentered(this, this.getWidth(), this.getHeight()); } public static void makeWindowCentered(Component component, int width, int height) { Point centered = SettingsManager.instance.getComponentPosition(width, height); component.setLocation(centered.x, centered.y); GuiDisplayUtil.keepComponentInsideScreen(centered.x, centered.y, component); } /** * Used to set a tooltip text on icon and titel bar * * @param text */ public void setTitelBarToolTip(final String text) { desktopIcon.setToolTipText(text); //tooltip on icon Component[] children = getComponents(); if (children != null) { for (Component children1 : children) { if (children1.getClass().getName().equalsIgnoreCase("javax.swing.plaf.synth.SynthInternalFrameTitlePane")) { ((JComponent) children1).setToolTipText(text); //tooltip on title bar break; } } } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 394, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 274, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables // End of variables declaration//GEN-END:variables }
5,028
2,313
/* * Copyright (c) 2021 Arm Limited. * * SPDX-License-Identifier: MIT * * 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 SRC_COMMON_IQUEUE_H_ #define SRC_COMMON_IQUEUE_H_ #include "src/common/IContext.h" struct AclQueue_ { arm_compute::detail::Header header{ arm_compute::detail::ObjectType::Queue, nullptr }; protected: AclQueue_() = default; ~AclQueue_() = default; }; namespace arm_compute { /** Base class specifying the queue interface */ class IQueue : public AclQueue_ { public: /** Explict Operator Constructor * * @param[in] ctx Context to be used by the operator */ explicit IQueue(IContext *ctx) { this->header.ctx = ctx; this->header.ctx->inc_ref(); } /** Destructor */ virtual ~IQueue() { this->header.ctx->dec_ref(); this->header.type = detail::ObjectType::Invalid; }; /** Checks if a queue is valid * * @return True if successful otherwise false */ bool is_valid() const { return this->header.type == detail::ObjectType::Queue; }; virtual StatusCode finish() = 0; }; /** Extract internal representation of a Queue * * @param[in] queue Opaque queue pointer * * @return The internal representation as an IQueue */ inline IQueue *get_internal(AclQueue queue) { return static_cast<IQueue *>(queue); } namespace detail { /** Check if an internal queue is valid * * @param[in] queue Internal queue to check * * @return A status code */ inline StatusCode validate_internal_queue(const IQueue *queue) { if(queue == nullptr || !queue->is_valid()) { ARM_COMPUTE_LOG_ERROR_ACL("[IQueue]: Invalid queue object"); return StatusCode::InvalidArgument; } return StatusCode::Success; } } // namespace detail } // namespace arm_compute #endif /* SRC_COMMON_IQUEUE_H_ */
956
441
import numpy as np import pandas as pd import yfinance import matplotlib.pyplot as plt import datetime as dt pd.set_option('display.max_columns', None) stock = input('Enter a ticker: ') start = dt.date.today() - dt.timedelta(days=1) ticker = yfinance.Ticker(stock) df = ticker.history(interval="1d") last_day = df.tail(1).copy().drop(columns=['Dividends', 'Stock Splits']) last_day['Pivot'] = (last_day['High'] + last_day['Low'] + last_day['Close'])/3 last_day['R1'] = 2*last_day['Pivot'] - last_day['Low'] last_day['S1'] = 2*last_day['Pivot'] - last_day['High'] last_day['R2'] = last_day['Pivot'] + (last_day['High'] - last_day['Low']) last_day['S2'] = last_day['Pivot'] - (last_day['High'] - last_day['Low']) last_day['R3'] = last_day['Pivot'] + 2*(last_day['High'] - last_day['Low']) last_day['S3'] = last_day['Pivot'] - 2*(last_day['High'] - last_day['Low']) print (last_day) data = yfinance.download(tickers=stock, period="1d", interval="1m") df = data['Close'] fig, ax = plt.subplots() plt.rcParams['figure.figsize'] = (15, 10) plt.plot(df) plt.axhline(last_day['R1'].tolist()[0], color='b', label='Resistance 1') plt.axhline(last_day['S1'].tolist()[0], color='b', label='Support 1') plt.axhline(last_day['R2'].tolist()[0], color='green', label='Resistance 2') plt.axhline(last_day['S2'].tolist()[0], color='green', label='Support 2') plt.axhline(last_day['R3'].tolist()[0], color='r', label='Resistance 3') plt.axhline(last_day['S3'].tolist()[0], color='r', label='Support 3') plt.legend() plt.title('{} - {}'.format(stock.upper(), start)) plt.xlabel('Time') plt.ylabel('Price') plt.show()
683
679
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef SC_SPELLPARAM_HXX #define SC_SPELLPARAM_HXX #include <vcl/font.hxx> // ============================================================================ /** Specifiers for sheet conversion (functions iterating over the sheet and modifying cells). */ enum ScConversionType { SC_CONVERSION_SPELLCHECK, /// Spell checker. SC_CONVERSION_HANGULHANJA, /// Hangul-Hanja converter. SC_CONVERSION_CHINESE_TRANSL /// Chinese simplified/traditional converter. }; // --------------------------------------------------------------------------- /** Parameters for conversion. */ class ScConversionParam { public: /** Constructs an empty parameter struct with the passed conversion type. */ explicit ScConversionParam( ScConversionType eConvType ); /** Constructs parameter struct for text conversion without changing the language. */ explicit ScConversionParam( ScConversionType eConvType, LanguageType eLang, sal_Int32 nOptions, bool bIsInteractive ); /** Constructs parameter struct for text conversion with language change. */ explicit ScConversionParam( ScConversionType eConvType, LanguageType eSourceLang, LanguageType eTargetLang, const Font& rTargetFont, sal_Int32 nOptions, bool bIsInteractive ); inline ScConversionType GetType() const { return meConvType; } inline LanguageType GetSourceLang() const { return meSourceLang; } inline LanguageType GetTargetLang() const { return meTargetLang; } inline const Font* GetTargetFont() const { return mbUseTargetFont ? &maTargetFont : 0; } inline sal_Int32 GetOptions() const { return mnOptions; } inline bool IsInteractive() const { return mbIsInteractive; } private: ScConversionType meConvType; /// Type of the conversion. LanguageType meSourceLang; /// Source language for conversion. LanguageType meTargetLang; /// Target language for conversion. Font maTargetFont; /// Target font to be used if language has to be changed. sal_Int32 mnOptions; /// Conversion options. bool mbUseTargetFont; /// True = Use maTargetFont to change font during conversion. bool mbIsInteractive; /// True = Text conversion has (specific) dialog that may be raised. }; // ============================================================================ #endif
1,298
2,151
<gh_stars>1000+ /* * Copyright (C) 2015 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.mtp; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.hardware.usb.UsbDevice; import android.hardware.usb.UsbManager; import android.util.Log; import java.io.IOException; public class UsbIntentReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { final UsbDevice device = intent.getExtras().getParcelable(UsbManager.EXTRA_DEVICE); switch (intent.getAction()) { case UsbManager.ACTION_USB_DEVICE_ATTACHED: MtpDocumentsProvider.getInstance().resumeRootScanner(); break; case UsbManager.ACTION_USB_DEVICE_DETACHED: try { MtpDocumentsProvider.getInstance().closeDevice(device.getDeviceId()); } catch (IOException | InterruptedException e) { Log.e(MtpDocumentsProvider.TAG, "Failed to close device", e); } break; } } }
618
2,094
//////////////////////////////////////////////////////////////////////////////////////////////////// // // Project: Embedded Learning Library (ELL) // File: Optional.h (utilities) // Authors: <NAME> // //////////////////////////////////////////////////////////////////////////////////////////////////// #pragma once #include "Exception.h" namespace ell { namespace utilities { /// <summary> An optional value. </summary> template <typename T> class Optional { public: /// <summary> Default constructor: creates an empty value </summary> constexpr Optional() {} /// <summary> Constructor with a (non-'auto') value </summary> /// /// <param name="value"> The value to set the object to. </param> constexpr Optional(T value) : _hasValue(true), _value(value) {} /// <summary> Query if the object has a value </summary> /// /// <returns> A boolean indicating if this object has a value set. </returns> bool HasValue() const { return _hasValue; } /// <summary> Get the value stored in the object. If it doesn't have a stored value, an exception is thrown. </summary> /// /// <returns> The stored value. </returns> const T& GetValue() const; /// <summary> Get the value stored in the object. If it doesn't have a stored value, return the supplied default value. </summary> /// /// <param name="defaultValue"> The value to return if this object is empty. </param> /// /// <returns> The stored value, if there is one, otherwise returns the default value supplied. </returns> const T& GetValue(const T& defaultValue) const; /// <summary> Sets the value stored in the object. </summary> /// /// <param name="value"> The value to set this object to. </param> void SetValue(const T& value); /// <summary> Clears the value stored in the object. </summary> void Clear(); private: bool _hasValue = false; T _value = {}; }; } // namespace utilities } // namespace ell #pragma region implementation #pragma once namespace ell { namespace utilities { template <typename T> const T& Optional<T>::GetValue() const { if (!HasValue()) { throw InputException(InputExceptionErrors::invalidArgument, "Error: called GetValue on an optional object without a value"); } return _value; } template <typename T> const T& Optional<T>::GetValue(const T& defaultValue) const { if (!HasValue()) { return defaultValue; } return _value; } template <typename T> void Optional<T>::SetValue(const T& value) { _value = value; _hasValue = true; } template <typename T> void Optional<T>::Clear() { _value = T(); _hasValue = false; } } // namespace utilities } // namespace ell #pragma endregion implementation
1,128
5,941
#include <stdio.h> #include <stdlib.h> #include <winpr/crt.h> #include <winpr/file.h> #include <winpr/windows.h> int TestFileDeleteFile(int argc, char* argv[]) { BOOL rc; int fd; char validA[] = "/tmp/valid-test-file-XXXXXX"; char validW[] = "/tmp/valid-test-file-XXXXXX"; WCHAR* validWW = NULL; const char* invalidA = "/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; const WCHAR invalidW[] = { '/', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', '\0' }; WINPR_UNUSED(argc); WINPR_UNUSED(argv); rc = DeleteFileA(invalidA); if (rc) return -1; rc = DeleteFileW(invalidW); if (rc) return -1; fd = mkstemp(validA); if (fd < 0) return -1; rc = DeleteFileA(validA); if (!rc) return -1; fd = mkstemp(validW); if (fd < 0) return -1; ConvertToUnicode(CP_UTF8, 0, validW, -1, &validWW, 0); rc = DeleteFileW(validWW); free(validWW); if (!rc) return -1; return 0; }
611
707
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. #include "hal/simulation/NotifierData.h" extern "C" { uint64_t HALSIM_GetNextNotifierTimeout(void) { return 0; } int32_t HALSIM_GetNumNotifiers(void) { return 0; } int32_t HALSIM_GetNotifierInfo(struct HALSIM_NotifierInfo* arr, int32_t size) { return 0; } } // extern "C"
175
310
{ "name": "Copperhead", "description": "A gaming mouse.", "url": "https://www.amazon.com/RAZER-Copperhead-Razor-Precision-Gaming/dp/B000C28VM0" }
62
1,471
<filename>tests/parser/exceptions/test_vyper_exception_pos.py from pytest import raises from vyper.exceptions import VyperException def test_type_exception_pos(): pos = (1, 2) with raises(VyperException) as e: raise VyperException("Fail!", pos) assert e.value.lineno == 1 assert e.value.col_offset == 2 assert str(e.value) == "line 1:2 Fail!" # multiple exceptions in file def test_multiple_exceptions(get_contract, assert_compile_failed): code = """ struct A: b: B # unknown type foo: immutable(uint256) bar: immutable(uint256) @external def __init__(): self.foo = 1 # SyntaxException self.bar = 2 # SyntaxException """ assert_compile_failed(lambda: get_contract(code), VyperException)
276
362
<filename>example/unitest/main.c #include <u/libu.h> #include "test.h" int facility = LOG_LOCAL0; int TC_1_1 (test_case_t *tc); int TC_1_2 (test_case_t *tc); int TC_2_1 (test_case_t *tc); int TC_2_2 (test_case_t *tc); int test_suite_TS1_register (test_t *t); int test_suite_TS2_register (test_t *t); int main (int argc, char *argv[]) { test_t *t = NULL; con_err_if (test_new("MY_TEST", &t)); con_err_if (test_suite_TS1_register(t)); con_err_if (test_suite_TS2_register(t)); con_err_if (test_run(argc, argv, t)); test_free(t); return EXIT_SUCCESS; err: test_free(t); return EXIT_FAILURE; } /* should go in a separate file */ int test_suite_TS1_register (test_t *t) { test_suite_t *ts = NULL; /* * - test suite "TS 1": * - test case "TC 1.1" which depends on "TC 1.2" * - test case "TC 1.2" */ con_err_if (test_suite_new("TS 1", &ts)); con_err_if (test_case_register("TC 1.1", TC_1_1, ts)); con_err_if (test_case_register("TC 1.2", TC_1_2, ts)); con_err_if (test_case_depends_on("TC 1.1", "TC 1.2", ts)); return test_suite_add(ts, t); err: test_suite_free(ts); return ~0; } int test_suite_TS2_register (test_t *t) { test_suite_t *ts = NULL; /* * - test suite "TS 2" which depends on "TS 1" * - test case "TC 2.1" * - test case "TC 2.2" */ con_err_if (test_suite_new("TS 2", &ts)); con_err_if (test_case_register("TC 2.1", TC_2_1, ts)); con_err_if (test_case_register("TC 2.2", TC_2_2, ts)); con_err_if (test_suite_dep_register("TS 1", ts)); return test_suite_add(ts, t); err: test_suite_free(ts); return ~0; } /* * fake test cases */ int TC_1_1 (test_case_t *tc) { char *x = malloc(10); u_con("hello TC_1_1"); return TEST_SUCCESS; } int TC_1_2 (test_case_t *tc) { unsigned int ts = 5; char *x = malloc(1000); u_con("hello TC_1_2 (sleeping)"); again: ts = sleep(ts); if (ts > 0 && errno == EINTR) goto again; return TEST_SUCCESS; } int TC_2_1 (test_case_t *tc) { unsigned int ts = 2; char *x = malloc(1000); u_con("hello TC_2_1"); again: ts = sleep(ts); if (ts > 0 && errno == EINTR) goto again; return TEST_SUCCESS; } int TC_2_2 (test_case_t *tc) { char r[1]; char *x = malloc(100); u_con("hello TC_2_2"); return TEST_SUCCESS; }
1,207
528
<reponame>anukaal/opytimizer<gh_stars>100-1000 import gc import tensorflow as tf from tensorflow.keras import datasets, layers, models, optimizers from opytimizer import Opytimizer from opytimizer.core import Function from opytimizer.optimizers.swarm import PSO from opytimizer.spaces import SearchSpace # Loads CIFAR-10 data (X_train, Y_train), (X_val, Y_val) = datasets.cifar10.load_data() # Normalizes inputs between 0 and 1 X_train, X_val = X_train / 255.0, X_val / 255.0 def cnn(opytimizer): # Gathers parameters from Opytimizer # Pay extremely attention to their order when declaring due to their bounds learning_rate = opytimizer[0][0] beta_1 = opytimizer[1][0] # Instanciating model model = models.Sequential() # Adding layers to the model itself model.add(layers.Conv2D( 32, (3, 3), activation='relu', input_shape=(32, 32, 3))) model.add(layers.MaxPooling2D((2, 2))) model.add(layers.Conv2D(64, (3, 3), activation='relu')) model.add(layers.MaxPooling2D((2, 2))) model.add(layers.Conv2D(64, (3, 3), activation='relu')) model.add(layers.Flatten()) model.add(layers.Dense(64, activation='relu')) model.add(layers.Dense(10, activation='softmax')) # Compiling the model model.compile(optimizer=optimizers.Adam(learning_rate=learning_rate, beta_1=beta_1), loss='sparse_categorical_crossentropy', metrics=['accuracy']) # Fitting the model history = model.fit(X_train, Y_train, epochs=3, validation_data=(X_val, Y_val)) # Gathers validation accuracy val_acc = history.history['val_accuracy'][-1] # Cleaning up memory del history del model # Calling the garbage collector gc.collect() return 1 - val_acc # Number of agents and decision variables n_agents = 5 n_variables = 2 # Lower and upper bounds (has to be the same size as `n_variables`) lower_bound = [0, 0] upper_bound = [0.001, 1] # Creates the space, optimizer and function space = SearchSpace(n_agents, n_variables, lower_bound, upper_bound) optimizer = PSO() function = Function(cnn) # Bundles every piece into Opytimizer class opt = Opytimizer(space, optimizer, function) # Runs the optimization task opt.start(n_iterations=3)
870
25,360
<reponame>linzhaojia77/jeecg-boot<gh_stars>1000+ package org.jeecg.modules.demo.cloud.service; import org.jeecg.common.api.vo.Result; public interface JcloudDemoService { Result<String> getMessage(String name); }
85
918
<filename>boost/libs/spirit/test/karma/regression_semantic_action_attribute.cpp // Copyright (c) 2010 <NAME> // Copyright (c) 2001-2010 <NAME> // // 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) #include <boost/config/warning_disable.hpp> #include <boost/detail/lightweight_test.hpp> #include <string> #include <vector> #include <boost/spirit/include/karma.hpp> #include <boost/spirit/include/phoenix.hpp> #include "test.hpp" using namespace spirit_test; namespace karma = boost::spirit::karma; namespace phx = boost::phoenix; int main() { using karma::int_; using karma::_1; BOOST_TEST(test("16909060", int_[ _1 = phx::val(0x01020304) ])); // make sure the passed attribute type does not enforce the attribute type // for the semantic action unsigned char char_value = 8; BOOST_TEST(test("16909060", int_[ _1 = phx::val(0x01020304) ], char_value)); return boost::report_errors(); }
367
14,668
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/sync/model/proxy_model_type_controller_delegate.h" #include <utility> #include "base/bind.h" #include "components/sync/base/bind_to_task_runner.h" #include "components/sync/engine/data_type_activation_response.h" #include "components/sync/model/data_type_activation_request.h" #include "components/sync/model/type_entities_count.h" namespace syncer { namespace { void OnSyncStartingHelperOnModelThread( const DataTypeActivationRequest& request, ModelTypeControllerDelegate::StartCallback callback_bound_to_ui_thread, base::WeakPtr<ModelTypeControllerDelegate> delegate) { DCHECK(delegate); delegate->OnSyncStarting(request, std::move(callback_bound_to_ui_thread)); } void GetAllNodesForDebuggingHelperOnModelThread( ProxyModelTypeControllerDelegate::AllNodesCallback callback_bound_to_ui_thread, base::WeakPtr<ModelTypeControllerDelegate> delegate) { DCHECK(delegate); delegate->GetAllNodesForDebugging(std::move(callback_bound_to_ui_thread)); } void GetTypeEntitiesCountForDebuggingHelperOnModelThread( base::OnceCallback<void(const TypeEntitiesCount&)> callback_bound_to_ui_thread, base::WeakPtr<ModelTypeControllerDelegate> delegate) { DCHECK(delegate); delegate->GetTypeEntitiesCountForDebugging( std::move(callback_bound_to_ui_thread)); } void StopSyncHelperOnModelThread( SyncStopMetadataFate metadata_fate, base::WeakPtr<ModelTypeControllerDelegate> delegate) { DCHECK(delegate); delegate->OnSyncStopping(metadata_fate); } void RecordMemoryUsageAndCountsHistogramsHelperOnModelThread( base::WeakPtr<ModelTypeControllerDelegate> delegate) { DCHECK(delegate); delegate->RecordMemoryUsageAndCountsHistograms(); } // Rurns some task on the destination task runner (backend sequence), first // exercising |delegate_provider| *also* in the backend sequence. void RunModelTask( const ProxyModelTypeControllerDelegate::DelegateProvider& delegate_provider, base::OnceCallback<void(base::WeakPtr<ModelTypeControllerDelegate>)> task) { base::WeakPtr<ModelTypeControllerDelegate> delegate = delegate_provider.Run(); // TODO(mastiz): Migrate away from weak pointers, since there is no actual // need, provided that KeyedServices have proper dependencies. DCHECK(delegate); std::move(task).Run(delegate); } } // namespace ProxyModelTypeControllerDelegate::ProxyModelTypeControllerDelegate( const scoped_refptr<base::SequencedTaskRunner>& task_runner, const DelegateProvider& delegate_provider) : task_runner_(task_runner), delegate_provider_(delegate_provider) { DCHECK(task_runner_); } ProxyModelTypeControllerDelegate::~ProxyModelTypeControllerDelegate() = default; void ProxyModelTypeControllerDelegate::OnSyncStarting( const DataTypeActivationRequest& request, StartCallback callback) { PostTask(FROM_HERE, base::BindOnce(&OnSyncStartingHelperOnModelThread, request, BindToCurrentSequence(std::move(callback)))); } void ProxyModelTypeControllerDelegate::OnSyncStopping( SyncStopMetadataFate metadata_fate) { PostTask(FROM_HERE, base::BindOnce(&StopSyncHelperOnModelThread, metadata_fate)); } void ProxyModelTypeControllerDelegate::GetAllNodesForDebugging( AllNodesCallback callback) { PostTask(FROM_HERE, base::BindOnce(&GetAllNodesForDebuggingHelperOnModelThread, BindToCurrentSequence(std::move(callback)))); } void ProxyModelTypeControllerDelegate::GetTypeEntitiesCountForDebugging( base::OnceCallback<void(const TypeEntitiesCount&)> callback) const { PostTask(FROM_HERE, base::BindOnce(&GetTypeEntitiesCountForDebuggingHelperOnModelThread, BindToCurrentSequence(std::move(callback)))); } void ProxyModelTypeControllerDelegate::RecordMemoryUsageAndCountsHistograms() { PostTask( FROM_HERE, base::BindOnce(&RecordMemoryUsageAndCountsHistogramsHelperOnModelThread)); } void ProxyModelTypeControllerDelegate::PostTask( const base::Location& location, base::OnceCallback<void(base::WeakPtr<ModelTypeControllerDelegate>)> task) const { task_runner_->PostTask( location, base::BindOnce(&RunModelTask, delegate_provider_, std::move(task))); } } // namespace syncer
1,494
467
<filename>MacForge/MacForgeHelper/MFAppDelegate.h<gh_stars>100-1000 // // MFAppDelegate.h // MFAppDelegate // // Created by <NAME> on 04/12/12. // Copyright (c) 2020 MacEnhance. All rights reserved. // #import <Cocoa/Cocoa.h> @interface MFAppDelegate : NSObject <NSApplicationDelegate, NSUserNotificationCenterDelegate> { AuthorizationRef _authRef; NSMutableArray *watchdogs; } @property (strong, nonatomic) NSStatusItem *statusBar; @property (assign) IBOutlet NSWindow *window; @end
182
1,773
<filename>src/TriggerThreadProcs.c<gh_stars>1000+ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License //-------------------------------------------------------------------- // // thread processes // //-------------------------------------------------------------------- #include "TriggerThreadProcs.h" extern long HZ; // clock ticks per second extern pthread_mutex_t ptrace_mutex; void *CommitMonitoringThread(void *thread_args /* struct ProcDumpConfiguration* */) { Trace("CommitMonitoringThread: Starting Trigger Thread"); struct ProcDumpConfiguration *config = (struct ProcDumpConfiguration *)thread_args; long pageSize_kb; unsigned long memUsage = 0; struct ProcessStat proc = {0}; int rc = 0; struct CoreDumpWriter *writer = NewCoreDumpWriter(COMMIT, config); pageSize_kb = sysconf(_SC_PAGESIZE) >> 10; // convert bytes to kilobytes (2^10) if ((rc = WaitForQuitOrEvent(config, &config->evtStartMonitoring, INFINITE_WAIT)) == WAIT_OBJECT_0 + 1) { while ((rc = WaitForQuit(config, config->PollingInterval)) == WAIT_TIMEOUT) { if (GetProcessStat(config->ProcessId, &proc)) { // Calc Commit memUsage = (proc.rss * pageSize_kb) >> 10; // get Resident Set Size memUsage += (proc.nswap * pageSize_kb) >> 10; // get Swap size // Commit Trigger if ((config->bMemoryTriggerBelowValue && (memUsage < config->MemoryThreshold)) || (!config->bMemoryTriggerBelowValue && (memUsage >= config->MemoryThreshold))) { Log(info, "Commit: %ld MB", memUsage); rc = WriteCoreDump(writer); if ((rc = WaitForQuit(config, config->ThresholdSeconds * 1000)) != WAIT_TIMEOUT) { break; } } } else { Log(error, "An error occurred while parsing procfs\n"); exit(-1); } } } free(writer); Trace("CommitMonitoringThread: Exiting Trigger Thread"); pthread_exit(NULL); } void* ThreadCountMonitoringThread(void *thread_args /* struct ProcDumpConfiguration* */) { Trace("ThreadCountMonitoringThread: Starting Thread Thread"); struct ProcDumpConfiguration *config = (struct ProcDumpConfiguration *)thread_args; struct ProcessStat proc = {0}; int rc = 0; struct CoreDumpWriter *writer = NewCoreDumpWriter(THREAD, config); if ((rc = WaitForQuitOrEvent(config, &config->evtStartMonitoring, INFINITE_WAIT)) == WAIT_OBJECT_0 + 1) { while ((rc = WaitForQuit(config, config->PollingInterval)) == WAIT_TIMEOUT) { if (GetProcessStat(config->ProcessId, &proc)) { if (proc.num_threads >= config->ThreadThreshold) { Log(info, "Threads: %ld", proc.num_threads); rc = WriteCoreDump(writer); if ((rc = WaitForQuit(config, config->ThresholdSeconds * 1000)) != WAIT_TIMEOUT) { break; } } } else { Log(error, "An error occurred while parsing procfs\n"); exit(-1); } } } free(writer); Trace("ThreadCountMonitoringThread: Exiting Thread trigger Thread"); pthread_exit(NULL); } void* FileDescriptorCountMonitoringThread(void *thread_args /* struct ProcDumpConfiguration* */) { Trace("FileDescriptorCountMonitoringThread: Starting Filedescriptor Thread"); struct ProcDumpConfiguration *config = (struct ProcDumpConfiguration *)thread_args; struct ProcessStat proc = {0}; int rc = 0; struct CoreDumpWriter *writer = NewCoreDumpWriter(FILEDESC, config); if ((rc = WaitForQuitOrEvent(config, &config->evtStartMonitoring, INFINITE_WAIT)) == WAIT_OBJECT_0 + 1) { while ((rc = WaitForQuit(config, config->PollingInterval)) == WAIT_TIMEOUT) { if (GetProcessStat(config->ProcessId, &proc)) { if (proc.num_filedescriptors >= config->FileDescriptorThreshold) { Log(info, "File descriptors: %ld", proc.num_filedescriptors); rc = WriteCoreDump(writer); if ((rc = WaitForQuit(config, config->ThresholdSeconds * 1000)) != WAIT_TIMEOUT) { break; } } } else { Log(error, "An error occurred while parsing procfs\n"); exit(-1); } } } free(writer); Trace("FileDescriptorCountMonitoringThread: Exiting Filedescriptor trigger Thread"); pthread_exit(NULL); } // // This thread monitors for a specific signal to be sent to target process. // It uses ptrace (PTRACE_SEIZE) and once the signal with the corresponding // signal number is intercepted, it detaches from the target process in a stopped state // followed by invoking gcore to generate the dump. Once completed, a SIGCONT followed by the // original signal is sent to the target process. Signals of non-interest are simply forwarded // to the target process. // // Polling interval has no meaning during signal monitoring. // void* SignalMonitoringThread(void *thread_args /* struct ProcDumpConfiguration* */) { Trace("SignalMonitoringThread: Starting SignalMonitoring Thread"); struct ProcDumpConfiguration *config = (struct ProcDumpConfiguration *)thread_args; int wstatus; int signum=-1; int rc = 0; struct CoreDumpWriter *writer = NewCoreDumpWriter(SIGNAL, config); if ((rc = WaitForQuitOrEvent(config, &config->evtStartMonitoring, INFINITE_WAIT)) == WAIT_OBJECT_0 + 1) { // Attach to the target process. We use SEIZE here to avoid // the SIGSTOP issues of the ATTACH method. if (ptrace(PTRACE_SEIZE, config->ProcessId, NULL, NULL) == -1) { Log(error, "Unable to PTRACE the target process"); } else { while(1) { // Wait for signal to be delivered waitpid(config->ProcessId, &wstatus, 0); if(WIFEXITED(wstatus) || WIFSIGNALED(wstatus)) { ptrace(PTRACE_DETACH, config->ProcessId, 0, 0); break; } pthread_mutex_lock(&ptrace_mutex); // We are now in a signal-stop state signum = WSTOPSIG(wstatus); if(signum == config->SignalNumber) { // We have to detach in a STOP state so we can invoke gcore if(ptrace(PTRACE_DETACH, config->ProcessId, 0, SIGSTOP) == -1) { Log(error, "Unable to PTRACE (DETACH) the target process"); pthread_mutex_unlock(&ptrace_mutex); break; } // Write core dump Log(info, "Signal intercepted: %d", signum); rc = WriteCoreDump(writer); kill(config->ProcessId, SIGCONT); if(config->NumberOfDumpsCollected >= config->NumberOfDumpsToCollect) { // If we are over the max number of dumps to collect, send the original signal we intercepted. kill(config->ProcessId, signum); pthread_mutex_unlock(&ptrace_mutex); break; } ptrace(PTRACE_CONT, config->ProcessId, NULL, signum); // Re-attach to the target process if (ptrace(PTRACE_SEIZE, config->ProcessId, NULL, NULL) == -1) { Log(error, "Unable to PTRACE the target process"); pthread_mutex_unlock(&ptrace_mutex); break; } pthread_mutex_unlock(&ptrace_mutex); continue; } // Resume execution of the target process ptrace(PTRACE_CONT, config->ProcessId, NULL, signum); pthread_mutex_unlock(&ptrace_mutex); } } } free(writer); Trace("SignalMonitoringThread: Exiting SignalMonitoring Thread"); pthread_exit(NULL); } void *CpuMonitoringThread(void *thread_args /* struct ProcDumpConfiguration* */) { Trace("CpuMonitoringThread: Starting Trigger Thread"); struct ProcDumpConfiguration *config = (struct ProcDumpConfiguration *)thread_args; unsigned long totalTime = 0; unsigned long elapsedTime = 0; struct sysinfo sysInfo; int cpuUsage; struct CoreDumpWriter *writer = NewCoreDumpWriter(CPU, config); int rc = 0; struct ProcessStat proc = {0}; if ((rc = WaitForQuitOrEvent(config, &config->evtStartMonitoring, INFINITE_WAIT)) == WAIT_OBJECT_0 + 1) { while ((rc = WaitForQuit(config, config->PollingInterval)) == WAIT_TIMEOUT) { sysinfo(&sysInfo); if (GetProcessStat(config->ProcessId, &proc)) { // Calc CPU totalTime = (unsigned long)((proc.utime + proc.stime) / HZ); elapsedTime = (unsigned long)(sysInfo.uptime - (long)(proc.starttime / HZ)); cpuUsage = (int)(100 * ((double)totalTime / elapsedTime)); // CPU Trigger if ((config->CpuUpperThreshold != -1 && (cpuUsage >= config->CpuUpperThreshold)) || (config->CpuLowerThreshold != -1 && (cpuUsage < config->CpuLowerThreshold))) { Log(info, "CPU:\t%d%%", cpuUsage); rc = WriteCoreDump(writer); if ((rc = WaitForQuit(config, config->ThresholdSeconds * 1000)) != WAIT_TIMEOUT) { break; } } } else { Log(error, "An error occurred while parsing procfs\n"); exit(-1); } } } free(writer); Trace("CpuTCpuMonitoringThread: Exiting Trigger Thread"); pthread_exit(NULL); } void *TimerThread(void *thread_args /* struct ProcDumpConfiguration* */) { Trace("TimerThread: Starting Trigger Thread"); struct ProcDumpConfiguration *config = (struct ProcDumpConfiguration *)thread_args; struct CoreDumpWriter *writer = NewCoreDumpWriter(TIME, config); int rc = 0; if ((rc = WaitForQuitOrEvent(config, &config->evtStartMonitoring, INFINITE_WAIT)) == WAIT_OBJECT_0 + 1) { while ((rc = WaitForQuit(config, 0)) == WAIT_TIMEOUT) { Log(info, "Timed:"); rc = WriteCoreDump(writer); if ((rc = WaitForQuit(config, config->ThresholdSeconds * 1000)) != WAIT_TIMEOUT) { break; } } } free(writer); Trace("TimerThread: Exiting Trigger Thread"); pthread_exit(NULL); }
5,475
7,482
<reponame>Davidfind/rt-thread /***************************************************************************//** * @file * @brief General Purpose IO (GPIO) peripheral API * devices. * @author Energy Micro AS * @version 3.0.0 ******************************************************************************* * @section License * <b>(C) Copyright 2012 Energy Micro AS, http://www.energymicro.com</b> ******************************************************************************* * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. * * DISCLAIMER OF WARRANTY/LIMITATION OF REMEDIES: Energy Micro AS has no * obligation to support this Software. Energy Micro AS is providing the * Software "AS IS", with no express or implied warranties of any kind, * including, but not limited to, any implied warranties of merchantability * or fitness for any particular purpose or warranties against infringement * of any proprietary rights of a third party. * * Energy Micro AS will not be liable for any consequential, incidental, or * special damages, or any other relief, or for any claim by any third party, * arising from your use of this Software. * ******************************************************************************/ #include "em_gpio.h" #include "em_bitband.h" #include "em_assert.h" /***************************************************************************//** * @addtogroup EM_Library * @{ ******************************************************************************/ /***************************************************************************//** * @addtogroup GPIO * @brief General Purpose Input/Output (GPIO) API * @{ ******************************************************************************/ /******************************************************************************* ******************************* DEFINES *********************************** ******************************************************************************/ /** @cond DO_NOT_INCLUDE_WITH_DOXYGEN */ /** Validation of pin typically usable in assert statements. */ #define GPIO_DRIVEMODE_VALID(mode) ((mode) <= 3) /** Validation of pin typically usable in assert statements. */ #define GPIO_PIN_VALID(pin) ((pin) < 16) /** Validation of port typically usable in assert statements. */ #define GPIO_PORT_VALID(port) ((port) <= gpioPortF) /** @endcond */ /******************************************************************************* ************************** GLOBAL FUNCTIONS ******************************* ******************************************************************************/ /***************************************************************************//** * @brief * Sets the pin location of the debug pins (Serial Wire interface). * * @note * Changing the pins used for debugging uncontrolled, may result in a lockout. * * @param[in] location * The debug pin location to use (0-3). ******************************************************************************/ void GPIO_DbgLocationSet(unsigned int location) { EFM_ASSERT(location < AFCHANLOC_MAX); GPIO->ROUTE = (GPIO->ROUTE & ~_GPIO_ROUTE_SWLOCATION_MASK) | (location << _GPIO_ROUTE_SWLOCATION_SHIFT); } /***************************************************************************//** * @brief * Sets the drive mode for a GPIO port. * * @param[in] port * The GPIO port to access. * * @param[in] mode * Drive mode to use for port. ******************************************************************************/ void GPIO_DriveModeSet(GPIO_Port_TypeDef port, GPIO_DriveMode_TypeDef mode) { EFM_ASSERT(GPIO_PORT_VALID(port) && GPIO_DRIVEMODE_VALID(mode)); GPIO->P[port].CTRL = (GPIO->P[port].CTRL & ~(_GPIO_P_CTRL_DRIVEMODE_MASK)) | (mode << _GPIO_P_CTRL_DRIVEMODE_SHIFT); } /***************************************************************************//** * @brief * Configure GPIO interrupt. * * @details * If reconfiguring a GPIO interrupt that is already enabled, it is generally * recommended to disable it first, see GPIO_Disable(). * * The actual GPIO interrupt handler must be in place before enabling the * interrupt. * * Notice that any pending interrupt for the selected pin is cleared by this * function. * * @note * A certain pin number can only be associated with one port. Ie, if GPIO * interrupt 1 is assigned to port A/pin 1, then it is not possibly to use * pin 1 from any other ports for interrupts. Please refer to the reference * manual. * * @param[in] port * The port to associate with @p pin. * * @param[in] pin * The GPIO interrupt number (= port pin). * * @param[in] risingEdge * Set to true if interrupts shall be enabled on rising edge, otherwise false. * * @param[in] fallingEdge * Set to true if interrupts shall be enabled on falling edge, otherwise false. * * @param[in] enable * Set to true if interrupt shall be enabled after configuration completed, * false to leave disabled. See GPIO_IntDisable() and GPIO_IntEnable(). ******************************************************************************/ void GPIO_IntConfig(GPIO_Port_TypeDef port, unsigned int pin, bool risingEdge, bool fallingEdge, bool enable) { uint32_t tmp; EFM_ASSERT(GPIO_PORT_VALID(port) && GPIO_PIN_VALID(pin)); /* There are two registers controlling the interrupt configuration: * The EXTIPSELL register controls pins 0-7 and EXTIPSELH controls * pins 8-15. */ if (pin < 8) { GPIO->EXTIPSELL = (GPIO->EXTIPSELL & ~(0xF << (4 * pin))) | (port << (4 * pin)); } else { tmp = pin - 8; GPIO->EXTIPSELH = (GPIO->EXTIPSELH & ~(0xF << (4 * tmp))) | (port << (4 * tmp)); } /* Enable/disable rising edge */ BITBAND_Peripheral(&(GPIO->EXTIRISE), pin, (unsigned int)risingEdge); /* Enable/disable falling edge */ BITBAND_Peripheral(&(GPIO->EXTIFALL), pin, (unsigned int)fallingEdge); /* Clear any pending interrupt */ GPIO->IFC = 1 << pin; /* Finally enable/disable interrupt */ BITBAND_Peripheral(&(GPIO->IEN), pin, (unsigned int)enable); } /***************************************************************************//** * @brief * Read the pad value for a single pin in a GPIO port. * * @param[in] port * The GPIO port to access. * * @param[in] pin * The pin number to read. * * @return * The pin value, 0 or 1. ******************************************************************************/ unsigned int GPIO_PinInGet(GPIO_Port_TypeDef port, unsigned int pin) { EFM_ASSERT(GPIO_PORT_VALID(port) && GPIO_PIN_VALID(pin)); return((unsigned int)((GPIO->P[port].DIN >> pin) & 0x1)); } /***************************************************************************//** * @brief * Set the mode for a GPIO pin. * * @param[in] port * The GPIO port to access. * * @param[in] pin * The pin number in the port. * * @param[in] mode * The desired pin mode. * * @param[in] out * Value to set for pin in DOUT register. The DOUT setting is important for * even some input mode configurations, determining pull-up/down direction. * Notice that this parameter is not used if disabling a pin, leaving the * corresponding DOUT bit unchanged. ******************************************************************************/ void GPIO_PinModeSet(GPIO_Port_TypeDef port, unsigned int pin, GPIO_Mode_TypeDef mode, unsigned int out) { EFM_ASSERT(GPIO_PORT_VALID(port) && GPIO_PIN_VALID(pin)); /* If disabling pin, do not modify DOUT in order to reduce chance for */ /* glitch/spike (may not be sufficient precaution in all use cases) */ if (mode != gpioModeDisabled) { if (out) { GPIO->P[port].DOUTSET = 1 << pin; } else { GPIO->P[port].DOUTCLR = 1 << pin; } } /* There are two registers controlling the pins for each port. The MODEL * register controls pins 0-7 and MODEH controls pins 8-15. */ if (pin < 8) { GPIO->P[port].MODEL = (GPIO->P[port].MODEL & ~(0xF << (pin * 4))) | (mode << (pin * 4)); } else { GPIO->P[port].MODEH = (GPIO->P[port].MODEH & ~(0xF << ((pin - 8) * 4))) | (mode << ((pin - 8) * 4)); } if (mode == gpioModeDisabled) { if (out) { GPIO->P[port].DOUTSET = 1 << pin; } else { GPIO->P[port].DOUTCLR = 1 << pin; } } } /***************************************************************************//** * @brief * Set a single pin in GPIO data out port register to 0. * * @note * In order for the setting to take effect on the output pad, the pin must * have been configured properly. If not, it will take effect whenever the * pin has been properly configured. * * @param[in] port * The GPIO port to access. * * @param[in] pin * The pin to set. ******************************************************************************/ void GPIO_PinOutClear(GPIO_Port_TypeDef port, unsigned int pin) { EFM_ASSERT(GPIO_PORT_VALID(port) && GPIO_PIN_VALID(pin)); GPIO->P[port].DOUTCLR = 1 << pin; } /***************************************************************************//** * @brief * Get current setting for a pin in a GPIO port data out register. * * @param[in] port * The GPIO port to access. * * @param[in] pin * The pin to get setting for. * * @return * The DOUT setting for the requested pin, 0 or 1. ******************************************************************************/ unsigned int GPIO_PinOutGet(GPIO_Port_TypeDef port, unsigned int pin) { EFM_ASSERT(GPIO_PORT_VALID(port) && GPIO_PIN_VALID(pin)); return((unsigned int)((GPIO->P[port].DOUT >> pin) & 0x1)); } /***************************************************************************//** * @brief * Set a single pin in GPIO data out register to 1. * * @note * In order for the setting to take effect on the output pad, the pin must * have been configured properly. If not, it will take effect whenever the * pin has been properly configured. * * @param[in] port * The GPIO port to access. * * @param[in] pin * The pin to set. ******************************************************************************/ void GPIO_PinOutSet(GPIO_Port_TypeDef port, unsigned int pin) { EFM_ASSERT(GPIO_PORT_VALID(port) && GPIO_PIN_VALID(pin)); GPIO->P[port].DOUTSET = 1 << pin; } /***************************************************************************//** * @brief * Toggle a single pin in GPIO port data out register. * * @note * In order for the setting to take effect on the output pad, the pin must * have been configured properly. If not, it will take effect whenever the * pin has been properly configured. * * @param[in] port * The GPIO port to access. * * @param[in] pin * The pin to toggle. ******************************************************************************/ void GPIO_PinOutToggle(GPIO_Port_TypeDef port, unsigned int pin) { EFM_ASSERT(GPIO_PORT_VALID(port) && GPIO_PIN_VALID(pin)); GPIO->P[port].DOUTTGL = 1 << pin; } /***************************************************************************//** * @brief * Read the pad values for GPIO port. * * @param[in] port * The GPIO port to access. ******************************************************************************/ uint32_t GPIO_PortInGet(GPIO_Port_TypeDef port) { EFM_ASSERT(GPIO_PORT_VALID(port)); return(GPIO->P[port].DIN & _GPIO_P_DIN_DIN_MASK); } /***************************************************************************//** * @brief * Set bits in DOUT register for a port to 0. * * @note * In order for the setting to take effect on the output pad, the pin must * have been configured properly. If not, it will take effect whenever the * pin has been properly configured. * * @param[in] port * The GPIO port to access. * * @param[in] pins * Bit mask for bits to clear in DOUT register. ******************************************************************************/ void GPIO_PortOutClear(GPIO_Port_TypeDef port, uint32_t pins) { EFM_ASSERT(GPIO_PORT_VALID(port)); GPIO->P[port].DOUTCLR = pins & _GPIO_P_DOUTCLR_DOUTCLR_MASK; } /***************************************************************************//** * @brief * Get current setting for a GPIO port data out register. * * @param[in] port * The GPIO port to access. * * @return * The data out setting for the requested port. ******************************************************************************/ uint32_t GPIO_PortOutGet(GPIO_Port_TypeDef port) { EFM_ASSERT(GPIO_PORT_VALID(port)); return(GPIO->P[port].DOUT & _GPIO_P_DOUT_DOUT_MASK); } /***************************************************************************//** * @brief * Set bits GPIO data out register to 1. * * @note * In order for the setting to take effect on the respective output pads, the * pins must have been configured properly. If not, it will take effect * whenever the pin has been properly configured. * * @param[in] port * The GPIO port to access. * * @param[in] pins * Bit mask for bits to set to 1 in DOUT register. ******************************************************************************/ void GPIO_PortOutSet(GPIO_Port_TypeDef port, uint32_t pins) { EFM_ASSERT(GPIO_PORT_VALID(port)); GPIO->P[port].DOUTSET = pins & _GPIO_P_DOUTSET_DOUTSET_MASK; } /***************************************************************************//** * @brief * Set GPIO port data out register. * * @note * In order for the setting to take effect on the respective output pads, the * pins must have been configured properly. If not, it will take effect * whenever the pin has been properly configured. * * @param[in] port * The GPIO port to access. * * @param[in] val * Value to write to port data out register. * * @param[in] mask * Mask indicating which bits to modify. ******************************************************************************/ void GPIO_PortOutSetVal(GPIO_Port_TypeDef port, uint32_t val, uint32_t mask) { EFM_ASSERT(GPIO_PORT_VALID(port)); GPIO->P[port].DOUT = (GPIO->P[port].DOUT & ~mask) | (val & mask); } /***************************************************************************//** * @brief * Toggle a single pin in GPIO port data out register. * * @note * In order for the setting to take effect on the output pad, the pin must * have been configured properly. If not, it will take effect whenever the * pin has been properly configured. * * @param[in] port * The GPIO port to access. * * @param[in] pins * Bitmask with pins to toggle. ******************************************************************************/ void GPIO_PortOutToggle(GPIO_Port_TypeDef port, uint32_t pins) { EFM_ASSERT(GPIO_PORT_VALID(port)); GPIO->P[port].DOUTTGL = pins & _GPIO_P_DOUTTGL_DOUTTGL_MASK; } /** @} (end addtogroup GPIO) */ /** @} (end addtogroup EM_Library) */
4,771
307
<filename>classloader-leak-prevention/classloader-leak-prevention-core/src/test/java/se/jiderhamn/classloader/leak/prevention/cleanup/IIOServiceProviderCleanUpTest.java package se.jiderhamn.classloader.leak.prevention.cleanup; import javax.imageio.ImageIO; import javax.swing.*; import org.junit.Before; /** * Test case for {@link IIOServiceProviderCleanUp} * @author <NAME> (1.x version) * @author <NAME> */ public class IIOServiceProviderCleanUpTest extends ClassLoaderPreMortemCleanUpTestBase<IIOServiceProviderCleanUp> { // ImageIO.scanForPlugins() triggers two different leaks, but the preventor only removes one, so we need to avoid // the other one by running some code in parent classloader @Before public void systemClassLoader() { new JEditorPane("text/plain", "dummy"); // java.awt.Toolkit.getDefaultToolkit() } @Override protected void triggerLeak() throws Exception { ImageIO.scanForPlugins(); } }
307
982
/* * This file contains dump parsing logic * * Copyright (c) 2008-2017 Red Hat, Inc. * * 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 names of the copyright holders nor the names of their contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "stdafx.h" #include "NetKVMDumpParser.h" #include "..\..\Common\DebugData.h" #include <sal.h> #ifdef _DEBUG #define new DEBUG_NEW #endif #define PRINT_SEPARATOR "-------------------------------------" #define DEBUG_SYMBOLS_IF IDebugSymbols3 FILE *outf = stdout; //#define UNDER_DEBUGGING #ifndef UNDER_DEBUGGING #define PRINT(fmt, ...) fprintf(outf, "[%s]: "##fmt##"\n", __FUNCTION__, __VA_ARGS__); #else #define PRINT(fmt, ...) { CString __s; __s.Format(TEXT("[%s]: ")##TEXT(fmt)##TEXT("\n"), TEXT(__FUNCTION__), __VA_ARGS__); OutputDebugString(__s.GetBuffer()); } #endif CString ErrorToString(HRESULT hr) { CString s; LPTSTR lpMessageBuffer; if (FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, hr, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), //The user default language (LPTSTR) &lpMessageBuffer, 0, NULL )) { s = lpMessageBuffer; LocalFree(lpMessageBuffer); } else { s.Format("[Error %lu]", hr); } return s; } static const LPCSTR OpNames[] = { "PowerOff ", "PowerOn ", "SysPause ", "SysResume ", "InternalSendPause ", "InternalReceivePause ", "InternalSendResume ", "InternalReceiveResume", "SysReset ", "Halt ", "ConnectIndication ", "DPC ", "Send ", "SendNBLRequest ", "SendPacketRequest ", "SendPacketMapped ", "SubmittedPacket ", "BufferSent ", "BufferReceivedStat ", "BufferReturned ", "SendComplete ", "TxProcess ", "PacketReceived ", "OidRequest ", "PnpEvent ", }; static CString HistoryOperationName(ULONG op) { CString s; if (op < sizeof(OpNames)/ sizeof(OpNames[0])) s = OpNames[op]; else s.Format("##%d", op); return s; } typedef struct _tagNamedFlag { ULONG64 flag; LPCSTR name; }tNamedFlag; typedef struct _tagNamedValue { ULONG64 value; LPCSTR name; }tNamedValue; #define STRINGER(x) #x #define VALUE(v) { v, STRINGER(##v) } #define ENDTABLE { 0, NULL } const tNamedValue SessionStatusValues[] = { VALUE(DEBUG_SESSION_ACTIVE), VALUE(DEBUG_SESSION_END_SESSION_ACTIVE_TERMINATE), VALUE(DEBUG_SESSION_END_SESSION_ACTIVE_DETACH), VALUE(DEBUG_SESSION_END_SESSION_PASSIVE), VALUE(DEBUG_SESSION_END), VALUE(DEBUG_SESSION_REBOOT), VALUE(DEBUG_SESSION_HIBERNATE), VALUE(DEBUG_SESSION_FAILURE), ENDTABLE }; const tNamedValue DebuggeeStateValues[] = { VALUE(DEBUG_CDS_ALL), VALUE(DEBUG_CDS_REGISTERS), VALUE(DEBUG_CDS_DATA), ENDTABLE }; const tNamedValue DebuggeeStateArgValues[] = { VALUE(DEBUG_DATA_SPACE_VIRTUAL), VALUE(DEBUG_DATA_SPACE_PHYSICAL), VALUE(DEBUG_DATA_SPACE_CONTROL), VALUE(DEBUG_DATA_SPACE_IO), VALUE(DEBUG_DATA_SPACE_MSR), VALUE(DEBUG_DATA_SPACE_BUS_DATA), VALUE(DEBUG_DATA_SPACE_DEBUGGER_DATA), VALUE(DEBUG_DATA_SPACE_COUNT), ENDTABLE }; const tNamedFlag EngineStateFlags[] = { VALUE(DEBUG_CES_ALL), VALUE(DEBUG_CES_CURRENT_THREAD), VALUE(DEBUG_CES_EFFECTIVE_PROCESSOR), VALUE(DEBUG_CES_BREAKPOINTS), VALUE(DEBUG_CES_CODE_LEVEL), VALUE(DEBUG_CES_EXECUTION_STATUS), VALUE(DEBUG_CES_ENGINE_OPTIONS), VALUE(DEBUG_CES_LOG_FILE), VALUE(DEBUG_CES_RADIX), VALUE(DEBUG_CES_EVENT_FILTERS), VALUE(DEBUG_CES_PROCESS_OPTIONS), VALUE(DEBUG_CES_EXTENSIONS), VALUE(DEBUG_CES_SYSTEMS), VALUE(DEBUG_CES_ASSEMBLY_OPTIONS), VALUE(DEBUG_CES_EXPRESSION_SYNTAX), VALUE(DEBUG_CES_TEXT_REPLACEMENTS), ENDTABLE }; const tNamedFlag SymbolStateFlags[] = { VALUE(DEBUG_CSS_ALL), VALUE(DEBUG_CSS_LOADS), VALUE(DEBUG_CSS_UNLOADS), VALUE(DEBUG_CSS_SCOPE), VALUE(DEBUG_CSS_PATHS), VALUE(DEBUG_CSS_SYMBOL_OPTIONS), VALUE(DEBUG_CSS_TYPE_OPTIONS), ENDTABLE }; #if !defined(DEBUG_STATUS_RESTART_REQUESTED) #error Path to debug SDK is not defined properly in Property Manager. #endif const tNamedValue EngineExecutionStatus[] = { VALUE(DEBUG_STATUS_NO_CHANGE), VALUE(DEBUG_STATUS_GO), VALUE(DEBUG_STATUS_GO_HANDLED), VALUE(DEBUG_STATUS_GO_NOT_HANDLED), VALUE(DEBUG_STATUS_STEP_OVER), VALUE(DEBUG_STATUS_STEP_INTO), VALUE(DEBUG_STATUS_BREAK), VALUE(DEBUG_STATUS_NO_DEBUGGEE), VALUE(DEBUG_STATUS_STEP_BRANCH), VALUE(DEBUG_STATUS_IGNORE_EVENT), VALUE(DEBUG_STATUS_RESTART_REQUESTED), VALUE(DEBUG_STATUS_REVERSE_GO), VALUE(DEBUG_STATUS_REVERSE_STEP_BRANCH), VALUE(DEBUG_STATUS_REVERSE_STEP_OVER), VALUE(DEBUG_STATUS_REVERSE_STEP_INTO), ENDTABLE }; const tNamedFlag EngineExecutionStatusFlags[] = { VALUE(DEBUG_STATUS_INSIDE_WAIT), VALUE(DEBUG_STATUS_WAIT_TIMEOUT), ENDTABLE }; const tNamedFlag ModuleFlags[] = { VALUE(DEBUG_MODULE_LOADED), VALUE(DEBUG_MODULE_UNLOADED), VALUE(DEBUG_MODULE_USER_MODE), VALUE(DEBUG_MODULE_EXPLICIT), VALUE(DEBUG_MODULE_SECONDARY), VALUE(DEBUG_MODULE_SYNTHETIC), VALUE(DEBUG_MODULE_SYM_BAD_CHECKSUM), ENDTABLE }; const tNamedValue SymbolTypeValues[] = { VALUE(DEBUG_SYMTYPE_NONE), VALUE(DEBUG_SYMTYPE_COFF), VALUE(DEBUG_SYMTYPE_CODEVIEW), VALUE(DEBUG_SYMTYPE_PDB), VALUE(DEBUG_SYMTYPE_EXPORT), VALUE(DEBUG_SYMTYPE_DEFERRED), VALUE(DEBUG_SYMTYPE_SYM), VALUE(DEBUG_SYMTYPE_DIA), ENDTABLE }; const tNamedFlag SymbolOptionsFlags[] = { VALUE(SYMOPT_CASE_INSENSITIVE), VALUE(SYMOPT_UNDNAME), VALUE(SYMOPT_DEFERRED_LOADS), VALUE(SYMOPT_NO_CPP), VALUE(SYMOPT_LOAD_LINES), VALUE(SYMOPT_OMAP_FIND_NEAREST), VALUE(SYMOPT_LOAD_ANYTHING), VALUE(SYMOPT_IGNORE_CVREC), VALUE(SYMOPT_NO_UNQUALIFIED_LOADS), VALUE(SYMOPT_FAIL_CRITICAL_ERRORS), VALUE(SYMOPT_EXACT_SYMBOLS), VALUE(SYMOPT_ALLOW_ABSOLUTE_SYMBOLS), VALUE(SYMOPT_IGNORE_NT_SYMPATH), VALUE(SYMOPT_INCLUDE_32BIT_MODULES), VALUE(SYMOPT_PUBLICS_ONLY), VALUE(SYMOPT_NO_PUBLICS), VALUE(SYMOPT_AUTO_PUBLICS), VALUE(SYMOPT_NO_IMAGE_SEARCH), VALUE(SYMOPT_SECURE), VALUE(SYMOPT_NO_PROMPTS), VALUE(SYMOPT_OVERWRITE), VALUE(SYMOPT_IGNORE_IMAGEDIR), VALUE(SYMOPT_FLAT_DIRECTORY), VALUE(SYMOPT_FAVOR_COMPRESSED), VALUE(SYMOPT_ALLOW_ZERO_ADDRESS), VALUE(SYMOPT_DISABLE_SYMSRV_AUTODETECT), VALUE(SYMOPT_DEBUG), ENDTABLE }; typedef struct _tagModule { LPCSTR name; ULONG64 Base; ULONG index; }tModule; class tDumpParser : public DebugBaseEventCallbacks, public IDebugOutputCallbacks { public: tDumpParser() : refCount(0), Client(NULL), Control(NULL), DataSpaces(NULL), DebugSymbols(NULL) { HRESULT hr; bEnableOutput = FALSE; hr = DebugCreate(__uuidof(IDebugClient), (void **)&Client); if (Client) hr = Client->QueryInterface(__uuidof(IDebugControl2), (void **)&Control); if (Client) hr = Client->QueryInterface(__uuidof(IDebugDataSpaces3), (void **)&DataSpaces); if (Client) hr = Client->QueryInterface(__uuidof(DEBUG_SYMBOLS_IF), (void **)&DebugSymbols); } ~tDumpParser() { ULONG ul = 0; if (DebugSymbols) DebugSymbols->Release(); if (Control) Control->Release(); if (DataSpaces) DataSpaces->Release(); if (Client) ul = Client->Release(); //PRINT("finished (%d)", ul); } BOOL LoadFile(TCHAR *filename) { HRESULT hr = S_FALSE; if (Client && Control && DataSpaces) { hr = Client->SetEventCallbacks(this); if (S_OK == hr) hr = Client->SetOutputCallbacks(this); DebugSymbols->AddSymbolOptions(SYMOPT_DEBUG); //DebugSymbols->RemoveSymbolOptions(SYMOPT_DEFERRED_LOADS); DebugSymbols->AppendSymbolPath("."); } else { CString sMessage = TEXT("Error: Not all required interfaces are up\n"); if (!Client) sMessage += TEXT("Client interface is not initialized\n"); if (!Control) sMessage += TEXT("Control interface is not initialized\n"); if (!DataSpaces) sMessage += TEXT("Data interface is not initialized\n"); PRINT("%s", sMessage.GetBuffer()); } if (hr == S_OK) { hr = Client->OpenDumpFile(filename); } if (hr == S_OK) Control->WaitForEvent(0, INFINITE); return hr == S_OK; } void ProcessDumpFile(); void FindOurTaggedCrashData(BOOL bWithSymbols); BOOL CheckLoadedSymbols(tModule *pModule); void ProcessSymbols(tModule *pModule); void ParseCrashData(tBugCheckStaticDataHeader *ph, ULONG64 databuffer, ULONG bytesRead, BOOL bWithSymbols); typedef enum _tageSystemProperty { espSymbolPath, espSystemVersion, espSystemTime, } eSystemProperty; CString GetProperty(eSystemProperty Prop); protected: CString Parse(ULONG64 val, const tNamedValue *pt) { CString s; while (pt->name) { if (pt->value == val) { s = pt->name; break; } pt++; } if (s.IsEmpty()) s.Format(TEXT("Unknown value 0x%I64X"), val); return s; } CString Parse(ULONG64 val, const tNamedFlag *pt) { CString s; while (pt->name && val) { if ((pt->flag & val) == pt->flag) { val &= ~pt->flag; if (!s.IsEmpty()) s += ' '; s += pt->name; } pt++; } if (val) { CString sv; sv.Format(TEXT("0x%X"), val); if (!s.IsEmpty()) s += ' '; s += sv; } return s; } protected: STDMETHOD_(ULONG, AddRef)( THIS ) { return ++refCount; } STDMETHOD_(ULONG, Release)( THIS ) { return --refCount; } STDMETHOD(QueryInterface)( THIS_ __in REFIID InterfaceId, __out PVOID* Interface ) { *Interface = NULL; if (IsEqualIID(InterfaceId, __uuidof(IUnknown)) || IsEqualIID(InterfaceId, __uuidof(IDebugEventCallbacks))) { *Interface = (IDebugEventCallbacks *)this; } else if (IsEqualIID(InterfaceId, __uuidof(IDebugOutputCallbacks))) { *Interface = (IDebugOutputCallbacks *)this; } if (*Interface) AddRef(); return (*Interface) ? S_OK : E_NOINTERFACE; } STDMETHOD(GetInterestMask)( THIS_ __out PULONG Mask ) { *Mask = DEBUG_EVENT_BREAKPOINT | DEBUG_EVENT_EXCEPTION | DEBUG_EVENT_LOAD_MODULE | DEBUG_EVENT_UNLOAD_MODULE | DEBUG_EVENT_SYSTEM_ERROR | DEBUG_EVENT_SESSION_STATUS | DEBUG_EVENT_CHANGE_DEBUGGEE_STATE | DEBUG_EVENT_CHANGE_ENGINE_STATE | DEBUG_EVENT_CHANGE_SYMBOL_STATE ; return S_OK; } STDMETHOD(Breakpoint)( THIS_ __in PDEBUG_BREAKPOINT Bp ) { PRINT(""); return DEBUG_STATUS_BREAK; } STDMETHOD(Exception)( THIS_ __in PEXCEPTION_RECORD64 Exception, __in ULONG FirstChance ) { PRINT(""); return DEBUG_STATUS_NO_CHANGE; } STDMETHOD(LoadModule)( THIS_ __in ULONG64 ImageFileHandle, __in ULONG64 BaseOffset, __in ULONG ModuleSize, __in PCSTR ModuleName, __in PCSTR ImageName, __in ULONG CheckSum, __in ULONG TimeDateStamp ) { PRINT("%s", ImageName); return DEBUG_STATUS_NO_CHANGE; } STDMETHOD(UnloadModule)( THIS_ __in PCSTR ImageBaseName, __in ULONG64 BaseOffset ) { PRINT("%s", ImageBaseName); return DEBUG_STATUS_NO_CHANGE; } STDMETHOD(SystemError)( THIS_ __in ULONG Error, __in ULONG Level ) { PRINT("error 0x%X, level 0x%X", Error, Level); return DEBUG_STATUS_NO_CHANGE; } STDMETHOD(SessionStatus)( THIS_ __in ULONG Status ) { CString s = Parse(Status, SessionStatusValues); PRINT("%s", s.GetBuffer()); return DEBUG_STATUS_NO_CHANGE; } STDMETHOD(ChangeDebuggeeState)( THIS_ __in ULONG Flags, __in ULONG64 Argument ) { CString sf = Parse(Flags, DebuggeeStateValues); CString sarg; if (Flags == DEBUG_CDS_DATA) sarg = Parse(Argument, DebuggeeStateArgValues); else sarg.Format(TEXT("0x%I64X"), Argument); PRINT("%s(%s)", sf.GetBuffer(), sarg.GetBuffer()); return DEBUG_STATUS_NO_CHANGE; return S_OK; } STDMETHOD(ChangeEngineState)( THIS_ __in ULONG Flags, __in ULONG64 Argument ) { CString s = Parse(Flags, EngineStateFlags); CString sArg; if (Flags == DEBUG_CES_EXECUTION_STATUS) { CString sWait = Parse(Argument & ~DEBUG_STATUS_MASK, EngineExecutionStatusFlags); sArg = Parse(Argument & DEBUG_STATUS_MASK, EngineExecutionStatus); sArg += ' '; sArg += sWait; } else sArg.Format(TEXT("arg 0x%I64X"), Argument); PRINT("%s(%s)", s.GetBuffer(), sArg.GetBuffer()); if (Flags == DEBUG_CES_EXECUTION_STATUS && (Argument & DEBUG_STATUS_MASK) == DEBUG_STATUS_BREAK && !(Argument & ~DEBUG_STATUS_MASK)) { ProcessDumpFile(); } return S_OK; } STDMETHOD(ChangeSymbolState)( THIS_ __in ULONG Flags, __in ULONG64 Argument ) { CString s = Parse(Flags, SymbolStateFlags); PRINT("%s(arg 0x%I64X)", s.GetBuffer(), Argument); return S_OK; } // IDebugOutputCallbacks. STDMETHOD(Output)( THIS_ __in ULONG Mask, __in PCSTR Text ) { if (bEnableOutput) { PRINT("%s", Text); } return S_OK; } ULONG refCount; IDebugClient *Client; IDebugControl2 *Control; IDebugDataSpaces3 *DataSpaces; DEBUG_SYMBOLS_IF *DebugSymbols; BOOL bEnableOutput; }; #define CHECK_INTERFACE(xf) { \ xf *p; HRESULT hr = Client->QueryInterface(__uuidof(xf), (void **)&p); \ PRINT("Interface " TEXT(STRINGER(xf)) TEXT(" %spresent"), p ? "" : "NOT "); \ if (p) p->Release(); } static void ParseHistoryEntry(LONGLONG basetime, tBugCheckHistoryDataEntry *phist, LONG Index) { if (!phist) { PRINT("Op Ctx Time Params"); } else if (phist[Index].Context) { LONGLONG diffInt = (basetime - phist[Index].TimeStamp.QuadPart) / 10; CString sOp = HistoryOperationName(phist[Index].operation); #if (PARANDIS_DEBUG_HISTORY_DATA_VERSION == 0) PRINT("%s %I64X [-%09I64d] x%08X x%08X x%08X %I64X", sOp.GetBuffer(), phist[Index].Context, diffInt, phist[Index].lParam2, phist[Index].lParam3, phist[Index].lParam4, phist[Index].pParam1 ); #elif (PARANDIS_DEBUG_HISTORY_DATA_VERSION == 1) PRINT("CPU[%d] IRQL[%d] %s %I64X [-%09I64d] x%08X x%08X x%08X %I64X", phist[Index].uProcessor, phist[Index].uIRQL, sOp.GetBuffer(), phist[Index].Context, diffInt, phist[Index].lParam2, phist[Index].lParam3, phist[Index].lParam4, phist[Index].pParam1 ); #endif } } void tDumpParser::ParseCrashData(tBugCheckStaticDataHeader *ph, ULONG64 databuffer, ULONG bytesRead, BOOL bWithSymbols) { UINT i; for (i = 0; i < ph->ulMaxContexts; ++i) { if (ph->PerNicDataVersion == 0) { tBugCheckPerNicDataContent_V0 *pndc = (tBugCheckPerNicDataContent_V0 *)(ph->PerNicData - databuffer + (PUCHAR)ph); pndc += i; if (pndc->Context) { LONGLONG diffInt = (ph->qCrashTime.QuadPart - pndc->LastInterruptTimeStamp.QuadPart) / 10; LONGLONG diffTx = (ph->qCrashTime.QuadPart - pndc->LastTxCompletionTimeStamp.QuadPart) / 10; PRINT(PRINT_SEPARATOR); PRINT("Context %I64X:", pndc->Context); PRINT("\tLastInterrupt %I64d us before crash", diffInt); PRINT("\tLast Tx complete %I64d us before crash", diffTx); PRINT("\tWaiting <unknown> packets, %d free buffers", pndc->nofReadyTxBuffers); PRINT(PRINT_SEPARATOR); } } else { PRINT("Unsupported per-NIC data version %d", ph->PerNicDataVersion); } } if (ph->StaticDataVersion == 0) { tBugCheckStaticDataContent_V0 *pd = (tBugCheckStaticDataContent_V0 *)(ph->DataArea - databuffer + (PUCHAR)ph); tBugCheckHistoryDataEntry_V1 *phist = (tBugCheckHistoryDataEntry *)(pd->HistoryData - databuffer + (PUCHAR)ph); PRINT(PRINT_SEPARATOR); if (pd->SizeOfHistory > 2) { PRINT("History: version %d, %d entries of %d, current at %d", pd->HistoryDataVersion, pd->SizeOfHistory, pd->SizeOfHistoryEntry, pd->CurrentHistoryIndex); LONG Index = pd->CurrentHistoryIndex % pd->SizeOfHistory; LONG EndIndex = Index; ParseHistoryEntry(NULL, NULL, 0); for (; Index < (LONG)pd->SizeOfHistory; Index++) { ParseHistoryEntry(ph->qCrashTime.QuadPart, phist, Index); } for (Index = 0; Index < EndIndex; Index++) { ParseHistoryEntry(ph->qCrashTime.QuadPart, phist, Index); } } else { PRINT("History records are not available"); } PRINT(PRINT_SEPARATOR); } else if (ph->StaticDataVersion == 1) { tBugCheckStaticDataContent_V1 *pd = (tBugCheckStaticDataContent_V1 *)(ph->DataArea - databuffer + (PUCHAR)ph); if (pd->PendingNblEntryVersion == 0) { tPendingNBlEntry_V0 *pNBL = (tPendingNBlEntry_V0 *)(pd->PendingNblData - databuffer + (PUCHAR)ph); if (pd->MaxPendingNbl > 1) { PRINT(PRINT_SEPARATOR); PRINT("Pending NBL%s, if any (time ago in us):", pd->fNBLOverflow ? "(was logging overflow)" : ""); for (ULONG i = 0; i < pd->MaxPendingNbl; ++i) { ULONGLONG diff = ph->qCrashTime.QuadPart - pNBL[i].TimeStamp.QuadPart; if (pNBL[i].NBL == 0) continue; PRINT("[%05d] NBL %I64x %I64d", i, pNBL[i].NBL, diff); } PRINT(PRINT_SEPARATOR); } } } } void tDumpParser::FindOurTaggedCrashData(BOOL bWithSymbols) { ULONG64 h; if (S_OK == DataSpaces->StartEnumTagged(&h)) { UCHAR ourBuffer[16]; ULONG size; GUID guid; while (S_OK == DataSpaces->GetNextTagged(h, &guid, &size)) { WCHAR string[64]; StringFromGUID2(guid, string, sizeof(string)/sizeof(string[0])); //PRINT("Found %S(size %d)", string, size); if (IsEqualGUID(ParaNdis_CrashGuid, guid)) { PRINT("Found NetKVM GUID"); if (S_OK == DataSpaces->ReadTagged(&guid, 0, ourBuffer, size, &size)) { if (size >= sizeof(tBugCheckDataLocation)) { tBugCheckDataLocation *bcdl = (tBugCheckDataLocation *)ourBuffer; PRINT("Found NetKVM data at %I64X, size %lld", bcdl->Address, bcdl->Size); ULONG bufferSize= (ULONG)bcdl->Size; ULONG bytesRead; PVOID databuffer = malloc(bufferSize); if (databuffer) { if (S_OK == DataSpaces->ReadVirtual(bcdl->Address, databuffer, bufferSize, &bytesRead)) { tBugCheckStaticDataHeader *ph = (tBugCheckStaticDataHeader *)databuffer; PRINT("Retrieved %d bytes of data", bytesRead); if (bytesRead >= sizeof(tBugCheckStaticDataHeader)) { PRINT("Versions: static data %d, per-NIC data %d, ptr size %d, %d contexts, crash time %I64X", ph->StaticDataVersion, ph->PerNicDataVersion, ph->SizeOfPointer, ph->ulMaxContexts, ph->qCrashTime.QuadPart); PRINT("Per-NIC data at %I64X, Static data at %I64X(%lld bytes)", ph->PerNicData, ph->DataArea, ph->DataAreaSize); ParseCrashData(ph, bcdl->Address, bytesRead, bWithSymbols); } } free(databuffer); } } } break; } } DataSpaces->EndEnumTagged(h); } } static BOOL GetModuleName(ULONG Which, ULONG64 Base, DEBUG_SYMBOLS_IF *DebugSymbols, CString& s) { HRESULT hr; ULONG bufsize = 1024; char *buf = (char *)malloc(bufsize); *buf = 0; hr = DebugSymbols->GetModuleNameString( Which, DEBUG_ANY_ID, Base, buf, bufsize, NULL); s = buf; free(buf); return S_OK == hr; } static BOOL TryMatchingSymbols(DEBUG_SYMBOLS_IF *DebugSymbols, PCSTR name, BOOL bPrintAll = FALSE) { UINT n = 0; CString s; s.Format("%s!*", name); ULONG64 matchHandle; if (S_OK == DebugSymbols->StartSymbolMatch(s.GetBuffer(), &matchHandle)) { ULONG size = 1024; char *buf = (char *)malloc(size); *buf = 0; while (S_OK == DebugSymbols->GetNextSymbolMatch( matchHandle, buf, size, NULL, NULL)) { n++; if (!bPrintAll) break; PRINT("%s", buf); } DebugSymbols->EndSymbolMatch(matchHandle); free(buf); } return n != 0; } BOOL tDumpParser::CheckLoadedSymbols(tModule *pModule) { BOOL bLoaded = FALSE; ULONG bufferSize = 2048, bufferUsage; UNREFERENCED_PARAMETER(bufferUsage); char *buffer = (char *)malloc(bufferSize); DEBUG_MODULE_PARAMETERS ModuleParams; HRESULT hr = DebugSymbols->GetModuleByModuleName(pModule->name, 0, &pModule->index, &pModule->Base); if (S_OK == hr) { CString s; PRINT("Found %s at %I64X", pModule->name, pModule->Base); if (GetModuleName(DEBUG_MODNAME_MODULE, pModule->Base, DebugSymbols, s)) PRINT("\tModule Name:%s", s.GetBuffer()); if (GetModuleName(DEBUG_MODNAME_IMAGE, pModule->Base, DebugSymbols, s)) PRINT("\tImage Name:%s", s.GetBuffer()); if (GetModuleName(DEBUG_MODNAME_SYMBOL_FILE, pModule->Base, DebugSymbols, s)) PRINT("\tSymbol file:%s", s.GetBuffer()); bLoaded = 0 != TryMatchingSymbols(DebugSymbols, pModule->name); PRINT("Symbols for %s %sLOADED", pModule->name, bLoaded ? "" : "NOT "); if (S_OK == DebugSymbols->GetModuleParameters(1, &pModule->Base, 0, &ModuleParams)) { CString sSymbolType = Parse(ModuleParams.SymbolType, SymbolTypeValues); CString sFlags = Parse(ModuleParams.Flags, ModuleFlags); PRINT("Symbol Type %s, Flags %s", sSymbolType.GetBuffer(), sFlags.GetBuffer()); // timestamp from 1.1.1970 __time32_t timestamp = ModuleParams.TimeDateStamp; tm *timer = _gmtime32(&timestamp); strftime(buffer, bufferSize, "%d %b %Y %H:%M:%S UTC", timer); //PRINT("Checksum: %X", ModuleParams.Checksum); PRINT("Time Stamp: %s(%X)", buffer, ModuleParams.TimeDateStamp); } } free(buffer); return bLoaded; } void tDumpParser::ProcessDumpFile() { ULONG SymbolOptions; BOOL bSymbols; CString s; tModule module; module.name = "netkvm"; if (S_OK == DebugSymbols->GetSymbolOptions(&SymbolOptions)) { s = Parse(SymbolOptions, SymbolOptionsFlags); PRINT("Symbol options %s", s.GetBuffer()); } s = GetProperty(espSymbolPath); PRINT("Symbol path:%s", s.GetBuffer()); s = GetProperty(espSystemVersion); PRINT("System version:%s", s.GetBuffer()); s = GetProperty(espSystemTime); PRINT("Crash time:%s", s.GetBuffer()); bSymbols = CheckLoadedSymbols(&module); FindOurTaggedCrashData(bSymbols); } CString tDumpParser::GetProperty(eSystemProperty Prop) { CString s; switch (Prop) { case espSymbolPath: if (DebugSymbols) { ULONG maxlen = 1024, len; char *buf = (char *)malloc(maxlen); *buf = 0; DebugSymbols->GetSymbolPath(buf, maxlen, &len); s = buf; free(buf); } break; case espSystemVersion: if (Control) { ULONG platform, major, minor, sp, buildsize = 128, buildused, procs = 0; char *buf = (char *)malloc(buildsize); *buf = 0; BOOL Is64 = Control->IsPointer64Bit() == S_OK; CString sSP; Control->GetNumberProcessors(&procs); Control->GetSystemVersion(&platform, &major, &minor, NULL, 0, NULL, &sp, buf, buildsize, &buildused); if (sp) sSP.Format("(SP%d.%d)", sp >> 8, sp & 0xff); s.Format("(%X)%d%s%s,%s,%d CPU", major, minor, sSP.GetBuffer(), Is64 ? "(64-bit)" : "", buf, procs); free(buf); } break; case espSystemTime: if (Control) { ULONG ulSecondSince1970 = 0, ulUpTime = 0; Control->GetCurrentTimeDate(&ulSecondSince1970); Control->GetCurrentSystemUpTime(&ulUpTime); s = "Unknown"; if (ulSecondSince1970) { char buffer[256] = {0}; ULONG days, hours, min, sec, rem; days = ulUpTime / (60*60*24); rem = ulUpTime - days * 60*60*24; hours = rem / (60*60); rem = rem - hours * 60 * 60; min = rem / 60; rem = rem - min * 60; sec = rem; __time32_t timestamp = ulSecondSince1970; tm *timer = _localtime32(&timestamp); strftime(buffer, sizeof(buffer), "%b %d %H:%M:%S %Y(Local)", timer); s.Format("%s (Up time %d:%d:%d:%d)", buffer, days, hours, min, sec); } } break; default: break; } return s; } #ifdef _DEBUG #define UNDER_DEBUGGING #endif int ParseDumpFile(int argc, TCHAR* argv[]) { if (argc == 2) { CString s = argv[1]; s += ".txt"; FILE *f = fopen(s.GetBuffer(), "w+t"); if (f) outf = f; tDumpParser Parser; #ifdef UNDER_DEBUGGING fputs("UNDER_DEBUGGING, the output is redirected to debugger", f); #endif if (!Parser.LoadFile(argv[1])) PRINT("Failed to load dump file %s", argv[1]); if (f) fclose(f); } else { PRINT("%s", SessionStatusValues[0].name); } return 0; }
14,124
317
<reponame>dinisAbranches/nwchem<filename>src/tce/ccc.py<gh_stars>100-1000 # Ground-state coupled-cluster ansatz generator for OCE # (c) All rights reserved by Battelle & Pacific Northwest Nat'l Lab (2002) from tkinter import * import tkinter.messagebox import tkinter.simpledialog import tkinter.filedialog #import tkMessageBox #import tkSimpleDialog #import tkFileDialog import string import copy import sys import oce import tce class Window: def __init__(self,master): self.frame = Frame(master) self.frame.pack(fill=X) self.progress = 0 Label(self.frame, text = "Tensor Contraction Engine, Version 1.0").grid(row=0,columnspan=6) Label(self.frame, text = "Copyright (c) 2003, Battelle & Pacific Northwest National Laboratory").grid(row=1,columnspan=6) self.l = IntVar() self.cl0 = Radiobutton(self.frame,text = "<0|", variable=self.l,value=0) self.cl0.grid(row=2,column=0,sticky=W) self.cl1 = Radiobutton(self.frame,text = "<S|", variable=self.l,value=1) self.cl1.grid(row=3,column=0,sticky=W) self.cl2 = Radiobutton(self.frame,text = "<D|", variable=self.l,value=2) self.cl2.grid(row=4,column=0,sticky=W) self.cl3 = Radiobutton(self.frame,text = "<T|", variable=self.l,value=3) self.cl3.grid(row=5,column=0,sticky=W) self.cl4 = Radiobutton(self.frame,text = "<Q|", variable=self.l,value=4) self.cl4.grid(row=6,column=0,sticky=W) self.y0 = IntVar() self.cy0 = Checkbutton(self.frame,text = "L0 = 1", variable=self.y0,onvalue=1,offvalue=0) self.cy0.grid(row=2,column=1,sticky=W) self.cy0.select() self.y1 = IntVar() self.cy1 = Checkbutton(self.frame,text = "L1 Operator", variable=self.y1,onvalue=1,offvalue=0) self.cy1.grid(row=3,column=1,sticky=W) self.y2 = IntVar() self.cy2 = Checkbutton(self.frame,text = "L2 Operator", variable=self.y2,onvalue=2,offvalue=0) self.cy2.grid(row=4,column=1,sticky=W) self.y3 = IntVar() self.cy3 = Checkbutton(self.frame,text = "L3 Operator", variable=self.y3,onvalue=3,offvalue=0) self.cy3.grid(row=5,column=1,sticky=W) self.y4 = IntVar() self.cy4 = Checkbutton(self.frame,text = "L4 Operator", variable=self.y4,onvalue=4,offvalue=0) self.cy4.grid(row=6,column=1,sticky=W) self.h1 = IntVar() self.ch1 = Checkbutton(self.frame,text = "<p|f|q>{p+q}", variable=self.h1,onvalue=1,offvalue=0) self.ch1.grid(row=3,column=2,sticky=W) self.ch1.select() self.h2 = IntVar() self.ch2 = Checkbutton(self.frame,text = "1/4<pq||rs>{p+q+sr}", variable=self.h2,onvalue=2,offvalue=0) self.ch2.grid(row=4,column=2,sticky=W) self.ch2.select() self.t1 = IntVar() self.c1 = Checkbutton(self.frame,text = "T1 Operator", variable=self.t1,onvalue=1,offvalue=0) self.c1.grid(row=3,column=3,sticky=W) self.t2 = IntVar() self.c2 = Checkbutton(self.frame,text = "T2 Operator", variable=self.t2,onvalue=2,offvalue=0) self.c2.grid(row=4,column=3,sticky=W) self.t3 = IntVar() self.c3 = Checkbutton(self.frame,text = "T3 Operator", variable=self.t3,onvalue=3,offvalue=0) self.c3.grid(row=5,column=3,sticky=W) self.t4 = IntVar() self.c4 = Checkbutton(self.frame,text = "T4 Operator", variable=self.t4,onvalue=4,offvalue=0) self.c4.grid(row=6,column=3,sticky=W) self.x0 = IntVar() self.cx0 = Checkbutton(self.frame,text = "R0 = 1", variable=self.x0,onvalue=1,offvalue=0) self.cx0.grid(row=2,column=4,sticky=W) self.cx0.select() self.x1 = IntVar() self.cx1 = Checkbutton(self.frame,text = "R1 Operator", variable=self.x1,onvalue=1,offvalue=0) self.cx1.grid(row=3,column=4,sticky=W) self.x2 = IntVar() self.cx2 = Checkbutton(self.frame,text = "R2 Operator", variable=self.x2,onvalue=2,offvalue=0) self.cx2.grid(row=4,column=4,sticky=W) self.x3 = IntVar() self.cx3 = Checkbutton(self.frame,text = "R3 Operator", variable=self.x3,onvalue=3,offvalue=0) self.cx3.grid(row=5,column=4,sticky=W) self.x4 = IntVar() self.cx4 = Checkbutton(self.frame,text = "R4 Operator", variable=self.x4,onvalue=4,offvalue=0) self.cx4.grid(row=6,column=4,sticky=W) self.r = IntVar() self.cr0 = Radiobutton(self.frame,text = "|0>", variable=self.r,value=0) self.cr0.grid(row=2,column=5,sticky=W) self.cr1 = Radiobutton(self.frame,text = "|S>", variable=self.r,value=1) self.cr1.grid(row=3,column=5,sticky=W) self.cr2 = Radiobutton(self.frame,text = "|D>", variable=self.r,value=2) self.cr2.grid(row=4,column=5,sticky=W) self.cr3 = Radiobutton(self.frame,text = "|T>", variable=self.r,value=3) self.cr3.grid(row=5,column=5,sticky=W) self.cr4 = Radiobutton(self.frame,text = "|Q>", variable=self.r,value=4) self.cr4.grid(row=6,column=5,sticky=W) self.ccv1 = IntVar() self.cc1 = Checkbutton(self.frame,text = "L Is Connected", variable=self.ccv1,onvalue=1,offvalue=0) self.cc1.grid(row=7,column=1,sticky=W) self.cc1.select() self.ccv2 = IntVar() self.cc2 = Checkbutton(self.frame,text = "H Is Connected", variable=self.ccv2,onvalue=1,offvalue=0) self.cc2.grid(row=7,column=2,sticky=W) self.cc2.select() self.ccv3 = IntVar() self.cc3 = Checkbutton(self.frame,text = "T Is Connected", variable=self.ccv3,onvalue=1,offvalue=0) self.cc3.grid(row=7,column=3,sticky=W) self.cc3.select() self.ccv4 = IntVar() self.cc4 = Checkbutton(self.frame,text = "R Is Connected", variable=self.ccv4,onvalue=1,offvalue=0) self.cc4.grid(row=7,column=4,sticky=W) self.cc4.select() self.ccv5 = IntVar() self.cc5 = Checkbutton(self.frame,text = "All Are Linked", variable=self.ccv5,onvalue=1,offvalue=0) self.cc5.grid(row=7,column=5,sticky=W) self.cc5.select() self.buttonOK = Button(self.frame, text = "Generate Ansatz", command = self.go, width=100).grid(row=8,columnspan=6) self.buttonSKIP = Button(self.frame, text = "Skip", command = self.skip, width=20).grid(row=9,column=0,columnspan=3) self.buttonCA = Button(self.frame, text = "Clear All", command = self.clearall, width=20).grid(row=9,column=3,columnspan=3) self.frame2 = Frame(master) self.frame2.pack(fill=X) self.scrollbar = Scrollbar(self.frame2) self.scrollbar.pack(side=RIGHT, fill=Y) self.listbox = Listbox(self.frame2, yscrollcommand=self.scrollbar.set) self.scrollbar.config(command=self.listbox.yview) self.oce_result = "" self.tce_result = "" self.frame3 = Frame(master) self.frame3.pack(fill=X) self.status = Label(self.frame3, text = "", bd=1, relief=SUNKEN, anchor=W) self.status.pack(side=BOTTOM, fill=X) menu = Menu(master) master.config(menu=menu) filemenu = Menu(master) menu.add_cascade(label="File",menu=filemenu) filemenu.add_command(label="Import second quantized expressions",command=self.read_oceinput) filemenu.add_command(label="Import tensor contraction expressions",command=self.read_tceinput) filemenu.add_command(label="Exit",command=self.exit) helpmenu = Menu(menu) menu.add_cascade(label="Help",menu=helpmenu) helpmenu.add_command(label="About",command=self.about) helpmenu.add_command(label="References",command=self.references) def read_oceinput(self): filename = tkinter.filedialog.askopenfilename() if (filename != ""): self.oce_result = oce.readfromfile(filename) self.listbox.delete(0,END) for line in self.oce_result.show(): self.listbox.insert(END, line) self.listbox.pack(fill=X) self.status.config(text = repr(len(self.oce_result.show()))+" second quantized expressions imported") self.status.update_idletasks() self.progress = 1 self.buttonOK = Button(self.frame, text = "Perform Operator Contractions", command = self.go, width = 100).grid(row=8,columnspan=6) return def read_tceinput(self): filename = tkinter.filedialog.askopenfilename() if (filename != ""): self.tce_result = tce.readfromfile(filename) self.listbox.delete(0,END) for line in self.tce_result.show(): self.listbox.insert(END, line) self.listbox.pack(fill=X) self.status.config(text = repr(len(self.tce_result.show()))+" multiple tensor contraction expressions imported") self.status.update_idletasks() self.progress = 61 self.buttonOK = Button(self.frame, text = "Perform Strength Reduction", command = self.go, width = 100).grid(row=8,columnspan=6) return def exit(self): sys.exit() def about(self): tkinter.messagebox.showinfo("About", "Tensor Contraction Engine, Version 1.0\nCopyright (c) 2003, Battelle & Pacific Northwest National Laboratory\n") def references(self): tkinter.messagebox.showinfo("References", "<NAME>, J. Phys. Chem. A 107, 9887-9897 (2003).\n") def go(self): if (self.progress == 0): horders = [] if (self.h1.get() != 0): horders.append(self.h1.get()) if (self.h2.get() != 0): horders.append(self.h2.get()) if (not horders): horders.append(0) torders = [0] if (self.t1.get() != 0): torders.append(self.t1.get()) if (self.t2.get() != 0): torders.append(self.t2.get()) if (self.t3.get() != 0): torders.append(self.t3.get()) if (self.t4.get() != 0): torders.append(self.t4.get()) xorders = [0] if (self.x1.get() != 0): xorders.append(self.x1.get()) if (self.x2.get() != 0): xorders.append(self.x2.get()) if (self.x3.get() != 0): xorders.append(self.x3.get()) if (self.x4.get() != 0): xorders.append(self.x4.get()) yorders = [0] if (self.y1.get() != 0): yorders.append(self.y1.get()) if (self.y2.get() != 0): yorders.append(self.y2.get()) if (self.y3.get() != 0): yorders.append(self.y3.get()) if (self.y4.get() != 0): yorders.append(self.y4.get()) r0is1 = self.x0.get() l0is1 = self.y0.get() leftprojection = self.l.get() rightprojection = self.r.get() def factorial(n): if (n == 0): return 1 else: return n*factorial(n-1) def newindex(type,number): index = string.join([type,repr(number)],"") return index def newtensor(type,indexes): tensor = string.join([type,"("],"") for index in indexes: tensor = string.join([tensor,index]) tensor = string.join([tensor,")"]) return tensor ansatz = "<"+repr(leftprojection)+"|" yans = "" for order in yorders: if ((order == 0) and l0is1): if (yans): yans = yans + "+1" else: yans = yans + " (1" else: if (yans): yans = yans + "+L"+repr(order) else: yans = yans + " (L"+repr(order) if (yans): ansatz = ansatz + yans + ")" if (horders == [1,2]): ansatz = ansatz + " H" elif (horders == [1]): ansatz = ansatz + " F" elif (horders == [2]): ansatz = ansatz + " V" tans = "" for order in torders: if (order > 0): if (tans): tans = tans + "+T"+repr(order) else: tans = tans + "(T"+repr(order) if (tans): ansatz = ansatz + " exp"+tans+")" xans = "" for order in xorders: if ((order == 0) and r0is1): if (xans): xans = xans + "+1" else: xans = xans + " (1" else: if (xans): xans = xans + "+R"+repr(order) else: xans = xans + " (R"+repr(order) if (xans): ansatz = ansatz + xans + ")" ansatz = ansatz + " |"+repr(rightprojection)+">" self.status.config(text = ansatz) self.status.update_idletasks() listofansatz = [] for t1 in torders: for t2 in torders: if (t2 < t1): continue for t3 in torders: if (t3 < t2): continue for t4 in torders: if (t4 < t3): continue for x in xorders: for y in yorders: if ((t1+t2+t3+t4+x+y == 0) and (leftprojection == 0) and (rightprojection == 0)): continue if ((rightprojection+t1+t2+t3+t4+x > leftprojection+y+2) or (rightprojection+t1+t2+t3+t4+x < leftprojection+y-2)): continue for hamiltonian in horders: counter = 0 summation = [] tensors = [] operator = [] # left projection if (leftprojection > 0): curly = [] for i in range(leftprojection): counter = counter + 1 j = newindex('h',counter) curly.append(j+"+") pointer = len(curly) for i in range(leftprojection): counter = counter + 1 a = newindex('p',counter) curly.insert(pointer,a) operator.append(curly) # right projection # # 6/18/03 we promoted right projection logic here, just to reserve # the same consecutive sets of indexes for the externals. # If externals have different indexes, the factorization will # break. The actual insertion of right projection occurs later. # if (rightprojection > 0): rightcurly = [] for i in range(rightprojection): counter = counter + 1 j = newindex('p',counter) rightcurly.append(j+"+") pointer = len(rightcurly) for i in range(rightprojection): counter = counter + 1 a = newindex('h',counter) rightcurly.insert(pointer,a) # tlinesused = 0 # tlinesleft = 0 # if (rightprojection > 0): # tlinesused = tlinesused + 1 # tlinesleft = tlinesleft + rightprojection*2 - 1 # if (t1 > 0): # tlinesused = tlinesused + 1 # tlinesleft = tlinesleft + t1*2 - 1 # if (t2 > 0): # tlinesused = tlinesused + 1 # tlinesleft = tlinesleft + t2*2 - 1 # if (t3 > 0): # tlinesused = tlinesused + 1 # tlinesleft = tlinesleft + t3*2 - 1 # if (t4 > 0): # tlinesused = tlinesused + 1 # tlinesleft = tlinesleft + t4*2 - 1 # if (x > 0): # tlinesused = tlinesused + 1 # tlinesleft = tlinesleft + x*2 - 1 factor = 1 if ((not l0is1) or (y > 0)): factor = factor * factorial(y) * factorial(y) curly = [] indexes = [] for i in range(y): counter = counter + 1 a = newindex('h',counter) curly.append(a+"+") summation.append(a) indexes.append(a) pointer = len(curly) for i in range(y): counter = counter + 1 j = newindex('p',counter) curly.insert(pointer,j) summation.append(j) indexes.append(j) operator.append(curly) tensors.append(newtensor('y',indexes)) if (hamiltonian == 1): # f operator # if (tlinesused > 2): # continue # if ((tlinesleft + (2 - tlinesused) < 2*(leftprojection+y)) or \ # (tlinesleft - (2 - tlinesused) > 2*(leftprojection+y))): # continue factor = factor * 1 counter = counter + 1 g1 = newindex('g',counter) counter = counter + 1 g2 = newindex('g',counter) summation.append(g1) summation.append(g2) tensors.append(newtensor('f',[g1,g2])) curly = [g1+"+",g2] operator.append(curly) elif (hamiltonian == 2): # v operator # if (tlinesused > 4): # continue # if ((tlinesleft + (4 - tlinesused) < 2*(leftprojection+y)) or \ # (tlinesleft - (4 - tlinesused) > 2*(leftprojection+y))): # continue factor = factor * 4 counter = counter + 1 g1 = newindex('g',counter) counter = counter + 1 g2 = newindex('g',counter) counter = counter + 1 g3 = newindex('g',counter) counter = counter + 1 g4 = newindex('g',counter) summation.append(g1) summation.append(g2) summation.append(g3) summation.append(g4) tensors.append(newtensor('v',[g1,g2,g3,g4])) curly = [g1+"+",g2+"+",g4,g3] operator.append(curly) elif (hamiltonian != 0): raise RuntimeError("unsupported operator rank") list = [] if (t1 > 0): list.append(t1) factor = factor * factorial(t1) * factorial(t1) curly = [] indexes = [] for i in range(t1): counter = counter + 1 a = newindex('p',counter) curly.append(a+"+") summation.append(a) indexes.append(a) pointer = len(curly) for i in range(t1): counter = counter + 1 j = newindex('h',counter) curly.insert(pointer,j) summation.append(j) indexes.append(j) operator.append(curly) tensors.append(newtensor('t',indexes)) if (t2 > 0): list.append(t2) factor = factor * factorial(t2) * factorial(t2) curly = [] indexes = [] for i in range(t2): counter = counter + 1 a = newindex('p',counter) curly.append(a+"+") summation.append(a) indexes.append(a) pointer = len(curly) for i in range(t2): counter = counter + 1 j = newindex('h',counter) curly.insert(pointer,j) summation.append(j) indexes.append(j) operator.append(curly) tensors.append(newtensor('t',indexes)) if (t3 > 0): list.append(t3) factor = factor * factorial(t3) * factorial(t3) curly = [] indexes = [] for i in range(t3): counter = counter + 1 a = newindex('p',counter) curly.append(a+"+") summation.append(a) indexes.append(a) pointer = len(curly) for i in range(t3): counter = counter + 1 j = newindex('h',counter) curly.insert(pointer,j) summation.append(j) indexes.append(j) operator.append(curly) tensors.append(newtensor('t',indexes)) if (t4 > 0): list.append(t4) factor = factor * factorial(t4) * factorial(t4) curly = [] indexes = [] for i in range(t4): counter = counter + 1 a = newindex('p',counter) curly.append(a+"+") summation.append(a) indexes.append(a) pointer = len(curly) for i in range(t4): counter = counter + 1 j = newindex('h',counter) curly.insert(pointer,j) summation.append(j) indexes.append(j) operator.append(curly) tensors.append(newtensor('t',indexes)) if ((not r0is1) or (x > 0)): factor = factor * factorial(x) * factorial(x) curly = [] indexes = [] for i in range(x): counter = counter + 1 a = newindex('p',counter) curly.append(a+"+") summation.append(a) indexes.append(a) pointer = len(curly) for i in range(x): counter = counter + 1 j = newindex('h',counter) curly.insert(pointer,j) summation.append(j) indexes.append(j) operator.append(curly) tensors.append(newtensor('x',indexes)) # right projection if (rightprojection > 0): operator.append(rightcurly) while (list): i = list[0] n = list.count(i) factor = factor * factorial(n) numberofi = list.count(i) for dummy in range(numberofi): list.remove(i) ansatz = "1.0/"+repr(factor)+".0" ansatz = string.join([ansatz,"Sum("]) for index in summation: ansatz = string.join([ansatz,index]) ansatz = string.join([ansatz,")"]) for tensor in tensors: ansatz = string.join([ansatz,tensor]) for curly in operator: ansatz = string.join([ansatz,"{"]) for index in curly: ansatz = string.join([ansatz,index]) ansatz = string.join([ansatz,"}"]) print (ansatz) listofansatz.append(ansatz) self.oce_result = oce.ListOperatorSequences() for line in listofansatz: self.oce_result.add(oce.stringtooperatorsequence(line)) for line in self.oce_result.show(): self.listbox.insert(END,line) self.listbox.pack(fill=X) self.progress = 1 self.buttonOK = Button(self.frame, text = "Perform Operator Contractions", command = self.go, width = 100).grid(row=8,columnspan=6) return if (self.progress == 1): self.oce_result = self.oce_result.performfullcontraction() self.listbox.delete(0,END) for line in self.oce_result.show(): self.listbox.insert(END, line) self.listbox.pack(fill=X) self.status.config(text = repr(len(self.oce_result.show()))+" multiple tensor contractions") self.status.update_idletasks() self.progress = 2 self.buttonOK = Button(self.frame, text = "Delete Disconnected Diagrams", command = self.go, width = 100).grid(row=8,columnspan=6) return if (self.progress == 2): originallen = len(self.oce_result.show()) connectedtensors = [] if (self.ccv1.get() == 1): connectedtensors.append('y') if (self.ccv2.get() == 1): connectedtensors.append('f') connectedtensors.append('v') if (self.ccv3.get() == 1): connectedtensors.append('t') if (self.ccv4.get() == 1): connectedtensors.append('x') if (connectedtensors): self.oce_result = self.oce_result.deletedisconnected(connectedtensors) self.listbox.delete(0,END) for line in self.oce_result.show(): self.listbox.insert(END, line) self.listbox.pack(fill=X) newlen = len(self.oce_result.show()) self.status.config(text = repr(newlen)+" multiple tensor contractions ("+repr(originallen-newlen)+" disconnected diagrams deleted)") self.status.update_idletasks() self.progress = 3 self.buttonOK = Button(self.frame, text = "Delete Unlinked Diagrams", command = self.go, width = 100).grid(row=8,columnspan=6) return if (self.progress == 3): originallen = len(self.oce_result.show()) if (self.ccv5.get() == 1): linked = 1 else: linked = 0 if (linked): originallen = len(self.oce_result.show()) self.oce_result = self.oce_result.deleteunlinked() self.listbox.delete(0,END) for line in self.oce_result.show(): self.listbox.insert(END, line) self.listbox.pack(fill=X) newlen = len(self.oce_result.show()) self.status.config(text = repr(newlen)+" multiple tensor contractions ("+repr(originallen-newlen)+" unlinked diagrams deleted)") self.status.update_idletasks() self.progress = 4 self.buttonOK = Button(self.frame, text = "Extract Permutation Symmetry", command = self.go, width = 100).grid(row=8,columnspan=6) return if (self.progress == 4): originallen = len(self.oce_result.show()) self.oce_result = self.oce_result.simplify() self.listbox.delete(0,END) for line in self.oce_result.show(): self.listbox.insert(END, line) self.listbox.pack(fill=X) newlen = len(self.oce_result.show()) self.status.config(text = repr(newlen)+" multiple tensor contractions ("+repr(originallen-newlen)+" diagrams merged)") if tkinter.messagebox.askyesno("TCE", "Relabel operators?\n"): oldname = tkinter.simpledialog.askstring("TCE", "Old label for operator?\n") newname = tkinter.simpledialog.askstring("TCE", "New label for operator?\n") while (oldname and newname): self.oce_result.relabelamplitudes(oldname,newname) self.listbox.delete(0,END) for line in self.oce_result.show(): self.listbox.insert(END,line) self.listbox.pack(fill=X) oldname = tkinter.simpledialog.askstring("TCE", "Old label for operator?\n") newname = tkinter.simpledialog.askstring("TCE", "New label for operator?\n") self.status.update_idletasks() self.progress = 5 self.buttonOK = Button(self.frame, text = "Save Working Equations...", command = self.go, width = 100).grid(row=8,columnspan=6) return if (self.progress == 5): if tkinter.messagebox.askyesno("TCE", "Save working equations?\n"): filename = tkinter.filedialog.asksaveasfilename() if (filename != ""): self.oce_result.writetofile(filename) self.status.config(text = "Working equation saved") self.status.update_idletasks() self.progress = 6 self.buttonOK = Button(self.frame, text = "Perform Strength Reduction", command = self.go, width = 100).grid(row=8,columnspan=6) return if (self.progress == 6): self.tce_result = tce.ListTensorContractions() for selfexpr in self.oce_result.list: selfexpr = string.split(selfexpr.show()) donewithfactors = 0 pointer = 1 coefficients = [] permutations = [] while (not donewithfactors): if (selfexpr[pointer] == "+"): parity = 1 pointer = pointer + 1 elif (selfexpr[pointer] == "-"): parity = -1 pointer = pointer + 1 else: # neither "+" or "-"; assume "+" and do not increment pointer parity = 1 coefficients.append(string.atof(selfexpr[pointer]) * parity) pointer = pointer + 1 if (selfexpr[pointer] == "]"): permutations.append([]) donewithfactors = 1 elif ((selfexpr[pointer] == "*") or (selfexpr[pointer] == "P") or (selfexpr[pointer] == "p")): if (selfexpr[pointer] == "*"): pointer = pointer + 1 indexes = [] while (selfexpr[pointer + 1] != ")"): pointer = pointer + 1 if (selfexpr[pointer] != "=>"): if (selfexpr[pointer][0] == "h"): type = "hole" elif (selfexpr[pointer][0] == "p"): type = "particle" else: type = "general" label = string.atoi(selfexpr[pointer][1:]) newindex = tce.Index(type,label) indexes.append(newindex) permutations.append(indexes) pointer = pointer + 2 if (selfexpr[pointer] == "]"): donewithfactors = 1 else: permutations.append([]) factor = tce.Factor(coefficients,permutations) summation = [] if ("Sum" in selfexpr): indexes = [] pointer = selfexpr.index("Sum") while (selfexpr[pointer + 1] != ")"): pointer = pointer + 1 if (selfexpr[pointer] != "("): if (selfexpr[pointer][0] == "h"): type = "hole" elif (selfexpr[pointer][0] == "p"): type = "particle" else: type = "general" label = string.atoi(selfexpr[pointer][1:]) newindex = tce.Index(type,label) indexes.append(newindex) summation = tce.Summation(indexes) tensors=[] ntensors = selfexpr[selfexpr.index("]"):].count("*") if (ntensors != selfexpr[selfexpr.index("]"):].count("(")): return "Wrong input format" if ("Sum" in selfexpr): ntensors = ntensors - 1 offset = 2 else: offset = 1 if (ntensors > 0): for itensor in range(0,ntensors): counter = 0 for pointer in range(selfexpr.index("]"),len(selfexpr)): if (selfexpr[pointer] == "*"): counter = counter + 1 if (counter == itensor + offset): if (selfexpr[pointer+1][len(selfexpr[pointer+1])-1] == "+"): tensortype = selfexpr[pointer + 1][0:len(selfexpr[pointer+1])-1] tensorconj = 1 else: tensortype = selfexpr[pointer + 1] tensorconj = 0 tensorlabel = itensor + 1 anotherpointer = pointer + 2 indexes = [] while (selfexpr[anotherpointer + 1] != ")"): anotherpointer = anotherpointer + 1 if (selfexpr[anotherpointer] != "("): if (selfexpr[anotherpointer][0] == "h"): type = "hole" elif (selfexpr[anotherpointer][0] == "p"): type = "particle" else: type = "general" label = string.atoi(selfexpr[anotherpointer][1:]) indexes.append(tce.Index(type,label)) tensors.append(tce.Tensor(tensortype,indexes,tensorlabel,tensorconj)) self.tce_result.list.append(tce.TensorContraction(factor,summation,tensors)) self.tce_result = self.tce_result.breakdown() self.listbox.delete(0,END) for line in self.tce_result.show(): self.listbox.insert(END, line) self.listbox.pack(fill=X) self.status.config(text = repr(len(self.tce_result.children))+" first order binary contractions") self.status.update_idletasks() self.progress = 7 self.buttonOK = Button(self.frame, text = "Perform Factorization", command = self.go, width = 100).grid(row=8,columnspan=6) return if (self.progress == 61): self.tce_result = self.tce_result.breakdown() self.listbox.delete(0,END) for line in self.tce_result.show(): self.listbox.insert(END, line) self.listbox.pack(fill=X) self.status.config(text = repr(len(self.tce_result.children))+" first order binary contractions") self.status.update_idletasks() self.progress = 7 self.buttonOK = Button(self.frame, text = "Perform Factorization", command = self.go, width = 100).grid(row=8,columnspan=6) return if (self.progress == 7): originallen = len(self.tce_result.children) self.tce_result = self.tce_result.fullyfactorize() self.listbox.delete(0,END) for line in self.tce_result.show(): self.listbox.insert(END, line) self.listbox.pack(fill=X) newlen = len(self.tce_result.children) self.status.config(text = repr(newlen)+" first order binary contractions ("+repr(originallen-newlen)+" first order contractions merged)") self.status.update_idletasks() self.progress = 8 self.buttonOK = Button(self.frame, text = "Generate Fortran77 Code", command = self.go, width = 100).grid(row=8,columnspan=6) return if (self.progress == 8): types = self.tce_result.tensortypes() message = "" excitation = "" excitationold = "" for type in types[1]: excitationold = excitationold + type + " " if (excitation): excitation = excitation + "and '" + type + "' " else: excitation = "'" + type + "' " if (excitation): message = message + excitation + "are excitation tensors\n" deexcitation = "" deexcitationold = "" for type in types[2]: deexcitationold = deexcitationold + type + " " if (deexcitation): deexcitation = deexcitation + "and '" + type + "' " else: deexcitation = "'" + type + "' " if (deexcitation): message = message + deexcitation + "are deexcitation tensors\n" intermediate = "" intermediateold = "" for type in types[3]: intermediateold = intermediateold + type + " " if (intermediate): intermediate = intermediate + "and '" + type + "' " else: intermediate = "'" + type + "' " if (intermediate): message = message + intermediate + "are intermediate tensors\n" general = "" generalold = "" for type in types[4]: generalold = generalold + type + " " if (general): general = general + "and '" + type + "' " else: general = "'" + type + "' " if (general): message = message + general + "are general tensors\n" if tkinter.messagebox.askyesno("TCE", message): subroutinename = tkinter.simpledialog.askstring("TCE", "Stub Name of Fortran77 code?\n") if (subroutinename): self.tce_result = self.tce_result.fortran77(subroutinename) self.listbox.delete(0,END) for line in self.tce_result.show(): self.listbox.insert(END, line) self.listbox.pack(fill=X) self.status.config(text = repr(len(self.tce_result.show()))+" lines of Fortran code generated") self.status.update_idletasks() self.progress = 9 self.buttonOK = Button(self.frame, text = "Save Fortran77 Code...", command = self.go, width = 100).grid(row=8,columnspan=6) else: excitationlist = [] deexcitationlist = [] intermediatelist = [] generallist = [] dialogresult = tkinter.simpledialog.askstring("TCE","Excitation Tensors",initialvalue=excitationold) if (dialogresult): excitationlist = string.split(dialogresult) dialogresult = tkinter.simpledialog.askstring("TCE","Deexcitation Tensors",initialvalue=deexcitationold) if (dialogresult): deexcitationlist = string.split(dialogresult) dialogresult = tkinter.simpledialog.askstring("TCE","Intermediate Tensors",initialvalue=intermediateold) if (dialogresult): intermediatelist = string.split(dialogresult) dialogresult = tkinter.simpledialog.askstring("TCE","General Tensors",initialvalue=generalold) if (dialogresult): generallist = string.split(dialogresult) subroutinename = tkinter.simpledialog.askstring("TCE", "Stub Name of Fortran77 code?\n") if (subroutinename): self.tce_result = self.tce_result.fortran77(subroutinename,excitationlist,deexcitationlist,intermediatelist,generallist) self.listbox.delete(0,END) for line in self.tce_result.show(): self.listbox.insert(END, line) self.listbox.pack(fill=X) self.status.config(text = repr(len(self.tce_result.show()))+" lines of Fortran code generated") self.status.update_idletasks() self.progress = 9 self.buttonOK = Button(self.frame, text = "Save Fortran77 Code...", command = self.go, width = 100).grid(row=8,columnspan=6) return if (self.progress == 9): if tkinter.messagebox.askyesno("TCE", "Save Fortran77 code?\n"): filename = tkinter.filedialog.asksaveasfilename() if (filename != ""): self.tce_result.writetofile(filename) self.status.config(text = "") self.status.update_idletasks() self.progress = 0 self.buttonOK = Button(self.frame, text = "Generate Ansatz", command = self.go, width = 100).grid(row=8,columnspan=6) self.listbox.delete(0,END) return def skip(self): if (self.progress == 0): tkinter.messagebox.showwarning("TCE", "Unable to skip") return if (self.progress == 1): tkinter.messagebox.showwarning("TCE", "Unable to skip") return if (self.progress == 2): self.progress = 3 self.buttonOK = Button(self.frame, text = "Delete Unlinked Diagrams", command = self.go, width = 100).grid(row=8,columnspan=6) return if (self.progress == 3): self.progress = 4 self.buttonOK = Button(self.frame, text = "Extract Permutation Symmetry", command = self.go, width = 100).grid(row=8,columnspan=6) return if (self.progress == 4): tkinter.messagebox.showwarning("TCE", "Unable to skip") return if (self.progress == 5): self.progress = 6 self.buttonOK = Button(self.frame, text = "Perform Strength Reduction", command = self.go, width = 100).grid(row=8,columnspan=6) return if (self.progress == 6): tkinter.messagebox.showwarning("TCE", "Unable to skip") return if (self.progress == 7): self.progress = 8 self.buttonOK = Button(self.frame, text = "Generate Fortran77 Code", command = self.go, width = 100).grid(row=8,columnspan=6) return if (self.progress == 8): tkinter.messagebox.showwarning("TCE", "Unable to skip") return if (self.progress == 9): self.progress = 0 self.buttonOK = Button(self.frame, text = "Generate Ansatz", command = self.go, width = 100).grid(row=8,columnspan=6) self.listbox.delete(0,END) return def clearall(self): self.cl0.select() self.cr0.select() self.cy0.select() self.cy1.deselect() self.cy2.deselect() self.cy3.deselect() self.cy4.deselect() self.c1.deselect() self.c2.deselect() self.c3.deselect() self.c4.deselect() self.ch1.select() self.ch2.select() self.cx0.select() self.cx1.deselect() self.cx2.deselect() self.cx3.deselect() self.cx4.deselect() self.cc1.select() self.cc2.select() self.cc3.select() self.cc4.select() self.cc5.select() self.listbox.delete(0,END) self.progress = 0 self.buttonOK = Button(self.frame, text = "Generate Ansatz", command = self.go, width = 100).grid(row=8,columnspan=6) self.status.config(text = "") self.status.update_idletasks() root = Tk() window = Window(root) root.mainloop()
26,500
997
<gh_stars>100-1000 #include "inner.h" /* * Encoding/decoding of keys and signatures. * * ==========================(LICENSE BEGIN)============================ * * Copyright (c) 2017-2019 Falcon Project * * 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. * * ===========================(LICENSE END)============================= * * @author <NAME> <<EMAIL>> */ /* see inner.h */ size_t PQCLEAN_FALCON1024_CLEAN_modq_encode( void *out, size_t max_out_len, const uint16_t *x, unsigned logn) { size_t n, out_len, u; uint8_t *buf; uint32_t acc; int acc_len; n = (size_t)1 << logn; for (u = 0; u < n; u ++) { if (x[u] >= 12289) { return 0; } } out_len = ((n * 14) + 7) >> 3; if (out == NULL) { return out_len; } if (out_len > max_out_len) { return 0; } buf = out; acc = 0; acc_len = 0; for (u = 0; u < n; u ++) { acc = (acc << 14) | x[u]; acc_len += 14; while (acc_len >= 8) { acc_len -= 8; *buf ++ = (uint8_t)(acc >> acc_len); } } if (acc_len > 0) { *buf = (uint8_t)(acc << (8 - acc_len)); } return out_len; } /* see inner.h */ size_t PQCLEAN_FALCON1024_CLEAN_modq_decode( uint16_t *x, unsigned logn, const void *in, size_t max_in_len) { size_t n, in_len, u; const uint8_t *buf; uint32_t acc; int acc_len; n = (size_t)1 << logn; in_len = ((n * 14) + 7) >> 3; if (in_len > max_in_len) { return 0; } buf = in; acc = 0; acc_len = 0; u = 0; while (u < n) { acc = (acc << 8) | (*buf ++); acc_len += 8; if (acc_len >= 14) { unsigned w; acc_len -= 14; w = (acc >> acc_len) & 0x3FFF; if (w >= 12289) { return 0; } x[u ++] = (uint16_t)w; } } if ((acc & (((uint32_t)1 << acc_len) - 1)) != 0) { return 0; } return in_len; } /* see inner.h */ size_t PQCLEAN_FALCON1024_CLEAN_trim_i16_encode( void *out, size_t max_out_len, const int16_t *x, unsigned logn, unsigned bits) { size_t n, u, out_len; int minv, maxv; uint8_t *buf; uint32_t acc, mask; unsigned acc_len; n = (size_t)1 << logn; maxv = (1 << (bits - 1)) - 1; minv = -maxv; for (u = 0; u < n; u ++) { if (x[u] < minv || x[u] > maxv) { return 0; } } out_len = ((n * bits) + 7) >> 3; if (out == NULL) { return out_len; } if (out_len > max_out_len) { return 0; } buf = out; acc = 0; acc_len = 0; mask = ((uint32_t)1 << bits) - 1; for (u = 0; u < n; u ++) { acc = (acc << bits) | ((uint16_t)x[u] & mask); acc_len += bits; while (acc_len >= 8) { acc_len -= 8; *buf ++ = (uint8_t)(acc >> acc_len); } } if (acc_len > 0) { *buf ++ = (uint8_t)(acc << (8 - acc_len)); } return out_len; } /* see inner.h */ size_t PQCLEAN_FALCON1024_CLEAN_trim_i16_decode( int16_t *x, unsigned logn, unsigned bits, const void *in, size_t max_in_len) { size_t n, in_len; const uint8_t *buf; size_t u; uint32_t acc, mask1, mask2; unsigned acc_len; n = (size_t)1 << logn; in_len = ((n * bits) + 7) >> 3; if (in_len > max_in_len) { return 0; } buf = in; u = 0; acc = 0; acc_len = 0; mask1 = ((uint32_t)1 << bits) - 1; mask2 = (uint32_t)1 << (bits - 1); while (u < n) { acc = (acc << 8) | *buf ++; acc_len += 8; while (acc_len >= bits && u < n) { uint32_t w; acc_len -= bits; w = (acc >> acc_len) & mask1; w |= -(w & mask2); if (w == -mask2) { /* * The -2^(bits-1) value is forbidden. */ return 0; } w |= -(w & mask2); x[u ++] = (int16_t) * (int32_t *)&w; } } if ((acc & (((uint32_t)1 << acc_len) - 1)) != 0) { /* * Extra bits in the last byte must be zero. */ return 0; } return in_len; } /* see inner.h */ size_t PQCLEAN_FALCON1024_CLEAN_trim_i8_encode( void *out, size_t max_out_len, const int8_t *x, unsigned logn, unsigned bits) { size_t n, u, out_len; int minv, maxv; uint8_t *buf; uint32_t acc, mask; unsigned acc_len; n = (size_t)1 << logn; maxv = (1 << (bits - 1)) - 1; minv = -maxv; for (u = 0; u < n; u ++) { if (x[u] < minv || x[u] > maxv) { return 0; } } out_len = ((n * bits) + 7) >> 3; if (out == NULL) { return out_len; } if (out_len > max_out_len) { return 0; } buf = out; acc = 0; acc_len = 0; mask = ((uint32_t)1 << bits) - 1; for (u = 0; u < n; u ++) { acc = (acc << bits) | ((uint8_t)x[u] & mask); acc_len += bits; while (acc_len >= 8) { acc_len -= 8; *buf ++ = (uint8_t)(acc >> acc_len); } } if (acc_len > 0) { *buf ++ = (uint8_t)(acc << (8 - acc_len)); } return out_len; } /* see inner.h */ size_t PQCLEAN_FALCON1024_CLEAN_trim_i8_decode( int8_t *x, unsigned logn, unsigned bits, const void *in, size_t max_in_len) { size_t n, in_len; const uint8_t *buf; size_t u; uint32_t acc, mask1, mask2; unsigned acc_len; n = (size_t)1 << logn; in_len = ((n * bits) + 7) >> 3; if (in_len > max_in_len) { return 0; } buf = in; u = 0; acc = 0; acc_len = 0; mask1 = ((uint32_t)1 << bits) - 1; mask2 = (uint32_t)1 << (bits - 1); while (u < n) { acc = (acc << 8) | *buf ++; acc_len += 8; while (acc_len >= bits && u < n) { uint32_t w; acc_len -= bits; w = (acc >> acc_len) & mask1; w |= -(w & mask2); if (w == -mask2) { /* * The -2^(bits-1) value is forbidden. */ return 0; } x[u ++] = (int8_t) * (int32_t *)&w; } } if ((acc & (((uint32_t)1 << acc_len) - 1)) != 0) { /* * Extra bits in the last byte must be zero. */ return 0; } return in_len; } /* see inner.h */ size_t PQCLEAN_FALCON1024_CLEAN_comp_encode( void *out, size_t max_out_len, const int16_t *x, unsigned logn) { uint8_t *buf; size_t n, u, v; uint32_t acc; unsigned acc_len; n = (size_t)1 << logn; buf = out; /* * Make sure that all values are within the -2047..+2047 range. */ for (u = 0; u < n; u ++) { if (x[u] < -2047 || x[u] > +2047) { return 0; } } acc = 0; acc_len = 0; v = 0; for (u = 0; u < n; u ++) { int t; unsigned w; /* * Get sign and absolute value of next integer; push the * sign bit. */ acc <<= 1; t = x[u]; if (t < 0) { t = -t; acc |= 1; } w = (unsigned)t; /* * Push the low 7 bits of the absolute value. */ acc <<= 7; acc |= w & 127u; w >>= 7; /* * We pushed exactly 8 bits. */ acc_len += 8; /* * Push as many zeros as necessary, then a one. Since the * absolute value is at most 2047, w can only range up to * 15 at this point, thus we will add at most 16 bits * here. With the 8 bits above and possibly up to 7 bits * from previous iterations, we may go up to 31 bits, which * will fit in the accumulator, which is an uint32_t. */ acc <<= (w + 1); acc |= 1; acc_len += w + 1; /* * Produce all full bytes. */ while (acc_len >= 8) { acc_len -= 8; if (buf != NULL) { if (v >= max_out_len) { return 0; } buf[v] = (uint8_t)(acc >> acc_len); } v ++; } } /* * Flush remaining bits (if any). */ if (acc_len > 0) { if (buf != NULL) { if (v >= max_out_len) { return 0; } buf[v] = (uint8_t)(acc << (8 - acc_len)); } v ++; } return v; } /* see inner.h */ size_t PQCLEAN_FALCON1024_CLEAN_comp_decode( int16_t *x, unsigned logn, const void *in, size_t max_in_len) { const uint8_t *buf; size_t n, u, v; uint32_t acc; unsigned acc_len; n = (size_t)1 << logn; buf = in; acc = 0; acc_len = 0; v = 0; for (u = 0; u < n; u ++) { unsigned b, s, m; /* * Get next eight bits: sign and low seven bits of the * absolute value. */ if (v >= max_in_len) { return 0; } acc = (acc << 8) | (uint32_t)buf[v ++]; b = acc >> acc_len; s = b & 128; m = b & 127; /* * Get next bits until a 1 is reached. */ for (;;) { if (acc_len == 0) { if (v >= max_in_len) { return 0; } acc = (acc << 8) | (uint32_t)buf[v ++]; acc_len = 8; } acc_len --; if (((acc >> acc_len) & 1) != 0) { break; } m += 128; if (m > 2047) { return 0; } } x[u] = (int16_t) m; if (s) { x[u] = (int16_t) - x[u]; } } return v; } /* * Key elements and signatures are polynomials with small integer * coefficients. Here are some statistics gathered over many * generated key pairs (10000 or more for each degree): * * log(n) n max(f,g) std(f,g) max(F,G) std(F,G) * 1 2 129 56.31 143 60.02 * 2 4 123 40.93 160 46.52 * 3 8 97 28.97 159 38.01 * 4 16 100 21.48 154 32.50 * 5 32 71 15.41 151 29.36 * 6 64 59 11.07 138 27.77 * 7 128 39 7.91 144 27.00 * 8 256 32 5.63 148 26.61 * 9 512 22 4.00 137 26.46 * 10 1024 15 2.84 146 26.41 * * We want a compact storage format for private key, and, as part of * key generation, we are allowed to reject some keys which would * otherwise be fine (this does not induce any noticeable vulnerability * as long as we reject only a small proportion of possible keys). * Hence, we enforce at key generation time maximum values for the * elements of f, g, F and G, so that their encoding can be expressed * in fixed-width values. Limits have been chosen so that generated * keys are almost always within bounds, thus not impacting neither * security or performance. * * IMPORTANT: the code assumes that all coefficients of f, g, F and G * ultimately fit in the -127..+127 range. Thus, none of the elements * of max_fg_bits[] and max_FG_bits[] shall be greater than 8. */ const uint8_t PQCLEAN_FALCON1024_CLEAN_max_fg_bits[] = { 0, /* unused */ 8, 8, 8, 8, 8, 7, 7, 6, 6, 5 }; const uint8_t PQCLEAN_FALCON1024_CLEAN_max_FG_bits[] = { 0, /* unused */ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }; /* * When generating a new key pair, we can always reject keys which * feature an abnormally large coefficient. This can also be done for * signatures, albeit with some care: in case the signature process is * used in a derandomized setup (explicitly seeded with the message and * private key), we have to follow the specification faithfully, and the * specification only enforces a limit on the L2 norm of the signature * vector. The limit on the L2 norm implies that the absolute value of * a coefficient of the signature cannot be more than the following: * * log(n) n max sig coeff (theoretical) * 1 2 412 * 2 4 583 * 3 8 824 * 4 16 1166 * 5 32 1649 * 6 64 2332 * 7 128 3299 * 8 256 4665 * 9 512 6598 * 10 1024 9331 * * However, the largest observed signature coefficients during our * experiments was 1077 (in absolute value), hence we can assume that, * with overwhelming probability, signature coefficients will fit * in -2047..2047, i.e. 12 bits. */ const uint8_t PQCLEAN_FALCON1024_CLEAN_max_sig_bits[] = { 0, /* unused */ 10, 11, 11, 12, 12, 12, 12, 12, 12, 12 };
7,317
416
<reponame>Zi0P4tch0/sdks // // VNGeometryUtils.h // Vision // // Copyright © 2020 Apple Inc. All rights reserved. // #import <Foundation/Foundation.h> #import <CoreGraphics/CoreGraphics.h> #import <simd/simd.h> #import <Vision/VNDefines.h> #import <Vision/VNTypes.h> #import <Vision/VNGeometry.h> NS_ASSUME_NONNULL_BEGIN @class VNContour; API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) @interface VNGeometryUtils : NSObject /*! @discussion Calculates a bounding circle that includes a collection of points or a VNContour object. Note that because this is based on a geometric shape the aspect ratio is important when using normalized points. This takes the aspect ratio of the contour into account when using a VNContour as an input. boundingCircleForPoints and boundingCircleForSIMDPoints assume that the aspect ratio is correctly applied to the points. @param contour A contour around which to find the bounding circle. @param points A collection of points around which to find the bounding circle. @param pointCount Number of points in points @param contour VNContour object whose bounding circle needs to be calculated @param error An output parameter, populated only in case of algorithmic failure @return the VNCircle object describing the bounding circle or nil, if the algorithm failed. The latter case is accompanied by populating an 'error' output parameter */ + (nullable VNCircle*)boundingCircleForContour:(VNContour*)contour error:(NSError**)error; + (nullable VNCircle*)boundingCircleForPoints:(NSArray<VNPoint*>*)points error:(NSError**)error; + (nullable VNCircle*)boundingCircleForSIMDPoints:(simd_float2 const *)points pointCount:(NSInteger)pointCount error:(NSError**)error; /*! @discussion Calculates a closed contour area using Green's theorem. The contour is represented by a set of points in VNContour object, It's important to note that a random set of points, or a contour with self-crossing edges will likely produce undefined results Note that because this is based on a geometric shape the aspect ratio is important when using normalized points. This takes the aspect ratio of the contour into account when using a VNContour as an input. @param area Output parameter to be populated with calculated contour area @param contour A VNContour object whose area is being calculated @param orientedArea If true, returns signed area - positive for CCW oriented contours and negative for CW oriented contours. If false, returned area is always positive. @param error An output parameter, populated only in case of algorithmic failure @return Area calculation status, YES indicates success, NO - failure. The failure case is accompanied by populating an 'error' output parameter */ + (BOOL)calculateArea:(double*)area forContour:(VNContour*)contour orientedArea:(BOOL)orientedArea error:(NSError**)error; /*! @discussion Calculates perimeter, or a sum of all arc-lengths (edges), of a closed contour. The contour is represented by a set of points in VNContour object. Note that because this is based on a geometric shape the aspect ratio is important when using normalized points. This takes the aspect ratio of the contour into account when using a VNContour as an input. @param perimeter Output parameter to be populated with calculated contour perimeter @param contour A VNContour object whose perimeter is being calculated @param error An output parameter, populated only in case of algorithmic failure @return Perimeter calculation status, YES indicates success, NO - failure. The failure case is accompanied by populating an 'error' output parameter */ + (BOOL)calculatePerimeter:(double*)perimeter forContour:(VNContour*)contour error:(NSError**)error; @end NS_ASSUME_NONNULL_END
1,560
4,606
<filename>examples/docs_snippets_crag/docs_snippets_crag/guides/dagster/graph_job_op/op_multi_out.py from typing import Tuple from dagster import In, Out, op @op( ins={"arg1": In(metadata={"a": "b"})}, out={"out1": Out(metadata={"c": "d"}), "out2": Out(metadata={"e": "f"})}, ) def do_something(arg1: str) -> Tuple[int, int]: return int(arg1), int(arg1) + 1
164
357
from cifar_configs import * from imagenet_configs import * from config_factory import get_config, get_config_from_json
37
2,587
package cn.hikyson.godeye.core.internal.modules.crash; import androidx.annotation.Keep; import java.io.Serializable; @Keep public class CrashConfig implements Serializable { public boolean immediate = false; public CrashConfig() { } public CrashConfig(boolean immediate) { this.immediate = immediate; } public boolean immediate() { return immediate; } @Override public String toString() { return "CrashConfig{" + "immediate=" + immediate + '}'; } }
217
412
{ "json-ui": true, "trace": true, "classpath": ".", "java-max-vla-length": 192, "java-unwind-enum-static": true, "max-nondet-string-length": 100, "depth": false, "java-assume-inputs-non-null": true, "max-nondet-array-length": 10, "max-nondet-string-length": 10, "java-max-vla-length": 4097, "string-printable": true, "unwind": 1, "timeout" : 60 }
195
5,168
<reponame>Olalaye/MegEngine<filename>src/core/impl/comp_node/cambricon/comp_node.cpp /** * \file src/core/impl/comp_node/cambricon/comp_node.cpp * MegEngine is Licensed under the Apache License, Version 2.0 (the "License") * * Copyright (c) 2014-2021 Megvii Inc. All rights reserved. * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ #include "./comp_node.h" #include "megbrain/comp_node_env.h" #include "megbrain/utils/thread.h" #include <string> using namespace mgb; #if MGB_CAMBRICON #include "megbrain/comp_node/alloc.h" #include <cctype> #include <cstdio> #include <thread> #include <cndev.h> #include <cnrt.h> using CambriconCompNodeImpl = CambriconCompNode::CompNodeImpl; namespace { size_t get_min_system_memory(size_t available) { // taken from src/core/impl/cuda/comp_node.cpp if (available < (1u << 31)) { // 225MiB return 225 * 1024 * 1024; } else { // max(300 MiB, 0.05 * available) return std::max<size_t>(300 * 1024 * 1024, available / 20); } } } // anonymous namespace /* ======================= CambriconRawAlloctor ======================*/ namespace mgb { namespace mem_alloc { class CambriconRawAlloctor final : public RawAllocator { public: void* alloc(size_t size) override { void* addr; cnrtRet_t ret = cnrtMalloc(&addr, size); if (ret == CNRT_RET_SUCCESS) { mgb_assert(addr); return addr; } auto msg = mgb_ssprintf_log( "cnrtMalloc failed while requesting %zd bytes (%.3fMiB) of " "memory; error: %s", size, size / (1024.0 * 1024), cnrtGetErrorStr(ret)); msg.append(CnrtError::get_cnrt_extra_info()); mgb_throw_raw(MemAllocError{msg}); } void free(void* ptr) override { cnrtRet_t ret = cnrtFree(ptr); if (ret == CNRT_RET_SUCCESS) return; auto msg = ssprintf("cnrtFree failed for %p: %s", ptr, cnrtGetErrorStr(ret)); msg.append(CnrtError::get_cnrt_extra_info()); mgb_throw_raw(MemAllocError{msg}); } void get_mem_info(size_t& free, size_t& tot) override; }; class CambriconDeviceRuntimePolicy : public DeviceRuntimePolicy { public: CompNode::DeviceType device_type() override { return CompNode::DeviceType::CAMBRICON; } void set_device(int device) override { cnrtDev_t dev; MGB_CNRT_CHECK(cnrtGetDeviceHandle(&dev, device)); MGB_CNRT_CHECK(cnrtSetCurrentDevice(dev)); } void device_synchronize(int device) override { cnrtDev_t dev; MGB_CNRT_CHECK(cnrtGetDeviceHandle(&dev, device)); MGB_CNRT_CHECK(cnrtSetCurrentDevice(dev)); MGB_CNRT_CHECK(cnrtSyncDevice()); } }; /* ====================== DevMemAlloc ================================*/ std::unique_ptr<DevMemAlloc> DevMemAlloc::make_cambricon_alloc() { return std::make_unique<FwdDevMemAlloc>(std::make_shared<CambriconRawAlloctor>()); } } // namespace mem_alloc } // namespace mgb /* ====================== CambriconCompNodeImpl ======================*/ class CambriconCompNode::CompNodeImpl final : public CompNode::Impl { MGB_DYN_TYPE_OBJ_FINAL_DECL; friend class EventImpl; friend class CambriconCompNode; friend class mgb::mem_alloc::CambriconRawAlloctor; struct DeviceInfo; struct StaticData; static StaticData* sd; static Spinlock sd_mtx; //! set to true when m_locator is assigned; set to false if init //! failed bool m_initialized = false; Locator m_locator, m_locator_logical; mem_alloc::StreamMemAlloc* m_mem_alloc; DeviceInfo* m_device_info; cnrtDev_t m_dev; void activate() { m_env.cnrt_env().activate(); } void init(const Locator& locator, const Locator& locator_logical); void fini(); static inline bool check_global_finalized(); //! enable peer copy from dev0 to dev1 static bool enable_peer_access(int dev0, int dev1); static void static_free_device(ImplBase* self, void* ptr) { static_cast<CompNodeImpl*>(self)->free_device(ptr); } static void static_free_host(ImplBase* self, void* ptr) { static_cast<CompNodeImpl*>(self)->free_host(ptr); } public: CompNodeImpl() : Impl(static_free_device, static_free_host) {} void* alloc_device(size_t size) override { activate(); return m_mem_alloc->alloc(size); } void free_device(void* ptr); void* alloc_host(size_t size) override { activate(); void* ptr; MGB_CNRT_CHECK(cnrtMallocHost(&ptr, size, CNRT_MEMTYPE_DEFAULT)); return ptr; } void free_host(void* ptr) { if (!check_global_finalized()) { activate(); } MGB_CNRT_CHECK(cnrtSetCurrentDevice(m_dev)); MGB_CNRT_CHECK(cnrtFreeHost(ptr)); } void copy_to_host(void* host_ptr, const void* device_ptr, size_t size) override { activate(); MGB_CNRT_CHECK(cnrtMemcpyAsync( host_ptr, const_cast<void*>(device_ptr), size, m_env.cnrt_env().queue, CNRT_MEM_TRANS_DIR_DEV2HOST)); } void copy_to_device(void* device_ptr, const void* host_ptr, size_t size) override { activate(); MGB_CNRT_CHECK(cnrtMemcpyAsync( device_ptr, const_cast<void*>(host_ptr), size, m_env.cnrt_env().queue, CNRT_MEM_TRANS_DIR_HOST2DEV)); } void peer_copy_to( Impl* dest_impl, void* dest, const void* src, size_t size) override; size_t get_mem_addr_alignment() override { return m_env.property().mem_alignment; } std::unique_ptr<Event> create_event(size_t flags) override; void sync() override; MemNode mem_node() override; std::pair<size_t, size_t> get_mem_status_bytes() override { m_env.cnrt_env().activate(); cndevMemoryInfo_t mem_info; MGB_CNDEV_CHECK(cndevGetMemoryUsage(&mem_info, m_env.cnrt_env().device)); size_t tot, used, free; constexpr size_t mb2size = 1024 * 1024; tot = static_cast<size_t>(mem_info.PhysicalMemoryTotal) * mb2size; used = static_cast<size_t>(mem_info.PhysicalMemoryUsed) * mb2size; free = tot - used + m_mem_alloc->get_free_memory_dev().tot; return {tot, free}; } Locator locator() override { return m_locator; } Locator locator_logical() override { return m_locator_logical; } }; MGB_DYN_TYPE_OBJ_FINAL_IMPL(CambriconCompNode::CompNodeImpl); struct CambriconCompNodeImpl::DeviceInfo { int dev_num = -1; cnrtDev_t dev; std::unique_ptr<mem_alloc::DevMemAlloc> mem_alloc; bool init_done() const { return mem_alloc.get(); } void init(const CompNodeEnv& env); // unlike cuda, we have to set device first, then release device memory void fini() { cnrtSetCurrentDevice(dev); return mem_alloc.reset(); } size_t get_mem_reserve_size(); }; struct CambriconCompNodeImpl::StaticData { static constexpr int MAX_NR_COMP_NODE = 4096, MAX_NR_DEVICE = 64; std::recursive_mutex mtx; mem_alloc::DevMemAlloc::PreAllocConfig prealloc_config; CambriconCompNode::CompNodeImpl node[MAX_NR_COMP_NODE]; DeviceInfo dev_info[MAX_NR_DEVICE]; int nr_node = 0, nr_dev_used = 0; StaticData() { prealloc_config.max_overhead = 0; prealloc_config.alignment = 1; } ~StaticData() { for (int i = 0; i < nr_node; ++i) node[i].fini(); for (int i = 0; i < nr_dev_used; ++i) dev_info[i].fini(); } }; CambriconCompNodeImpl::StaticData* CambriconCompNodeImpl::sd = nullptr; Spinlock CambriconCompNodeImpl::sd_mtx; void CambriconCompNodeImpl::init( const Locator& locator, const Locator& locator_logical) { m_locator = locator; m_locator_logical = locator_logical; m_initialized = true; auto on_succ = [this](cnrtQueue_t queue) { auto locator = m_locator; log_comp_node_created(locator, m_locator_logical); MGB_LOCK_GUARD(sd->mtx); DeviceInfo* dev_info = nullptr; for (int i = 0; i < sd->nr_dev_used; ++i) { if (sd->dev_info[i].dev_num == locator.device) { dev_info = &sd->dev_info[i]; break; } } if (!dev_info) { dev_info = &sd->dev_info[sd->nr_dev_used]; dev_info->init(m_env); ++sd->nr_dev_used; } m_device_info = dev_info; m_mem_alloc = dev_info->mem_alloc->add_stream(static_cast<void*>(queue)); m_dev = m_device_info->dev; }; auto on_error = [this](std::exception&) { MGB_LOCK_GUARD(sd->mtx); m_initialized = false; }; m_env.init_cnrt( locator.device, make_comp_node_from_impl(this), {on_succ, on_error}); } void CambriconCompNodeImpl::fini() { if (!m_initialized) return; m_env.fini(); m_mem_alloc = nullptr; m_device_info = nullptr; m_initialized = false; } void CambriconCompNodeImpl::free_device(void* ptr) { if (check_global_finalized()) return; activate(); m_mem_alloc->free(ptr); } void CambriconCompNodeImpl::peer_copy_to( Impl* dest_impl, void* dest, const void* src, size_t size) { if (dest_impl->same_type<CambriconCompNodeImpl>()) { auto&& dst_env = static_cast<CambriconCompNodeImpl*>(dest_impl)->m_env.cnrt_env(); auto&& src_env = m_env.cnrt_env(); activate(); if (dst_env.device == src_env.device) { // remark: transfering data from device to device does not // support async sync(); dest_impl->sync(); MGB_CNRT_CHECK(cnrtMemcpy( dest, const_cast<void*>(src), size, CNRT_MEM_TRANS_DIR_DEV2DEV)); } else { mgb_throw_if( !enable_peer_access(src_env.device, dst_env.device) || !enable_peer_access(dst_env.device, src_env.device), CnrtError, "directly memory access is not available for " "src=%d,dst=%d", src_env.device, dst_env.device); sync(); dest_impl->sync(); MGB_CNRT_CHECK(cnrtMemcpyPeer( dest, dst_env.device, const_cast<void*>(src), src_env.device, size)); } return; } mgb_assert( dest_impl->env().property().type == DeviceType::CPU, "cnrt peer_copy_to only implemented for CPU"); auto copy = [this, dest, src, size]() { m_env.cnrt_env().activate(); auto queue = m_env.cnrt_env().queue; MGB_CNRT_CHECK(cnrtMemcpyAsync( dest, const_cast<void*>(src), size, queue, CNRT_MEM_TRANS_DIR_DEV2HOST)); MGB_CNRT_CHECK(cnrtSyncQueue(queue)); }; dest_impl->env().cpu_env().dispatch(copy); } MemNode CambriconCompNodeImpl::mem_node() { return MemNode{sd->dev_info + m_locator.device}; } void CambriconCompNodeImpl::sync() { activate(); // remark: CNRT does not provide interface like cudaEventQuery to test // whether an event is finished. so we just call the cnrtSyncQueue MGB_CNRT_CHECK(cnrtSyncQueue(m_env.cnrt_env().queue)); } bool CambriconCompNodeImpl::enable_peer_access(int dev0, int dev1) { static bool queried_enabled[StaticData::MAX_NR_DEVICE][StaticData::MAX_NR_DEVICE]; if (queried_enabled[dev0][dev1]) return queried_enabled[dev0][dev1]; static std::mutex global_lock; MGB_LOCK_GUARD(global_lock); unsigned int can = 0; MGB_CNRT_CHECK(cnrtGetPeerAccessibility(&can, dev0, dev1)); if (can) mgb_log("device(%d) can directly access memories on device(%d)", dev0, dev1); queried_enabled[dev0][dev1] = can; return can; } /* ================== CambriconCompNodeImpl::DeviceInfo ===============*/ void CambriconCompNodeImpl::DeviceInfo::init(const CompNodeEnv& env) { mgb_assert(!mem_alloc); auto&& cnenv = env.cnrt_env(); cnenv.activate(); dev_num = cnenv.device; MGB_CNRT_CHECK(cnrtGetDeviceHandle(&dev, dev_num)); // remark: Because free_device will be called after global finalize, so the // implementation of mem_alloc should handle the deallocation of memories // allocated by the mem_alloc. As a result, we should use the DevMemAlloc // instead of FwdDevMemAlloc. #if 0 // forward cnrtMalloc mem_alloc = mem_alloc::DevMemAlloc::make_cambricon_alloc(); #else auto reserve_size = get_mem_reserve_size(); mem_alloc = mem_alloc::DevMemAlloc::make( dev_num, reserve_size, std::make_shared<mem_alloc::CambriconRawAlloctor>(), std::make_shared<mem_alloc::CambriconDeviceRuntimePolicy>()); mem_alloc->prealloc_config(sd->prealloc_config); auto align = env.property().mem_alignment; mem_alloc->alignment(align); cnrtDeviceInfo_t device_info; MGB_CNRT_CHECK(cnrtGetDeviceInfo(&device_info, dev_num)); mgb_log("cambricon: card%d: name=`%s' dyn_mem_reserve=%.2fMiB " "alignment=0x%zx", dev_num, device_info.device_name, reserve_size / 1024.0 / 1024, align); #endif } size_t CambriconCompNodeImpl::DeviceInfo::get_mem_reserve_size() { if (auto setting = MGB_GETENV("MGB_CAMBRICON_RESERVE_MEMORY")) { if (!strncmp(setting, "b:", 2)) { return std::stoull(setting + 2); } size_t tot, free; cndevMemoryInfo_t mem_info; MGB_CNDEV_CHECK(cndevGetMemoryUsage(&mem_info, dev_num)); constexpr size_t mb2size = 1024 * 1024; tot = static_cast<size_t>(mem_info.PhysicalMemoryTotal) * mb2size; size_t used = static_cast<size_t>(mem_info.PhysicalMemoryUsed) * mb2size; free = tot - used; return free - get_min_system_memory(free); } else { return 0; } } bool CambriconCompNodeImpl::check_global_finalized() { if (!sd) { static std::atomic_flag warn_printed = ATOMIC_FLAG_INIT; if (!warn_printed.test_and_set()) { mgb_log_warn("cambricon comp node method called after global finalize"); } return true; } return false; } /* ================== CambriconCompNodeImpl::EventImpl ================*/ class CambriconCompNode::EventImpl final : public EventImplHelper { bool m_placed_notifier = false; bool m_sync_queue_called = false; bool m_init_finished = false; cnrtNotifier_t m_cnrt_notifier; CambriconCompNodeImpl* cambricon_comp_node_impl() const { return static_cast<CambriconCompNodeImpl*>(m_comp_node_impl); } void do_record() override { m_sync_queue_called = false; cambricon_comp_node_impl()->activate(); auto&& env = cambricon_comp_node_impl()->m_env.cnrt_env(); if (!m_placed_notifier) { MGB_CNRT_CHECK(cnrtPlaceNotifier(m_cnrt_notifier, env.queue)); m_placed_notifier = true; } } void call_sync_queue() { mgb_assert(m_placed_notifier); if (!m_sync_queue_called) { cambricon_comp_node_impl()->activate(); auto&& env = cambricon_comp_node_impl()->m_env.cnrt_env(); MGB_CNRT_CHECK(cnrtSyncQueue(env.queue)); m_sync_queue_called = true; } } bool do_finished() override { call_sync_queue(); return true; } void host_wait_cv() override { mgb_assert(m_placed_notifier); cambricon_comp_node_impl()->activate(); auto&& env = cambricon_comp_node_impl()->m_env.cnrt_env(); MGB_CNRT_CHECK(cnrtSyncQueue(env.queue)); } double do_elapsed_time_until(EventImplHelper& end) override { cambricon_comp_node_impl()->activate(); auto&& env = cambricon_comp_node_impl()->m_env.cnrt_env(); MGB_CNRT_CHECK(cnrtSyncQueue(env.queue)); float ret = 0.f; MGB_CNRT_CHECK(cnrtNotifierDuration( m_cnrt_notifier, static_cast<EventImpl&>(end).m_cnrt_notifier, &ret)); return static_cast<double>(ret) * 1e-3; } void do_device_wait_by(Impl* cn_impl) override; public: EventImpl(CambriconCompNodeImpl* comp_node_impl, size_t create_flags) : EventImplHelper(comp_node_impl, create_flags) { cambricon_comp_node_impl()->activate(); MGB_CNRT_CHECK(cnrtCreateNotifier(&m_cnrt_notifier)); m_init_finished = true; } ~EventImpl() { if (m_init_finished) { MGB_TRY { MGB_CNRT_CHECK(cnrtDestroyNotifier(&m_cnrt_notifier)); } MGB_CATCH(MegBrainError & exc, { mgb_log_error("failed to destroy cnrt notifier: %s", exc.what()); }) } } }; std::unique_ptr<CompNode::Event> CambriconCompNodeImpl::create_event(size_t flags) { return std::make_unique<EventImpl>(this, flags); } void CambriconCompNode::EventImpl::do_device_wait_by(Impl* cn_impl) { if (cn_impl->env().property().type == DeviceType::CAMBRICON) { auto imp = static_cast<CambriconCompNodeImpl*>(cn_impl); auto queue = imp->m_env.cnrt_env().queue; imp->activate(); MGB_CNRT_CHECK(cnrtSyncQueue(queue)); return; } if (cn_impl->env().property().type == DeviceType::CPU) { auto waiter = [this]() { cambricon_comp_node_impl()->activate(); auto queue = cambricon_comp_node_impl()->m_env.cnrt_env().queue; MGB_CNRT_CHECK(cnrtSyncQueue(queue)); }; cn_impl->add_callback(std::move(waiter)); return; } mgb_throw(MegBrainError, "unimplemented event device_wait_by config"); } /* ================== CambriconCompNode static methods ================*/ bool CambriconCompNode::available() { CompNodeEnv::CnrtEnv::init(); static int result = -1; static Spinlock mtx; MGB_LOCK_GUARD(mtx); if (result == -1) { unsigned int dev_num = 0; auto err = cnrtGetDeviceCount(&dev_num); result = err == CNRT_RET_SUCCESS && dev_num >= 1; if (!result) { mgb_log_warn( "cambricon unavailable: %d(%s) dev_num=%u", static_cast<int>(err), cnrtGetErrorStr(err), dev_num); } } return result; } void CambriconCompNode::finalize() { if (CambriconCompNodeImpl::sd) { sync_all(); auto ptr = CambriconCompNodeImpl::sd; CambriconCompNodeImpl::sd = nullptr; ptr->~StaticData(); } } CompNode::Impl* CambriconCompNode::load_cambricon( const Locator& locator, const Locator& locator_logical) { int nr_devs = get_device_count(); mgb_assert( locator.device >= 0 && locator.device < nr_devs, "request device%d out of range [0, %d)", locator.device, nr_devs); auto&& sdptr = CambriconCompNodeImpl::sd; { MGB_LOCK_GUARD(CambriconCompNodeImpl::sd_mtx); if (!sdptr) { using T = CambriconCompNodeImpl::StaticData; static std::aligned_storage_t<sizeof(T), alignof(T)> storage; sdptr = new (&storage) T; } } auto&& sd = *sdptr; MGB_LOCK_GUARD(sd.mtx); CompNodeImpl* available_node = nullptr; for (int i = 0; i < sd.nr_node; ++i) { auto&& cur = sd.node[i]; if (cur.m_initialized) { if (cur.m_locator == locator && cur.m_locator_logical == locator_logical) { return &cur; } } else { available_node = &cur; } } if (!available_node) { mgb_assert(sd.nr_node < sd.MAX_NR_COMP_NODE, "too many CompNode allocated"); mgb_assert(locator.device < sd.MAX_NR_COMP_NODE, "device number too large"); available_node = &sd.node[sd.nr_node++]; } mgb_assert(!available_node->m_initialized); available_node->init(locator, locator_logical); return available_node; } void CambriconCompNode::try_coalesce_all_free_memory() { auto sd = CambriconCompNodeImpl::sd; if (!sd) return; size_t size = 0; for (int i = 0; i < sd->nr_dev_used; ++i) { size += sd->dev_info[i].mem_alloc->gather_stream_free_blk_and_release_full(); } if (size) { mgb_log_debug("%zu bytes freed by try_coalesce_all_free_memory()", size); } } void CambriconCompNode::sync_all() { auto sd = CambriconCompNodeImpl::sd; if (!sd) return; for (int i = 0;; ++i) { CompNodeEnv* env; { MGB_LOCK_GUARD(sd->mtx); if (i >= sd->nr_node) { break; } env = &sd->node[i].env(); } env->cnrt_env(); } MGB_LOCK_GUARD(sd->mtx); for (int i = 0; i < sd->nr_dev_used; ++i) { cnrtDev_t dev; MGB_CNRT_CHECK(cnrtGetDeviceHandle(&dev, sd->dev_info[i].dev_num)); MGB_CNRT_CHECK(cnrtSetCurrentDevice(dev)); MGB_CNRT_CHECK(cnrtSyncDevice()); } } void CambriconCompNode::foreach (thin_function<void(CompNode)> callback) { auto sd = CambriconCompNodeImpl::sd; if (!sd) return; for (int i = 0;; ++i) { CompNode cur; { MGB_LOCK_GUARD(sd->mtx); if (i >= sd->nr_node) return; cur = make_comp_node_from_impl(&sd->node[i]); } callback(cur); } } size_t CambriconCompNode::get_device_count() { CompNodeEnv::CnrtEnv::init(); static int cnt = -1; static Spinlock mtx; MGB_LOCK_GUARD(mtx); if (cnt == -1) { unsigned int dev_cnt = 0; auto ret = cnrtGetDeviceCount(&dev_cnt); if (ret != CNRT_RET_SUCCESS) { mgb_log_error( "cnrtGetDeviceCount faild: %s (err %d)", cnrtGetErrorStr(ret), int(ret)); cnt = 0; } cnt = dev_cnt; mgb_assert(cnt >= 0); } return cnt; } void mgb::mem_alloc::CambriconRawAlloctor::get_mem_info(size_t& free, size_t& tot) { auto sd = CambriconCompNodeImpl::sd; int device = -1; { cnrtDev_t dev; MGB_CNRT_CHECK(cnrtGetCurrentDevice(&dev)); for (int i = 0; i < sd->nr_dev_used; ++i) { if (sd->dev_info[i].dev == dev) { device = sd->dev_info[i].dev_num; break; } } } mgb_assert(device >= 0, "current device has not been initialized in static data"); cndevMemoryInfo_t mem_info; auto ret = cndevGetMemoryUsage(&mem_info, device); if (ret == CNDEV_SUCCESS) { constexpr size_t mb2size = 1024 * 1024; tot = static_cast<size_t>(mem_info.PhysicalMemoryTotal) * mb2size; size_t used = static_cast<size_t>(mem_info.PhysicalMemoryUsed) * mb2size; free = tot - used; return; } auto msg = ssprintf("cndevGetMemoryUsage faild %s", cndevGetErrorString(ret)); mgb_throw_raw(MemAllocError{msg}); } #else bool CambriconCompNode::available() { return false; } void CambriconCompNode::try_coalesce_all_free_memory() {} void CambriconCompNode::foreach (thin_function<void(CompNode)>) {} void CambriconCompNode::finalize() {} size_t CambriconCompNode::get_device_count() { return 0; } CambriconCompNode::Impl* CambriconCompNode::load_cambricon( const Locator&, const Locator&) { mgb_throw(MegBrainError, "cambricon disabled at compile time"); } void CambriconCompNode::sync_all() {} #undef err #endif // MGB_CAMBRICON // vim: syntax=cpp.doxygen foldmethod=marker foldmarker=f{{{,f}}}
10,885
386
<reponame>ccoderJava/bus /********************************************************************************* * * * The MIT License (MIT) * * * * Copyright (c) 2015-2021 aoju.org <NAME> and other contributors. * * * * 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. * * * ********************************************************************************/ package org.aoju.bus.gitlab.support; import org.aoju.bus.core.lang.Header; import org.glassfish.jersey.message.MessageUtils; import javax.annotation.Priority; import javax.ws.rs.WebApplicationException; import javax.ws.rs.client.ClientRequestContext; import javax.ws.rs.client.ClientRequestFilter; import javax.ws.rs.client.ClientResponseContext; import javax.ws.rs.client.ClientResponseFilter; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.WriterInterceptor; import javax.ws.rs.ext.WriterInterceptorContext; import java.io.*; import java.net.URI; import java.nio.charset.Charset; import java.util.*; import java.util.Map.Entry; import java.util.concurrent.atomic.AtomicLong; import java.util.logging.Level; import java.util.logging.Logger; /** * This class logs request and response info masking HTTP header values that are known to * contain sensitive information. * <p> * This class was patterned after org.glassfish.jersey.logging.LoggingInterceptor, but written in * such a way that it could be sub-classed and have its behavior modified. */ @Priority(Integer.MIN_VALUE) public class MaskingLoggingFilter implements ClientRequestFilter, ClientResponseFilter, WriterInterceptor { /** * Default list of header names that should be masked. */ public static final List<String> DEFAULT_MASKED_HEADER_NAMES = Collections.unmodifiableList(Arrays.asList("PRIVATE-TOKEN", Header.AUTHORIZATION, Header.PROXY_AUTHORIZATION)); /** * Prefix for request log entries. */ protected static final String REQUEST_PREFIX = "> "; /** * Prefix for response log entries. */ protected static final String RESPONSE_PREFIX = "< "; /** * Prefix that marks the beginning of a request or response section. */ protected static final String SECTION_PREFIX = "- "; /** * Property name for the entity stream property */ protected static final String ENTITY_STREAM_PROPERTY = MaskingLoggingFilter.class.getName() + ".entityStream"; /** * Property name for the logging record id property */ protected static final String LOGGING_ID_PROPERTY = MaskingLoggingFilter.class.getName() + ".id"; protected final Logger logger; protected final Level level; protected final int maxEntitySize; protected final AtomicLong _id = new AtomicLong(0); protected Set<String> maskedHeaderNames = new HashSet<String>(); /** * Creates a masking logging filter for the specified logger with entity logging disabled. * * @param logger the logger to log messages to * @param level level at which the messages will be logged */ public MaskingLoggingFilter(final Logger logger, final Level level) { this(logger, level, 0, null); } /** * Creates a masking logging filter for the specified logger. * * @param logger the logger to log messages to * @param level level at which the messages will be logged * @param maxEntitySize maximum number of entity bytes to be logged. When logging if the maxEntitySize * is reached, the entity logging will be truncated at maxEntitySize and "...more..." will be added at * the end of the log entry. If maxEntitySize is &lt;= 0, entity logging will be disabled */ public MaskingLoggingFilter(final Logger logger, final Level level, final int maxEntitySize) { this(logger, level, maxEntitySize, null); } /** * Creates a masking logging filter for the specified logger with entity logging disabled. * * @param logger the logger to log messages to * @param level level at which the messages will be logged * @param maskedHeaderNames a list of header names that should have the values masked */ public MaskingLoggingFilter(final Logger logger, final Level level, final List<String> maskedHeaderNames) { this(logger, level, 0, maskedHeaderNames); } /** * Creates a masking logging filter for the specified logger. * * @param logger the logger to log messages to * @param level level at which the messages will be logged * @param maxEntitySize maximum number of entity bytes to be logged. When logging if the maxEntitySize * is reached, the entity logging will be truncated at maxEntitySize and "...more..." will be added at * the end of the log entry. If maxEntitySize is &lt;= 0, entity logging will be disabled * @param maskedHeaderNames a list of header names that should have the values masked */ public MaskingLoggingFilter(final Logger logger, final Level level, final int maxEntitySize, final List<String> maskedHeaderNames) { this.logger = logger; this.level = level; this.maxEntitySize = maxEntitySize; if (maskedHeaderNames != null) { maskedHeaderNames.forEach(h -> this.maskedHeaderNames.add(h.toLowerCase())); } } /** * Set the list of header names to mask values for. If null, will clear the header names to mask. * * @param maskedHeaderNames a list of header names that should have the values masked, if null, will clear * the header names to mask */ public void setMaskedHeaderNames(final List<String> maskedHeaderNames) { this.maskedHeaderNames.clear(); if (maskedHeaderNames != null) { maskedHeaderNames.forEach(h -> { addMaskedHeaderName(h); }); } } /** * Add a header name to the list of masked header names. * * @param maskedHeaderName the masked header name to add */ public void addMaskedHeaderName(String maskedHeaderName) { if (maskedHeaderName != null) { maskedHeaderName = maskedHeaderName.trim(); if (maskedHeaderName.length() > 0) { maskedHeaderNames.add(maskedHeaderName.toLowerCase()); } } } protected void log(final StringBuilder sb) { if (logger != null) { logger.log(level, sb.toString()); } } protected StringBuilder appendId(final StringBuilder sb, final long id) { sb.append(Long.toString(id)).append(' '); return (sb); } protected void printRequestLine(final StringBuilder sb, final String note, final long id, final String method, final URI uri) { appendId(sb, id).append(SECTION_PREFIX) .append(note) .append(" on thread ").append(Thread.currentThread().getName()) .append('\n'); appendId(sb, id).append(REQUEST_PREFIX).append(method).append(' ') .append(uri.toASCIIString()).append('\n'); } protected void printResponseLine(final StringBuilder sb, final String note, final long id, final int status) { appendId(sb, id).append(SECTION_PREFIX) .append(note) .append(" on thread ").append(Thread.currentThread().getName()).append('\n'); appendId(sb, id).append(RESPONSE_PREFIX) .append(Integer.toString(status)) .append('\n'); } protected Set<Entry<String, List<String>>> getSortedHeaders(final Set<Entry<String, List<String>>> headers) { final TreeSet<Entry<String, List<String>>> sortedHeaders = new TreeSet<Entry<String, List<String>>>( (Entry<String, List<String>> o1, Entry<String, List<String>> o2) -> o1.getKey().compareToIgnoreCase(o2.getKey())); sortedHeaders.addAll(headers); return sortedHeaders; } /** * Logs each of the HTTP headers, masking the value of the header if the header key is * in the list of masked header names. * * @param sb the StringBuilder to build up the logging info in * @param id the ID for the logging line * @param prefix the logging line prefix character * @param headers a MultiValue map holding the header keys and values */ protected void printHeaders(final StringBuilder sb, final long id, final String prefix, final MultivaluedMap<String, String> headers) { getSortedHeaders(headers.entrySet()).forEach(h -> { final List<?> values = h.getValue(); final String header = h.getKey(); final boolean isMaskedHeader = maskedHeaderNames.contains(header.toLowerCase()); if (values.size() == 1) { String value = (isMaskedHeader ? "********" : values.get(0).toString()); appendId(sb, id).append(prefix).append(header).append(": ").append(value).append('\n'); } else { final StringBuilder headerBuf = new StringBuilder(); for (final Object value : values) { if (headerBuf.length() == 0) { headerBuf.append(", "); } headerBuf.append(isMaskedHeader ? "********" : value.toString()); } appendId(sb, id).append(prefix).append(header).append(": ").append(headerBuf.toString()).append('\n'); } }); } protected void buildEntityLogString(StringBuilder sb, byte[] entity, int entitySize, Charset charset) { sb.append(new String(entity, 0, Math.min(entitySize, maxEntitySize), charset)); if (entitySize > maxEntitySize) { sb.append("...more..."); } sb.append('\n'); } private InputStream logResponseEntity(final StringBuilder sb, InputStream stream, final Charset charset) throws IOException { if (maxEntitySize <= 0) { return (stream); } if (!stream.markSupported()) { stream = new BufferedInputStream(stream); } stream.mark(maxEntitySize + 1); final byte[] entity = new byte[maxEntitySize + 1]; final int entitySize = stream.read(entity); buildEntityLogString(sb, entity, entitySize, charset); stream.reset(); return stream; } @Override public void filter(ClientRequestContext requestContext) throws IOException { if (!logger.isLoggable(level)) { return; } final long id = _id.incrementAndGet(); requestContext.setProperty(LOGGING_ID_PROPERTY, id); final StringBuilder sb = new StringBuilder(); printRequestLine(sb, "Sending client request", id, requestContext.getMethod(), requestContext.getUri()); printHeaders(sb, id, REQUEST_PREFIX, requestContext.getStringHeaders()); if (requestContext.hasEntity() && maxEntitySize > 0) { final OutputStream stream = new LoggingStream(sb, requestContext.getEntityStream()); requestContext.setEntityStream(stream); requestContext.setProperty(ENTITY_STREAM_PROPERTY, stream); } else { log(sb); } } @Override public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException { if (!logger.isLoggable(level)) { return; } final Object requestId = requestContext.getProperty(LOGGING_ID_PROPERTY); final long id = requestId != null ? (Long) requestId : _id.incrementAndGet(); final StringBuilder sb = new StringBuilder(); printResponseLine(sb, "Received server response", id, responseContext.getStatus()); printHeaders(sb, id, RESPONSE_PREFIX, responseContext.getHeaders()); if (responseContext.hasEntity() && maxEntitySize > 0) { responseContext.setEntityStream(logResponseEntity(sb, responseContext.getEntityStream(), MessageUtils.getCharset(responseContext.getMediaType()))); } log(sb); } @Override public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException { final LoggingStream stream = (LoggingStream) context.getProperty(ENTITY_STREAM_PROPERTY); context.proceed(); if (stream == null) { return; } MediaType mediaType = context.getMediaType(); if (mediaType.isCompatible(MediaType.APPLICATION_JSON_TYPE) || mediaType.isCompatible(MediaType.APPLICATION_FORM_URLENCODED_TYPE)) { log(stream.getStringBuilder(MessageUtils.getCharset(mediaType))); } } /** * This class is responsible for logging the request entities, it will truncate at maxEntitySize * and add "...more..." to the end of the entity log string. */ protected class LoggingStream extends FilterOutputStream { private final StringBuilder sb; private final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); LoggingStream(StringBuilder sb, OutputStream out) { super(out); this.sb = sb; } StringBuilder getStringBuilder(Charset charset) { final byte[] entity = outputStream.toByteArray(); buildEntityLogString(sb, entity, entity.length, charset); return (sb); } @Override public void write(final int i) throws IOException { if (outputStream.size() <= maxEntitySize) { outputStream.write(i); } out.write(i); } } }
6,384
416
<filename>sfm-test/src/main/java/org/simpleflatmapper/test/beans/DbArrayOfString.java<gh_stars>100-1000 package org.simpleflatmapper.test.beans; public class DbArrayOfString { private int id; private String[] objects; public int getId() { return id; } public void setId(int id) { this.id = id; } public String[] getObjects() { return objects; } public void setObjects(String[] objects) { this.objects = objects; } }
164
505
<filename>cppForSwig/ScriptRecipient.h //////////////////////////////////////////////////////////////////////////////// // // // Copyright (C) 2016, goatpig // // Distributed under the MIT license // // See LICENSE-MIT or https://opensource.org/licenses/MIT // // // //////////////////////////////////////////////////////////////////////////////// #ifndef _H_SCRIPT_RECIPIENT #define _H_SCRIPT_RECIPIENT #include <stdint.h> #include "BinaryData.h" #include "BtcUtils.h" //// enum SpendScriptType { SST_P2PKH, SST_P2SH, SST_P2WPKH, SST_NESTED_P2WPKH, SST_P2WSH, SST_NESTED_P2WSH, SST_OPRETURN, SST_UNIVERSAL, SST_BECH32 }; //// class ScriptRecipientException : public runtime_error { public: ScriptRecipientException(const string& err) : runtime_error(err) {} }; //////////////////////////////////////////////////////////////////////////////// class ScriptRecipient { protected: const SpendScriptType type_; uint64_t value_ = UINT64_MAX; BinaryData script_; public: //tors ScriptRecipient(SpendScriptType sst, uint64_t value) : type_(sst), value_(value) {} //virtuals virtual const BinaryData& getSerializedScript(void) { if (script_.getSize() == 0) serialize(); return script_; } virtual ~ScriptRecipient(void) = 0; virtual void serialize(void) = 0; virtual size_t getSize(void) const = 0; //locals uint64_t getValue(void) const { return value_; } void setValue(uint64_t val) { value_ = val; } //static static shared_ptr<ScriptRecipient> deserialize(const BinaryDataRef& dataPtr); }; //////////////////////////////////////////////////////////////////////////////// class Recipient_P2PKH : public ScriptRecipient { private: const BinaryData h160_; public: Recipient_P2PKH(const BinaryData& h160, uint64_t val) : ScriptRecipient(SST_P2PKH, val), h160_(h160) { if (h160_.getSize() != 20) throw ScriptRecipientException("a160 is not 20 bytes long!"); } void serialize(void) { BinaryWriter bw; bw.put_uint64_t(value_); bw.put_uint8_t(25); bw.put_uint8_t(OP_DUP); bw.put_uint8_t(OP_HASH160); bw.put_uint8_t(20); bw.put_BinaryData(h160_); bw.put_uint8_t(OP_EQUALVERIFY); bw.put_uint8_t(OP_CHECKSIG); script_ = move(bw.getData()); } //return size is static size_t getSize(void) const { return 34; } }; //////////////////////////////////////////////////////////////////////////////// class Recipient_P2WPKH : public ScriptRecipient { private: const BinaryData h160_; public: Recipient_P2WPKH(const BinaryData& h160, uint64_t val) : ScriptRecipient(SST_P2WPKH, val), h160_(h160) { if (h160_.getSize() != 20) throw ScriptRecipientException("a160 is not 20 bytes long!"); } void serialize(void) { BinaryWriter bw; bw.put_uint64_t(value_); bw.put_uint8_t(22); bw.put_uint8_t(0); bw.put_uint8_t(20); bw.put_BinaryData(h160_); script_ = move(bw.getData()); } size_t getSize(void) const { return 31; } }; //////////////////////////////////////////////////////////////////////////////// class Recipient_P2SH : public ScriptRecipient { private: const BinaryData h160_; public: Recipient_P2SH(const BinaryData& h160, uint64_t val) : ScriptRecipient(SST_P2SH, val), h160_(h160) { if (h160_.getSize() != 20) throw ScriptRecipientException("a160 is not 20 bytes long!"); } void serialize(void) { BinaryWriter bw; bw.put_uint64_t(value_); bw.put_uint8_t(23); bw.put_uint8_t(OP_HASH160); bw.put_uint8_t(20); bw.put_BinaryData(h160_); bw.put_uint8_t(OP_EQUAL); script_ = move(bw.getData()); } size_t getSize(void) const { return 32; } }; //////////////////////////////////////////////////////////////////////////////// class Recipient_P2WSH : public ScriptRecipient { private: const BinaryData h256_; public: Recipient_P2WSH(const BinaryData& h256, uint64_t val) : ScriptRecipient(SST_P2WSH, val), h256_(h256) { if (h256_.getSize() != 32) throw ScriptRecipientException("a256 is not 32 bytes long!"); } void serialize(void) { BinaryWriter bw; bw.put_uint64_t(value_); bw.put_uint8_t(34); bw.put_uint8_t(0); bw.put_uint8_t(32); bw.put_BinaryData(h256_); script_ = move(bw.getData()); } size_t getSize(void) const { return 43; } }; //////////////////////////////////////////////////////////////////////////////// class Recipient_OPRETURN : public ScriptRecipient { private: const BinaryData message_; public: Recipient_OPRETURN(const BinaryData& message) : ScriptRecipient(SST_OPRETURN, 0), message_(message) { if (message_.getSize() > 80) throw ScriptRecipientException( "OP_RETURN message cannot exceed 80 bytes"); } void serialize(void) { BinaryWriter bw; bw.put_uint64_t(0); BinaryWriter bw_msg; auto size = message_.getSize(); if (size > 75) { bw_msg.put_uint8_t(OP_PUSHDATA1); bw_msg.put_uint8_t(size); } else if (size > 0) { bw_msg.put_uint8_t(size); } if (size > 0) bw_msg.put_BinaryData(message_); bw.put_uint8_t(bw_msg.getSize() + 1); bw.put_uint8_t(OP_RETURN); bw.put_BinaryData(bw_msg.getData()); script_ = bw.getData(); } size_t getSize(void) const { auto size = message_.getSize(); if (size > 75) size += 2; else if (size > 0) size += 1; size += 9; //8 for value, one for op_return return size; } }; //////////////////////////////////////////////////////////////////////////////// class Recipient_Universal : public ScriptRecipient { private: const BinaryData binScript_; public: Recipient_Universal(const BinaryData& script, uint64_t val) : ScriptRecipient(SST_UNIVERSAL, val), binScript_(script) {} void serialize(void) { if (script_.getSize() != 0) return; BinaryWriter bw; bw.put_uint64_t(value_); bw.put_var_int(binScript_.getSize()); bw.put_BinaryData(binScript_); script_ = move(bw.getData()); } size_t getSize(void) const { size_t varint_len = 1; if (binScript_.getSize() >= 0xfd) varint_len = 3; //larger scripts would make the tx invalid return 8 + binScript_.getSize() + varint_len; } }; //////////////////////////////////////////////////////////////////////////////// class Recipient_Bech32 : public ScriptRecipient { private: const BinaryData binScript_; public: Recipient_Bech32(const BinaryData& binScript, uint64_t val) : ScriptRecipient(SST_P2WSH, val), binScript_(binScript) { if (binScript.getSize() != 20 && binScript.getSize() != 32) throw ScriptRecipientException("invalid segwit script size"); } void serialize(void) { if (script_.getSize() != 0) return; BinaryWriter bw; bw.put_uint64_t(value_); bw.put_var_int(binScript_.getSize() + 2); bw.put_uint8_t(0); bw.put_uint8_t(binScript_.getSize()); bw.put_BinaryData(binScript_); script_ = move(bw.getData()); } size_t getSize(void) const { size_t varint_len = 1; if (binScript_.getSize() >= 0xfd) varint_len = 3; //larger scripts would make the tx invalid return 9 + binScript_.getSize(); } }; #endif
3,449
3,508
<gh_stars>1000+ package com.fishercoder.solutions; import java.util.ArrayList; import java.util.List; import java.util.TreeMap; public class _1862 { public static class Solution1 { /** * TODO: this results in TLE, fix it. */ public int sumOfFlooredPairs(int[] nums) { TreeMap<Integer, Integer> map = new TreeMap<>(); for (int num : nums) { map.put(num, map.getOrDefault(num, 0) + 1); } List<Integer> list = new ArrayList<>(map.keySet()); int mod = 1000000007; long sum = 0L; for (int i = list.size() - 1; i >= 0; i--) { for (int j = i; j >= 0; j--) { sum += (list.get(i) / list.get(j)) * map.get(list.get(j)) * map.get(list.get(i)); sum %= mod; } } return (int) sum; } } }
500
346
bool_one = False or not True and True bool_two = False and not True or True bool_three = True and not (False or False) bool_four = not not True or False and not True bool_five = False or not (True and True)
65
1,175
<reponame>amoniaka-knabino/Crypton from sage.all import * from Crypto.Util.number import * def func_f(X_i, P, Q, E): """ To calculate X_(i+1) = f(X_i) :parameters: X_i : sage.schemes.elliptic_curves.ell_point.EllipticCurvePoint_finite_field X_i = (a_i * P) + (b_i * Q) P : sage.schemes.elliptic_curves.ell_point.EllipticCurvePoint_finite_field Base point on which ECDLP is defined Q : sage.schemes.elliptic_curves.ell_point.EllipticCurvePoint_finite_field Q = x*P, where `x` is the secret key E : sage.schemes.elliptic_curves.ell_finite_field.EllipticCurve_finite_field_with_category Elliptic Curve defined as y^2 = x^3 + a*x + b mod p """ try: # Point P and Q should lie on the Elliptic Curve E assert P == E((P[0], P[1])) assert Q == E((Q[0], Q[1])) except Exception as e: # Do not return anything if the point is invalid print "[-] Point does not lie on the curve!" return None if int(X_i[0]) % 3 == 2: # Partition S_1 return X_i + Q if int(X_i[0]) % 3 == 0: # Partition S_2 return 2*X_i if int(X_i[0]) % 3 == 1: # Partition S_3 return X_i + P else: print "[-] Something's Wrong!" return -1 def func_g(a, P, X_i, E): """ Calculate a_(i+1) = g(a) :parameters: a : int/long Equivalent to a_i in X_i = a_i*P + b_i*Q P : sage.schemes.elliptic_curves.ell_point.EllipticCurvePoint_finite_field Base point on which ECDLP is defined X_i : sage.schemes.elliptic_curves.ell_point.EllipticCurvePoint_finite_field X_i = a_i*P + b_i*Q E : sage.schemes.elliptic_curves.ell_finite_field.EllipticCurve_finite_field_with_category Elliptic Curve defined as y^2 = x^3 + a*x + b mod p """ try: assert P == E((P[0], P[1])) except Exception as e: print e print "[-] Point does not lie on the curve" return None n = P.order() if int(X_i[0]) % 3 == 2: # Partition S_1 return a if int(X_i[0]) % 3 == 0: # Partition S_2 return 2*a % n if int(X_i[0]) % 3 == 1: # Partition S_3 return (a + 1) % n else: print "[-] Something's Wrong!" return None def func_h(b, P, X_i, E): """ Calculate a_(i+1) = g(a) :parameters: a : int/long Equivalent to a_i in X_i = a_i*P + b_i*Q P : sage.schemes.elliptic_curves.ell_point.EllipticCurvePoint_finite_field Base point on which ECDLP is defined X_i : sage.schemes.elliptic_curves.ell_point.EllipticCurvePoint_finite_field X_i = a_i*P + b_i*Q E : sage.schemes.elliptic_curves.ell_finite_field.EllipticCurve_finite_field_with_category Elliptic Curve defined as y^2 = x^3 + a*x + b mod p """ try: assert P == E((P[0], P[1])) except Exception as e: print e print "[-] Point does not lie on the curve" return None n = P.order() if int(X_i[0]) % 3 == 2: # Partition S_1 return (b + 1) % n if int(X_i[0]) % 3 == 0: # Partition S_2 return 2*b % n if int(X_i[0]) % 3 == 1: # Partition S_3 return b else: print "[-] Something's Wrong!" return None def pollardrho(P, Q, E): try: assert P == E((P[0], P[1])) assert Q == E((Q[0], Q[1])) except Exception as e: print e print "[-] Point does not lie on the curve" return None n = P.order() for j in range(10): a_i = random.randint(2, P.order()-2) b_i = random.randint(2, P.order()-2) a_2i = random.randint(2, P.order()-2) b_2i = random.randint(2, P.order()-2) X_i = a_i*P + b_i*Q X_2i = a_2i*P + b_2i*Q i = 1 while i <= n: # Single Step Calculations a_i = func_g(a_i, P, X_i, E) b_i = func_h(b_i, P, X_i, E) X_i = func_f(X_i, P, Q, E) # Double Step Calculations a_2i = func_g(func_g(a_2i, P, X_2i, E), P, func_f(X_2i, P, Q, E), E) b_2i = func_h(func_h(b_2i, P, X_2i, E), P, func_f(X_2i, P, Q, E), E) X_2i = func_f(func_f(X_2i, P, Q, E), P, Q, E) if X_i == X_2i: if b_i == b_2i: break assert GCD(b_2i - b_i, n) == 1 return ((a_i - a_2i) * inverse(b_2i - b_i, n)) % n else: i += 1 continue if __name__ == "__main__": import random for i in range(100): E = EllipticCurve(GF(17), [2, 2]) P = E((5, 1)) x = random.randint(2, P.order()-2) Q = x*P assert pollardrho(P, Q, E)*P == Q
2,736
892
<filename>advisories/unreviewed/2022/05/GHSA-gg9m-7hf2-hmp9/GHSA-gg9m-7hf2-hmp9.json { "schema_version": "1.2.0", "id": "GHSA-gg9m-7hf2-hmp9", "modified": "2022-05-12T00:01:50Z", "published": "2022-05-12T00:01:50Z", "aliases": [ "CVE-2022-29898" ], "details": "On various RAD-ISM-900-EN-* devices by PHOENIX CONTACT an admin user could use the configuration file uploader in the WebUI to execute arbitrary code with root privileges on the OS due to an improper validation of an integrity check value in all versions of the firmware.", "severity": [ { "type": "CVSS_V3", "score": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:C/C:H/I:H/A:H" } ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2022-29898" }, { "type": "WEB", "url": "https://cert.vde.com/en/advisories/VDE-2022-018/" } ], "database_specific": { "cwe_ids": [ "CWE-354" ], "severity": "CRITICAL", "github_reviewed": false } }
498
14,668
<filename>components/sync/trusted_vault/trusted_vault_connection.cc // Copyright 2020 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/sync/trusted_vault/trusted_vault_connection.h" namespace syncer { TrustedVaultKeyAndVersion::TrustedVaultKeyAndVersion( const std::vector<uint8_t>& key, int version) : key(key), version(version) {} TrustedVaultKeyAndVersion::TrustedVaultKeyAndVersion( const TrustedVaultKeyAndVersion& other) = default; TrustedVaultKeyAndVersion& TrustedVaultKeyAndVersion::operator=( const TrustedVaultKeyAndVersion& other) = default; TrustedVaultKeyAndVersion::~TrustedVaultKeyAndVersion() = default; } // namespace syncer
258
2,206
/* * * Copyright (c) 2006-2020, Speedment, 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. */ package com.speedment.runtime.core.issue; import static java.util.stream.Collectors.toList; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; import com.speedment.runtime.core.component.sql.SqlStreamOptimizerComponent; import com.speedment.runtime.core.component.sql.SqlStreamOptimizerInfo; import com.speedment.runtime.core.component.sql.override.SqlStreamTerminatorComponent; import com.speedment.runtime.core.db.AsynchronousQueryResult; import com.speedment.runtime.core.db.DbmsType; import com.speedment.runtime.core.internal.component.sql.SqlStreamOptimizerComponentImpl; import com.speedment.runtime.core.internal.component.sql.SqlTracer; import com.speedment.runtime.core.internal.component.sql.override.SqlStreamTerminatorComponentImpl; import com.speedment.runtime.core.internal.db.AsynchronousQueryResultImpl; import com.speedment.runtime.core.internal.manager.sql.SqlStreamTerminator; import com.speedment.runtime.core.internal.stream.builder.ReferenceStreamBuilder; import com.speedment.runtime.core.internal.stream.builder.pipeline.PipelineImpl; import com.speedment.runtime.core.stream.parallel.ParallelStrategy; import com.speedment.runtime.field.Field; import com.speedment.runtime.test_support.MockDbmsType; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.DoublePredicate; import java.util.function.IntPredicate; import java.util.function.LongPredicate; import java.util.function.Predicate; import java.util.function.ToDoubleFunction; import java.util.function.ToIntFunction; import java.util.function.ToLongFunction; import java.util.stream.DoubleStream; import java.util.stream.IntStream; import java.util.stream.LongStream; import java.util.stream.Stream; /** * * @author <NAME> */ final class Issue403TakeWhileDropWhileTest { private static final String[] ELEMENTS = {"a", "b", "c", "d", "e", "a"}; private static final Predicate<String> GREATER_THAN_B = (String s) -> "b".compareTo(s) < 0; private static final Predicate<String> LESS_THAN_C = (String s) -> "c".compareTo(s) > 0; private static final double EPSILON = 0.0000001; private static final double[] DOUBLE_ELEMENTS = {1.0, 2.0, 3.0, 4.0, 5.0, 1.0}; private static final DoublePredicate DOUBLE_GREATER_THAN_2 = (double d) -> Double.compare(2.0, d) < 0; private static final DoublePredicate DOUBLE_LESS_THAN_3 = (double d) -> Double.compare(3.0, d) > 0; private static final ToDoubleFunction<String> TO_DOUBLE_FUNCTION = s -> s.charAt(0) - 'a' + 1.0; private static final int[] INT_ELEMENTS = {1, 2, 3, 4, 5, 1}; private static final IntPredicate INT_GREATER_THAN_2 = (int d) -> Integer.compare(2, d) < 0; private static final IntPredicate INT_LESS_THAN_3 = (int d) -> Integer.compare(3, d) > 0; private static final ToIntFunction<String> TO_INT_FUNCTION = s -> s.charAt(0) - 'a' + 1; private static final long[] LONG_ELEMENTS = {1, 2, 3, 4, 5, 1}; private static final LongPredicate LONG_GREATER_THAN_2 = (long d) -> Long.compare(2, d) < 0; private static final LongPredicate LONG_LESS_THAN_3 = (long d) -> Long.compare(3, d) > 0; private static final ToLongFunction<String> TO_LONG_FUNCTION = s -> s.charAt(0) - 'a' + 1; private Stream<String> stream; @BeforeEach void before() { final PipelineImpl<String> pipeline = new PipelineImpl<>(() -> Stream.of(ELEMENTS)); final DbmsType dbmsType = new MockDbmsType(); final SqlStreamOptimizerInfo<String> info = SqlStreamOptimizerInfo.of( dbmsType, "select name from name_table", "select count(*) from name_table", (s, l) -> 1l, (Field<String> f) -> "name", (Field<String> f) -> String.class ); final AsynchronousQueryResult<String> asynchronousQueryResult = new AsynchronousQueryResultImpl<>( "select name from name_table", new ArrayList<>(), rs -> "z", () -> null, ParallelStrategy.computeIntensityDefault(), ps -> { }, rs -> { } ); final SqlStreamOptimizerComponent sqlStreamOptimizerComponent = new SqlStreamOptimizerComponentImpl(); final SqlStreamTerminatorComponent sqlStreamTerminatorComponent = new SqlStreamTerminatorComponentImpl(); SqlStreamTerminator<String> streamTerminator = new SqlStreamTerminator<>( info, asynchronousQueryResult, sqlStreamOptimizerComponent, sqlStreamTerminatorComponent, SqlTracer.from(null), true ); stream = new ReferenceStreamBuilder<>( pipeline, streamTerminator ); } @Test void testStream() { assertArrayEquals(ELEMENTS, stream.toArray(String[]::new)); } @Test void testPredicateGreaterThanB() { assertEquals( Arrays.asList("c", "d", "e"), stream.filter(GREATER_THAN_B).collect(toList()) ); } @Test void testPredicateLessThanC() { assertEquals( Arrays.asList("a", "b", "a"), stream.filter(LESS_THAN_C).collect(toList()) ); } @Test void testFilter() { try { final AtomicInteger closeCounter = new AtomicInteger(); stream.onClose(() -> closeCounter.incrementAndGet()); final Method method = Stream.class.getMethod("filter", Predicate.class); log("Filter exists"); @SuppressWarnings("unchecked") final Stream<String> newStream = (Stream<String>) method.invoke(stream, LESS_THAN_C); final List<String> expected = Arrays.asList("a", "b", "a"); log("expected:" + expected); final List<String> actual = newStream.collect(toList()); log("actual:" + actual); assertEquals(expected, actual); assertEquals( 1, closeCounter.get(), "Stream was not closed"); } catch (NoSuchMethodException | SecurityException e) { log("We run under Java 8: takeWhile does not exist"); // We are under Java 8. Just ignore. } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { // We are on Java 9 but it failed fail(e.getMessage()); } } @Test void testTakeWhile() { try { final AtomicInteger closeCounter = new AtomicInteger(); stream.onClose(() -> closeCounter.incrementAndGet()); final Method method = Stream.class.getMethod("takeWhile", Predicate.class); log("We are running under Java 9: takeWhile exists"); @SuppressWarnings("unchecked") final Stream<String> newStream = (Stream<String>) method.invoke(stream, LESS_THAN_C); final List<String> expected = Arrays.asList("a", "b"); log("expected:" + expected); final List<String> actual = newStream.collect(toList()); log("actual:" + actual); assertEquals(expected, actual); assertEquals(1, closeCounter.get(), "Stream was not closed"); } catch (NoSuchMethodException | SecurityException e) { log("We run under Java 8: takeWhile does not exist"); // We are under Java 8. Just ignore. } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { // We are on Java 9 but it failed fail(e.getMessage()); } } @Test void testDropWhile() { try { final AtomicInteger closeCounter = new AtomicInteger(); stream.onClose(() -> closeCounter.incrementAndGet()); final Method method = Stream.class.getMethod("dropWhile", Predicate.class); log("We are running under Java 9: dropWhile exists"); @SuppressWarnings("unchecked") final Stream<String> newStream = (Stream<String>) method.invoke(stream, LESS_THAN_C); final List<String> expected = Arrays.asList("c", "d", "e", "a"); log("expected:" + expected); final List<String> actual = newStream.collect(toList()); log("actual:" + actual); assertEquals(expected, actual); assertEquals(1, closeCounter.get(), "Stream was not closed"); } catch (NoSuchMethodException | SecurityException e) { log("We run under Java 8: dropWhile does not exist"); // We are under Java 8. Just ignore. } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { // We are on Java 9 but it failed fail(e.getMessage()); } } @Test void testDoubleStream() { assertArrayEquals(DOUBLE_ELEMENTS, stream.mapToDouble(TO_DOUBLE_FUNCTION).toArray(), EPSILON); } @Test void testDoublePredicateGreaterThanB() { assertArrayEquals( new double[]{3.0, 4.0, 5.0}, stream.mapToDouble(TO_DOUBLE_FUNCTION).filter(DOUBLE_GREATER_THAN_2).toArray(), EPSILON ); } @Test void testDoublePredicateLessThanC() { assertArrayEquals( new double[]{1.0, 2.0, 1.0}, stream.mapToDouble(TO_DOUBLE_FUNCTION).filter(DOUBLE_LESS_THAN_3).toArray(), EPSILON ); } @Test void testDoubleFilter() { try { final AtomicInteger closeCounter = new AtomicInteger(); stream.onClose(() -> closeCounter.incrementAndGet()); final DoubleStream doubleStream = stream.mapToDouble(TO_DOUBLE_FUNCTION); final Method method = DoubleStream.class.getMethod("filter", DoublePredicate.class); log("Filter exists"); @SuppressWarnings("unchecked") final DoubleStream newStream = (DoubleStream) method.invoke(doubleStream, DOUBLE_LESS_THAN_3); final double[] expected = new double[]{1.0, 2.0, 1.0}; final double[] actual = newStream.toArray(); log("expected:" + Arrays.toString(expected)); log("actual:" + Arrays.toString(actual)); assertArrayEquals(expected, actual, EPSILON); assertEquals( 1, closeCounter.get(), "Stream was not closed"); } catch (NoSuchMethodException | SecurityException e) { log("We run under Java 8: takeWhile does not exist"); // We are under Java 8. Just ignore. } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { // We are on Java 9 but it failed fail(e.getMessage()); } } @Test void testDoubleTakeWhile() { try { final AtomicInteger closeCounter = new AtomicInteger(); stream.onClose(() -> closeCounter.incrementAndGet()); final DoubleStream doubleStream = stream.mapToDouble(TO_DOUBLE_FUNCTION); final Method method = DoubleStream.class.getMethod("takeWhile", DoublePredicate.class); log("We are running under Java 9: takeWhile exists"); @SuppressWarnings("unchecked") final DoubleStream newStream = (DoubleStream) method.invoke(doubleStream, DOUBLE_LESS_THAN_3); final double[] expected = new double[]{1.0, 2.0}; final double[] actual = newStream.toArray(); log("expected:" + Arrays.toString(expected)); log("actual:" + Arrays.toString(actual)); assertArrayEquals(expected, actual, EPSILON); } catch (NoSuchMethodException | SecurityException e) { log("We run under Java 8: takeWhile does not exist"); // We are under Java 8. Just ignore. } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { // We are on Java 9 but it failed fail(e.getMessage()); } } @Test void testDoubleDropWhile() { try { final AtomicInteger closeCounter = new AtomicInteger(); stream.onClose(() -> closeCounter.incrementAndGet()); final DoubleStream doubleStream = stream.mapToDouble(TO_DOUBLE_FUNCTION); final Method method = DoubleStream.class.getMethod("dropWhile", DoublePredicate.class); log("We are running under Java 9: dropWhile exists"); @SuppressWarnings("unchecked") final DoubleStream newStream = (DoubleStream) method.invoke(doubleStream, DOUBLE_LESS_THAN_3); final double[] expected = new double[]{3.0, 4.0, 5.0, 1.0}; final double[] actual = newStream.toArray(); log("expected:" + Arrays.toString(expected)); log("actual:" + Arrays.toString(actual)); assertArrayEquals(expected, actual, EPSILON); assertEquals( 1, closeCounter.get(), "Stream was not closed"); } catch (NoSuchMethodException | SecurityException e) { log("We run under Java 8: dropWhile does not exist"); // We are under Java 8. Just ignore. } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { // We are on Java 9 but it failed fail(e.getMessage()); } } @Test void testIntStream() { assertArrayEquals(INT_ELEMENTS, stream.mapToInt(TO_INT_FUNCTION).toArray()); } @Test void testIntPredicateGreaterThanB() { assertArrayEquals( new int[]{3, 4, 5}, stream.mapToInt(TO_INT_FUNCTION).filter(INT_GREATER_THAN_2).toArray() ); } @Test void testIntPredicateLessThanC() { assertArrayEquals( new int[]{1, 2, 1}, stream.mapToInt(TO_INT_FUNCTION).filter(INT_LESS_THAN_3).toArray() ); } @Test void testIntFilter() { try { final AtomicInteger closeCounter = new AtomicInteger(); stream.onClose(() -> closeCounter.incrementAndGet()); final IntStream intStream = stream.mapToInt(TO_INT_FUNCTION); final Method method = IntStream.class.getMethod("filter", IntPredicate.class); log("Filter exists"); @SuppressWarnings("unchecked") final IntStream newStream = (IntStream) method.invoke(intStream, INT_LESS_THAN_3); final int[] expected = new int[]{1, 2, 1}; final int[] actual = newStream.toArray(); log("expected:" + Arrays.toString(expected)); log("actual:" + Arrays.toString(actual)); assertArrayEquals(expected, actual); assertEquals( 1, closeCounter.get(), "Stream was not closed"); } catch (NoSuchMethodException | SecurityException e) { log("We run under Java 8: takeWhile does not exist"); // We are under Java 8. Just ignore. } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { // We are on Java 9 but it failed fail(e.getMessage()); } } @Test void testIntTakeWhile() { try { final AtomicInteger closeCounter = new AtomicInteger(); stream.onClose(() -> closeCounter.incrementAndGet()); final IntStream intStream = stream.mapToInt(TO_INT_FUNCTION); final Method method = IntStream.class.getMethod("takeWhile", IntPredicate.class); log("We are running under Java 9: takeWhile exists"); @SuppressWarnings("unchecked") final IntStream newStream = (IntStream) method.invoke(intStream, INT_LESS_THAN_3); final int[] expected = new int[]{1, 2}; final int[] actual = newStream.toArray(); log("expected:" + Arrays.toString(expected)); log("actual:" + Arrays.toString(actual)); assertArrayEquals(expected, actual); } catch (NoSuchMethodException | SecurityException e) { log("We run under Java 8: takeWhile does not exist"); // We are under Java 8. Just ignore. } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { // We are on Java 9 but it failed fail(e.getMessage()); } } @Test void testIntDropWhile() { try { final AtomicInteger closeCounter = new AtomicInteger(); stream.onClose(() -> closeCounter.incrementAndGet()); final IntStream intStream = stream.mapToInt(TO_INT_FUNCTION); final Method method = IntStream.class.getMethod("dropWhile", IntPredicate.class); log("We are running under Java 9: dropWhile exists"); @SuppressWarnings("unchecked") final IntStream newStream = (IntStream) method.invoke(intStream, INT_LESS_THAN_3); final int[] expected = new int[]{3, 4, 5, 1}; final int[] actual = newStream.toArray(); log("expected:" + Arrays.toString(expected)); log("actual:" + Arrays.toString(actual)); assertArrayEquals(expected, actual); assertEquals( 1, closeCounter.get(), "Stream was not closed"); } catch (NoSuchMethodException | SecurityException e) { log("We run under Java 8: dropWhile does not exist"); // We are under Java 8. Just ignore. } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { // We are on Java 9 but it failed fail(e.getMessage()); } } @Test void testLongStream() { assertArrayEquals(LONG_ELEMENTS, stream.mapToLong(TO_LONG_FUNCTION).toArray()); } @Test void testLongPredicateGreaterThanB() { assertArrayEquals( new long[]{3, 4, 5}, stream.mapToLong(TO_LONG_FUNCTION).filter(LONG_GREATER_THAN_2).toArray() ); } @Test void testLongPredicateLessThanC() { assertArrayEquals( new long[]{1, 2, 1}, stream.mapToLong(TO_LONG_FUNCTION).filter(LONG_LESS_THAN_3).toArray() ); } @Test void testLongFilter() { try { final AtomicInteger closeCounter = new AtomicInteger(); stream.onClose(() -> closeCounter.incrementAndGet()); final LongStream longStream = stream.mapToLong(TO_LONG_FUNCTION); final Method method = LongStream.class.getMethod("filter", LongPredicate.class); log("Filter exists"); @SuppressWarnings("unchecked") final LongStream newStream = (LongStream) method.invoke(longStream, LONG_LESS_THAN_3); final long[] expected = new long[]{1, 2, 1}; final long[] actual = newStream.toArray(); log("expected:" + Arrays.toString(expected)); log("actual:" + Arrays.toString(actual)); assertArrayEquals(expected, actual); assertEquals( 1, closeCounter.get(), "Stream was not closed"); } catch (NoSuchMethodException | SecurityException e) { log("We run under Java 8: takeWhile does not exist"); // We are under Java 8. Just ignore. } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { // We are on Java 9 but it failed fail(e.getMessage()); } } @Test void testLongTakeWhile() { try { final AtomicInteger closeCounter = new AtomicInteger(); stream.onClose(() -> closeCounter.incrementAndGet()); final LongStream longStream = stream.mapToLong(TO_LONG_FUNCTION); final Method method = LongStream.class.getMethod("takeWhile", LongPredicate.class); log("We are running under Java 9: takeWhile exists"); @SuppressWarnings("unchecked") final LongStream newStream = (LongStream) method.invoke(longStream, LONG_LESS_THAN_3); final long[] expected = new long[]{1, 2}; final long[] actual = newStream.toArray(); log("expected:" + Arrays.toString(expected)); log("actual:" + Arrays.toString(actual)); assertArrayEquals(expected, actual); } catch (NoSuchMethodException | SecurityException e) { log("We run under Java 8: takeWhile does not exist"); // We are under Java 8. Just ignore. } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { // We are on Java 9 but it failed fail(e.getMessage()); } } @Test void testLongDropWhile() { try { final AtomicInteger closeCounter = new AtomicInteger(); stream.onClose(() -> closeCounter.incrementAndGet()); final LongStream longStream = stream.mapToLong(TO_LONG_FUNCTION); final Method method = LongStream.class.getMethod("dropWhile", LongPredicate.class); log("We are running under Java 9: dropWhile exists"); @SuppressWarnings("unchecked") final LongStream newStream = (LongStream) method.invoke(longStream, LONG_LESS_THAN_3); final long[] expected = new long[]{3, 4, 5, 1}; final long[] actual = newStream.toArray(); log("expected:" + Arrays.toString(expected)); log("actual:" + Arrays.toString(actual)); assertArrayEquals(expected, actual); assertEquals( 1, closeCounter.get(), "Stream was not closed"); } catch (NoSuchMethodException | SecurityException e) { log("We run under Java 8: dropWhile does not exist"); // We are under Java 8. Just ignore. } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { // We are on Java 9 but it failed fail(e.getMessage()); } } private void log(String msg) { // System.out.println("******** " + msg); } }
9,428
831
/* * Copyright (C) 2018 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.tools.idea.gradle.project.build.output; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import com.intellij.build.events.BuildEvent; import com.intellij.build.events.MessageEvent; import com.intellij.build.events.impl.MessageEventImpl; import com.intellij.build.output.BuildOutputInstantReader; import java.util.List; import java.util.function.Consumer; import org.jetbrains.annotations.Nullable; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mock; public class AndroidGradlePluginOutputParserTest { @Mock private BuildOutputInstantReader myReader; @Mock private Consumer<BuildEvent> myConsumer; @Nullable private AndroidGradlePluginOutputParser myParser; @Before public void setUp() { initMocks(this); myParser = new AndroidGradlePluginOutputParser(); } @Test public void testParseWarningFromOutput() { String line = "WARNING: Configuration 'compile' is obsolete and has been replaced with 'implementation'."; String expected = "Configuration 'compile' is obsolete and has been replaced with 'implementation'."; when(myReader.getParentEventId()).thenReturn("BUILD_ID_MOCK"); ArgumentCaptor<MessageEvent> messageCaptor = ArgumentCaptor.forClass(MessageEvent.class); assertTrue(myParser.parse(line, myReader, myConsumer)); verify(myConsumer).accept(messageCaptor.capture()); List<MessageEvent> generatedMessages = messageCaptor.getAllValues(); assertThat(generatedMessages).hasSize(1); assertThat(generatedMessages.get(0)).isInstanceOf(MessageEventImpl.class); MessageEventImpl fileMessageEvent = (MessageEventImpl)generatedMessages.get(0); assertThat(fileMessageEvent.getResult().getDetails()).isEqualTo(expected); } @Test public void testParseJavacWithSource() { String line = "MyClass.java:38: warning: [serial] serializable class MyClass has no definition of serialVersionUID"; when(myReader.getParentEventId()).thenReturn("BUILD_ID_MOCK"); assertFalse(myParser.parse(line, myReader, myConsumer)); } /** * Javac warnings without sources are currently treated as AGP warnings as there is no reliable way to distinguish them from each other. */ @Test public void testParseJavacWithoutSource() { String line = "warning: [serial] serializable class MyClass has no definition of serialVersionUID"; when(myReader.getParentEventId()).thenReturn("BUILD_ID_MOCK"); assertTrue(myParser.parse(line, myReader, myConsumer)); } @Test public void testParseAGPResourceWarning() { String line = "warning: string 'snowball' has no default translation.\n"; when(myReader.getParentEventId()).thenReturn("BUILD_ID_MOCK"); assertTrue(myParser.parse(line, myReader, myConsumer)); } @Test public void testParseAGPError() { String line = "ERROR: Something went wrong!\n"; when(myReader.getParentEventId()).thenReturn("BUILD_ID_MOCK"); assertTrue(myParser.parse(line, myReader, myConsumer)); } @Test public void testParseJavaError() { String line = "MyClass.java:23 error: Something went REALLY wrong!\n"; when(myReader.getParentEventId()).thenReturn("BUILD_ID_MOCK"); assertFalse(myParser.parse(line, myReader, myConsumer)); } }
1,273
575
<reponame>sarang-apps/darshan_browser // 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 "third_party/blink/renderer/bindings/core/v8/script_iterator.h" #include "third_party/blink/renderer/bindings/core/v8/script_controller.h" #include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h" #include "third_party/blink/renderer/bindings/core/v8/v8_string_resource.h" #include "third_party/blink/renderer/platform/bindings/exception_state.h" namespace blink { // static ScriptIterator ScriptIterator::FromIterable(v8::Isolate* isolate, v8::Local<v8::Object> value, ExceptionState& exception_state) { // First, call the GetMethod(V, @@iterator) abstract ES operation. const v8::Local<v8::Function> iterator_method = GetEsIteratorMethod(isolate, value, exception_state); if (exception_state.HadException()) return ScriptIterator(); if (iterator_method.IsEmpty()) return ScriptIterator(); // Use the method returned above to invoke the GetIterator(V, sync, method) // abstract ES operation. const v8::Local<v8::Object> iterator = GetEsIteratorWithMethod(isolate, iterator_method, value, exception_state); if (exception_state.HadException()) return ScriptIterator(); return ScriptIterator(isolate, iterator); } ScriptIterator::ScriptIterator(v8::Isolate* isolate, v8::Local<v8::Object> iterator) : isolate_(isolate), iterator_(iterator), next_key_(V8AtomicString(isolate, "next")), done_key_(V8AtomicString(isolate, "done")), value_key_(V8AtomicString(isolate, "value")), done_(false) { DCHECK(!iterator.IsEmpty()); } bool ScriptIterator::Next(ExecutionContext* execution_context, ExceptionState& exception_state, v8::Local<v8::Value> next_value) { DCHECK(!IsNull()); v8::TryCatch try_catch(isolate_); v8::Local<v8::Context> context = isolate_->GetCurrentContext(); v8::Local<v8::Value> next; if (!iterator_->Get(context, next_key_).ToLocal(&next)) { CHECK(!try_catch.Exception().IsEmpty()); exception_state.RethrowV8Exception(try_catch.Exception()); done_ = true; return false; } if (!next->IsFunction()) { exception_state.ThrowTypeError("Expected next() function on iterator."); done_ = true; return false; } Vector<v8::Local<v8::Value>, 1> argv; if (!next_value.IsEmpty()) argv = {next_value}; v8::Local<v8::Value> result; if (!V8ScriptRunner::CallFunction(v8::Local<v8::Function>::Cast(next), execution_context, iterator_, argv.size(), argv.data(), isolate_) .ToLocal(&result)) { CHECK(!try_catch.Exception().IsEmpty()); exception_state.RethrowV8Exception(try_catch.Exception()); done_ = true; return false; } if (!result->IsObject()) { exception_state.ThrowTypeError( "Expected iterator.next() to return an Object."); done_ = true; return false; } v8::Local<v8::Object> result_object = v8::Local<v8::Object>::Cast(result); value_ = result_object->Get(context, value_key_); if (value_.IsEmpty()) { CHECK(!try_catch.Exception().IsEmpty()); exception_state.RethrowV8Exception(try_catch.Exception()); } v8::Local<v8::Value> done; if (!result_object->Get(context, done_key_).ToLocal(&done)) { CHECK(!try_catch.Exception().IsEmpty()); exception_state.RethrowV8Exception(try_catch.Exception()); done_ = true; return false; } done_ = done->BooleanValue(isolate_); return !done_; } } // namespace blink
1,525
487
<gh_stars>100-1000 #include <stdint.h> /* * This file implements sample C extern function. It contains definition of the following C extern function: * * extern bit<16> compute_hash(in <bit<32> srcAddr, in bit<32> dstAddr) * */ struct data { uint32_t ipSrcAddr; uint32_t ipDstAddr; }; /** * This is really simple (not verified) hash function generating 16-bit hash. * @param a 1st field * @param b 2nd field * @return 16-bit wide hashed value. */ uint16_t compute_hash(const uint32_t a, const uint32_t b) { struct data s = { .ipSrcAddr = a, .ipDstAddr = b }; unsigned char *to_hash = (unsigned char *) &s; int length = sizeof(s); unsigned char x; uint16_t crc = 0xFFFF; for (int i = length-1; i > 0; i--) { x = crc >> 8 ^ *to_hash++; x ^= x>>4; crc = (crc << 8) ^ ((unsigned short)(x << 12)) ^ ((unsigned short)(x <<5)) ^ ((unsigned short)x); } return crc; }
356
1,374
<gh_stars>1000+ package def.dom; public class SVGPathSegList extends def.js.Object { public double numberOfItems; native public SVGPathSeg appendItem(SVGPathSeg newItem); native public void clear(); native public SVGPathSeg getItem(double index); native public SVGPathSeg initialize(SVGPathSeg newItem); native public SVGPathSeg insertItemBefore(SVGPathSeg newItem, double index); native public SVGPathSeg removeItem(double index); native public SVGPathSeg replaceItem(SVGPathSeg newItem, double index); public static SVGPathSegList prototype; public SVGPathSegList(){} }
184
360
<filename>src/common/interfaces/libpq/client_logic_processor/stmt_processor.cpp /* * Copyright (c) 2020 Huawei Technologies Co.,Ltd. * * openGauss is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. * ------------------------------------------------------------------------- * * stmt_processor.cpp * * IDENTIFICATION * src\common\interfaces\libpq\client_logic_processor\stmt_processor.cpp * * ------------------------------------------------------------------------- */ #include "pg_config.h" #include "stmt_processor.h" #include "client_logic_cache/icached_column_manager.h" #include "client_logic_cache/icached_column.h" #include "client_logic_cache/cached_columns.h" #include "client_logic_cache/cached_column.h" #include "client_logic_cache/icached_columns.h" #include "client_logic_cache/cache_loader.h" #include "client_logic_cache/cached_column_setting.h" #include "client_logic_cache/column_hook_executors_list.h" #include "client_logic_common/client_logic_utils.h" #include "client_logic_expressions/column_ref_data.h" #include "client_logic/cstrings_map.h" #include "raw_value.h" #include "raw_values_cont.h" #include "prepared_statement.h" #include "prepared_statements_list.h" #include "libpq-fe.h" #include "libpq-int.h" #include "where_clause_processor.h" #include "create_stmt_processor.h" #include "client_logic_hooks/hooks_manager.h" #include "client_logic_fmt/gs_fmt.h" #include "client_logic_fmt/gs_copy.h" #include "values_processor.h" #include "processor_utils.h" #include "raw_values_list.h" #include <algorithm> #include "frontend_parser/Parser.h" #include "nodes/feparser_memutils.h" #include "client_logic_expressions/expr_processor.h" #include "encryption_pre_process.h" #include "client_logic_expressions/expr_parts_list.h" #include "client_logic_expressions/pg_functions_support.h" #include "catalog/pg_class.h" #include "func_processor.h" #include <iostream> bool Processor::run_pre_update_statement_set(const UpdateStmt * const update_stmt, StatementData *statement_data) { /* get column configuration from cache (for every column in query) */ CachedColumns cached_columns; bool ret = statement_data->GetCacheManager()->get_cached_columns(update_stmt, &cached_columns); if (!ret || cached_columns.is_empty()) { return true; } /* get actual values from query */ RawValuesList raw_values_list; if (!RawValues::get_raw_values_from_update_statement(update_stmt, statement_data, &raw_values_list)) { fprintf(stderr, "error getting raw valued from statment\n"); return false; } if (!cached_columns.is_divisor(raw_values_list.size())) { fprintf(stderr, "columns and values do not match.\n"); return false; } /* iterate on all of the values, and process if required by the configuration */ return ValuesProcessor::process_values(statement_data, &cached_columns, 1, &raw_values_list); /* 1 : one row */ } bool Processor::run_pre_update_statement_where(const UpdateStmt * const update_stmt, StatementData *statement_data) { ExprPartsList where_expr_parts_list; if (!exprProcessor::expand_expr(update_stmt->whereClause, statement_data, &where_expr_parts_list)) { return false; } /* get all columns relevant for this query's where clause */ bool is_op_forbidden(false); CachedColumns cached_columns; bool ret = statement_data->GetCacheManager()->get_cached_columns(update_stmt->relation, &where_expr_parts_list, is_op_forbidden, &cached_columns); if (is_op_forbidden) { printfPQExpBuffer(&statement_data->conn->errorMessage, "ERROR(CLIENT): operator is not allowed on datatype of this column\n"); return false; } if (!ret || cached_columns.is_empty()) { return true; // nothing to do } /* rewrite WHERE statement clause in the query */ for (size_t i = 0; i < statement_data->params.nParams; ++i) { libpq_free(statement_data->params.new_param_values[i]); } libpq_free(statement_data->params.new_param_values); libpq_free(statement_data->params.copy_sizes); statement_data->params.new_param_values = (unsigned char **)malloc(statement_data->nParams * sizeof(unsigned char *)); if (statement_data->params.new_param_values == NULL) { printfPQExpBuffer(&statement_data->conn->errorMessage, "ERROR(CLIENT): out of memory when malloc new param value.\n"); return false; } statement_data->params.copy_sizes = (size_t *)calloc(sizeof(size_t), statement_data->nParams); if (statement_data->params.copy_sizes == NULL) { printfPQExpBuffer(&statement_data->conn->errorMessage, "ERROR(CLIENT): out of memory when calloc copy size.\n"); return false; } if (!WhereClauseProcessor::process(&cached_columns, &where_expr_parts_list, statement_data)) { return false; } if (!process_clause_value(statement_data)) { return false; } return true; } bool Processor::run_pre_update_statement(const UpdateStmt * const update_stmt, StatementData *statement_data, ICachedColumns* cached_columns) { /* check if feature is used */ if (statement_data->GetCacheManager()->is_cache_empty()) { return true; } /* validate input */ if (update_stmt == nullptr || update_stmt->relation == nullptr || update_stmt->targetList == nullptr) { fprintf(stderr, "wrong arguments list for update statment\n"); return true; } if (!run_pre_update_statement_set(update_stmt, statement_data)) { return false; } if (!run_pre_update_statement_where(update_stmt, statement_data)) { return false; } /* update c1 set col1 = ... returning [] */ CachedColumns cached_column_temp; statement_data->GetCacheManager()->get_cached_columns(update_stmt->relation, &cached_column_temp); if (!run_pre_returning_list_statement(update_stmt->returningList, &cached_column_temp, cached_columns, statement_data)) { return false; } return true; } /* update/insert/delete returning [] the returning CacheColumn is useful for (with cte as... ) */ bool Processor::run_pre_returning_list_statement(const List *return_list, ICachedColumns *cached_columns_from, ICachedColumns *cached_columns, StatementData *statement_data) { if (cached_columns != NULL && return_list != NULL && !cached_columns_from->is_empty()) { CStringsMap returning_list; if (!get_column_names_from_target_list(return_list, &returning_list, statement_data)) { return false; } for (size_t i = 0; i < cached_columns_from->size(); i++) { const ICachedColumn *cached_column = cached_columns_from->at(i); if (cached_column != NULL && find_in_name_map(returning_list, cached_column->get_col_name())) { CachedColumn *return_cached = new (std::nothrow) CachedColumn(cached_columns_from->at(i)); if (return_cached == NULL) { fprintf(stderr, "failed to new CachedColumn object\n"); return false; } cached_columns->push(return_cached); } } } return true; } bool Processor::run_pre_insert_statement(const InsertStmt * const insert_stmt, StatementData *statement_data, ICachedColumns* cached_columns) { if (statement_data->GetCacheManager()->is_cache_empty()) { return true; } RETURN_IF(insert_stmt == NULL, false); /* get column configuration from cache (for every column in query) */ CachedColumns cached_columns_temp; bool ret = statement_data->GetCacheManager()->get_cached_columns(insert_stmt, &cached_columns_temp); if (!ret) { return true; } CachedColumns cached_column_insert(false, true); if (insert_stmt->withClause) { ret = run_pre_with_list_statement(insert_stmt->withClause->ctes, statement_data, &cached_column_insert); RETURN_IF(!ret, false); } SelectStmt *select_stmt = (SelectStmt *)(insert_stmt->selectStmt); if (select_stmt != nullptr && select_stmt->fromClause != nullptr && select_stmt->targetList != nullptr) { SetOperation set_operation(SETOP_NONE); bool all(false); CachedColumns cached_columns_select(false, true); ret = run_pre_select_statement(select_stmt, set_operation, all, statement_data, &cached_columns_select, &cached_column_insert); RETURN_IF(!ret, false); if (cached_columns_select.size() != cached_columns_temp.not_null_size()) { if (cached_columns_select.size() < cached_columns_temp.size()) { printfPQExpBuffer(&statement_data->conn->errorMessage, "ERROR(CLIENT): unencrypted data should not be inserted into encrypted column\n"); } else { printfPQExpBuffer(&statement_data->conn->errorMessage, "ERROR(CLIENT): encrypted data should not be inserted into unencrypted column\n"); } return false; } size_t i = 0; size_t j = 0; ColumnHookExecutor *select_exe = NULL; ColumnHookExecutor *insert_exe = NULL; /* * if a column is unencrypted, we push nothing in the 'cached_columns_select' * but, we need to push a 'NULL' in the 'cached_columns_temp' to reserve the position of this column */ for (; i < cached_columns_select.size(); i++, j++) { select_exe = cached_columns_select.at(i)->get_column_hook_executors()->at(0); for (; j < cached_columns_temp.size(); j++) { if (cached_columns_temp.at(j) != NULL) { break; } } insert_exe = cached_columns_temp.at(j)->get_column_hook_executors()->at(0); if (insert_exe != select_exe) { printfPQExpBuffer(&statement_data->conn->errorMessage, "ERROR(CLIENT): encrypted data should not be inserted into encrypted column with different keys\n"); return false; } } } if (cached_columns_temp.is_empty()) { return true; } /* get actual values from query */ RawValuesList raw_values_list; if (!RawValues::get_raw_values_from_insert_statement(insert_stmt, statement_data, &raw_values_list)) { fprintf(stderr, "error getting raw valued from statment\n"); return false; } /* in "INSERT DEFAULT VALUES" there are no values therefore we have nothing to do. */ if (raw_values_list.empty()) { return true; } /* check that if columns were retrieved in a list from the query, then the number of raw values equals (modulo) */ if (insert_stmt->cols && !cached_columns_temp.is_divisor(raw_values_list.size())) { return true; } /* insert c1 values () returning [] */ ret = run_pre_returning_list_statement(insert_stmt->returningList, &cached_columns_temp, cached_columns, statement_data); RETURN_IF(!ret, false); return ValuesProcessor::process_values(statement_data, &cached_columns_temp, list_length(select_stmt->valuesLists), &raw_values_list); } bool Processor::deal_order_by_statement(const SelectStmt * const select_stmt, ICachedColumns *select_cached_columns, StatementData *statement_data) { if (select_stmt == NULL || select_cached_columns == NULL || !select_cached_columns->is_to_process()) { return true; } List *sort_list = select_stmt->sortClause; ListCell *list_node = NULL; if (sort_list != NIL) { foreach (list_node, sort_list) { Node *n = (Node *)lfirst(list_node); if (IsA(n, SortBy)) { SortBy *sort = (SortBy *)n; Node *sort_node = sort->node; if (IsA(sort_node, ColumnRef)) { ColumnRef *cref = (ColumnRef *)sort_node; ColumnRefData column_ref_data; if (!exprProcessor::expand_column_ref(cref, column_ref_data)) { return false; } for (size_t i = 0; i < select_cached_columns->size(); i++) { if (select_cached_columns->at(i) && select_cached_columns->at(i)->get_col_name()) { if (strcmp(select_cached_columns->at(i)->get_col_name(), NameStr(column_ref_data.m_column_name)) == 0) { printfPQExpBuffer(&statement_data->conn->errorMessage, libpq_gettext( "ERROR(CLIENT): could not support order by operator for column encryption\n")); return false; } } } } } } } return true; } bool Processor::run_pre_cached_global_setting(PGconn *conn, const char *stmt_name, CreateClientLogicGlobal *client_logic_global) { char *function_name(NULL); StringArgs string_args; bool result = EncryptionPreProcess::run_pre_client_master_key(conn, client_logic_global, &function_name, string_args); if (!result) { return false; } PreparedStatement *prepared_statement = conn->client_logic->pendingStatements->get_or_create(stmt_name); if (!prepared_statement) { return false; } check_strncpy_s(strncpy_s(prepared_statement->m_function_name, sizeof(prepared_statement->m_function_name), function_name, strlen(function_name))); prepared_statement->m_string_args = string_args; /* * hooks arguments validatity checks * We are actually creating the hook here using the factory for this operation. But it will not be saved. * Only in the CacheLoader do we care the hook and save in the memory */ size_t existing_global_hook_executors_size(0); const GlobalHookExecutor **existing_global_hook_executors = conn->client_logic->m_cached_column_manager->get_global_hook_executors(existing_global_hook_executors_size); bool ret = HooksManager::GlobalSettings::pre_create(*conn->client_logic, function_name, string_args, existing_global_hook_executors, existing_global_hook_executors_size); if (existing_global_hook_executors) { free(existing_global_hook_executors); } return ret; } bool Processor::run_pre_column_setting_statement(PGconn *conn, const char *stmt_name, CreateClientLogicColumn *client_logic_column, const char *query, PGClientLogicParams &params) { if (!conn->client_logic->m_cached_column_manager->has_global_setting()) { conn->client_logic->cacheRefreshType |= CacheRefreshType::GLOBAL_SETTING; conn->client_logic->m_cached_column_manager->load_cache(conn); if (!conn->client_logic->m_cached_column_manager->has_global_setting()) { printfPQExpBuffer(&conn->errorMessage, "ERROR(CLIENT): no global setting found in local cache\n"); return false; } } int location = 0; char global_key_name[NAMEDATALEN * NAME_CNT]; errno_t rc = EOK; rc = memset_s(global_key_name, NAMEDATALEN * NAME_CNT, 0, NAMEDATALEN * NAME_CNT); securec_check_c(rc, "\0", "\0"); const char *function_name(NULL); StringArgs string_args; int encrypted_value_location = 0; size_t encrypted_value_size = 0; size_t quote_num = 0; bool result = EncryptionPreProcess::run_pre_column_encryption_key(conn, client_logic_column, global_key_name, &function_name, string_args, &location, &encrypted_value_location, &encrypted_value_size, &quote_num); if (!result) { return false; } StringArgs new_strings_args; const CachedGlobalSetting *global_setting = conn->client_logic->m_cached_column_manager->get_global_setting_by_fqdn(global_key_name); if (global_setting == NULL) { conn->client_logic->cacheRefreshType = CacheRefreshType::CACHE_ALL; conn->client_logic->m_cached_column_manager->load_cache(conn); global_setting = conn->client_logic->m_cached_column_manager->get_global_setting_by_fqdn(global_key_name); if (global_setting == NULL) { if (strlen(global_key_name) == 0) { printfPQExpBuffer(&conn->errorMessage, libpq_gettext("ERROR(CLIENT): failed to get client master key from cache\n")); } else { printfPQExpBuffer(&conn->errorMessage, libpq_gettext("ERROR(CLIENT): failed to get client master key %s from cache\n"), global_key_name); } return false; } } if (!HooksManager::ColumnSettings::pre_create(*conn->client_logic, global_setting->get_executor(), function_name, string_args, new_strings_args)) { return false; } // update query params.new_query_size = strlen(query); params.new_query = (char *)malloc(params.new_query_size + 1); if (params.new_query == NULL) { return false; } check_strncpy_s(strncpy_s(params.new_query, params.new_query_size + 1, query, params.new_query_size)); params.new_query[params.new_query_size] = '\0'; EncryptionPreProcess::set_new_query(&params.new_query, params.new_query_size, new_strings_args, location, encrypted_value_location, encrypted_value_size, quote_num); params.adjusted_query = params.new_query; params.adjusted_query_size = params.new_query_size; return true; } bool Processor::find_in_name_map(const CStringsMap &col_alias_map, const char *name) { if (col_alias_map.Size() == 0) { /* should happen only if the commmand was SELECT* */ return true; } if (col_alias_map.find(name)) { return true; } return false; } bool Processor::is_set_operation_allowed_on_datatype(const ICachedColumns *cached_columns, const CStringsMap &col_alias_map) { /* operation is allowed if no specific column */ size_t cached_columns_size = cached_columns->size(); for (size_t i = 0; i < cached_columns_size; ++i) { const ICachedColumn *cached_column = cached_columns->at(i); if (find_in_name_map(col_alias_map, cached_column->get_col_name())) { if (!HooksManager::is_set_operation_allowed(cached_column)) { return false; } } } return true; } bool Processor::get_column_names_from_target_list(const List* target_list, CStringsMap* col_alias_map, StatementData* statement_data) { ListCell *tl = NULL; if (target_list) { foreach (tl, target_list) { Node *n = (Node *)lfirst(tl); if (IsA(n, ResTarget)) { ResTarget *rt = (ResTarget *)n; char alias_name[NAMEDATALEN]; errno_t rc = EOK; rc = memset_s(alias_name, NAMEDATALEN, 0, NAMEDATALEN); securec_check_c(rc, "\0", "\0"); if (rt->name) { check_strncat_s(strncat_s(alias_name, NAMEDATALEN, rt->name, strlen(rt->name))); } if IsA (rt->val, ColumnRef) { ColumnRef *cr = (ColumnRef *)rt->val; Node *field1 = (Node *)linitial(cr->fields); if IsA (field1, A_Star) continue; ColumnRefData column_ref_data; if (!exprProcessor::expand_column_ref(cr, column_ref_data)) { return false; } if (strcmp(alias_name, "") != 0) { col_alias_map->set(alias_name, column_ref_data.m_alias_fqdn, strlen(column_ref_data.m_alias_fqdn)); } else { /* hack for not having empty map as it needed for is_set_operation_allowed_on_datatype */ col_alias_map->set(column_ref_data.m_alias_fqdn, column_ref_data.m_alias_fqdn, strlen(column_ref_data.m_alias_fqdn)); } } else if IsA (rt->val, FuncCall) { FuncCall* fc = (FuncCall*)rt->val; func_name_data func_name; exprProcessor::expand_function_name(fc, func_name); CachedProc* cached_proc = statement_data->GetCacheManager()->get_cached_proc(NameStr(func_name.m_catalogName), NameStr(func_name.m_schemaName), NameStr(func_name.m_functionName)); if (cached_proc) { const char* fname = alias_name && strlen(alias_name) > 0 ? alias_name : func_name.m_functionName.data; statement_data->conn->client_logic->insert_function(fname, cached_proc); } } } } } return true; } bool Processor::is_set_operation_allowed(const SelectStmt * const select_stmt, const ICachedColumns *cached_columns, const SetOperation &parent_select_operation, const bool &parent_all, StatementData *statement_data) { /* check whether operations on sets are allowed on this data type (UNION,INTERSECT,ETC) */ CStringsMap col_alias_map; if (!get_column_names_from_target_list(select_stmt->targetList, &col_alias_map, statement_data)) { return false; } /* check if SET OPERATION is allowed on all of the data types */ bool is_union_all = (parent_select_operation == SETOP_UNION && parent_all); const bool isSetOperation = (parent_select_operation != SETOP_NONE && !is_union_all); if (isSetOperation && !is_set_operation_allowed_on_datatype(cached_columns, col_alias_map)) { printfPQExpBuffer(&statement_data->conn->errorMessage, "ERROR(CLIENT): set operations are not allowed on randomized encrypted column\n"); return false; } return true; } /* from a, (select * from b), c join d */ bool Processor::run_pre_from_list_statement(const List * const from_list, StatementData *statement_data, ICachedColumns *cached_columns, const ICachedColumns* cached_columns_parents) { ListCell *fl = NULL; foreach (fl, from_list) { Node *n = (Node *)lfirst(fl); if (!run_pre_from_item_statement(n, statement_data, cached_columns, cached_columns_parents)) { return false; } } return true; } bool Processor::run_pre_range_statement(const RangeVar * const range_var, StatementData *statement_data, ICachedColumns *cached_columns, const ICachedColumns* cached_columns_parents) { CachedColumns cached_column_range(false); statement_data->conn->client_logic->m_cached_column_manager->get_cached_columns(range_var, &cached_column_range); for (size_t i = 0; i < cached_column_range.size(); i++) { CachedColumn *range_cached = new (std::nothrow) CachedColumn(cached_column_range.at(i)); if (range_cached == NULL) { fprintf(stderr, "failed to new CachedColumn object\n"); return false; } cached_columns->push(range_cached); } if (cached_columns_parents != NULL) { for (size_t i = 0; i < cached_columns_parents->size(); i++) { if (range_var->relname != NULL && strcmp(cached_columns_parents->at(i)->get_table_name(), range_var->relname) == 0) { CachedColumn *range_cached = new (std::nothrow) CachedColumn(cached_columns_parents->at(i)); if (range_cached == NULL) { fprintf(stderr, "failed to new CachedColumn object\n"); return false; } cached_columns->push(range_cached); } } } return true; } /* from a as alias , (select * from b), c join d */ bool Processor::run_pre_from_item_statement(const Node * const from_item, StatementData *statement_data, ICachedColumns *cached_columns, const ICachedColumns* cached_columns_parents) { CachedColumns cached_column_temp(false, true); bool if_alias = false; char *alias_name(NULL); if (IsA(from_item, RangeSubselect)) { SelectStmt *select_stmt_node = (SelectStmt *)((RangeSubselect *)from_item)->subquery; SetOperation set_operation(SETOP_NONE); bool all(false); if (!run_pre_select_statement(select_stmt_node, set_operation, all, statement_data, &cached_column_temp)) { return false; } if (((RangeSubselect *)from_item)->alias != NULL) { if_alias = true; alias_name = ((RangeSubselect *)from_item)->alias->aliasname; } } else if (IsA(from_item, JoinExpr)) { if (!run_pre_join_statement((JoinExpr *)from_item, statement_data, &cached_column_temp)) { return false; } } else if (IsA(from_item, RangeVar)) { RangeVar *range_var = (RangeVar *)from_item; if (range_var == NULL) { return false; } if (range_var->alias != NULL) { if_alias = true; alias_name = range_var->alias->aliasname; } if (!run_pre_range_statement(range_var, statement_data, &cached_column_temp, cached_columns_parents)) { return false; } } else if (IsA(from_item, RangeFunction)) { RangeFunction* range_func = (RangeFunction*)from_item; ExprPartsList func_expr_parts_list; if (range_func->funccallnode) { if (handle_func_call((const FuncCall*)range_func->funccallnode, &func_expr_parts_list, statement_data)) { func_processor::process(&func_expr_parts_list, statement_data); } } } for (size_t i = 0; i < cached_column_temp.size(); i++) { CachedColumn *alias_cached = new (std::nothrow) CachedColumn(cached_column_temp.at(i)); if (alias_cached == NULL) { fprintf(stderr, "failed to new CachedColumn object\n"); return false; } if (if_alias) { alias_cached->set_table_name(alias_name); } cached_columns->push(alias_cached); } return true; } /* with cte1 as (), cte2 as () */ bool Processor::run_pre_with_list_statement(const List * const with_list, StatementData *statement_data, ICachedColumns *cached_columns) { ListCell *fl = NULL; foreach (fl, with_list) { Node *n = (Node *)lfirst(fl); if (!run_pre_with_item_statement(n, statement_data, cached_columns)) { return false; } } return true; } /* with cte [name list]as (insert/update/delete/select) */ bool Processor::run_pre_with_item_statement(const Node * const with_item, StatementData *statement_data, ICachedColumns *cached_columns) { bool re = true; CommonTableExpr *with_cte = (CommonTableExpr *)with_item; Node *n = with_cte->ctequery; CachedColumns cached_columns_sub(false, true); switch (nodeTag(n)) { case T_InsertStmt: re = run_pre_insert_statement((InsertStmt *)n, statement_data, &cached_columns_sub); break; case T_DeleteStmt: re = run_pre_delete_statement((DeleteStmt *)n, statement_data, &cached_columns_sub); break; case T_UpdateStmt: re = run_pre_update_statement((UpdateStmt *)n, statement_data, &cached_columns_sub); break; case T_SelectStmt: { SetOperation set_operation(SETOP_NONE); bool all(false); CachedColumns cached_columns_sub(false, true); re = run_pre_select_statement((SelectStmt *)n, set_operation, all, statement_data, &cached_columns_sub); } default: break; } size_t col_index = 0; for (; col_index < cached_columns_sub.size(); col_index++) { CachedColumn *alias_cached = new (std::nothrow) CachedColumn(cached_columns_sub.at(col_index)); if (alias_cached == NULL) { fprintf(stderr, "failed to new CachedColumn object\n"); return false; } alias_cached->set_table_name(with_cte->ctename); cached_columns->push(alias_cached); } return re; } /* from a join b */ bool Processor::run_pre_join_statement(const JoinExpr * const join_stmt, StatementData *statement_data, ICachedColumns *cached_columns) { CachedColumns cached_larg(false); if (!run_pre_from_item_statement(join_stmt->larg, statement_data, &cached_larg)) { return false; } CachedColumns cached_rarg(false); if (!run_pre_from_item_statement(join_stmt->rarg, statement_data, &cached_rarg)) { return false; } cached_columns->append(&cached_larg); cached_columns->append(&cached_rarg); if (join_stmt->quals) { ExprPartsList equal_clause; CachedColumns cached_euqal(false); if (!exprProcessor::expand_expr(join_stmt->quals, statement_data, &equal_clause)) { return false; } bool is_operator_forbidden(false); statement_data->conn->client_logic->m_cached_column_manager->filter_cached_columns(cached_columns, &equal_clause, is_operator_forbidden, &cached_euqal); if (is_operator_forbidden) { printfPQExpBuffer(&statement_data->conn->errorMessage, "ERROR(CLIENT): euqal operator is not allowed on datatype of this column\n"); return false; } if (!WhereClauseProcessor::process(cached_columns, &equal_clause, statement_data)) { return false; } } else if (join_stmt->usingClause) { if (!join_with_same_key(join_stmt->usingClause, &cached_larg, &cached_rarg, statement_data)) { return false; } } else if (join_stmt->isNatural) { /* from a natural join b we need to judge each column which have the same name in a and b shares the same key */ for (size_t i = 0; i < cached_larg.size(); i++) { for (size_t j = 0; j < cached_rarg.size(); j++) { const ICachedColumn *cached_left = cached_larg.at(i); const ICachedColumn *cached_right = cached_rarg.at(j); if ((cached_left) && (cached_right) && strcmp(cached_left->get_col_name(), cached_right->get_col_name()) == 0) { ColumnHookExecutor *larg_exe = cached_left->get_column_hook_executors()->at(0); ColumnHookExecutor *rarg_exe = cached_right->get_column_hook_executors()->at(0); if (larg_exe != rarg_exe) { printfPQExpBuffer(&statement_data->conn->errorMessage, "ERROR(CLIENT): Natural join is not allowed on columns with different keys\n"); return false; } } } } } return true; } bool Processor::join_with_same_key(List *usingClause, ICachedColumns *cached_larg, ICachedColumns *cached_rarg, StatementData *statement_data) { /* from a join b using (id) we need to judge id in a and id in b share the same key */ ListCell *tl = NULL; foreach (tl, usingClause) { char *column = strVal(lfirst(tl)); for (size_t i = 0; i < cached_larg->size(); i++) { const ICachedColumn *cached_left = cached_larg->at(i); if ((cached_left) && strcmp(cached_left->get_col_name(), column) == 0) { for (size_t j = 0; j < cached_rarg->size(); j++) { const ICachedColumn *cached_right = cached_rarg->at(j); if ((cached_right) && strcmp(cached_right->get_col_name(), column) == 0) { ColumnHookExecutor *larg_exe = cached_left->get_column_hook_executors()->at(0); ColumnHookExecutor *rarg_exe = cached_right->get_column_hook_executors()->at(0); if (larg_exe != rarg_exe) { printfPQExpBuffer(&statement_data->conn->errorMessage, "ERROR(CLIENT): equal operator is not allowed on columns with different keys\n"); return false; } } } } } } return true; } bool Processor::process_res_target(ResTarget* resTarget, StatementData* statementData, ExprPartsList* funcExprPartsList) { if (resTarget) { if (nodeTag(resTarget->val) == T_FuncCall) { return handle_func_call((FuncCall*)resTarget->val, funcExprPartsList, statementData); } } return true; } bool Processor::run_pre_select_target_list(List* targetList, StatementData* statementData, ExprPartsList* funcExprPartsList) { ListCell* listNode = NULL; if (targetList) { foreach (listNode, targetList) { Node* n = (Node*)lfirst(listNode); if (nodeTag(n) == T_ResTarget) { if (!process_res_target((ResTarget*)n, statementData, funcExprPartsList)) { return false; } } } } return true; } bool Processor::run_pre_select_statement(const SelectStmt * const select_stmt, StatementData *statement_data) { SetOperation set_operation(SETOP_NONE); bool all(false); CachedColumns cached_columns(false, true); CachedColumns cached_columns_parents(false, true); return run_pre_select_statement(select_stmt, set_operation, all, statement_data, &cached_columns, &cached_columns_parents); } bool Processor::run_pre_select_statement(const SelectStmt * const select_stmt, const SetOperation &parent_set_operation, const bool &parent_all, StatementData *statement_data, ICachedColumns *cached_columns, ICachedColumns *cached_columns_parents) { if (statement_data->GetCacheManager()->is_cache_empty()) { return true; } bool select_res = false; /* recurse over SELECT's for SET operations such as UNION/INTERSECT/ETC. */ if (select_stmt->op != SETOP_NONE) { select_res = process_select_set_operation(select_stmt, statement_data, cached_columns); RETURN_IF(!select_res, false); } /* Handle function calls */ ExprPartsList func_expr_parts_list; if (!run_pre_select_target_list(select_stmt->targetList, statement_data, &func_expr_parts_list)) { return false; } /* procees fuction calls */ if (!func_processor::process(&func_expr_parts_list, statement_data)) { return false; } /* handle single WHERE and HAVING statement */ ExprPartsList where_expr_parts_list; select_res = exprProcessor::expand_expr(select_stmt->whereClause, statement_data, &where_expr_parts_list); RETURN_IF(!select_res, false); ExprPartsList having_expr_vec; select_res = exprProcessor::expand_expr(select_stmt->havingClause, statement_data, &having_expr_vec); RETURN_IF(!select_res, false); /* * filtered_cached_where get all columns relevant for this query's where clause * filtered_cached_having get all columns relevant for this query's haing clause * cached_columns_from get all columns relevant for this query's from clause * cachedColumns get all columns relevant for this query's target list */ bool is_operator_forbidden(false); CachedColumns filtered_cached_where(false); CachedColumns filtered_cached_having(false); CachedColumns cached_columns_from(false, true); /* get target list */ CStringsMap target_list; select_res = get_column_names_from_target_list(select_stmt->targetList, &target_list, statement_data); RETURN_IF(!select_res, false); /* from (select *) */ if (select_stmt->withClause) { if (!run_pre_with_list_statement(select_stmt->withClause->ctes, statement_data, cached_columns_parents)) { return false; } } select_res = run_pre_from_list_statement(select_stmt->fromClause, statement_data, &cached_columns_from, cached_columns_parents); RETURN_IF(!select_res, false); statement_data->conn->client_logic->m_cached_column_manager->filter_cached_columns(&cached_columns_from, &where_expr_parts_list, is_operator_forbidden, &filtered_cached_where); if (is_operator_forbidden) { printfPQExpBuffer(&statement_data->conn->errorMessage, "ERROR(CLIENT): operator is not allowed on datatype of this column\n"); return false; } statement_data->conn->client_logic->m_cached_column_manager->filter_cached_columns(&cached_columns_from, &having_expr_vec, is_operator_forbidden, &filtered_cached_where); if (is_operator_forbidden) { printfPQExpBuffer(&statement_data->conn->errorMessage, "ERROR(CLIENT): operator is not allowed on datatype of this column\n"); return false; } for (size_t i = 0; i < cached_columns_from.size(); i++) { if (find_in_name_map(target_list, cached_columns_from.at(i)->get_col_name())) { CachedColumn *target = new (std::nothrow) CachedColumn(cached_columns_from.at(i)); if (target == NULL) { fprintf(stderr, "failed to new CachedColumn object\n"); return false; } cached_columns->push(target); } } if (cached_columns_from.is_empty()) { return true; /* nothing to do */ } if (is_operator_forbidden) { printfPQExpBuffer(&statement_data->conn->errorMessage, "ERROR(CLIENT): operator is not allowed on datatype of this column\n"); return false; } /* check if operation is already on all columns (basesd on their data types) only with target list */ if (!is_set_operation_allowed(select_stmt, cached_columns, parent_set_operation, parent_all, statement_data)) { return false; } if (!deal_order_by_statement(select_stmt, cached_columns, statement_data)) { return false; } if (!select_stmt->whereClause && !select_stmt->havingClause) { return true; } /* rewrite WHERE statement clause and having clause the query */ if (!WhereClauseProcessor::process(&cached_columns_from, &where_expr_parts_list, statement_data, &target_list)) { return false; } if (!WhereClauseProcessor::process(&cached_columns_from, &having_expr_vec, statement_data, &target_list)) { return false; } return true; } bool Processor::process_select_set_operation(const SelectStmt * const select_stmt, StatementData *statement_data, ICachedColumns *cached_columns) { /* recursion */ CachedColumns cached_larg(false, true); if (!run_pre_select_statement(select_stmt->larg, select_stmt->op, select_stmt->all, statement_data, &cached_larg)) { return false; } CachedColumns cached_rarg(false, true); if (!run_pre_select_statement(select_stmt->rarg, select_stmt->op, select_stmt->all, statement_data, &cached_rarg)) { return false; } /* * func : 1. need to judge each cachedcolumn's key in cached_larg exists in cached_rarg. * 2. need to judge |cached_larg| equals |cached_rarg|. */ if (cached_larg.size() != cached_rarg.size()) { printfPQExpBuffer(&statement_data->conn->errorMessage, "ERROR(CLIENT): set operator is not allowed on columns with different keys\n"); return false; } for (size_t i = 0; i < cached_larg.size(); ++i) { ColumnHookExecutor *larg_exe = cached_larg.at(i)->get_column_hook_executors()->at(0); ColumnHookExecutor *rarg_exe = cached_rarg.at(i)->get_column_hook_executors()->at(0); Oid lorigdatatype_oid = cached_larg.at(i)->get_origdatatype_oid(); Oid rorigdatatype_oid = cached_rarg.at(i)->get_origdatatype_oid(); if (larg_exe != rarg_exe) { printfPQExpBuffer(&statement_data->conn->errorMessage, "ERROR(CLIENT): set operator is not allowed on columns with different keys\n"); return false; } else if (lorigdatatype_oid != rorigdatatype_oid) { printfPQExpBuffer(&statement_data->conn->errorMessage, "ERROR(CLIENT): set operator is not allowed on columns with different type\n"); return false; } } for (size_t i = 0; i < cached_larg.size(); i++) { CachedColumn *set_cached = new (std::nothrow) CachedColumn(cached_larg.at(i)); if (set_cached == NULL) { fprintf(stderr, "failed to new CachedColumn object\n"); return false; } cached_columns->push(set_cached); } return true; } bool Processor::run_pre_delete_statement(const DeleteStmt *delete_stmt, StatementData *statement_data, ICachedColumns *cached_columns) { /* checking if featue is in use */ if (statement_data->GetCacheManager()->is_cache_empty()) { return true; // nothing to do } /* handle single WHERE statement */ ExprPartsList where_expr_parts_list; if (!exprProcessor::expand_expr(delete_stmt->whereClause, statement_data, &where_expr_parts_list)) { return false; } /* get all columns relevant for this query's where clause */ bool is_operator_forbidden(false); CachedColumns cached_column_temp(false, true); CachedColumns filter_cached_columns_temp(false); CachedColumns filter_cached_columns(false, true); bool ret = statement_data->GetCacheManager()->get_cached_columns(delete_stmt, &where_expr_parts_list, is_operator_forbidden, &cached_column_temp); if (is_operator_forbidden) { printfPQExpBuffer(&statement_data->conn->errorMessage, "ERROR(CLIENT): operator is not allowed on datatype of this column\n"); return false; } if (!ret || cached_column_temp.is_empty()) { return true; /* nothing to do */ } /* return list is useful for with cte as () */ if (!run_pre_returning_list_statement(delete_stmt->returningList, &cached_column_temp, cached_columns, statement_data)) { return false; } ret = statement_data->GetCacheManager()->filter_cached_columns(&cached_column_temp, &where_expr_parts_list, is_operator_forbidden, &filter_cached_columns_temp); if (is_operator_forbidden) { printfPQExpBuffer(&statement_data->conn->errorMessage, "ERROR(CLIENT): operator is not allowed on datatype of this column\n"); return false; } if (!ret) { return false; } for (size_t i = 0; i < filter_cached_columns_temp.size(); i++) { if (filter_cached_columns_temp.at(i) == NULL) { filter_cached_columns.push(NULL); } else { CachedColumn *filter_cached = new (std::nothrow) CachedColumn(filter_cached_columns_temp.at(i)); if (filter_cached == NULL) { fprintf(stderr, "failed to new CachedColumn object\n"); return false; } filter_cached_columns.push(filter_cached); } } /* rewrite WHERE statement clause in the query */ if (!WhereClauseProcessor::process(&filter_cached_columns, &where_expr_parts_list, statement_data)) { return false; }; return true; } bool Processor::run_pre_prepare_statement(const PrepareStmt *prepare_stmt, StatementData *statement_data) { if (statement_data->GetCacheManager()->is_cache_empty()) return true; /* * func : call create() function instead but * we need to make sure to always delete the prepared statements when they * are no longer in use */ statement_data->conn->client_logic->pendingStatements->get_or_create(prepare_stmt->name); statement_data->stmtName = prepare_stmt->name; return run_pre_statement(prepare_stmt->query, statement_data); } bool Processor::run_pre_execute_statement(const ExecuteStmt * const execute_stmt, StatementData *statement_data) { if (statement_data->GetCacheManager()->is_cache_empty()) return true; PreparedStatement *prepares_statement = statement_data->conn->client_logic->preparedStatements->get_or_create(execute_stmt->name); if (!prepares_statement) { return false; } if (!prepares_statement->cached_params || prepares_statement->cached_params->is_empty()) { /* no processed columns */ return true; } RawValuesList raw_values_list; bool ret = RawValues::get_raw_values_from_execute_statement(execute_stmt, statement_data, &raw_values_list); if (!ret) { fprintf(stderr, "error getting raw valued from statment\n"); return false; } return ValuesProcessor::process_values(statement_data, prepares_statement->cached_params, 1, &raw_values_list); } bool Processor::run_pre_declare_cursor_statement(const DeclareCursorStmt * const declareCursorStmt, StatementData *statement_data) { if (statement_data->GetCacheManager()->is_cache_empty()) { return true; } return run_pre_statement(declareCursorStmt->query, statement_data); } bool Processor::run_pre_copy_statement(const CopyStmt * const copy_stmt, StatementData *statement_data) { /* checking if feature is in use */ if (statement_data->GetCacheManager()->is_cache_empty()) { return true; /* nothing to do */ } if (copy_stmt->filename || copy_stmt->encrypted) { // we have a file the data will not pass through the client fprintf(stderr, "ERROR(CLIENT): column encryption does't support copy from server file to table\n"); return false; } if (copy_stmt->query) /* we have a COPY FILE statement so the data is not passed through the client - it's a server side operation. */ if (copy_stmt->filename) { // nothing to do return true; } PreparedStatement *prepared_statement = NULL; if (copy_stmt->query) { /* * we have a "COPY (stmt) TO STDOUT" query * make sure that the query is a SELECT statement and that the SELECT statement is valid */ if (nodeTag(copy_stmt->query) != T_SelectStmt) return false; if (!run_pre_select_statement((SelectStmt *)copy_stmt->query, statement_data)) return false; } else if (copy_stmt->relation) { /* * "COPY <relation> FROM STDIN" requires us to build a cached columns list for the csv that will be inserted * "COPY <relation> TO STDOUT" does not need any more processing */ if (copy_stmt->is_from) { /* "COPY <relation> FROM STDIN" */ prepared_statement = statement_data->conn->client_logic->pendingStatements->get_or_create(statement_data->stmtName); if (!prepared_statement) { fprintf(stderr, "failed to get PreparedStatement object\n"); return false; } if (!prepared_statement->cached_copy_columns) { prepared_statement->cached_copy_columns = new (std::nothrow) CachedColumns; if (prepared_statement->cached_copy_columns == NULL) { fprintf(stderr, "failed to new CachedColumns object\n"); return false; } } statement_data->GetCacheManager()->get_cached_columns(copy_stmt, prepared_statement->cached_copy_columns); prepared_statement->partial_csv_column_size = 0; } } else { /* shouldn't get here */ return false; } if (!prepared_statement) { prepared_statement = statement_data->conn->client_logic->pendingStatements->get_or_create(statement_data->stmtName); } if (!prepared_statement) { return false; } delete_copy_state(prepared_statement->copy_state); prepared_statement->copy_state = pre_copy(copy_stmt, statement_data->query); return true; } bool Processor::run_pre_alter_table_statement(const AlterTableStmt *stmt, StatementData *statement_data) { const List *cmds = reinterpret_cast<const AlterTableStmt * const>(stmt)->cmds; CachedColumns cached_columns; if (!statement_data->GetCacheManager()->get_cached_columns(stmt->relation, &cached_columns)) { return false; } ListCell *iter = NULL; foreach (iter, cmds) { const AlterTableCmd *cmd = (AlterTableCmd *)lfirst(iter); switch (cmd->subtype) { case AT_AddColumn: { /* ALTER TABLE ADD COLUMN */ ColumnDef *def = (ColumnDef *)cmd->def; if (def->clientLogicColumnRef) { ExprPartsList expr_vec; if (!(def->clientLogicColumnRef->column_key_name)) { fprintf(stderr, "ERROR(CLIENT): column encryption key cannot be empty\n"); return false; } char column_key_name[NAMEDATALEN * NAME_CNT]; errno_t rc = EOK; rc = memset_s(column_key_name, NAMEDATALEN * NAME_CNT, 0, NAMEDATALEN * NAME_CNT); securec_check_c(rc, "\0", "\0"); if (!name_list_to_cstring(def->clientLogicColumnRef->column_key_name, column_key_name, sizeof(column_key_name))) { fprintf(stderr, "ERROR(CLIENT): column encryption key name cannot be empty\n"); return false; } char object_fqdn[NAMEDATALEN * NAME_CNT]; rc = memset_s(object_fqdn, NAMEDATALEN * NAME_CNT, 0, NAMEDATALEN * NAME_CNT); securec_check_c(rc, "\0", "\0"); size_t object_fqdn_size = statement_data->GetCacheManager()->get_object_fqdn(column_key_name, false, object_fqdn); if (object_fqdn_size == 0) { statement_data->conn->client_logic->cacheRefreshType = CacheRefreshType::CACHE_ALL; statement_data->GetCacheManager()->load_cache(statement_data->conn); object_fqdn_size = statement_data->GetCacheManager()->get_object_fqdn(column_key_name, false, object_fqdn); if (object_fqdn_size == 0) { fprintf(stderr, "ERROR(CLIENT): error while trying to retrieve column encryption key from cache\n"); return false; } } /* add DATATYPE_CL to "client logic" column */ CachedColumns cached_columns(false, true); CachedColumns cached_columns_for_replace; bool error = false; RawValue *raw_value = createStmtProcessor::trans_column_definition(def, &expr_vec, &cached_columns, &cached_columns_for_replace, statement_data, object_fqdn, error); RETURN_IF(error, false); if (raw_value) { PreparedStatement *prepared_statement = statement_data->conn->client_logic->pendingStatements->get_or_create( statement_data->stmtName); if (prepared_statement) { prepared_statement->cacheRefresh |= CacheRefreshType::COLUMNS; } statement_data->conn->client_logic->rawValuesForReplace->add(raw_value); } if (expr_vec.empty()) { continue; } /* process default value in column definition */ RawValuesList raw_values_list; bool res = RawValues::get_raw_values_from_consts_vec(&expr_vec, statement_data, 0, &raw_values_list); RETURN_IF(!res, false); res = ValuesProcessor::process_values(statement_data, &cached_columns_for_replace, 1, &raw_values_list); RETURN_IF(!res, false); } continue; } case AT_DropColumn:{ const ICachedColumn *cached_column = statement_data->GetCacheManager()->get_cached_column( stmt->relation->catalogname, stmt->relation->schemaname, stmt->relation->relname, cmd->name); if (!cached_column) { continue; } PreparedStatement *prepared_statement = statement_data->conn->client_logic->pendingStatements->get_or_create( statement_data->stmtName); if (prepared_statement) { prepared_statement->cacheRefresh |= CacheRefreshType::COLUMNS; } break; } case AT_ColumnDefault: { ExprPartsList expr_vec; const ICachedColumn *cached_column = statement_data->GetCacheManager()->get_cached_column( stmt->relation->catalogname, stmt->relation->schemaname, stmt->relation->relname, cmd->name); if (!cached_column) { continue; } CachedColumns cached_columns; cached_columns.push(cached_column); bool expr_res = exprProcessor::expand_expr(cmd->def, statement_data, &expr_vec); RETURN_IF(!expr_res, false); if (expr_vec.empty()) { continue; } RawValuesList raw_values_list; expr_res = RawValues::get_raw_values_from_consts_vec(&expr_vec, statement_data, 0, &raw_values_list); RETURN_IF(!expr_res, false); return ValuesProcessor::process_values(statement_data, &cached_columns, 1, &raw_values_list); } case AT_AddConstraint: { if (!alter_add_constraint(cmd, &cached_columns, statement_data)) { return false; } break; } default: continue; } } return true; } bool Processor::alter_add_constraint(const AlterTableCmd *cmd, ICachedColumns *cached_columns, StatementData *statement_data) { if (IsA(cmd->def, Constraint)) { Constraint * constraint = (Constraint *)cmd->def; if (constraint->keys != NULL) { ListCell *ixcell = NULL; foreach (ixcell, constraint->keys) { char *ikname = strVal(lfirst(ixcell)); for (size_t i = 0; i < cached_columns->size(); i++) { if (cached_columns->at(i)->get_col_name() != NULL && strcmp(cached_columns->at(i)->get_col_name(), ikname) == 0 && !createStmtProcessor::check_constraint(constraint, cached_columns->at(i)->get_data_type(), ikname, cached_columns, statement_data)) { return false; } } } } else if (constraint->raw_expr != NULL) { if (!createStmtProcessor::transform_expr(constraint->raw_expr, "", cached_columns, statement_data)) { return false; } } } else { fprintf(stderr, "ERROR(CLIENT): unrecognized node type: %d\n", (int)nodeTag(cmd->def)); } return true; } bool Processor::run_pre_drop_table_statement(const DropStmt *stmt, StatementData *statement_data) { ListCell *cell = NULL; bool need_refresh = false; foreach (cell, stmt->objects) { List *names = (List *)lfirst(cell); char *relname = NULL; char *schemaname = NULL; char *catalogname = NULL; switch (list_length(names)) { case 1: relname = strVal(linitial(names)); break; case 2: schemaname = strVal(linitial(names)); relname = strVal(lsecond(names)); break; case 3: catalogname = strVal(linitial(names)); schemaname = strVal(lsecond(names)); relname = strVal(lthird(names)); break; default: char full_table_name[NAMEDATALEN * NAME_CNT]; errno_t rc = EOK; rc = memset_s(full_table_name, NAMEDATALEN * NAME_CNT, 0, NAMEDATALEN * NAME_CNT); securec_check_c(rc, "\0", "\0"); name_list_to_cstring(names, full_table_name, sizeof(full_table_name)); fprintf(stderr, "ERROR(CLIENT): improper relation name (too many dotted names): %s\n", full_table_name); break; } if (statement_data->GetCacheManager()->has_cached_columns(catalogname, schemaname, relname)) { need_refresh = true; } } if (need_refresh) { PreparedStatement *prepared_statement = statement_data->conn->client_logic->pendingStatements->get_or_create(statement_data->stmtName); if (!prepared_statement) { return false; } prepared_statement->cacheRefresh |= CacheRefreshType::COLUMNS; } return true; } bool Processor::run_pre_drop_schema_statement(const DropStmt *stmt, StatementData *statement_data) { /* * check if the schema is not empty * and only if it is not empty and the schema is about to be removed (DROP CASCADE) * then invoke the cache to reload */ bool is_schema_contains_objects = false; ListCell *cell = NULL; foreach (cell, stmt->objects) { List *objname = (List *)lfirst(cell); char schema_name[NAMEDATALEN * 2]; errno_t rc = EOK; rc = memset_s(schema_name, NAMEDATALEN * 2, 0, NAMEDATALEN * 2); securec_check_c(rc, "\0", "\0"); if (!name_list_to_cstring(objname, schema_name, sizeof(schema_name))) { return false; } /* extend array if required */ if (statement_data->conn->client_logic->droppedSchemas_size + 1 > statement_data->conn->client_logic->droppedSchemas_allocated) { statement_data->conn->client_logic->droppedSchemas = (ObjectFqdn *)libpq_realloc(statement_data->conn->client_logic->droppedSchemas, sizeof(*statement_data->conn->client_logic->droppedSchemas) * statement_data->conn->client_logic->droppedSchemas_size, sizeof(*statement_data->conn->client_logic->droppedSchemas) * (statement_data->conn->client_logic->droppedSchemas_size + 1)); if (statement_data->conn->client_logic->droppedSchemas == NULL) { return false; } statement_data->conn->client_logic->droppedSchemas_allocated = statement_data->conn->client_logic->droppedSchemas_size + 1; } /* copy object name */ check_strncpy_s(strncpy_s( statement_data->conn->client_logic->droppedSchemas[statement_data->conn->client_logic->droppedSchemas_size] .data, sizeof(statement_data->conn->client_logic ->droppedSchemas[statement_data->conn->client_logic->droppedSchemas_size]), schema_name, strlen(schema_name))); ++statement_data->conn->client_logic->droppedSchemas_size; if (statement_data->GetCacheManager()->is_schema_contains_objects(schema_name)) { is_schema_contains_objects = true; break; } } /* check if objects are going to be dropped */ if (stmt->behavior != DROP_CASCADE || !is_schema_contains_objects) { return true; } PreparedStatement *prepared_statement = statement_data->conn->client_logic->pendingStatements->get_or_create(statement_data->stmtName); if (!prepared_statement) { return false; } prepared_statement->cacheRefresh |= CacheRefreshType::GLOBAL_SETTING; prepared_statement->cacheRefresh |= CacheRefreshType::COLUMN_SETTING; prepared_statement->cacheRefresh |= CacheRefreshType::COLUMNS; return true; } bool Processor::run_pre_drop_statement(const DropStmt *stmt, StatementData *statement_data) { /* * update the (prepared) statement's object's cacheRefresh value according to the DROP statement in progress * this value will be used in the PostQuery to override the value of the cacheRefresh in the session and then used * in the load_cache function */ if (stmt->removeType == OBJECT_GLOBAL_SETTING) { ListCell *cell = NULL; char object_name[NAMEDATALEN * NAME_CNT]; errno_t rc = EOK; ObjName *to_drop_cmk_list = NULL; rc = memset_s(object_name, NAMEDATALEN * NAME_CNT, 0, NAMEDATALEN * NAME_CNT); securec_check_c(rc, "\0", "\0"); foreach (cell, stmt->objects) { /* get object name */ List *names = (List *)lfirst(cell); if (!name_list_to_cstring(names, object_name, NAMEDATALEN * NAME_CNT)) { return false; } char object_fqdn[NAMEDATALEN * NAME_CNT]; rc = memset_s(object_fqdn, NAMEDATALEN * NAME_CNT, 0, NAMEDATALEN * NAME_CNT); securec_check_c(rc, "\0", "\0"); size_t object_fqdn_size = statement_data->GetCacheManager()->get_object_fqdn(object_name, true, object_fqdn); /* skip if the object doesn't exist */ if (object_fqdn_size == 0) { continue; } check_strncpy_s(strncpy_s(object_name, NAMEDATALEN * NAME_CNT, object_fqdn, strlen(object_fqdn))); to_drop_cmk_list = obj_list_append(to_drop_cmk_list, object_name); if (to_drop_cmk_list == NULL) { return false; } if (stmt->behavior == DROP_CASCADE) { /* add dependant column settings */ size_t column_settings_list_size(0); const CachedColumnSetting **depened_column_settings = statement_data->GetCacheManager()->get_column_setting_by_global_setting_fqdn(object_name, column_settings_list_size); /* extend array if required */ if (statement_data->conn->client_logic->droppedColumnSettings_size + column_settings_list_size > statement_data->conn->client_logic->droppedColumnSettings_allocated) { statement_data->conn->client_logic->droppedColumnSettings = (ObjectFqdn *)libpq_realloc(statement_data->conn->client_logic->droppedColumnSettings, sizeof(*statement_data->conn->client_logic->droppedColumnSettings) * statement_data->conn->client_logic->droppedColumnSettings_size, sizeof(*statement_data->conn->client_logic->droppedColumnSettings) * (statement_data->conn->client_logic->droppedColumnSettings_size + column_settings_list_size)); if (statement_data->conn->client_logic->droppedColumnSettings == NULL) { libpq_free(depened_column_settings); free_obj_list(to_drop_cmk_list); return false; } statement_data->conn->client_logic->droppedColumnSettings_allocated = statement_data->conn->client_logic->droppedColumnSettings_size + column_settings_list_size; } for (size_t i = 0; i < column_settings_list_size; ++i) { check_strncpy_s(strncpy_s( statement_data->conn->client_logic ->droppedColumnSettings[statement_data->conn->client_logic->droppedColumnSettings_size + i] .data, sizeof( statement_data->conn->client_logic ->droppedColumnSettings[statement_data->conn->client_logic->droppedColumnSettings_size + i].data), depened_column_settings[i]->get_fqdn(), strlen(depened_column_settings[i]->get_fqdn()))); } libpq_free(depened_column_settings); statement_data->conn->client_logic->droppedColumnSettings_size += column_settings_list_size; } } PreparedStatement *prepared_statement = statement_data->conn->client_logic->pendingStatements->get_or_create(statement_data->stmtName); if (!prepared_statement) { free_obj_list(to_drop_cmk_list); return false; } statement_data->conn->client_logic->droppedGlobalSettings = to_drop_cmk_list; prepared_statement->cacheRefresh |= CacheRefreshType::GLOBAL_SETTING; if (stmt->behavior == DROP_CASCADE) { prepared_statement->cacheRefresh |= CacheRefreshType::COLUMN_SETTING; prepared_statement->cacheRefresh |= CacheRefreshType::COLUMNS; } } else if (stmt->removeType == OBJECT_COLUMN_SETTING) { PreparedStatement *prepared_statement = statement_data->conn->client_logic->pendingStatements->get_or_create(statement_data->stmtName); if (!prepared_statement) { return false; } prepared_statement->cacheRefresh |= CacheRefreshType::COLUMN_SETTING; if (stmt->behavior == DROP_CASCADE) { prepared_statement->cacheRefresh |= CacheRefreshType::COLUMNS; } ListCell *cell = NULL; char object_name[NAMEDATALEN * NAME_CNT]; foreach (cell, stmt->objects) { /* get object name */ List *names = (List *)lfirst(cell); if (!name_list_to_cstring(names, object_name, NAMEDATALEN * NAME_CNT)) { return false; } char object_fqdn[NAMEDATALEN * NAME_CNT]; errno_t rc = EOK; rc = memset_s(object_fqdn, NAMEDATALEN * NAME_CNT, 0, NAMEDATALEN * NAME_CNT); securec_check_c(rc, "\0", "\0"); size_t object_fqdn_size = statement_data->GetCacheManager()->get_object_fqdn(object_name, false, object_fqdn); /* skip if the object doesn't exist */ if (object_fqdn_size == 0) { continue; } check_strncpy_s(strncpy_s(object_name, NAMEDATALEN * NAME_CNT, object_fqdn, object_fqdn_size)); /* extend array if required */ if (statement_data->conn->client_logic->droppedColumnSettings_size + 1 > statement_data->conn->client_logic->droppedColumnSettings_allocated) { statement_data->conn->client_logic->droppedColumnSettings = (ObjectFqdn *)libpq_realloc(statement_data->conn->client_logic->droppedColumnSettings, sizeof(*statement_data->conn->client_logic->droppedColumnSettings) * statement_data->conn->client_logic->droppedColumnSettings_size, sizeof(*statement_data->conn->client_logic->droppedColumnSettings) * (statement_data->conn->client_logic->droppedColumnSettings_size + 1)); if (statement_data->conn->client_logic->droppedColumnSettings == NULL) { return false; } statement_data->conn->client_logic->droppedColumnSettings_allocated = statement_data->conn->client_logic->droppedColumnSettings_size + 1; } /* add dependant column settings copy object name */ check_strncpy_s( strncpy_s(statement_data->conn->client_logic ->droppedColumnSettings[statement_data->conn->client_logic->droppedColumnSettings_size] .data, sizeof(statement_data->conn->client_logic ->droppedColumnSettings[statement_data->conn->client_logic->droppedColumnSettings_size]), object_name, strlen(object_name))); ++statement_data->conn->client_logic->droppedColumnSettings_size; } } else if (stmt->removeType == OBJECT_TABLE || stmt->removeType == OBJECT_VIEW) { run_pre_drop_table_statement(stmt, statement_data); } else if (stmt->removeType == OBJECT_SCHEMA) { run_pre_drop_schema_statement(stmt, statement_data); } else if (stmt->removeType == OBJECT_FUNCTION) { PreparedStatement* prepared_statement = statement_data->conn->client_logic->pendingStatements->get_or_create(statement_data->stmtName); if (!prepared_statement) { return false; } prepared_statement->cacheRefresh |= CacheRefreshType::PROCEDURES; } return true; } bool Processor::run_pre_exec_direct_statement(const ExecDirectStmt *stmt, StatementData *statement_data) { size_t add_length = stmt->location + strlen("\'"); if (add_length <= 0) { return false; } statement_data->params.new_query_size = strlen(statement_data->query); statement_data->params.new_query = (char *)malloc(statement_data->params.new_query_size + 1); if (statement_data->params.new_query == NULL) { return false; } check_strncpy_s(strncpy_s(statement_data->params.new_query, statement_data->params.new_query_size + 1, statement_data->query, statement_data->params.new_query_size)); statement_data->params.new_query[statement_data->params.new_query_size] = '\0'; StatementData direct_statement_data(statement_data->conn, "", stmt->query, 0, 0, 0, 0, 0); PGconn *conn = direct_statement_data.conn; direct_statement_data.stmtName = direct_statement_data.stmtName ? direct_statement_data.stmtName : ""; if (direct_statement_data.query == nullptr) { return false; } /* func : call create() function instead but we need to make sure to always delete the prepared statements when they * are no longer in use */ conn->client_logic->pendingStatements->get_or_create(direct_statement_data.stmtName); ListCell *stmt_iter = NULL; List *stmts = Parser::Parse(direct_statement_data.conn->client_logic, direct_statement_data.query); foreach (stmt_iter, stmts) { Node *direct_stmt = (Node *)lfirst(stmt_iter); bool client_logic_ret = run_pre_statement(direct_stmt, &direct_statement_data); if (!client_logic_ret) { return false; } } statement_data->conn->client_logic->rawValuesForReplace = direct_statement_data.conn->client_logic->rawValuesForReplace; size_t size = statement_data->conn->client_logic->rawValuesForReplace->size(); statement_data->conn->client_logic->rawValuesForReplace->sort_by_location(); int i = (int)(size - 1); for (; i >= 0; --i) { RawValue *raw_value = statement_data->conn->client_logic->rawValuesForReplace->at(i); if (raw_value == NULL || raw_value->m_processed_data == NULL) { continue; } raw_value->m_location += add_length; unsigned char *processed_data = (unsigned char *)malloc(raw_value->m_processed_data_size + strlen("\'\'")); if (processed_data == NULL) { printfPQExpBuffer(&statement_data->conn->errorMessage, libpq_gettext("ERROR(CLIENT): could not malloc buffer for processed_data\n")); return false; } check_memcpy_s(memcpy_s(processed_data, raw_value->m_processed_data_size + strlen("\'\'"), "'", 1)); check_memcpy_s(memcpy_s(processed_data + 1, raw_value->m_processed_data_size + 1, raw_value->m_processed_data, raw_value->m_processed_data_size)); check_memcpy_s(memcpy_s(processed_data + raw_value->m_processed_data_size + 1, 1, "'", 1)); if (raw_value->m_processed_data != NULL) { free(raw_value->m_processed_data); raw_value->m_processed_data = NULL; } raw_value->m_processed_data = processed_data; raw_value->m_processed_data_size += strlen("\'\'"); } return true; } bool Processor::run_pre_rlspolicy_using(const Node *stmt, StatementData *statement_data) { Node *using_qual = NULL; RangeVar *relation = NULL; if (nodeTag(stmt) == T_CreateRlsPolicyStmt) { using_qual = ((CreateRlsPolicyStmt *)stmt)->usingQual; relation = ((CreateRlsPolicyStmt *)stmt)->relation; } else if (nodeTag(stmt) == T_AlterRlsPolicyStmt) { using_qual = ((AlterRlsPolicyStmt *)stmt)->usingQual; relation = ((AlterRlsPolicyStmt *)stmt)->relation; } ExprPartsList using_expr_parts_list; if (!exprProcessor::expand_expr(using_qual, statement_data, &using_expr_parts_list)) { return false; } /* get all columns relevant for this query's using clause */ bool is_operation_forbidden(false); CachedColumns cached_columns; bool ret = statement_data->GetCacheManager()->get_cached_columns(relation, &using_expr_parts_list, is_operation_forbidden, &cached_columns); if (is_operation_forbidden) { printfPQExpBuffer(&statement_data->conn->errorMessage, "ERROR(CLIENT): operator is not allowed on datatype of this column\n"); return false; } if (!ret || cached_columns.is_empty()) { return true; // nothing to do } /* rewrite using statement clause in the query */ statement_data->params.new_param_values = (unsigned char **)malloc(statement_data->nParams * sizeof(unsigned char *)); if (statement_data->params.new_param_values == NULL) { return false; } statement_data->params.copy_sizes = (size_t *)calloc(sizeof(size_t), statement_data->nParams); if (statement_data->params.copy_sizes == NULL) { return false; } ret = WhereClauseProcessor::process(&cached_columns, &using_expr_parts_list, statement_data); if (!ret) { return false; } if (!process_clause_value(statement_data)) { return false; } return true; } bool Processor::process_clause_value(StatementData *statement_data) { PGClientLogicParams tmp_params(statement_data->params); if (!tmp_params.copy_sizes) { return true; } for (size_t i = 0; i < statement_data->nParams; ++i) { if (tmp_params.new_param_values != NULL && tmp_params.new_param_values[i]) { statement_data->params.new_param_values[i] = (unsigned char *)malloc(tmp_params.copy_sizes[i]); if (statement_data->params.new_param_values[i] == NULL) { return false; } statement_data->params.copy_sizes[i] = tmp_params.copy_sizes[i]; check_memcpy_s(memcpy_s(statement_data->params.new_param_values[i], statement_data->params.copy_sizes[i], tmp_params.new_param_values[i], tmp_params.copy_sizes[i])); } if (statement_data->params.copy_sizes[i] > 0) { statement_data->params.adjusted_param_values[i] = (const char *)(statement_data->params.new_param_values[i]); } } return true; } bool Processor::run_pre_create_rlspolicy_stmt(const CreateRlsPolicyStmt *stmt, StatementData *statement_data) { if (statement_data->GetCacheManager()->is_cache_empty()) { return true; } /* validate input */ if (stmt == nullptr || stmt->relation == nullptr) { return false; } else if (stmt->usingQual == nullptr) { return true; } if (!run_pre_rlspolicy_using((Node *)stmt, statement_data)) { return true; } return true; } bool Processor::run_pre_alter_rlspolicy_stmt(const AlterRlsPolicyStmt *stmt, StatementData *statement_data) { if (statement_data->GetCacheManager()->is_cache_empty()) { return true; } /* validate input */ if (stmt == nullptr || stmt->relation == nullptr) { return false; } else if (stmt->usingQual == nullptr) { return true; } if (!run_pre_rlspolicy_using((Node *)stmt, statement_data)) { return true; } return true; } static void handle_conforming(const VariableSetStmt *set_stmt, StatementData *statement_data) { ListCell *args_iter = NULL; foreach (args_iter, set_stmt->args) { Node *node = (Node *)lfirst(args_iter); if (IsA(node, A_Const)) { A_Const *con = (A_Const *)node; if (IsA((Node *)&con->val, String)) { const char *sval = strVal(&con->val); statement_data->conn->client_logic->val_to_update |= updateGucValues::CONFORMING; if (pg_strcasecmp(sval, "true") == 0 || pg_strcasecmp(sval, "on") == 0 || pg_strcasecmp(sval, "yes") == 0 || pg_strcasecmp(sval, "1") == 0) { statement_data->conn->client_logic->tmpGucParams.standard_conforming_strings = true; } else if (pg_strcasecmp(sval, "false") == 0 || pg_strcasecmp(sval, "off") == 0 || pg_strcasecmp(sval, "no") == 0 || pg_strcasecmp(sval, "0") == 0) { statement_data->conn->client_logic->tmpGucParams.standard_conforming_strings = false; } } } } } static void handle_searchpath_set(const VariableSetStmt *set_stmt, StatementData *statement_data) { ListCell *args_iter = NULL; bool is_first_search_path = true; foreach (args_iter, set_stmt->args) { Node *node = (Node *)lfirst(args_iter); if (IsA(node, A_Const)) { statement_data->conn->client_logic->val_to_update |= updateGucValues::SEARCH_PATH; A_Const *con = (A_Const *)node; if (is_first_search_path && (IsA((Node *)&con->val, String))) { statement_data->conn->client_logic->tmpGucParams.searchpathStr.assign(strVal(&con->val)); is_first_search_path = false; } else if (IsA((Node *)&con->val, String)) { statement_data->conn->client_logic->tmpGucParams.searchpathStr.append(","); statement_data->conn->client_logic->tmpGucParams.searchpathStr.append(strVal(&con->val)); } } } } static void handle_back_slash_quote(const VariableSetStmt *set_stmt, StatementData *statement_data) { ListCell *args_iter = NULL; foreach (args_iter, set_stmt->args) { Node *node = (Node *)lfirst(args_iter); if (IsA(node, A_Const)) { A_Const *con = (A_Const *)node; if (IsA((Node *)&con->val, String)) { const char *sval = strVal(&con->val); statement_data->conn->client_logic->val_to_update |= updateGucValues::BACKSLASH_QUOTE; if (pg_strcasecmp(sval, "true") == 0 || pg_strcasecmp(sval, "on") == 0 || pg_strcasecmp(sval, "yes") == 0 || pg_strcasecmp(sval, "1") == 0) { statement_data->conn->client_logic->tmpGucParams.backslash_quote = BACKSLASH_QUOTE_ON; } else if (pg_strcasecmp(sval, "false") == 0 || pg_strcasecmp(sval, "off") == 0 || pg_strcasecmp(sval, "no") == 0 || pg_strcasecmp(sval, "0") == 0) { statement_data->conn->client_logic->tmpGucParams.backslash_quote = BACKSLASH_QUOTE_OFF; } else if (pg_strcasecmp(sval, "safe_encoding") == 0) { statement_data->conn->client_logic->tmpGucParams.backslash_quote = BACKSLASH_QUOTE_SAFE_ENCODING; } } } } } static void handle_escape_string(const VariableSetStmt *set_stmt, StatementData *statement_data) { ListCell *args_iter = NULL; foreach (args_iter, set_stmt->args) { Node *node = (Node *)lfirst(args_iter); if (IsA(node, A_Const)) { A_Const *con = (A_Const *)node; if (IsA((Node *)&con->val, String)) { const char *sval = strVal(&con->val); statement_data->conn->client_logic->val_to_update |= updateGucValues::ESCAPE_STRING; if (pg_strcasecmp(sval, "true") == 0 || pg_strcasecmp(sval, "on") == 0 || pg_strcasecmp(sval, "yes") == 0 || pg_strcasecmp(sval, "1") == 0) { statement_data->conn->client_logic->tmpGucParams.escape_string_warning = true; } else if (pg_strcasecmp(sval, "false") == 0 || pg_strcasecmp(sval, "off") == 0 || pg_strcasecmp(sval, "no") == 0 || pg_strcasecmp(sval, "0") == 0) { statement_data->conn->client_logic->tmpGucParams.escape_string_warning = false; } } } } } bool Processor::run_pre_set_statement(const VariableSetStmt *set_stmt, StatementData *statement_data) { PreparedStatement *current_statement = statement_data->conn->client_logic->pendingStatements->get_or_create(statement_data->stmtName); if (set_stmt->kind == VAR_RESET_ALL) { if (current_statement == NULL) { return false; } current_statement->cacheRefresh |= CacheRefreshType::SEARCH_PATH; } else if (set_stmt->kind == VAR_SET_ROLEPWD) { statement_data->conn->client_logic->val_to_update |= updateGucValues::GUC_ROLE; current_statement->cacheRefresh |= CacheRefreshType::CACHE_ALL; statement_data->conn->client_logic->tmpGucParams.role = strVal(&((A_Const *)(linitial(set_stmt->args)))->val); } else if (set_stmt->name && (pg_strcasecmp(set_stmt->name, "search_path") == 0 || pg_strcasecmp(set_stmt->name, "current_schema") == 0)) { handle_searchpath_set(set_stmt, statement_data); } else if (set_stmt->name && pg_strcasecmp(set_stmt->name, "backslash_quote") == 0) { handle_back_slash_quote(set_stmt, statement_data); } else if (set_stmt->name && pg_strcasecmp(set_stmt->name, "standard_conforming_strings") == 0) { handle_conforming(set_stmt, statement_data); } else if (set_stmt->name && pg_strcasecmp(set_stmt->name, "escape_string_warning") == 0) { handle_escape_string(set_stmt, statement_data); } else if (set_stmt->name && (pg_strcasecmp(set_stmt->name, "role") == 0 || pg_strcasecmp(set_stmt->name, "session_authorization") == 0)) { if (current_statement == NULL) { return false; } current_statement->cacheRefresh |= CacheRefreshType::CACHE_ALL; } return true; } bool Processor::run_pre_statement(const Node * const stmt, StatementData *statement_data) { if (!stmt) { /* null valued in parser means fe do not care about this value */ return true; } PreparedStatement *current_statement = statement_data->conn->client_logic->pendingStatements->get_or_create(statement_data->stmtName); if (!current_statement) { return false; } switch (nodeTag(stmt)) { case T_InsertStmt: return run_pre_insert_statement((InsertStmt *)stmt, statement_data); case T_DeleteStmt: return run_pre_delete_statement((DeleteStmt *)stmt, statement_data); case T_UpdateStmt: return run_pre_update_statement((UpdateStmt *)stmt, statement_data); break; case T_SelectStmt: return run_pre_select_statement((SelectStmt *)stmt, statement_data); case T_PrepareStmt: return run_pre_prepare_statement((PrepareStmt *)stmt, statement_data); case T_ExecuteStmt: return run_pre_execute_statement((ExecuteStmt *)stmt, statement_data); case T_DeclareCursorStmt: return run_pre_declare_cursor_statement((const DeclareCursorStmt * const)stmt, statement_data); case T_CopyStmt: return run_pre_copy_statement((CopyStmt *)stmt, statement_data); case T_AlterTableStmt: return run_pre_alter_table_statement((AlterTableStmt *)stmt, statement_data); case T_AlterRoleStmt: if (((AlterRoleStmt *)stmt)->options != NIL) { current_statement->cacheRefresh |= CacheRefreshType::CACHE_ALL; } break; case T_CreateStmt: { CreateStmt *create_stmt = (CreateStmt *)stmt; if (create_stmt->relation->relpersistence == RELPERSISTENCE_TEMP) { current_statement->cacheRefresh |= CacheRefreshType::SEARCH_PATH; } return createStmtProcessor::run_pre_create_statement(create_stmt, statement_data); } case T_CreateClientLogicGlobal: current_statement->cacheRefresh |= CacheRefreshType::GLOBAL_SETTING; return run_pre_cached_global_setting(statement_data->conn, statement_data->stmtName, (CreateClientLogicGlobal *)stmt); case T_CreateClientLogicColumn: current_statement->cacheRefresh |= CacheRefreshType::COLUMN_SETTING; return run_pre_column_setting_statement(statement_data->conn, statement_data->stmtName, (CreateClientLogicColumn *)stmt, statement_data->query, statement_data->params); case T_VariableSetStmt: { const VariableSetStmt *set_stmt = (const VariableSetStmt *)stmt; return run_pre_set_statement(set_stmt, statement_data); } case T_ViewStmt: current_statement->cacheRefresh |= CacheRefreshType::COLUMNS; /* rewrite query in the CREATE VIEW clause if query has relevant columns */ return run_pre_select_statement((SelectStmt *)((ViewStmt *)stmt)->query, statement_data); case T_DropStmt: return run_pre_drop_statement((DropStmt *)stmt, statement_data); break; case T_TransactionStmt: if (((TransactionStmt *)stmt)->kind == TRANS_STMT_ROLLBACK) { current_statement->cacheRefresh |= CacheRefreshType::CACHE_ALL; } break; case T_ExecDirectStmt: return run_pre_exec_direct_statement((ExecDirectStmt *)stmt, statement_data); case T_CreateRlsPolicyStmt: return run_pre_create_rlspolicy_stmt((CreateRlsPolicyStmt *)stmt, statement_data); case T_AlterRlsPolicyStmt: return run_pre_alter_rlspolicy_stmt((AlterRlsPolicyStmt *)stmt, statement_data); case T_CreateFunctionStmt: current_statement->cacheRefresh |= CacheRefreshType::PROCEDURES; return func_processor::run_pre_create_function_stmt(((CreateFunctionStmt*)stmt)->options, statement_data); case T_DoStmt: return func_processor::run_pre_create_function_stmt(((DoStmt*)stmt)->args, statement_data, true); case T_MergeStmt: return run_pre_merge_stmt((MergeStmt *)stmt, statement_data); case T_RenameStmt: current_statement->cacheRefresh |= CacheRefreshType::COLUMNS; break; case T_DropRoleStmt: if (((DropRoleStmt *)stmt)->behavior == DROP_CASCADE) { current_statement->cacheRefresh |= CacheRefreshType::GLOBAL_SETTING; } break; default: break; } return true; } bool Processor::run_pre_merge_stmt(const MergeStmt *stmt, StatementData *statement_data) { if (statement_data->GetCacheManager()->is_cache_empty()) { return true; } RETURN_IF(stmt == NULL, false); CachedColumns cached_columns(false, true); RangeVar *target_relation = (RangeVar *)stmt->relation; RangeVar *source_relation = (RangeVar *)stmt->source_relation; CachedColumns target_cached_columns; bool ret = true; ret = statement_data->GetCacheManager()->get_cached_columns(target_relation->catalogname, target_relation->schemaname, target_relation->relname, &target_cached_columns); RETURN_IF(!ret, false); CachedColumns source_cached_columns; ret = statement_data->GetCacheManager()->get_cached_columns(source_relation->catalogname, source_relation->schemaname, source_relation->relname, &source_cached_columns); RETURN_IF(!ret, false); for (size_t col_index = 0; col_index < target_cached_columns.size(); col_index++) { CachedColumn *target_alias_cached = new (std::nothrow) CachedColumn(target_cached_columns.at(col_index)); if (target_alias_cached == NULL) { fprintf(stderr, "failed to new CachedColumn object\n"); return false; } target_alias_cached->set_table_name(target_relation->alias->aliasname); cached_columns.push(target_alias_cached); } for (size_t col_index = 0; col_index < source_cached_columns.size(); col_index++) { CachedColumn *source_alias_cached = new (std::nothrow) CachedColumn(source_cached_columns.at(col_index)); if (source_alias_cached == NULL) { fprintf(stderr, "failed to new CachedColumn object\n"); return false; } source_alias_cached->set_table_name(source_relation->alias->aliasname); cached_columns.push(source_alias_cached); } ExprPartsList join_condition_expr; /* no-support merge into operator when column using different keys to encrypt */ ret = exprProcessor::expand_condition_expr(stmt->join_condition, &join_condition_expr); RETURN_IF(!ret, false); CachedColumns v_res; bool is_source_found = false; bool is_target_found = false; size_t join_exprs_list_size = join_condition_expr.size(); for (size_t i = 0; i < join_exprs_list_size; i++) { const ExprParts *expr_part = join_condition_expr.at(i); RETURN_IF(expr_part == NULL, false); ColumnRefData column_ref_data; ret = exprProcessor::expand_column_ref(expr_part->column_ref, column_ref_data); RETURN_IF(!ret, false); size_t source_cached_columns_size = source_cached_columns.size(); if (!is_target_found) { for (size_t i = 0; i < source_cached_columns_size; i++) { const ICachedColumn *source_tmp = source_cached_columns.at(i); if (source_tmp != NULL && strcmp(source_tmp->get_col_name(), (const char *)(NameStr(column_ref_data.m_column_name))) == 0) { /* found that column is encryped */ v_res.push(source_tmp); is_source_found = true; is_target_found = true; break; } } } if (!is_source_found) { size_t target_cached_columns_size = target_cached_columns.size(); for (size_t i = 0; i < target_cached_columns_size; i++) { const ICachedColumn *target_tmp = source_cached_columns.at(i); if (target_tmp != NULL && strcmp(target_tmp->get_col_name(), (const char *)(NameStr(column_ref_data.m_column_name))) == 0) { /* found that column is encryped */ v_res.push(target_tmp); is_target_found = true; is_source_found = true; break; } } } } ColumnHookExecutor *rarg_exe = NULL; ColumnHookExecutor *larg_exe = NULL; for (size_t i = 0; i < v_res.size(); ++i) { const ICachedColumn *tmp = v_res.at(i); if (i == 0) { larg_exe = tmp->get_column_hook_executors()->at(0); continue; } else if (i == 1) { rarg_exe = tmp->get_column_hook_executors()->at(0); } } if (larg_exe != rarg_exe) { printfPQExpBuffer(&statement_data->conn->errorMessage, "ERROR(CLIENT): operator is not allowed on encrypted columns with different encryption keys\n"); return false; } ListCell *l = NULL; foreach (l, stmt->mergeWhenClauses) { MergeWhenClause *mergeWhenClause = (MergeWhenClause*)lfirst(l); ExprPartsList where_expr_list; ret = exprProcessor::expand_expr(mergeWhenClause->condition, statement_data, &where_expr_list); RETURN_IF(!ret, false); ret = WhereClauseProcessor::process(&cached_columns, &where_expr_list, statement_data); RETURN_IF(!ret, false); } return true; } bool Processor::run_pre_query(StatementData *statement_data, bool is_inner_query, bool *failed_to_parse) { PGconn *conn = statement_data->conn; Assert(conn->client_logic && conn->client_logic->enable_client_encryption); if (statement_data->query == nullptr) { return false; } statement_data->params.adjusted_query = statement_data->query; statement_data->copy_params(); /* * func : call create() function instead but we need to make sure to always delete the prepared statements when they * are no longer in use */ conn->client_logic->pendingStatements->get_or_create(statement_data->stmtName); /* just create a default one */ check_strncat_s(strncat_s(conn->client_logic->lastStmtName, NAMEDATALEN, statement_data->stmtName, strlen(statement_data->stmtName))); ListCell *stmt_iter = NULL; List *stmts = Parser::Parse(statement_data->conn->client_logic, statement_data->query); foreach (stmt_iter, stmts) { Node *stmt = (Node *)lfirst(stmt_iter); if (!run_pre_statement(stmt, statement_data)) { conn->client_logic->pendingStatements->clear(); return false; } } statement_data->replace_raw_values(); if (!is_inner_query) { free_memory(); } else { statement_data->conn->client_logic->rawValuesForReplace->clear(); } /* some callers may want to know if the batch query passed was parsed successfully by the bison parser */ if (failed_to_parse != NULL) { if (stmts != NULL) { *failed_to_parse = false; } else { *failed_to_parse = true; } } return true; } bool Processor::run_pre_exec(StatementData *statement_data) { errno_t rc; Assert(statement_data->conn->client_logic && statement_data->conn->client_logic->enable_client_encryption); statement_data->copy_params(); rc = strncat_s(statement_data->conn->client_logic->lastStmtName, NAMEDATALEN, statement_data->stmtName, strlen(statement_data->stmtName)); securec_check_c(rc, "\0", "\0"); PreparedStatement *prepares_statement = statement_data->conn->client_logic->preparedStatements->get_or_create(statement_data->stmtName); if (!prepares_statement) { return prepares_statement; } if (!prepares_statement->cached_params || prepares_statement->cached_params->is_empty()) { return true; /* no columns to process */ } RawValuesList raw_values_list; raw_values_list.resize(statement_data->nParams); for (size_t param_num = 0; param_num < statement_data->nParams; ++param_num) { RawValue *raw_value = new (std::nothrow) RawValue(statement_data->conn); if (raw_value == NULL) { fprintf(stderr, "failed to new RawValue object\n"); return false; } raw_value->m_is_param = true; raw_value->m_location = param_num; /* func : do not reset this variable. it's confusing. */ raw_value->set_data((const unsigned char *)statement_data->paramValues[param_num], statement_data->paramLengths ? statement_data->paramLengths[param_num] : strlen(statement_data->paramValues[param_num])); raw_value->m_data_value_format = statement_data->paramFormats ? statement_data->paramFormats[param_num] : 0; raw_values_list.set(param_num, raw_value); } if (!ValuesProcessor::process_values(statement_data, prepares_statement->cached_params, 1, &raw_values_list)) { return true; } statement_data->replace_raw_values(); return true; } void Processor::remove_dropped_column_settings(PGconn *conn, const bool is_success) { Assert(conn->client_logic && conn->client_logic->enable_client_encryption); if (conn->client_logic->droppedColumnSettings_size == 0) { return; } if (!is_success) { conn->client_logic->droppedColumnSettings_size = 0; return; } for (size_t i = 0; i < conn->client_logic->droppedColumnSettings_size; ++i) { const char *object_name = conn->client_logic->droppedColumnSettings[i].data; HooksManager::ColumnSettings::set_deletion_expected(*conn->client_logic, object_name, false); } conn->client_logic->droppedColumnSettings_size = 0; } void Processor::remove_dropped_global_settings(PGconn *conn, const bool is_success) { ObjName *cur_cmk = conn->client_logic->droppedGlobalSettings; ObjName *to_free = NULL; Assert(conn->client_logic && conn->client_logic->enable_client_encryption); if (cur_cmk == NULL) { return; } if (!is_success) { free_obj_list(conn->client_logic->droppedGlobalSettings); conn->client_logic->droppedGlobalSettings = NULL; return; } while (cur_cmk != NULL) { HooksManager::GlobalSettings::set_deletion_expected(*conn->client_logic, cur_cmk->obj_name, false); to_free = cur_cmk; cur_cmk = cur_cmk->next; free(to_free); to_free = NULL; } conn->client_logic->droppedGlobalSettings = NULL; } const bool Processor::remove_droppend_schemas(PGconn *conn, const bool is_success) { Assert(conn->client_logic && conn->client_logic->enable_client_encryption); if (conn->client_logic->droppedSchemas_size == 0) { return true; } if (!is_success) { conn->client_logic->droppedSchemas_size = 0; return true; } for (size_t i = 0; i < conn->client_logic->droppedSchemas_size; ++i) { const char *object_name = conn->client_logic->droppedSchemas[i].data; HooksManager::GlobalSettings::set_deletion_expected(*conn->client_logic, object_name, true); HooksManager::ColumnSettings::set_deletion_expected(*conn->client_logic, object_name, true); conn->client_logic->m_cached_column_manager->remove_schema(object_name); } conn->client_logic->droppedSchemas_size = 0; return true; } bool Processor::accept_pending_statements(PGconn *conn, bool is_success) { Assert(conn->client_logic && conn->client_logic->enable_client_encryption); if (!is_success) { conn->client_logic->pendingStatements->clear(); return true; } conn->client_logic->preparedStatements->merge(conn->client_logic->pendingStatements); conn->client_logic->pendingStatements->clear(); return true; } void handle_post_set_stmt(PGconn *conn, const bool is_success) { if (!is_success) { return; } if (conn->client_logic->val_to_update & updateGucValues::GUC_ROLE) { conn->client_logic->m_cached_column_manager->set_user_schema(conn->client_logic->tmpGucParams.role.c_str()); conn->client_logic->gucParams.role = conn->client_logic->tmpGucParams.role; conn->client_logic->val_to_update ^= updateGucValues::GUC_ROLE; } if (conn->client_logic->val_to_update & updateGucValues::SEARCH_PATH) { conn->client_logic->m_cached_column_manager->load_search_path( conn->client_logic->tmpGucParams.searchpathStr.c_str(), conn->client_logic->gucParams.role.c_str()); conn->client_logic->val_to_update ^= updateGucValues::SEARCH_PATH; } if (conn->client_logic->val_to_update & updateGucValues::BACKSLASH_QUOTE) { conn->client_logic->gucParams.backslash_quote = conn->client_logic->tmpGucParams.backslash_quote; conn->client_logic->val_to_update ^= updateGucValues::BACKSLASH_QUOTE; } if (conn->client_logic->val_to_update & updateGucValues::CONFORMING) { conn->client_logic->gucParams.standard_conforming_strings = conn->client_logic->tmpGucParams.standard_conforming_strings; conn->client_logic->val_to_update ^= updateGucValues::CONFORMING; } if (conn->client_logic->val_to_update & updateGucValues::ESCAPE_STRING) { conn->client_logic->gucParams.escape_string_warning = conn->client_logic->tmpGucParams.escape_string_warning; conn->client_logic->val_to_update ^= updateGucValues::ESCAPE_STRING; } } bool Processor::run_post_query(PGconn *conn) { if (!conn) { return false; } Assert(conn->client_logic && conn->client_logic->enable_client_encryption); if (conn->client_logic->rawValuesForReplace) { conn->client_logic->rawValuesForReplace->clear(); } char last_stmt_name[NAMEDATALEN]; errno_t rc = EOK; rc = memset_s(last_stmt_name, NAMEDATALEN, 0, NAMEDATALEN); securec_check_c(rc, "\0", "\0"); char temp_stmt_name[NAMEDATALEN]; rc = memset_s(temp_stmt_name, NAMEDATALEN, 0, NAMEDATALEN); securec_check_c(rc, "\0", "\0"); /* swap local lastStmtName with lastStmtName object on connection */ check_strncat_s(strncat_s(temp_stmt_name, NAMEDATALEN, conn->client_logic->lastStmtName, strlen(conn->client_logic->lastStmtName))); check_strncpy_s(strncpy_s(conn->client_logic->lastStmtName, NAMEDATALEN, last_stmt_name, strlen(last_stmt_name))); check_strncat_s(strncat_s(last_stmt_name, NAMEDATALEN, temp_stmt_name, strlen(temp_stmt_name))); int last_result = conn->client_logic->m_lastResultStatus; conn->client_logic->m_lastResultStatus = PGRES_EMPTY_QUERY; bool is_success = (last_result == PGRES_COMMAND_OK); accept_pending_statements(conn, is_success); remove_droppend_schemas(conn, is_success); remove_dropped_global_settings(conn, is_success); remove_dropped_column_settings(conn, is_success); handle_post_set_stmt(conn, is_success); conn->client_logic->clear_functions_list(); if (!is_success || (conn->queryclass != PGQUERY_SIMPLE && conn->queryclass != PGQUERY_EXTENDED)) { /* we only want to process successful queries that were actually executed */ return true; } PreparedStatement *prepared_statement = conn->client_logic->preparedStatements->get_or_create(last_stmt_name); if (!prepared_statement) { return false; } if (!is_success || (conn->queryclass != PGQUERY_SIMPLE && conn->queryclass != PGQUERY_EXTENDED)) { /* we only want to process successful queries that were actually executed */ return true; } if ((prepared_statement->cacheRefresh & CacheRefreshType::GLOBAL_SETTING) == CacheRefreshType::GLOBAL_SETTING && prepared_statement->m_function_name[0] != '\0') { /* * run post_create hook requirements after the arguments have been validaity and the Global Setting is sure to * be created We conduct this operation here to support incremental executions of post_create. So we only call * post_create for the new Global Setting and not for existing Global Settings. We actually create a copy of the * hook here but we don't save it in memory - we toss it right away. The hook will be saved in memory when the * CacheLoader loads it from the catalog table */ bool ret = HooksManager::GlobalSettings::post_create(*conn->client_logic, prepared_statement->m_function_name, prepared_statement->m_string_args); if (!ret) { return false; } } /* * we override the cacheRefreshType from the (prepared) statement object * otherwise, the cacheRefreshType is filled with the value from the getReadyForQuery */ conn->client_logic->cacheRefreshType = prepared_statement->cacheRefresh; prepared_statement->cacheRefresh = CacheRefreshType::CACHE_NONE; conn->client_logic->m_cached_column_manager->load_cache(conn); return true; }
46,936
392
/* * Copyright 1997-2021 Optimatika * * 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. */ package org.ojalgo.function.constant; import static org.ojalgo.function.constant.PrimitiveMath.*; import org.junit.jupiter.api.Test; import org.ojalgo.TestUtils; import org.ojalgo.function.constant.PrimitiveMath.Prefix; import org.ojalgo.type.context.NumberContext; public class PrimitiveMathTest { private static final double TOLERANCE = MACHINE_EPSILON; private static void compare(final double arg0, final double arg1) { if (arg0 == arg1) { if (NumberContext.compare(arg0, arg1) != 0) { TestUtils.fail(); } } else { //no inspection, Result Of Method Call Ignored NumberContext.compare(arg0, arg1); TestUtils.fail(); } } @Test public void testACOSH() { TestUtils.assertEquals(ZERO, ACOSH.invoke(ONE), MACHINE_EPSILON); } @Test public void testASINH() { TestUtils.assertEquals(ZERO, ASINH.invoke(ZERO), MACHINE_EPSILON); } @Test public void testATANH() { TestUtils.assertEquals(ZERO, ATANH.invoke(ZERO), MACHINE_EPSILON); TestUtils.assertEquals(POSITIVE_INFINITY, ATANH.invoke(ONE), MACHINE_EPSILON); TestUtils.assertEquals(NEGATIVE_INFINITY, ATANH.invoke(NEG), MACHINE_EPSILON); } @Test public void testCompareToZeros() { final double negDbl = -0.0; final double posInt = 0; final double posDbl = 0.0; final double negInt = -0; PrimitiveMathTest.compare(negDbl, posInt); PrimitiveMathTest.compare(negDbl, posDbl); PrimitiveMathTest.compare(negDbl, negInt); PrimitiveMathTest.compare(posInt, negDbl); PrimitiveMathTest.compare(posInt, posDbl); PrimitiveMathTest.compare(posInt, negInt); PrimitiveMathTest.compare(posDbl, negDbl); PrimitiveMathTest.compare(posDbl, posInt); PrimitiveMathTest.compare(posDbl, negInt); PrimitiveMathTest.compare(negInt, negDbl); PrimitiveMathTest.compare(negInt, posInt); PrimitiveMathTest.compare(negInt, posDbl); } @Test public void testHYPOT() { TestUtils.assertEquals(FIVE, HYPOT.invoke(FOUR, THREE), MACHINE_EPSILON); TestUtils.assertEquals(NaN, HYPOT.invoke(NaN, NaN), MACHINE_EPSILON); } @Test public void testPOWER() { TestUtils.assertEquals(ONE, POWER.invoke(ZERO, 0), MACHINE_EPSILON); TestUtils.assertEquals(ONE, POWER.invoke(PI, 0), MACHINE_EPSILON); TestUtils.assertEquals(ONE, POWER.invoke(E, 0), MACHINE_EPSILON); TestUtils.assertEquals(ZERO, POWER.invoke(ZERO, 1), MACHINE_EPSILON); TestUtils.assertEquals(PI, POWER.invoke(PI, 1), MACHINE_EPSILON); TestUtils.assertEquals(E, POWER.invoke(E, 1), MACHINE_EPSILON); TestUtils.assertEquals(ZERO * ZERO, POWER.invoke(ZERO, 2), MACHINE_EPSILON); TestUtils.assertEquals(PI * PI, POWER.invoke(PI, 2), MACHINE_EPSILON); TestUtils.assertEquals(E * E, POWER.invoke(E, 2), MACHINE_EPSILON); TestUtils.assertEquals(1 / ZERO, POWER.invoke(ZERO, -1), MACHINE_EPSILON); TestUtils.assertEquals(1 / PI, POWER.invoke(PI, -1), MACHINE_EPSILON); TestUtils.assertEquals(1 / E, POWER.invoke(E, -1), MACHINE_EPSILON); } @Test public void testPrefixes() { double expected = Double.NaN; expected = POWER.invoke(TEN, -24); TestUtils.assertEquals("yocto, y", expected, Prefix.YOCTO, TOLERANCE); expected = POWER.invoke(TEN, -21); TestUtils.assertEquals("zepto, z", expected, Prefix.ZEPTO, TOLERANCE); expected = POWER.invoke(TEN, -18); TestUtils.assertEquals("atto, a", expected, Prefix.ATTO, TOLERANCE); expected = POWER.invoke(TEN, -15); TestUtils.assertEquals("femto, f", expected, Prefix.FEMTO, TOLERANCE); expected = POWER.invoke(TEN, -12); TestUtils.assertEquals("pico, p", expected, Prefix.PICO, TOLERANCE); expected = POWER.invoke(TEN, -9); TestUtils.assertEquals("nano, n", expected, Prefix.NANO, TOLERANCE); expected = POWER.invoke(TEN, -6); TestUtils.assertEquals("micro, my", expected, Prefix.MICRO, TOLERANCE); expected = POWER.invoke(TEN, -3); TestUtils.assertEquals("milli, m", expected, Prefix.MILLI, TOLERANCE); expected = POWER.invoke(TEN, -2); TestUtils.assertEquals("centi, c", expected, Prefix.CENTI, TOLERANCE); expected = POWER.invoke(TEN, -1); TestUtils.assertEquals("deci, d", expected, Prefix.DECI, TOLERANCE); expected = POWER.invoke(TEN, 1); TestUtils.assertEquals("deka, da", expected, Prefix.DEKA, TOLERANCE); expected = POWER.invoke(TEN, 2); TestUtils.assertEquals("hecto, h", expected, Prefix.HECTO, TOLERANCE); expected = POWER.invoke(TEN, 3); TestUtils.assertEquals("kilo, k", expected, Prefix.KILO, TOLERANCE); expected = POWER.invoke(TEN, 6); TestUtils.assertEquals("mega, M", expected, Prefix.MEGA, TOLERANCE); expected = POWER.invoke(TEN, 9); TestUtils.assertEquals("giga, G", expected, Prefix.GIGA, TOLERANCE); expected = POWER.invoke(TEN, 12); TestUtils.assertEquals("tera, T", expected, Prefix.TERA, TOLERANCE); expected = POWER.invoke(TEN, 15); TestUtils.assertEquals("peta, P", expected, Prefix.PETA, TOLERANCE); expected = POWER.invoke(TEN, 18); TestUtils.assertEquals("exa, E", expected, Prefix.EXA, TOLERANCE); expected = POWER.invoke(TEN, 21); TestUtils.assertEquals("zetta, CmplxNmbr", expected, Prefix.ZETTA, TOLERANCE); expected = POWER.invoke(TEN, 24); TestUtils.assertEquals("yotta, Y", expected, Prefix.YOTTA, TOLERANCE); } }
2,927
7,886
<reponame>ishaanthakur/litho /* * Copyright (c) Meta Platforms, Inc. and affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.samples.litho.java.documentation; import static com.facebook.litho.SizeSpec.UNSPECIFIED; import com.facebook.litho.Component; import com.facebook.litho.ComponentContext; import com.facebook.litho.Size; import com.facebook.litho.SizeSpec; import com.facebook.litho.annotations.LayoutSpec; import com.facebook.litho.annotations.OnCreateLayoutWithSizeSpec; import com.facebook.litho.widget.Image; import com.facebook.litho.widget.Text; import com.facebook.samples.litho.R; // start_example @LayoutSpec class LongTextReplacerComponentSpec { @OnCreateLayoutWithSizeSpec static Component onCreateLayoutWithSizeSpec(ComponentContext c, int widthSpec, int heightSpec) { final Component textComponent = Text.create(c).textSizeSp(16).text("Some text to measure.").build(); // UNSPECIFIED sizeSpecs will measure the text as being one line only, // having unlimited width. final Size textOutputSize = new Size(); textComponent.measure( c, SizeSpec.makeSizeSpec(0, UNSPECIFIED), SizeSpec.makeSizeSpec(0, UNSPECIFIED), textOutputSize); // Small component to use in case textComponent doesn’t fit within // the current layout. final Component imageComponent = Image.create(c).drawableRes(R.drawable.ic_launcher).build(); // Assuming SizeSpec.getMode(widthSpec) == EXACTLY or AT_MOST. final int layoutWidth = SizeSpec.getSize(widthSpec); final boolean textFits = (textOutputSize.width <= layoutWidth); return textFits ? textComponent : imageComponent; } } // end_example
698
4,879
#pragma once #include <cstdint> #include <vector> namespace dp { class IndexStorage { public: IndexStorage(); explicit IndexStorage(std::vector<uint32_t> && initial); uint32_t Size() const; void Resize(uint32_t size); void * GetRaw(uint32_t offsetInElements = 0); void const * GetRawConst() const; static bool IsSupported32bit(); static uint32_t SizeOfIndex(); private: std::vector<uint32_t> m_storage; uint32_t m_size; uint32_t GetStorageSize(uint32_t elementsCount) const; }; } // namespace dp
189
2,728
<gh_stars>1000+ # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- import pytest from azure.core.exceptions import ClientAuthenticationError, HttpResponseError from azure.ai.metricsadvisor import MetricsAdvisorClient, MetricsAdvisorKeyCredential from base_testcase import TestMetricsAdvisorClientBase class TestMetricsAdvisorCredential(TestMetricsAdvisorClientBase): def __init__(self, method_name): super(TestMetricsAdvisorCredential, self).__init__(method_name) if self.is_live: self.service_endpoint = self.get_settings_value("METRICS_ADVISOR_ENDPOINT") self.subscription_key = self.get_settings_value("METRICS_ADVISOR_SUBSCRIPTION_KEY") self.api_key = self.get_settings_value("METRICS_ADVISOR_API_KEY") else: self.service_endpoint = "https://endpointname.cognitiveservices.azure.com" self.subscription_key = "METRICS_ADVISOR_SUBSCRIPTION_KEY" self.api_key = "METRICS_ADVISOR_API_KEY" def test_credential_rotate_both_keys(self): credential = MetricsAdvisorKeyCredential(self.subscription_key, self.api_key) client = MetricsAdvisorClient(self.service_endpoint, credential) # make successful call result = client.get_feedback(feedback_id=self.feedback_id) assert result # rotate both keys credential.update_key(subscription_key="xxx") assert credential.subscription_key == "xxx" credential.update_key(api_key="xxx") assert credential.api_key == "xxx" # call fails with pytest.raises(ClientAuthenticationError): result = client.get_feedback(feedback_id=self.feedback_id) # rotate back to valid credentials credential.update_key(subscription_key=self.subscription_key) assert credential.subscription_key == self.subscription_key credential.update_key(api_key=self.api_key) assert credential.api_key == self.api_key # make successful call result = client.get_feedback(feedback_id=self.feedback_id) assert result def test_credential_rotate_sub_key_only(self): credential = MetricsAdvisorKeyCredential(self.subscription_key, self.api_key) client = MetricsAdvisorClient(self.service_endpoint, credential) # make successful call result = client.get_feedback(feedback_id=self.feedback_id) assert result # rotate one key credential.update_key(subscription_key="xxx") assert credential.subscription_key == "xxx" assert credential.api_key == self.api_key # call fails with pytest.raises(ClientAuthenticationError): result = client.get_feedback(feedback_id=self.feedback_id) # rotate back to valid credentials credential.update_key(subscription_key=self.subscription_key) assert credential.subscription_key == self.subscription_key assert credential.api_key == self.api_key # make successful call result = client.get_feedback(feedback_id=self.feedback_id) assert result def test_credential_rotate_api_key_only(self): credential = MetricsAdvisorKeyCredential(self.subscription_key, self.api_key) client = MetricsAdvisorClient(self.service_endpoint, credential) # make successful call result = client.get_feedback(feedback_id=self.feedback_id) assert result # rotate one key credential.update_key(api_key="xxx") assert credential.subscription_key == self.subscription_key assert credential.api_key == "xxx" # call fails with pytest.raises(HttpResponseError): result = client.get_feedback(feedback_id=self.feedback_id) # rotate back to valid credentials credential.update_key(api_key=self.api_key) assert credential.subscription_key == self.subscription_key assert credential.api_key == self.api_key # make successful call result = client.get_feedback(feedback_id=self.feedback_id) assert result def test_credential_bad_input(self): credential = MetricsAdvisorKeyCredential(self.subscription_key, self.api_key) with pytest.raises(TypeError): credential.update_key(subscription_key=34) with pytest.raises(TypeError): credential.update_key(api_key=34)
1,793
732
/* Copyright 2014 Adobe Systems Incorporated (http://www.adobe.com/). All Rights Reserved. This software is licensed as OpenSource, under the Apache License, Version 2.0. This license is available at: http://opensource.org/licenses/Apache-2.0. */ "/OtherSubrs[systemdict/internaldict known{1183615869 systemdict/internaldict\n" "get exec/FlxProc known{save true}{false}ifelse}{userdict/internaldict known\n" "not{userdict/internaldict{count 0 eq{/internaldict errordict/invalidaccess get\n" "exec}if dup type/integertype ne{/internaldict errordict/invalidaccess get exec\n" "}if dup 1183615869 eq{pop 0}{/internaldict errordict/invalidaccess get exec}\n", "ifelse}dup 14 get 1 25 dict put bind executeonly put}if 1183615869 userdict\n" "/internaldict get exec/FlxProc known{save true}{false}ifelse}ifelse[systemdict\n" "/internaldict known not{100 dict/begin cvx/mtx matrix/def cvx}if systemdict\n" "/currentpacking known{currentpacking true setpacking}if{systemdict\n" "/internaldict known{1183615869 systemdict/internaldict get exec dup/$FlxDict\n" "known not{dup dup length exch maxlength eq{pop userdict dup/$FlxDict known not\n", "{100 dict begin/mtx matrix def dup/$FlxDict currentdict put end}if}{100 dict\n" "begin/mtx matrix def dup/$FlxDict currentdict put end}ifelse}if/$FlxDict get\n" "begin}if grestore/exdef{exch def}def/dmin exch abs 100 div def/epX exdef/epY\n" "exdef/c4y2 exdef/c4x2 exdef/c4y1 exdef/c4x1 exdef/c4y0 exdef/c4x0 exdef/c3y2\n" "exdef/c3x2 exdef/c3y1 exdef/c3x1 exdef/c3y0 exdef/c3x0 exdef/c1y2 exdef/c1x2\n" "exdef/c2x2 c4x2 def/c2y2 c4y2 def/yflag c1y2 c3y2 sub abs c1x2 c3x2 sub abs gt\n", "def/PickCoords{{c1x0 c1y0 c1x1 c1y1 c1x2 c1y2 c2x0 c2y0 c2x1 c2y1 c2x2 c2y2}{\n" "c3x0 c3y0 c3x1 c3y1 c3x2 c3y2 c4x0 c4y0 c4x1 c4y1 c4x2 c4y2}ifelse/y5 exdef/x5\n" "exdef/y4 exdef/x4 exdef/y3 exdef/x3 exdef/y2 exdef/x2 exdef/y1 exdef/x1 exdef\n" "/y0 exdef/x0 exdef}def mtx currentmatrix pop mtx 0 get abs 1e-05 lt mtx 3 get\n" "abs 1e-05 lt or{/flipXY -1 def}{mtx 1 get abs 1e-05 lt mtx 2 get abs 1e-05 lt\n" "or{/flipXY 1 def}{/flipXY 0 def}ifelse}ifelse/erosion 1 def systemdict\n", "/internaldict known{1183615869 systemdict/internaldict get exec dup/erosion\n" "known{/erosion get/erosion exch def}{pop}ifelse}if yflag{flipXY 0 eq c3y2 c4y2\n" "eq or{false PickCoords}{/shrink c3y2 c4y2 eq{0}{c1y2 c4y2 sub c3y2 c4y2 sub\n" "div abs}ifelse def/yshrink{c4y2 sub shrink mul c4y2 add}def/c1y0 c3y0 yshrink\n" "def/c1y1 c3y1 yshrink def/c2y0 c4y0 yshrink def/c2y1 c4y1 yshrink def/c1x0\n" "c3x0 def/c1x1 c3x1 def/c2x0 c4x0 def/c2x1 c4x1 def/dY 0 c3y2 c1y2 sub round\n", "dtransform flipXY 1 eq{exch}if pop abs def dY dmin lt PickCoords y2 c1y2 sub\n" "abs .001 gt{c1x2 c1y2 transform flipXY 1 eq{exch}if/cx exch def/cy exch def/dY\n" "0 y2 c1y2 sub round dtransform flipXY 1 eq{exch}if pop def dY round dup 0 ne{\n" "/dY exdef}{pop dY 0 lt{-1}{1}ifelse/dY exdef}ifelse/erode PaintType 2 ne\n" "erosion .5 ge and def erode{/cy cy .5 sub def}if/ey cy dY add def/ey ey\n" "ceiling ey sub ey floor add def erode{/ey ey .5 add def}if ey cx flipXY 1 eq{\n", "exch}if itransform exch pop y2 sub/eShift exch def/y1 y1 eShift add def/y2 y2\n" "eShift add def/y3 y3 eShift add def}if}ifelse}{flipXY 0 eq c3x2 c4x2 eq or{\n" "false PickCoords}{/shrink c3x2 c4x2 eq{0}{c1x2 c4x2 sub c3x2 c4x2 sub div abs}\n" "ifelse def/xshrink{c4x2 sub shrink mul c4x2 add}def/c1x0 c3x0 xshrink def/c1x1\n" "c3x1 xshrink def/c2x0 c4x0 xshrink def/c2x1 c4x1 xshrink def/c1y0 c3y0 def\n" "/c1y1 c3y1 def/c2y0 c4y0 def/c2y1 c4y1 def/dX c3x2 c1x2 sub round 0 dtransform\n", "flipXY -1 eq{exch}if pop abs def dX dmin lt PickCoords x2 c1x2 sub abs .001 gt\n" "{c1x2 c1y2 transform flipXY -1 eq{exch}if/cy exch def/cx exch def/dX x2 c1x2\n" "sub round 0 dtransform flipXY -1 eq{exch}if pop def dX round dup 0 ne{/dX\n" "exdef}{pop dX 0 lt{-1}{1}ifelse/dX exdef}ifelse/erode PaintType 2 ne erosion\n" ".5 ge and def erode{/cx cx .5 sub def}if/ex cx dX add def/ex ex ceiling ex sub\n" "ex floor add def erode{/ex ex .5 add def}if ex cy flipXY -1 eq{exch}if\n", "itransform pop x2 sub/eShift exch def/x1 x1 eShift add def/x2 x2 eShift add\n" "def/x3 x3 eShift add def}if}ifelse}ifelse x2 x5 eq y2 y5 eq or{x5 y5 lineto}{\n" "x0 y0 x1 y1 x2 y2 curveto x3 y3 x4 y4 x5 y5 curveto}ifelse epY epX}systemdict\n" "/currentpacking known{exch setpacking}if/exec cvx/end cvx]cvx executeonly exch\n" "{pop true exch restore}{systemdict/internaldict known not{1183615869 userdict\n" "/internaldict get exec exch/FlxProc exch put true}{1183615869 systemdict\n", "/internaldict get exec dup length exch maxlength eq{false}{1183615869\n" "systemdict/internaldict get exec exch/FlxProc exch put true}ifelse}ifelse}\n" "ifelse{systemdict/internaldict known{{1183615869 systemdict/internaldict get\n" "exec/FlxProc get exec}}{{1183615869 userdict/internaldict get exec/FlxProc get\n" "exec}}ifelse executeonly}if{gsave currentpoint newpath moveto}executeonly{\n" "currentpoint grestore gsave currentpoint newpath moveto}executeonly{systemdict\n", "/internaldict known not{pop 3}{1183615869 systemdict/internaldict get exec dup\n" "/startlock known{/startlock get exec}{dup/strtlck known{/strtlck get exec}{pop\n" "3}ifelse}ifelse}ifelse}executeonly]def\n"
2,329
533
<reponame>coomar2841/image-chooser-library package com.kbeanie.imagechooser.helpers; import android.database.Cursor; import android.graphics.Bitmap; import android.net.Uri; import android.os.ParcelFileDescriptor; import android.util.Log; import com.kbeanie.imagechooser.exceptions.ChooserException; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * Created by vervik on 9/27/15. */ public class StreamHelper { static final String TAG = StreamHelper.class.getSimpleName(); public static void closeSilent(Closeable stream) { try { close(stream); } catch (ChooserException e) { Log.e(TAG, e.getMessage(), e); } } public static void close(Closeable stream) throws ChooserException { if(stream != null) { try { stream.close(); } catch (IOException e) { throw new ChooserException(e); } } } public static void flush(OutputStream stream) throws ChooserException { if(stream != null) { try { stream.close(); } catch (IOException e) { throw new ChooserException(e); } } } public static void close(ParcelFileDescriptor parcelFileDescriptor) throws ChooserException { if (parcelFileDescriptor != null) { try { parcelFileDescriptor.close(); } catch (IOException e) { throw new ChooserException(e); } } } public static void verifyCursor(Uri uri, Cursor cursor) throws ChooserException { if(cursor == null) { throw new ChooserException("Didnt not get cursor in return for = " + uri); } } public static void verifyStream(String path, ParcelFileDescriptor descriptor) throws ChooserException { if(descriptor == null) { throw new ChooserException("Could not read file descriptor from file at path = " + path); } } public static void verifyStream(String path, InputStream is) throws ChooserException { if(is == null) { throw new ChooserException("Could not open stream to read path = " + path); } } public static void verifyBitmap(String path, Bitmap bitmap) throws ChooserException { if(bitmap == null) { throw new ChooserException("Could not read bitmap from this path = " + path); } } public static boolean isNonNull(Bitmap bitmap) { if(bitmap != null) { return true; } Log.w(TAG, "Bitmap is null. No good."); return false; } public static byte[] toByteArray(InputStream input) throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024 * 4]; int n; while (-1 != (n = input.read(buffer))) { byteArrayOutputStream.write(buffer, 0, n); } return byteArrayOutputStream.toByteArray(); } }
1,317
14,668
// Copyright 2019 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 "chrome/chrome_cleaner/os/secure_dll_loading.h" #include <windows.h> #include <memory> #include <set> #include <string> #include <vector> #include "base/base_paths.h" #include "base/command_line.h" #include "base/files/file_path.h" #include "base/files/scoped_temp_dir.h" #include "base/logging.h" #include "base/path_service.h" #include "base/process/launch.h" #include "base/process/process.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/synchronization/waitable_event.h" #include "base/test/test_timeouts.h" #include "base/win/win_util.h" #include "chrome/chrome_cleaner/buildflags.h" #include "chrome/chrome_cleaner/constants/chrome_cleaner_switches.h" #include "chrome/chrome_cleaner/os/inheritable_event.h" #include "chrome/chrome_cleaner/os/process.h" #include "chrome/chrome_cleaner/test/child_process_logger.h" #include "chrome/chrome_cleaner/test/test_util.h" #include "components/chrome_cleaner/public/constants/constants.h" #include "components/chrome_cleaner/test/test_name_helper.h" #include "testing/gtest/include/gtest/gtest.h" class SecureDLLLoadingTest : public testing::TestWithParam<std::wstring> { protected: void SetUp() override { ASSERT_TRUE(child_process_logger_.Initialize()); base::FilePath out_dir; ASSERT_TRUE(base::PathService::Get(base::DIR_EXE, &out_dir)); exe_path_ = out_dir.Append(GetParam() + L".exe"); empty_dll_path_ = out_dir.Append(chrome_cleaner::kEmptyDll); ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); } base::Process LaunchProcess(bool disable_secure_dll_loading) { std::unique_ptr<base::WaitableEvent> init_done_notifier = chrome_cleaner::CreateInheritableEvent( base::WaitableEvent::ResetPolicy::AUTOMATIC, base::WaitableEvent::InitialState::NOT_SIGNALED); base::CommandLine command_line(exe_path_); command_line.AppendSwitchNative( chrome_cleaner::kInitDoneNotifierSwitch, base::NumberToWString( base::win::HandleToUint32(init_done_notifier->handle()))); command_line.AppendSwitch(chrome_cleaner::kLoadEmptyDLLSwitch); #if !BUILDFLAG(IS_OFFICIAL_CHROME_CLEANER_BUILD) if (disable_secure_dll_loading) command_line.AppendSwitch(chrome_cleaner::kAllowUnsecureDLLsSwitch); #endif // BUILDFLAG(IS_OFFICIAL_CHROME_CLEANER_BUILD) // The default execution mode (ExecutionMode::kNone) is no longer supported // and displays an error dialog instead of trying to load the DLLs. command_line.AppendSwitchASCII( chrome_cleaner::kExecutionModeSwitch, base::NumberToString( static_cast<int>(chrome_cleaner::ExecutionMode::kCleanup))); chrome_cleaner::AppendTestSwitches(temp_dir_, &command_line); base::LaunchOptions options; options.handles_to_inherit.push_back(init_done_notifier->handle()); child_process_logger_.UpdateLaunchOptions(&options); base::Process process = base::LaunchProcess(command_line, options); if (!process.IsValid()) { child_process_logger_.DumpLogs(); return process; } // Make sure the process has finished its initialization (including loading // DLLs). Also check the process handle in case it exits with an error. std::vector<HANDLE> wait_handles{init_done_notifier->handle(), process.Handle()}; DWORD wait_result = ::WaitForMultipleObjects( wait_handles.size(), wait_handles.data(), /*bWaitAll=*/false, TestTimeouts::action_max_timeout().InMilliseconds()); // WAIT_OBJECT_0 is the first handle in the vector. if (wait_result == WAIT_OBJECT_0 + 1) { DWORD exit_code = 0; PLOG_IF(ERROR, !::GetExitCodeProcess(process.Handle(), &exit_code)); ADD_FAILURE() << "Process exited with " << exit_code << " before signalling init_done_notifier"; child_process_logger_.DumpLogs(); } else { EXPECT_EQ(wait_result, WAIT_OBJECT_0); } return process; } bool EmptyDLLLoaded(const base::Process& process) { std::set<std::wstring> module_paths; chrome_cleaner::GetLoadedModuleFileNames(process.Handle(), &module_paths); for (const auto& module_path : module_paths) { if (base::EqualsCaseInsensitiveASCII(empty_dll_path_.value(), module_path)) return true; } return false; } private: chrome_cleaner::ChildProcessLogger child_process_logger_; base::FilePath exe_path_; base::FilePath empty_dll_path_; // Temp directory for child process log files. base::ScopedTempDir temp_dir_; }; INSTANTIATE_TEST_SUITE_P(SecureDLLLoading, SecureDLLLoadingTest, // The value names cannot include ".exe" because "." // is not a valid character in a test case name. ::testing::Values(L"software_reporter_tool", L"chrome_cleanup_tool"), chrome_cleaner::GetParamNameForTest()); #if !BUILDFLAG(IS_OFFICIAL_CHROME_CLEANER_BUILD) TEST_P(SecureDLLLoadingTest, Disabled) { base::Process process = LaunchProcess(/*disable_secure_dll_loading=*/true); EXPECT_TRUE(EmptyDLLLoaded(process)); // There is no need to finish running the process. EXPECT_TRUE(process.Terminate(0U, /*wait=*/true)); } #endif // BUILDFLAG(IS_OFFICIAL_CHROME_CLEANER_BUILD) TEST_P(SecureDLLLoadingTest, Default) { if (!::GetProcAddress(::GetModuleHandleW(L"kernel32.dll"), "SetDefaultDllDirectories")) { // Skip this test if the SetDefaultDllDirectories function is unavailable // (this is normal on Windows 7 without update KB2533623.) return; } base::Process process = LaunchProcess(/*disable_secure_dll_loading=*/false); EXPECT_FALSE(EmptyDLLLoaded(process)); // There is no need to finish running the process. EXPECT_TRUE(process.Terminate(0U, /*wait=*/true)); }
2,437
346
<reponame>FluffyQuack/ja2-stracciatella #include "Campaign_Init.h" #include "Overhead.h" #include "FileMan.h" #include "Creature_Spreading.h" #include "Campaign_Types.h" #include "Queen_Command.h" #include "Strategic_Movement.h" #include "Game_Event_Hook.h" #include "GameSettings.h" #include "Random.h" #include "Message.h" #include "Font_Control.h" #include "Soldier_Init_List.h" #include "Lighting.h" #include "StrategicMap.h" #include "Game_Clock.h" #include "Strategic_Mines.h" #include "Music_Control.h" #include "ContentMusic.h" #include "Strategic.h" #include "JAScreens.h" #include "Town_Militia.h" #include "Strategic_Town_Loyalty.h" #include "PreBattle_Interface.h" #include "Map_Edgepoints.h" #include "Animation_Data.h" #include "OppList.h" #include "Meanwhile.h" #include "Strategic_AI.h" #include "Map_Information.h" #include "MemMan.h" #include "Debug.h" #include "ScreenIDs.h" #include "GameInstance.h" #include "ContentManager.h" #include "MineModel.h" #include "CreatureLairModel.h" #include "GameInstance.h" #include "ContentManager.h" #include "MineModel.h" #include <algorithm> #include <stdexcept> #include <vector> //GAME BALANCING DEFINITIONS FOR CREATURE SPREADING //Hopefully, adjusting these following definitions will ease the balancing of the //creature spreading. //The one note here is that for any definitions that have a XXX_BONUS at the end of a definition, //it gets added on to it's counterpart via: // XXX_VALUE + Random( 1 + XXX_BONUS ) //This is how often the creatures spread, once the quest begins. The smaller the gap, //the faster the creatures will advance. This is also directly related to the reproduction //rates which are applied each time the creatures spread. #define EASY_SPREAD_TIME_IN_MINUTES 510 //easy spreads every 8.5 hours #define NORMAL_SPREAD_TIME_IN_MINUTES 450 //normal spreads every 7.5 hours #define HARD_SPREAD_TIME_IN_MINUTES 390 //hard spreads every 6.5 hours //Once the queen is added to the game, we can instantly let her spread x number of times //to give her a head start. This can also be a useful tool for having slow reproduction rates //but quicker head start to compensate to make the creatures less aggressive overall. #define EASY_QUEEN_INIT_BONUS_SPREADS 1 #define NORMAL_QUEEN_INIT_BONUS_SPREADS 2 #define HARD_QUEEN_INIT_BONUS_SPREADS 3 //This value modifies the chance to populate a given sector. This is different from the previous definition. //This value gets applied to a potentially complicated formula, using the creature habitat to modify //chance to populate, along with factoring in the relative distance to the hive range (to promote deeper lair //population increases), etc. I would recommend not tweaking the value too much in either direction from //zero due to the fact that this can greatly effect spread times and maximum populations. Basically, if the //creatures are spreading too quickly, increase the value, otherwise decrease it to a negative value #define EASY_POPULATION_MODIFIER 0 #define NORMAL_POPULATION_MODIFIER 0 #define HARD_POPULATION_MODIFIER 0 //Augments the chance that the creatures will attack a town. The conditions for attacking a town //are based strictly on the occupation of the creatures in each of the four mine exits. For each creature //there is a base chance of 10% that the creatures will feed sometime during the night. #define EASY_CREATURE_TOWN_AGGRESSIVENESS -10 #define NORMAL_CREATURE_TOWN_AGGRESSIVENESS 0 #define HARD_CREATURE_TOWN_AGGRESSIVENESS 10 //This is how many creatures the queen produces for each cycle of spreading. The higher //the numbers the faster the creatures will advance. #define EASY_QUEEN_REPRODUCTION_BASE 6 //6-7 #define EASY_QUEEN_REPRODUCTION_BONUS 1 #define NORMAL_QUEEN_REPRODUCTION_BASE 7 //7-9 #define NORMAL_QUEEN_REPRODUCTION_BONUS 2 #define HARD_QUEEN_REPRODUCTION_BASE 9 //9-12 #define HARD_QUEEN_REPRODUCTION_BONUS 3 //When either in a cave level with blue lights or there is a creature presence, then //we override the normal music with the creature music. The conditions are maintained //inside the function PrepareCreaturesForBattle() in this module. BOOLEAN gfUseCreatureMusic = FALSE; BOOLEAN gfCreatureMeanwhileScenePlayed = FALSE; struct CREATURE_DIRECTIVE { CREATURE_DIRECTIVE* next; UNDERGROUND_SECTORINFO *pLevel; }; CREATURE_DIRECTIVE *gLair; const CreatureLairModel* gLairModel; INT32 giHabitatedDistance = 0; INT32 giPopulationModifier = 0; INT32 giLairID = 0; INT32 giDestroyedLairID = 0; //various information required for keeping track of the battle sector involved for //prebattle interface, autoresolve, etc. INT16 gsCreatureInsertionCode = 0; INT16 gsCreatureInsertionGridNo = 0; UINT8 gubNumCreaturesAttackingTown = 0; UINT8 gubYoungMalesAttackingTown = 0; UINT8 gubYoungFemalesAttackingTown = 0; UINT8 gubAdultMalesAttackingTown = 0; UINT8 gubAdultFemalesAttackingTown = 0; UINT8 gubCreatureBattleCode = CREATURE_BATTLE_CODE_NONE; UINT8 gubSectorIDOfCreatureAttack = 0; static CREATURE_DIRECTIVE* NewDirective(UINT8 ubSectorID, UINT8 ubSectorZ, UINT8 ubCreatureHabitat) { UINT8 ubSectorX, ubSectorY; CREATURE_DIRECTIVE* const curr = new CREATURE_DIRECTIVE{}; ubSectorX = (UINT8)((ubSectorID % 16) + 1); ubSectorY = (UINT8)((ubSectorID / 16) + 1); curr->pLevel = FindUnderGroundSector( ubSectorX, ubSectorY, ubSectorZ ); if( !curr->pLevel ) { SLOGA("Could not find underground sector node (%c%db_%d) that should exist.", ubSectorY + 'A' - 1, ubSectorX, ubSectorZ); delete curr; return 0; } curr->pLevel->ubCreatureHabitat = ubCreatureHabitat; curr->next = NULL; return curr; } static void InitCreatureLair(const CreatureLairModel* lairModel) { gLairModel = lairModel; CREATURE_DIRECTIVE* curr = NULL; giLairID = lairModel->lairId; //initialize the linked list of lairs for (auto sec : lairModel->lairSectors) { auto next = NewDirective(sec.sectorId, sec.sectorLevel, sec.habitatType); if (sec.habitatType == QUEEN_LAIR && !next->pLevel->ubNumCreatures) { next->pLevel->ubNumCreatures = 1; //for the queen. } if (curr == NULL) { // first node, set gLair to the start of list gLair = next; } else { // append to list curr->next = next; } curr = next; } } static bool IsMineInfestible(const MineModel* mine) { // If neither head miner was attacked, ore will/has run out nor enemy controlled UINT8 id = mine->mineId; MINE_STATUS_TYPE const& m = gMineStatus[id]; return !m.fAttackedHeadMiner && m.uiOreRunningOutPoint == 0 && !StrategicMap[SECTOR_INFO_TO_STRATEGIC_INDEX(mine->entranceSector)].fEnemyControlled; } void InitCreatureQuest() { INT32 i=-1; UINT8 ubChosenMineId; INT32 iRandom; INT32 iNumMinesInfestible; std::vector<UINT8> ubMinesInfestible; if( giLairID ) { return; //already active! } if( !gfCreatureMeanwhileScenePlayed ) { //Start the meanwhile scene for the queen ordering the release of the creatures. HandleCreatureRelease(); gfCreatureMeanwhileScenePlayed = TRUE; } giHabitatedDistance = 0; switch( gGameOptions.ubDifficultyLevel ) { case DIF_LEVEL_EASY: giPopulationModifier = EASY_POPULATION_MODIFIER; break; case DIF_LEVEL_MEDIUM: giPopulationModifier = NORMAL_POPULATION_MODIFIER; break; case DIF_LEVEL_HARD: giPopulationModifier = HARD_POPULATION_MODIFIER; break; } /* Determine which of the four mines are infectible by creatures. Infectible * mines are those that are player controlled and unlimited. We don't want the * creatures to infect the mine that runs out. */ for (auto lair : GCM->getCreatureLairs()) { auto mine = GCM->getMine(lair->associatedMineId); if (IsMineInfestible(mine)) { ubMinesInfestible.push_back(mine->mineId); } } iNumMinesInfestible = ubMinesInfestible.size(); if( !iNumMinesInfestible ) { return; } //Choose one of the infectible mines randomly iRandom = Random( iNumMinesInfestible ); ubChosenMineId = ubMinesInfestible[iRandom]; //Now, choose a start location for the queen. auto lairModel = GCM->getCreatureLairByMineId(ubChosenMineId); InitCreatureLair(lairModel); // enable the lair entrance UINT8 entranceSector = lairModel->entranceSector; UNDERGROUND_SECTORINFO* lairEntrance = FindUnderGroundSector(SECTORX(entranceSector), SECTORY(entranceSector), lairModel->entranceSectorLevel); if (lairEntrance == NULL) { throw std::runtime_error("Lair entrance sector is not defined as an underground sector"); } lairEntrance->uiFlags |= SF_PENDING_ALTERNATE_MAP; //Now determine how often we will spread the creatures. switch( gGameOptions.ubDifficultyLevel ) { case DIF_LEVEL_EASY: i = EASY_QUEEN_INIT_BONUS_SPREADS; AddPeriodStrategicEvent( EVENT_CREATURE_SPREAD, EASY_SPREAD_TIME_IN_MINUTES, 0 ); break; case DIF_LEVEL_MEDIUM: i = NORMAL_QUEEN_INIT_BONUS_SPREADS; AddPeriodStrategicEvent( EVENT_CREATURE_SPREAD, NORMAL_SPREAD_TIME_IN_MINUTES, 0 ); break; case DIF_LEVEL_HARD: i = HARD_QUEEN_INIT_BONUS_SPREADS; AddPeriodStrategicEvent( EVENT_CREATURE_SPREAD, HARD_SPREAD_TIME_IN_MINUTES, 0 ); break; } //Set things up so that the creatures can plan attacks on helpless miners and civilians while //they are sleeping. They do their planning at 10PM every day, and decide to attack sometime //during the night. AddEveryDayStrategicEvent( EVENT_CREATURE_NIGHT_PLANNING, 1320, 0 ); //Got to give the queen some early protection, so do some creature spreading. while( i-- ) { //# times spread is based on difficulty, and the values in the defines. SpreadCreatures(); } } static void AddCreatureToNode(CREATURE_DIRECTIVE* node) { node->pLevel->ubNumCreatures++; if( node->pLevel->uiFlags & SF_PENDING_ALTERNATE_MAP ) { //there is an alternate map meaning that there is a dynamic opening. From now on //we substitute this map. node->pLevel->uiFlags &= ~SF_PENDING_ALTERNATE_MAP; node->pLevel->uiFlags |= SF_USE_ALTERNATE_MAP; } } static BOOLEAN PlaceNewCreature(CREATURE_DIRECTIVE* node, INT32 iDistance) { if( !node ) return FALSE; //check to see if the creatures are permitted to spread into certain areas. There are 4 mines (human perspective), and //creatures won't spread to them until the player controls them. Additionally, if the player has recently cleared the //mine, then temporarily prevent the spreading of creatures. if( giHabitatedDistance == iDistance ) { //FRONT-LINE CONDITIONS -- consider expansion or frontline fortification. The formulae used //in this sector are geared towards outer expansion. //we have reached the distance limitation for the spreading. We will determine if //the area is populated enough to spread further. The minimum population must be 4 before //spreading is even considered. if( node->pLevel->ubNumCreatures*10 - 10 <= (INT32)Random( 60 ) ) { // x<=1 100% // x==2 83% // x==3 67% // x==4 50% // x==5 33% // x==6 17% // x>=7 0% AddCreatureToNode( node ); return TRUE; } } else if( giHabitatedDistance > iDistance ) { //we are within the "safe" habitated area of the creature's area of influence. The chance of //increasing the population inside this sector depends on how deep we are within the sector. if( node->pLevel->ubNumCreatures < MAX_STRATEGIC_TEAM_SIZE || (node->pLevel->ubNumCreatures < 32 && node->pLevel->ubCreatureHabitat == QUEEN_LAIR) ) { //there is ALWAYS a chance to habitate an interior sector, though the chances are slim for //highly occupied sectors. This chance is modified by the type of area we are in. INT32 iAbsoluteMaxPopulation; INT32 iMaxPopulation=-1; INT32 iChanceToPopulate; switch( node->pLevel->ubCreatureHabitat ) { case QUEEN_LAIR: //Defend the queen bonus iAbsoluteMaxPopulation = 32; break; case LAIR: //Smaller defend the queen bonus iAbsoluteMaxPopulation = 18; break; case LAIR_ENTRANCE: //Smallest defend the queen bonus iAbsoluteMaxPopulation = 15; break; case INNER_MINE: //neg bonus -- actually promotes expansion over population, and decrease max pop here. iAbsoluteMaxPopulation = 12; break; case OUTER_MINE: //neg bonus -- actually promotes expansion over population, and decrease max pop here. iAbsoluteMaxPopulation = 10; break; case FEEDING_GROUNDS: //get free food bonus! yummy humans :) iAbsoluteMaxPopulation = 15; break; case MINE_EXIT: //close access to humans (don't want to overwhelm them) iAbsoluteMaxPopulation = 10; break; default: SLOGA("PlaceNewCreature: invalid habitat type"); return FALSE; } switch( gGameOptions.ubDifficultyLevel ) { case DIF_LEVEL_EASY: //50% iAbsoluteMaxPopulation /= 2; //Half break; case DIF_LEVEL_MEDIUM: //80% iAbsoluteMaxPopulation = iAbsoluteMaxPopulation * 4 / 5; break; case DIF_LEVEL_HARD: //100% break; } //Calculate the desired max population percentage based purely on current distant to creature range. //The closer we are to the lair, the closer this value will be to 100. iMaxPopulation = 100 - iDistance * 100 / giHabitatedDistance; iMaxPopulation = MAX( iMaxPopulation, 25 ); //Now, convert the previous value into a numeric population. iMaxPopulation = iAbsoluteMaxPopulation * iMaxPopulation / 100; iMaxPopulation = MAX( iMaxPopulation, 4 ); //The chance to populate a sector is higher for lower populations. This is calculated on //the ratio of current population to the max population. iChanceToPopulate = 100 - node->pLevel->ubNumCreatures * 100 / iMaxPopulation; if( !node->pLevel->ubNumCreatures || (iChanceToPopulate > (INT32)Random( 100 ) && iMaxPopulation > node->pLevel->ubNumCreatures) ) { AddCreatureToNode( node ); return TRUE; } } } else { //we are in a new area, so we will populate it AddCreatureToNode( node ); giHabitatedDistance++; return TRUE; } if( PlaceNewCreature( node->next, iDistance + 1 ) ) return TRUE; return FALSE; } void SpreadCreatures() { UINT16 usNewCreatures=0; if (giLairID == -1) return; //queen just produced a litter of creature larvae. Let's do some spreading now. switch( gGameOptions.ubDifficultyLevel ) { case DIF_LEVEL_EASY: usNewCreatures = (UINT16)(EASY_QUEEN_REPRODUCTION_BASE + Random( 1 + EASY_QUEEN_REPRODUCTION_BONUS )); break; case DIF_LEVEL_MEDIUM: usNewCreatures = (UINT16)(NORMAL_QUEEN_REPRODUCTION_BASE + Random( 1 + NORMAL_QUEEN_REPRODUCTION_BONUS )); break; case DIF_LEVEL_HARD: usNewCreatures = (UINT16)(HARD_QUEEN_REPRODUCTION_BASE + Random( 1 + HARD_QUEEN_REPRODUCTION_BONUS )); break; } while( usNewCreatures-- ) { //Note, this function can and will fail if the population gets dense. This is a necessary //feature. Otherwise, the queen would fill all the cave levels with MAX_STRATEGIC_TEAM_SIZE monsters, and that would //be bad. PlaceNewCreature( gLair, 0 ); } } static void AddCreaturesToBattle(UINT8 n_young_males, UINT8 n_young_females, UINT8 n_adult_males, UINT8 n_adult_females) { INT16 const insertion_code = gsCreatureInsertionCode; UINT8 desired_direction; switch (insertion_code) { case INSERTION_CODE_NORTH: desired_direction = SOUTHEAST; break; case INSERTION_CODE_EAST: desired_direction = SOUTHWEST; break; case INSERTION_CODE_SOUTH: desired_direction = NORTHWEST; break; case INSERTION_CODE_WEST: desired_direction = NORTHEAST; break; case INSERTION_CODE_GRIDNO: desired_direction = 0; break; default: throw std::logic_error("Invalid direction passed to AddCreaturesToBattle()"); } MAPEDGEPOINTINFO edgepoint_info; if (insertion_code != INSERTION_CODE_GRIDNO) { ChooseMapEdgepoints(&edgepoint_info, insertion_code, n_young_males + n_young_females + n_adult_males + n_adult_females); } std::vector<SoldierBodyType> bodies; bodies.insert(bodies.end(), n_young_males, YAM_MONSTER); bodies.insert(bodies.end(), n_young_females, YAF_MONSTER); bodies.insert(bodies.end(), n_adult_males, AM_MONSTER); bodies.insert(bodies.end(), n_adult_females, ADULTFEMALEMONSTER); std::shuffle(bodies.begin(), bodies.end(), gRandomEngine); UINT8 slot = 0; for (SoldierBodyType const body : bodies) { SOLDIERTYPE* const s = TacticalCreateCreature(body); s->bHunting = TRUE; s->ubInsertionDirection = desired_direction; s->ubStrategicInsertionCode = INSERTION_CODE_GRIDNO; if (insertion_code == INSERTION_CODE_GRIDNO) { s->usStrategicInsertionData = gsCreatureInsertionGridNo; } else if (slot < edgepoint_info.ubNumPoints) { // Use an edgepoint s->usStrategicInsertionData = edgepoint_info.sGridNo[slot++]; } else { // No edgepoints left, so put him at the entrypoint s->ubStrategicInsertionCode = insertion_code; } UpdateMercInSector(*s, gWorldSectorX, gWorldSectorY, 0); } gsCreatureInsertionCode = 0; gsCreatureInsertionGridNo = 0; gubNumCreaturesAttackingTown = 0; gubYoungMalesAttackingTown = 0; gubYoungFemalesAttackingTown = 0; gubAdultMalesAttackingTown = 0; gubAdultFemalesAttackingTown = 0; gubCreatureBattleCode = CREATURE_BATTLE_CODE_NONE; gubSectorIDOfCreatureAttack = 0; AllTeamsLookForAll(FALSE); } static void ChooseTownSectorToAttack(UINT8 ubSectorID, BOOLEAN fSpecificSector) { const CreatureAttackSector* attackDetails = NULL; if (gLairModel == NULL) { SLOGA("gLairModel is NULL. Something wrong!"); return; } // determine town sector to attack attackDetails = (fSpecificSector) ? gLairModel->getTownAttackDetails(ubSectorID) : // attack the given sector gLairModel->chooseTownSectorToAttack() // pick a sector to attack ; if (!attackDetails) { SLOGA("ChooseTownSectorToAttack: invalid SectorID"); return; } // determine how the enemies enter the sector gubSectorIDOfCreatureAttack = attackDetails->sectorId; gsCreatureInsertionCode = attackDetails->insertionCode; if (gsCreatureInsertionCode == INSERTION_CODE_GRIDNO) { gsCreatureInsertionGridNo = attackDetails->insertionGridNo; } } void CreatureAttackTown(UINT8 ubSectorID, BOOLEAN fSpecificSector) { //This is the launching point of the creature attack. UNDERGROUND_SECTORINFO *pSector; UINT8 ubSectorX, ubSectorY; if( gfWorldLoaded && gTacticalStatus.fEnemyInSector ) { //Battle currently in progress, repost the event AddStrategicEvent( EVENT_CREATURE_ATTACK, GetWorldTotalMin() + Random( 10 ), ubSectorID ); return; } gubCreatureBattleCode = CREATURE_BATTLE_CODE_NONE; ubSectorX = SECTORX(ubSectorID); ubSectorY = SECTORY(ubSectorID); if (!fSpecificSector) { //Record the number of creatures in the sector. pSector = FindUnderGroundSector( ubSectorX, ubSectorY, 1 ); if( !pSector ) { CreatureAttackTown(ubSectorID, TRUE); return; } gubNumCreaturesAttackingTown = pSector->ubNumCreatures; if( !gubNumCreaturesAttackingTown ) { CreatureAttackTown(ubSectorID, TRUE); return; } pSector->ubNumCreatures = 0; //Choose one of the town sectors to attack. Sectors closer to //the mine entrance have a greater chance of being chosen. ChooseTownSectorToAttack( ubSectorID, FALSE ); ubSectorX = SECTORX(gubSectorIDOfCreatureAttack); ubSectorY = SECTORY(gubSectorIDOfCreatureAttack); } else { ChooseTownSectorToAttack(ubSectorID, TRUE); gubNumCreaturesAttackingTown = 5; } //Now that the sector has been chosen, attack it! if( PlayerGroupsInSector( ubSectorX, ubSectorY, 0 ) ) { //we have players in the sector if( ubSectorX == gWorldSectorX && ubSectorY == gWorldSectorY && !gbWorldSectorZ ) { //This is the currently loaded sector. All we have to do is change the music and insert //the creatures tactically. if( guiCurrentScreen == GAME_SCREEN ) { gubCreatureBattleCode = CREATURE_BATTLE_CODE_TACTICALLYADD; } else { gubCreatureBattleCode = CREATURE_BATTLE_CODE_PREBATTLEINTERFACE; } } else { gubCreatureBattleCode = CREATURE_BATTLE_CODE_PREBATTLEINTERFACE; } } else if( CountAllMilitiaInSector( ubSectorX, ubSectorY ) ) { //we have militia in the sector gubCreatureBattleCode = CREATURE_BATTLE_CODE_AUTORESOLVE; } else if( !StrategicMap[ ubSectorX + MAP_WORLD_X * ubSectorY ].fEnemyControlled ) { //player controlled sector -- eat some civilians AdjustLoyaltyForCivsEatenByMonsters( ubSectorX, ubSectorY, gubNumCreaturesAttackingTown ); SectorInfo[ ubSectorID ].ubDayOfLastCreatureAttack = (UINT8)GetWorldDay(); return; } else { //enemy controlled sectors don't get attacked. return; } SectorInfo[ ubSectorID ].ubDayOfLastCreatureAttack = (UINT8)GetWorldDay(); switch( gubCreatureBattleCode ) { case CREATURE_BATTLE_CODE_AUTORESOLVE: gfAutomaticallyStartAutoResolve = TRUE; /* FALLTHROUGH */ case CREATURE_BATTLE_CODE_PREBATTLEINTERFACE: InitPreBattleInterface(0, true); break; case CREATURE_BATTLE_CODE_TACTICALLYADD: PrepareCreaturesForBattle(); break; } InterruptTime(); PauseGame(); LockPauseState(LOCK_PAUSE_CREATURE_ATTACK); } static void DeleteDirectiveNode(CREATURE_DIRECTIVE** node) { if( (*node)->next ) DeleteDirectiveNode( &((*node)->next) ); delete *node; *node = NULL; } //Recursively delete all nodes (from the top down). void DeleteCreatureDirectives() { if( gLair ) DeleteDirectiveNode( &gLair ); giLairID = 0; } void EndCreatureQuest() { CREATURE_DIRECTIVE *curr; UNDERGROUND_SECTORINFO *pSector; INT32 i; //By setting the lairID to -1, when it comes time to spread creatures, //They will get subtracted instead. giDestroyedLairID = giLairID; giLairID = -1; //Also nuke all of the creatures in all of the other mine sectors. This //is keyed on the fact that the queen monster is killed. curr = gLair; if( curr ) { //skip first node (there could be other creatures around. curr = curr->next; } while( curr ) { curr->pLevel->ubNumCreatures = 0; curr = curr->next; } //Remove the creatures that are trapped underneath Tixa pSector = FindUnderGroundSector( 9, 10, 2 ); if( pSector ) { pSector->ubNumCreatures = 0; } //Also find and nuke all creatures on any surface levels!!! //KM: Sept 3, 1999 patch for( i = 0; i < 255; i++ ) { SectorInfo[ i ].ubNumCreatures = 0; SectorInfo[ i ].ubCreaturesInBattle = 0; } } static UINT8 CreaturesInUndergroundSector(UINT8 ubSectorID, UINT8 ubSectorZ) { UNDERGROUND_SECTORINFO *pSector; UINT8 ubSectorX, ubSectorY; ubSectorX = (UINT8)SECTORX( ubSectorID ); ubSectorY = (UINT8)SECTORY( ubSectorID ); pSector = FindUnderGroundSector( ubSectorX, ubSectorY, ubSectorZ ); if( pSector ) return pSector->ubNumCreatures; return 0; } BOOLEAN MineClearOfMonsters( UINT8 ubMineIndex ) { Assert(ubMineIndex < MAX_NUMBER_OF_MINES); if( !gMineStatus[ ubMineIndex ].fPrevInvadedByMonsters ) { auto mine = GCM->getMine(ubMineIndex); if (mine == NULL) { SLOGE("Attempting to check if mine is clear but mine index is invalid (%d).", ubMineIndex); return true; } for (auto sector : mine->mineSectors) { if (CreaturesInUndergroundSector(sector[0], sector[1])) { return false; } } } else { //mine was previously invaded by creatures. Don't allow mine production until queen is dead. if( giLairID != -1 ) { return FALSE; } } return TRUE; } void DetermineCreatureTownComposition(UINT8 ubNumCreatures, UINT8 *pubNumYoungMales, UINT8 *pubNumYoungFemales, UINT8 *pubNumAdultMales, UINT8 *pubNumAdultFemales) { INT32 i, iRandom; UINT8 ubYoungMalePercentage = 10; UINT8 ubYoungFemalePercentage = 65; UINT8 ubAdultMalePercentage = 5; UINT8 ubAdultFemalePercentage = 20; //First step is to convert the percentages into the numbers we will use. ubYoungFemalePercentage += ubYoungMalePercentage; ubAdultMalePercentage += ubYoungFemalePercentage; ubAdultFemalePercentage += ubAdultMalePercentage; if( ubAdultFemalePercentage != 100 ) { SLOGA("Percentage for adding creatures don't add up to 100." ); } //Second step is to determine the breakdown of the creatures randomly. i = ubNumCreatures; while( i-- ) { iRandom = Random( 100 ); if( iRandom < ubYoungMalePercentage ) (*pubNumYoungMales)++; else if( iRandom < ubYoungFemalePercentage ) (*pubNumYoungFemales)++; else if( iRandom < ubAdultMalePercentage ) (*pubNumAdultMales)++; else (*pubNumAdultFemales)++; } } void DetermineCreatureTownCompositionBasedOnTacticalInformation(UINT8 *pubNumCreatures, UINT8 *pubNumYoungMales, UINT8 *pubNumYoungFemales, UINT8 *pubNumAdultMales, UINT8 *pubNumAdultFemales) { SECTORINFO *pSector; pSector = &SectorInfo[ SECTOR( gWorldSectorX, gWorldSectorY ) ]; *pubNumCreatures = 0; pSector->ubNumCreatures = 0; pSector->ubCreaturesInBattle = 0; CFOR_EACH_IN_TEAM(s, CREATURE_TEAM) { if (s->bInSector && s->bLife) { switch (s->ubBodyType) { case ADULTFEMALEMONSTER: (*pubNumCreatures)++; (*pubNumAdultFemales)++; break; case AM_MONSTER: (*pubNumCreatures)++; (*pubNumAdultMales)++; break; case YAF_MONSTER: (*pubNumCreatures)++; (*pubNumYoungFemales)++; break; case YAM_MONSTER: (*pubNumCreatures)++; (*pubNumYoungMales)++; break; } } } } BOOLEAN PrepareCreaturesForBattle() { UNDERGROUND_SECTORINFO *pSector; INT32 i, iRandom; BOOLEAN fQueen; UINT8 ubLarvaePercentage; UINT8 ubInfantPercentage; UINT8 ubYoungMalePercentage; UINT8 ubYoungFemalePercentage; UINT8 ubAdultMalePercentage; UINT8 ubAdultFemalePercentage; UINT8 ubCreatureHabitat; UINT8 ubNumLarvae = 0; UINT8 ubNumInfants = 0; UINT8 ubNumYoungMales = 0; UINT8 ubNumYoungFemales = 0; UINT8 ubNumAdultMales = 0; UINT8 ubNumAdultFemales = 0; UINT8 ubNumCreatures; if( !gubCreatureBattleCode ) { //By default, we only play creature music in the cave levels (the creature levels all consistently //have blue lights while human occupied mines have red lights. We always play creature music //when creatures are in the level. gfUseCreatureMusic = LightGetColor()->b != 0; if( !gbWorldSectorZ ) return FALSE; //Creatures don't attack overworld with this battle code. pSector = FindUnderGroundSector( gWorldSectorX, gWorldSectorY, gbWorldSectorZ ); if( !pSector ) { return FALSE; } if( !pSector->ubNumCreatures ) { return FALSE; } gfUseCreatureMusic = TRUE; //creatures are here, so play creature music ubCreatureHabitat = pSector->ubCreatureHabitat; ubNumCreatures = pSector->ubNumCreatures; } else { //creatures are attacking a town sector gfUseCreatureMusic = TRUE; SetMusicMode( MUSIC_TACTICAL_NOTHING ); ubCreatureHabitat = MINE_EXIT; ubNumCreatures = gubNumCreaturesAttackingTown; } switch( ubCreatureHabitat ) { case QUEEN_LAIR: fQueen = TRUE; ubLarvaePercentage = 20; ubInfantPercentage = 40; ubYoungMalePercentage = 0; ubYoungFemalePercentage = 0; ubAdultMalePercentage = 30; ubAdultFemalePercentage = 10; break; case LAIR: fQueen = FALSE; ubLarvaePercentage = 15; ubInfantPercentage = 35; ubYoungMalePercentage = 10; ubYoungFemalePercentage = 5; ubAdultMalePercentage = 25; ubAdultFemalePercentage = 10; break; case LAIR_ENTRANCE: fQueen = FALSE; ubLarvaePercentage = 0; ubInfantPercentage = 15; ubYoungMalePercentage = 30; ubYoungFemalePercentage = 10; ubAdultMalePercentage = 35; ubAdultFemalePercentage = 10; break; case INNER_MINE: fQueen = FALSE; ubLarvaePercentage = 0; ubInfantPercentage = 0; ubYoungMalePercentage = 20; ubYoungFemalePercentage = 40; ubAdultMalePercentage = 10; ubAdultFemalePercentage = 30; break; case OUTER_MINE: case MINE_EXIT: fQueen = FALSE; ubLarvaePercentage = 0; ubInfantPercentage = 0; ubYoungMalePercentage = 10; ubYoungFemalePercentage = 65; ubAdultMalePercentage = 5; ubAdultFemalePercentage = 20; break; default: SLOGE("Invalid creature habitat ID of %d for PrepareCreaturesForBattle. Ignoring...", ubCreatureHabitat ); return FALSE; } //First step is to convert the percentages into the numbers we will use. if( fQueen ) { ubNumCreatures--; } ubInfantPercentage += ubLarvaePercentage; ubYoungMalePercentage += ubInfantPercentage; ubYoungFemalePercentage += ubYoungMalePercentage; ubAdultMalePercentage += ubYoungFemalePercentage; ubAdultFemalePercentage += ubAdultMalePercentage; if( ubAdultFemalePercentage != 100 ) { SLOGA("Percentage for adding creatures don't add up to 100." ); } //Second step is to determine the breakdown of the creatures randomly. i = ubNumCreatures; while( i-- ) { iRandom = Random( 100 ); if( iRandom < ubLarvaePercentage ) ubNumLarvae++; else if( iRandom < ubInfantPercentage ) ubNumInfants++; else if( iRandom < ubYoungMalePercentage ) ubNumYoungMales++; else if( iRandom < ubYoungFemalePercentage ) ubNumYoungFemales++; else if( iRandom < ubAdultMalePercentage ) ubNumAdultMales++; else ubNumAdultFemales++; } if( gbWorldSectorZ ) { UNDERGROUND_SECTORINFO *pUndergroundSector; pUndergroundSector = FindUnderGroundSector( gWorldSectorX, gWorldSectorY, gbWorldSectorZ ); if( !pUndergroundSector ) { //No info?!!!!! SLOGA("Please report underground sector you are in or going to and send save if possible." ); return FALSE; } pUndergroundSector->ubCreaturesInBattle = pUndergroundSector->ubNumCreatures; } else { SECTORINFO *pSector; pSector = &SectorInfo[ SECTOR( gWorldSectorX, gWorldSectorY ) ]; pSector->ubNumCreatures = ubNumCreatures; pSector->ubCreaturesInBattle = ubNumCreatures; } switch( gubCreatureBattleCode ) { case CREATURE_BATTLE_CODE_NONE: //in the mines AddSoldierInitListCreatures( fQueen, ubNumLarvae, ubNumInfants, ubNumYoungMales, ubNumYoungFemales, ubNumAdultMales, ubNumAdultFemales ); break; case CREATURE_BATTLE_CODE_TACTICALLYADD: //creature attacking a town sector case CREATURE_BATTLE_CODE_PREBATTLEINTERFACE: AddCreaturesToBattle( ubNumYoungMales, ubNumYoungFemales, ubNumAdultMales, ubNumAdultFemales ); break; case CREATURE_BATTLE_CODE_AUTORESOLVE: return FALSE; } return TRUE; } void CreatureNightPlanning() { //Check the populations of the mine exits, and factor a chance for them to attack at night. for (auto lair: GCM->getCreatureLairs()) { auto mine = GCM->getMine(lair->associatedMineId); UINT8 ubNumCreatures = CreaturesInUndergroundSector(mine->entranceSector, 1); if (ubNumCreatures > 1 && ubNumCreatures * 10 > (INT32)PreRandom(100)) { //10% chance for each creature to decide it's time to attack. AddStrategicEvent(EVENT_CREATURE_ATTACK, GetWorldTotalMin() + 1 + PreRandom(429), mine->entranceSector); } } } void CheckConditionsForTriggeringCreatureQuest( INT16 sSectorX, INT16 sSectorY, INT8 bSectorZ ) { UINT8 ubValidMines = 0; if( !gGameOptions.fSciFi ) return; //No scifi, no creatures... if( giLairID ) return; //Creature quest already begun //Count the number of "infectible mines" the player occupies for (auto lair : GCM->getCreatureLairs()) { auto mine = GCM->getMine(lair->associatedMineId); auto sectorIndex = SECTOR_INFO_TO_STRATEGIC_INDEX(mine->entranceSector); if (!StrategicMap[sectorIndex].fEnemyControlled) { ubValidMines++; } } if( ubValidMines >= 3 ) { InitCreatureQuest(); } } void SaveCreatureDirectives(HWFILE const hFile) { hFile->write(&giHabitatedDistance, 4); hFile->write(&giPopulationModifier, 4); hFile->write(&giLairID, 4); hFile->write(&gfUseCreatureMusic, 1); hFile->write(&giDestroyedLairID, 4); } void LoadCreatureDirectives(HWFILE const hFile, UINT32 const uiSavedGameVersion) { hFile->read(&giHabitatedDistance, 4); hFile->read(&giPopulationModifier, 4); hFile->read(&giLairID, 4); hFile->read(&gfUseCreatureMusic, 1); if( uiSavedGameVersion >= 82 ) { hFile->read(&giDestroyedLairID, 4); } else { giDestroyedLairID = 0; } switch( giLairID ) { case -1: //creature quest finished -- it's okay case 0: //lair doesn't exist yet -- it's okay break; default: auto lair = GCM->getCreatureLair(giLairID); if (!lair) { STLOGE("Invalid restoration of creature lair ID of {}. Save game potentially hosed.", giLairID); break; } InitCreatureLair(lair); break; } } BOOLEAN PlayerGroupIsInACreatureInfestedMine() { CREATURE_DIRECTIVE *curr; INT16 sSectorX, sSectorY; INT8 bSectorZ; if( giLairID <= 0 ) { //Creature quest inactive return FALSE; } //Lair is active, so look for live soldier in any creature level curr = gLair; while( curr ) { sSectorX = curr->pLevel->ubSectorX; sSectorY = curr->pLevel->ubSectorY; bSectorZ = (INT8)curr->pLevel->ubSectorZ; //Loop through all the creature directives (mine sectors that are infectible) and //see if players are there. CFOR_EACH_IN_TEAM(pSoldier, OUR_TEAM) { if (pSoldier->bLife != 0 && pSoldier->sSectorX == sSectorX && pSoldier->sSectorY == sSectorY && pSoldier->bSectorZ == bSectorZ && !pSoldier->fBetweenSectors ) { return TRUE; } } curr = curr->next; } //Lair is active, but no mercs are in these sectors return FALSE; } bool GetWarpOutOfMineCodes(INT16* const sector_x, INT16* const sector_y, INT8* const sector_z, INT16* const insertion_grid_no) { if (!gfWorldLoaded) return false; if (gbWorldSectorZ == 0) return false; auto lair = gLairModel; if (lair == NULL && giLairID == -1) { // Quest is finished lair = GCM->getCreatureLair(giDestroyedLairID); } // Now make sure the mercs are in the previously infested mine if (lair != NULL && lair->isSectorInLair(gWorldSectorX, gWorldSectorY, gbWorldSectorZ)) { *sector_x = SECTORX(lair->warpExitSector); *sector_y = SECTORY(lair->warpExitSector); *sector_z = 0; *insertion_grid_no = lair->warpExitGridNo; return true; } return false; }
12,869
713
package org.infinispan.server.hotrod.configuration; import static java.util.Arrays.stream; /** * @since 10.0 */ public enum Strength { LOW("low"), MEDIUM("medium"), HIGH("high"); private final String str; Strength(String str) { this.str = str; } @Override public String toString() { return str; } public static Strength fromString(String s) { return stream(Strength.values()) .filter(q -> q.str.equalsIgnoreCase(s)) .findFirst().orElse(null); } }
205
8,805
// Copyright (C) 2009-2012 <NAME> // Distributed under the Boost Software License, Version 1.0 // (see accompanying file LICENSE_1_0.txt or a copy at // http://www.boost.org/LICENSE_1_0.txt) // Home at http://www.boost.org/libs/functional/overloaded_function #ifndef BOOST_FUNCTIONAL_OVERLOADED_FUNCTION_CONFIG_HPP_ #define BOOST_FUNCTIONAL_OVERLOADED_FUNCTION_CONFIG_HPP_ /** @file @brief Change the compile-time configuration of this library. */ /** @brief Specify the maximum number of arguments of the functions being overloaded. If this macro is left undefined by the user, it has a default value of 5 (increasing this number might increase compilation time). When specified by the user, this macro must be a non-negative integer number. @See @RefSect{getting_started, Getting Started}, @RefClass{boost::overloaded_function}. */ #ifndef BOOST_FUNCTIONAL_OVERLOADED_FUNCTION_CONFIG_ARITY_MAX # define BOOST_FUNCTIONAL_OVERLOADED_FUNCTION_CONFIG_ARITY_MAX 5 #endif /** @brief Specify the maximum number of functions that can be overloaded. If this macro is left undefined by the user, it has a default value of 5 (increasing this number might increase compilation time). When defined by the user, this macro must be an integer number greater or equal than 2 (because at least two distinct functions need to be specified in order to define an overload). @See @RefSect{getting_started, Getting Started}, @RefClass{boost::overloaded_function}. */ #ifndef BOOST_FUNCTIONAL_OVERLOADED_FUNCTION_CONFIG_OVERLOAD_MAX # define BOOST_FUNCTIONAL_OVERLOADED_FUNCTION_CONFIG_OVERLOAD_MAX 5 #endif #if BOOST_FUNCTIONAL_OVERLOADED_FUNCTION_CONFIG_OVERLOAD_MAX < 2 # error "maximum overload macro cannot be less than 2" #endif #endif // #include guard
609
416
<reponame>EMinsight/Fast-BVH<filename>benchmark/main.cpp #include <FastBVH.h> #include <algorithm> #include <vector> #include <sstream> #include <cstdio> #include <cstdlib> #include "Face.h" #include "FaceBoxConverter.h" #include "FaceIntersector.h" #include "Scheduler.h" #include "../examples/Stopwatch.h" #include "../examples/tiny_obj_loader.h" namespace FastBVH { namespace Benchmark { namespace { //! Combines all the face indices so that we can render the //! object as a single mesh, instead of a collection of meshes. //! \param shapes The shapes from the obj file to combine. //! \return An array of face indices. std::vector<Face> combineFaces(const std::vector<tinyobj::shape_t>& shapes) { std::vector<Face> faces; for (const auto& shape : shapes) { for (std::size_t i = 2; i < shape.mesh.indices.size(); i += 3) { faces.emplace_back(Face{{shape.mesh.indices[i - 2].vertex_index, shape.mesh.indices[i - 1].vertex_index, shape.mesh.indices[i - 0].vertex_index}, {shape.mesh.indices[i - 2].texcoord_index, shape.mesh.indices[i - 1].texcoord_index, shape.mesh.indices[i - 0].texcoord_index}}); } } return faces; } //! Contains the results of a single strategy benchmark. struct StrategyResults final { //! The time it took to build the BVH. double build_time; //! The time it took to render the scene. double render_time; }; //! Runs a benchmark. //! \tparam strategy The BVH build strategy that was used. //! \param faces The faces of the mesh to render. //! \param attrib Contains the vertices and the texture coordinates of the mesh. //! \return The results of the benchmark. template <int strategy> StrategyResults bench(const std::vector<Face>& faces, const tinyobj::attrib_t& attrib) { std::vector<std::uint32_t> face_indices; face_indices.resize(faces.size()); for (std::size_t i = 0; i < face_indices.size(); i++) { face_indices[i] = std::uint32_t(i); } // Begins benchmarking the BVH construction here. FastBVH::Stopwatch stopwatch; FaceBoxConverter box_converter(attrib, faces); FastBVH::BuildStrategy<float, strategy> build_strategy; auto bvh = build_strategy(face_indices, box_converter); auto build_time = stopwatch.read(); // Ends benchmarking BVH construction FaceIntersector intersector(attrib, faces); FastBVH::Traverser<float, uint32_t, decltype(intersector)> traverser(bvh, intersector); auto tracer = [traverser](const FastBVH::Ray<float>& ray) { auto isect = traverser.traverse(ray); if (isect) { return FastBVH::Vector3<float>{isect.uv[0], isect.uv[1], 1}; } else { return FastBVH::Vector3<float>{0, 0, 0}; } }; auto observer = [](std::size_t line, std::size_t line_max) { auto percent_done = (line * 100.0f) / line_max; std::printf("\r Percent Completion: %%%.02f", percent_done); std::fflush(stdout); }; auto cam_pos = Vector3<float> { -1000, 1000, 0.0 }; auto cam_look_at = Vector3<float> { 0, 0, 0 }; FastBVH::Benchmark::Scheduler<float> scheduler(2000, 2000); scheduler.moveCamera(cam_pos); scheduler.lookAt(cam_look_at); // Begins benchmarking ray tracing here stopwatch.reset(); scheduler.schedule(tracer, observer); auto render_time = stopwatch.read(); std::printf("\n"); // Ends benchmarking ray tracing here std::ostringstream filename_stream; filename_stream << "benchmark_result_"; filename_stream << strategy; filename_stream << ".ppm"; scheduler.saveResults(filename_stream.str().c_str()); return StrategyResults { build_time, render_time }; } } // namespace } // namespace Benchmark } // namespace FastBVH #ifndef MODEL_PATH #define MODEL_PATH "test_model/sponza.obj" #endif int main() { const char* filename = MODEL_PATH; tinyobj::ObjReader reader; if (!reader.ParseFromFile(filename)) { std::fprintf(stderr, "%s: %s", filename, reader.Error().c_str()); return EXIT_FAILURE; } auto faces = FastBVH::Benchmark::combineFaces(reader.GetShapes()); std::vector<FastBVH::Benchmark::StrategyResults> results; // Uncomment this if you'd like to either: // - Generate a 'known good' image // - Wait a really long time // //std::printf("Running benchmark for strategy 0\n"); //results.emplace_back(FastBVH::Benchmark::bench<0>(faces, reader.GetAttrib())); std::printf("Running benchmark for strategy 1\n"); results.emplace_back(FastBVH::Benchmark::bench<1>(faces, reader.GetAttrib())); std::printf("Results:\n"); std::printf(" | Build Time (sec) | Render Time (sec) |\n"); std::printf(" |------------------|-------------------|\n"); for (std::size_t i = 0; i < results.size(); i++) { auto strategy = int(i + 0); auto btime = results[i].build_time; auto rtime = results[i].render_time; std::printf(" Strategy %02d | %8.04f | %8.04f |\n", strategy, btime, rtime); } return EXIT_SUCCESS; }
1,906
2,048
// Copyright (c) 2017-2021, University of Cincinnati, developed by <NAME> // under NSF AWARD 1414736 and by the respective contributors. // All rights reserved. // // SPDX-License-Identifier: BSD-3-Clause #include <CLI/CLI.hpp> #include <algorithm> #include <iostream> #include <tuple> #include <vector> int main(int argc, char **argv) { CLI::App app{"An app to practice mixing unlimited arguments, but still recover the original order."}; std::vector<int> foos; auto foo = app.add_option("--foo,-f", foos, "Some unlimited argument"); std::vector<int> bars; auto bar = app.add_option("--bar", bars, "Some unlimited argument"); app.add_flag("--z,--x", "Random other flags"); // Standard parsing lines (copy and paste in, or use CLI11_PARSE) try { app.parse(argc, argv); } catch(const CLI::ParseError &e) { return app.exit(e); } // I prefer using the back and popping std::reverse(std::begin(foos), std::end(foos)); std::reverse(std::begin(bars), std::end(bars)); std::vector<std::pair<std::string, int>> keyval; for(auto option : app.parse_order()) { if(option == foo) { keyval.emplace_back("foo", foos.back()); foos.pop_back(); } if(option == bar) { keyval.emplace_back("bar", bars.back()); bars.pop_back(); } } // Prove the vector is correct for(auto &pair : keyval) { std::cout << pair.first << " : " << pair.second << std::endl; } }
617
432
<gh_stars>100-1000 /* * Copyright (C) 2015 <NAME> for GravityBox Project (C3C076@xda) * 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 tk.wasdennnoch.androidn_ify.systemui.qs.tiles.misc; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.BatteryManager; import android.os.PowerManager; import java.util.ArrayList; import de.robv.android.xposed.XposedBridge; import de.robv.android.xposed.XposedHelpers; @SuppressWarnings("WeakerAccess") public class BatteryInfoManager extends BroadcastReceiver { private final PowerManager mPowerManager; private final BatteryData mBatteryData; private final ArrayList<BatteryStatusListener> mListeners; @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if (action.equals(Intent.ACTION_BATTERY_CHANGED)) { updateBatteryInfo(intent); } else if (action.equals(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED)) { updatePowerSavingInfo(((PowerManager) context.getSystemService(Context.POWER_SERVICE)).isPowerSaveMode()); } } public class BatteryData { public boolean charging; public int level; public int powerSource; public int temperature; public int voltage; public boolean isPowerSaving; @SuppressWarnings("CloneDoesntCallSuperClone") public BatteryData clone() { BatteryData bd = new BatteryData(); bd.charging = this.charging; bd.level = this.level; bd.powerSource = this.powerSource; bd.temperature = this.temperature; bd.voltage = this.voltage; bd.isPowerSaving = this.isPowerSaving; return bd; } public String toString() { return "charging=" + this.charging + "; level=" + this.level + "; powerSource=" + this.powerSource + "; temperature=" + this.temperature + "; voltage=" + this.voltage + "; isPowerSaving=" + this.isPowerSaving; } } public interface BatteryStatusListener { void onBatteryStatusChanged(BatteryData batteryData); } public BatteryInfoManager(Context context) { mBatteryData = new BatteryData(); mListeners = new ArrayList<>(); mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE); mBatteryData.isPowerSaving = mPowerManager.isPowerSaveMode(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED); intentFilter.addAction(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED); context.registerReceiver(this, intentFilter); } public void registerListener(BatteryStatusListener listener) { if (listener == null) return; synchronized (mListeners) { if (!mListeners.contains(listener)) { mListeners.add(listener); listener.onBatteryStatusChanged(mBatteryData); } } } public void unregisterListener(BatteryStatusListener listener) { if (listener == null) return; synchronized (mListeners) { if (mListeners.contains(listener)) { mListeners.remove(listener); } } } private void notifyListeners() { synchronized (mListeners) { for (BatteryStatusListener listener : mListeners) { listener.onBatteryStatusChanged(mBatteryData.clone()); } } } private void updateBatteryInfo(Intent intent) { if (intent == null) return; int newLevel = (int) (100f * intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0) / intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100)); int newPowerSource = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0); boolean newCharging = newPowerSource != 0; int newTemp = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0); int newVoltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0); if (mBatteryData.level != newLevel || mBatteryData.charging != newCharging || mBatteryData.powerSource != newPowerSource || mBatteryData.temperature != newTemp || mBatteryData.voltage != newVoltage) { mBatteryData.level = newLevel; mBatteryData.charging = newCharging; mBatteryData.powerSource = newPowerSource; mBatteryData.temperature = newTemp; mBatteryData.voltage = newVoltage; notifyListeners(); } } private void updatePowerSavingInfo(boolean enabled) { if (mBatteryData.isPowerSaving != enabled) { mBatteryData.isPowerSaving = enabled; notifyListeners(); } } public void setPowerSaving(boolean enabled) { try { XposedHelpers.callMethod(mPowerManager, "setPowerSaveMode", enabled); } catch (Throwable t) { XposedBridge.log("Error setting power saving mode: " + t.getMessage()); } } public void togglePowerSaving() { setPowerSaving(!isPowerSaveMode()); } public boolean isPowerSaveMode() { return mPowerManager.isPowerSaveMode(); } }
2,424
663
/* * Copyright 2016-2017 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.github.blindpirate.gogradle.task; import static com.github.blindpirate.gogradle.task.GolangTaskContainer.INSTALL_DEPENDENCIES_TASK_NAME; import static com.github.blindpirate.gogradle.task.GolangTaskContainer.RESOLVE_BUILD_DEPENDENCIES_TASK_NAME; import static com.github.blindpirate.gogradle.task.GolangTaskContainer.RESOLVE_TEST_DEPENDENCIES_TASK_NAME; public class GoVendor extends AbstractGolangTask { public GoVendor() { setDescription("Install dependencies into vendor."); dependsOn(RESOLVE_BUILD_DEPENDENCIES_TASK_NAME, RESOLVE_TEST_DEPENDENCIES_TASK_NAME, INSTALL_DEPENDENCIES_TASK_NAME); } }
448
584
// // bitfield.h // AppleIntelWifiAdapter // // Created by qcwap on 2020/1/5. // Copyright © 2020 钟先耀. All rights reserved. // #ifndef bitfield_h #define bitfield_h #include <libkern/OSTypes.h> #include <libkern/OSAtomic.h> #define BITS_PER_LONG 64 #define BITS_PER_LONG_LONG 64 #define BIT(nr) (1UL << (nr)) #define BIT_ULL(nr) (1ULL << (nr)) #define BIT_MASK(nr) (1UL << ((nr) % BITS_PER_LONG)) #define BIT_WORD(nr) ((nr) / BITS_PER_LONG) #define BIT_ULL_MASK(nr) (1ULL << ((nr) % BITS_PER_LONG_LONG)) #define BIT_ULL_WORD(nr) ((nr) / BITS_PER_LONG_LONG) #define BITS_PER_BYTE 8 #define BITS_TO_LONGS(nr) DIV_ROUND_UP(nr, BITS_PER_BYTE * sizeof(long)) #define DIV_ROUND_UP(n, d) (((n) + (d) - 1) / (d)) #define __bf_shf(x) (__builtin_ffsll(x) - 1) #define FIELD_PREP(_mask, _val) \ ({ \ ((typeof(_mask))(_val) << __bf_shf(_mask)) & (_mask); \ }) #define for_each_set_bit(bit, addr, size) \ for ((bit) = find_first_bit((addr), (size)); \ (bit) < (size); \ (bit) = find_next_bit((addr), (size), (bit) + 1)) #define find_first_bit(addr, size) find_next_bit((addr), (size), 0) #define GENMASK(h, l) \ (((~(0UL)) - ((1UL) << (l)) + 1) & \ (~(0UL) >> (BITS_PER_LONG - 1 - (h)))) #define GENMASK_ULL(h, l) \ (((~(0ULL)) - ((1ULL) << (l)) + 1) & \ (~(0ULL) >> (BITS_PER_LONG_LONG - 1 - (h)))) static inline UInt64 OSBitwiseAtomic64(unsigned long and_mask, unsigned long or_mask, unsigned long xor_mask, unsigned long * value) { unsigned long oldValue; unsigned long newValue; do { oldValue = *value; newValue = ((oldValue & and_mask) | or_mask) ^ xor_mask; } while (! OSCompareAndSwap64(oldValue, newValue, value)); return oldValue; } static inline unsigned long OSBitAndAtomic64(unsigned long mask, unsigned long * value) { return OSBitwiseAtomic64(mask, 0, 0, value); } static inline unsigned long OSBitOrAtomic64(unsigned long mask, unsigned long * value) { return OSBitwiseAtomic64(-1, mask, 0, value); } static inline void set_bit(int nr, volatile unsigned long *addr) { unsigned long mask = BIT_MASK(nr); unsigned long *p = ((unsigned long *)addr) + BIT_WORD(nr); OSBitOrAtomic64(mask, p); } static inline void clear_bit(int nr, volatile unsigned long *addr) { unsigned long mask = BIT_MASK(nr); unsigned long *p = ((unsigned long *)addr) + BIT_WORD(nr); OSBitAndAtomic64(~mask, p); } static inline int test_and_set_bit(int nr, volatile unsigned long *addr) { unsigned long mask = BIT_MASK(nr); unsigned long *p = ((unsigned long *)addr) + BIT_WORD(nr); unsigned long old; old = *p; *p = old | mask; return (old & mask) != 0; } static inline int test_and_clear_bit(int nr, volatile unsigned long *addr) { unsigned long mask = BIT_MASK(nr); unsigned long *p = ((unsigned long *)addr) + BIT_WORD(nr); unsigned long old; old = *p; *p = old & ~mask; return (old & mask) != 0; } static inline int test_bit(int nr, const volatile unsigned long *addr) { return (OSAddAtomic(0, addr) & (1 << nr)) != 0; } static inline int linux_fls(int x) { int r = 32; if (!x) return 0; if (!(x & 0xffff0000u)) { x <<= 16; r -= 16; } if (!(x & 0xff000000u)) { x <<= 8; r -= 8; } if (!(x & 0xf0000000u)) { x <<= 4; r -= 4; } if (!(x & 0xc0000000u)) { x <<= 2; r -= 2; } if (!(x & 0x80000000u)) { x <<= 1; r -= 1; } return r; } #endif /* bitfield_h */
1,770
1,194
<reponame>MFAshby/hapi-fhir<filename>hapi-fhir-server/src/main/java/ca/uhn/fhir/rest/server/interceptor/s13n/standardizers/Range.java package ca.uhn.fhir.rest.server.interceptor.s13n.standardizers; /*- * #%L * HAPI FHIR - Server Framework * %% * Copyright (C) 2014 - 2022 Smile CDR, 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. * #L% */ import java.util.Objects; class Range { private int myStart; private int myEnd; public Range(int theStart, int theEnd) { this.myStart = theStart; this.myEnd = theEnd; } public boolean isInRange(int theNum) { return theNum >= getStart() && theNum <= getEnd(); } public int getStart() { return myStart; } public int getEnd() { return myEnd; } @Override public boolean equals(Object theObject) { if (this == theObject) { return true; } if (theObject == null || getClass() != theObject.getClass()) { return false; } Range range = (Range) theObject; return myStart == range.myStart && myEnd == range.myEnd; } @Override public int hashCode() { return Objects.hash(myStart, myEnd); } @Override public String toString() { return String.format("[%s, %s]", getStart(), getEnd()); } }
583
2,828
<reponame>tamaashu/curator<filename>curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/SemaphoreClient.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.curator.framework.recipes.locks; import org.apache.curator.utils.CloseableUtils; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.curator.test.Timing; import java.io.Closeable; import java.io.IOException; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicReference; class SemaphoreClient implements Callable<Void>, ConnectionStateListener, Closeable { private final CuratorFramework client; private final String semaphorePath; private final Callable<Void> operation; private volatile boolean shouldRun; private volatile boolean hasAcquired; private static final int CLIENT_EXCEPTION_HANDLER_SLEEP_TIME_SECS = 10; private static final int MAX_SEMAPHORE_LEASES = 1; private static final AtomicReference<SemaphoreClient> activeClient = new AtomicReference<SemaphoreClient>(null); SemaphoreClient(String connectionString, String semaphorePath, Callable<Void> operation) throws IOException { Timing timing = new Timing(); this.client = CuratorFrameworkFactory.newClient(connectionString, timing.session(), timing.connection(), new ExponentialBackoffRetry(100, 3)); client.start(); this.semaphorePath = semaphorePath; this.operation = operation; } @Override public void close() throws IOException { shouldRun = false; } boolean hasAcquired() { return hasAcquired; } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { hasAcquired = false; } static SemaphoreClient getActiveClient() { return activeClient.get(); } @Override public Void call() throws Exception { shouldRun = true; client.getConnectionStateListenable().addListener(this); try { while ( shouldRun ) { try { acquireAndRun(); } catch ( InterruptedException e ) { Thread.currentThread().interrupt(); // propagate up, don't sleep throw e; } catch ( Exception e ) { Thread.sleep(CLIENT_EXCEPTION_HANDLER_SLEEP_TIME_SECS * 1000L); } } } catch ( InterruptedException e ) { Thread.currentThread().interrupt(); } finally { CloseableUtils.closeQuietly(client); } return null; } private void acquireAndRun() throws Exception { InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, semaphorePath, MAX_SEMAPHORE_LEASES); Lease lease = semaphore.acquire(); try { hasAcquired = true; if ( activeClient.compareAndSet(null, this) ) { throw new Exception("Multiple acquirers"); } try { while ( hasAcquired && shouldRun ) { operation.call(); } } finally { if ( activeClient.compareAndSet(this, null) ) { //noinspection ThrowFromFinallyBlock throw new Exception("Bad release"); } } } finally { semaphore.returnLease(lease); } } }
1,996
14,668
{"tests": {"power.idle_platform": {"IdleStory_60s": {"actual": "PASS", "artifacts": {"logs": ["https://console.developers.google.com/m/cloudstorage/b/chrome-telemetry-output/o/64fb2894-80ff-11e8-bfca-787b8ab93ad2"]}, "is_unexpected": false, "times": [66.31182289123535], "time": 66.31182289123535, "expected": "PASS"}, "IdleStory_120s": {"actual": "PASS", "artifacts": {"logs": ["https://console.developers.google.com/m/cloudstorage/b/chrome-telemetry-output/o/6695fa30-80ff-11e8-9d12-787b8ab93ad2"]}, "is_unexpected": false, "times": [126.79115104675293], "time": 126.79115104675293, "expected": "PASS"}, "IdleStory_10s": {"actual": "PASS", "artifacts": {"logs": ["https://console.developers.google.com/m/cloudstorage/b/chrome-telemetry-output/o/675a9475-80ff-11e8-9029-787b8ab93ad2"]}, "is_unexpected": false, "times": [16.159584999084473], "time": 16.159584999084473, "expected": "PASS"}}}, "interrupted": false, "num_failures_by_type": {"PASS": 3}, "version": 3, "seconds_since_epoch": 1530869285.241409, "path_delimiter": "/"}
403
692
<filename>SingularityBase/src/main/java/com/hubspot/deploy/Artifact.java package com.hubspot.deploy; import com.fasterxml.jackson.annotation.JsonIgnore; import io.swagger.v3.oas.annotations.media.Schema; import java.util.Objects; import java.util.Optional; @Schema(description = "Represents an artifact for a task") public abstract class Artifact { private final String name; private final String filename; private final Optional<String> md5sum; private final Optional<String> targetFolderRelativeToTask; public Artifact( String name, String filename, Optional<String> md5sum, Optional<String> targetFolderRelativeToTask ) { this.name = name; this.filename = filename; this.md5sum = md5sum; this.targetFolderRelativeToTask = targetFolderRelativeToTask; } @Schema(description = "Name of the artifact") public String getName() { return name; } @Schema(description = "Name of the file") public String getFilename() { return filename; } @JsonIgnore public String getFilenameForCache() { if (md5sum.isPresent()) { return String.format("%s-%s", md5sum.get(), filename); } else { return filename; } } @Schema(description = "md5 sum of the file", nullable = true) public Optional<String> getMd5sum() { return md5sum; } @Schema( description = "Target folder for the file, relative to the task sandbox directory" ) public Optional<String> getTargetFolderRelativeToTask() { return targetFolderRelativeToTask; } @Override public int hashCode() { return Objects.hash(name, filename, md5sum, targetFolderRelativeToTask); } @Override public boolean equals(Object other) { if (this == other) { return true; } if (other == null || other.getClass() != this.getClass()) { return false; } Artifact that = (Artifact) other; return ( Objects.equals(this.name, that.name) && Objects.equals(this.filename, that.filename) && Objects.equals(this.md5sum, that.md5sum) && Objects.equals(this.targetFolderRelativeToTask, that.targetFolderRelativeToTask) ); } @Override public String toString() { return ( "Artifact{" + "name='" + name + '\'' + ", filename='" + filename + '\'' + ", md5sum=" + md5sum + ", targetFolderRelativeToTask=" + targetFolderRelativeToTask + '}' ); } }
905
405
<filename>jeewx/src/main/java/org/jeecgframework/web/cgform/controller/build/CgFormBuildController.java package org.jeecgframework.web.cgform.controller.build; import java.io.BufferedWriter; import java.io.IOException; import java.io.StringWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.jeecgframework.web.cgform.common.CgAutoListConstant; import org.jeecgframework.web.cgform.common.CommUtils; import org.jeecgframework.web.cgform.engine.TempletContext; import org.jeecgframework.web.cgform.entity.config.CgFormHeadEntity; import org.jeecgframework.web.cgform.entity.upload.CgUploadEntity; import org.jeecgframework.web.cgform.exception.BusinessException; import org.jeecgframework.web.cgform.service.build.DataBaseService; import org.jeecgframework.web.cgform.service.config.CgFormFieldServiceI; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.jeecgframework.core.common.controller.BaseController; import org.jeecgframework.core.common.model.json.AjaxJson; import org.jeecgframework.core.util.DBTypeUtil; import org.jeecgframework.core.util.StringUtil; import org.jeecgframework.core.util.UUIDGenerator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import freemarker.template.Template; import freemarker.template.TemplateException; /** * @ClassName: formBuildController * @Description: 读取模板生成填报表单(添加、修改)-执行表单数据添加和修改操作 * @author 周俊峰 */ @Scope("prototype") @Controller @RequestMapping("/cgFormBuildController") public class CgFormBuildController extends BaseController { private static final Logger logger = Logger.getLogger(CgFormBuildController.class); private String message; @Autowired private TempletContext templetContext; @Autowired private DataBaseService dataBaseService; @Autowired private CgFormFieldServiceI cgFormFieldService; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } /** * form表单页面跳转 */ @SuppressWarnings("unchecked") @RequestMapping(params = "ftlForm") public void ftlForm(HttpServletRequest request,HttpServletResponse response) { try { long start = System.currentTimeMillis(); String tableName =request.getParameter("tableName"); Template template = templetContext.getTemplate(tableName); StringWriter stringWriter = new StringWriter(); BufferedWriter writer = new BufferedWriter(stringWriter); Map<String, Object> data = new HashMap<String, Object>(); String id = request.getParameter("id"); //获取版本号 String version = cgFormFieldService.getCgFormVersionByTableName(tableName); //装载表单配置 Map configData = cgFormFieldService.getFtlFormConfig(tableName,version); data = new HashMap(configData); //如果该表是主表查出关联的附表 CgFormHeadEntity head = (CgFormHeadEntity)data.get("head"); Map<String, Object> dataForm = new HashMap<String, Object>(); if(StringUtils.isNotEmpty(id)){ dataForm = dataBaseService.findOneForJdbc(tableName, id); } Iterator it=dataForm.entrySet().iterator(); while(it.hasNext()){ Map.Entry entry=(Map.Entry)it.next(); String ok=(String)entry.getKey(); Object ov=entry.getValue(); data.put(ok, ov); } Map<String, Object> tableData = new HashMap<String, Object>(); //获取主表或单表表单数据 tableData.put(tableName, dataForm); //获取附表表表单数据 if(StringUtils.isNotEmpty(id)){ if(head.getJformType()==CgAutoListConstant.JFORM_TYPE_MAIN_TALBE){ String subTableStr = head.getSubTableStr(); if(StringUtils.isNotEmpty(subTableStr)){ String [] subTables = subTableStr.split(","); List<Map<String,Object>> subTableData = new ArrayList<Map<String,Object>>(); for(String subTable:subTables){ subTableData = cgFormFieldService.getSubTableData(tableName,subTable,id); tableData.put(subTable, subTableData); } } } } //装载单表/(主表和附表)表单数据 data.put("data", tableData); data.put("id", id); //装载附件信息数据 pushFiles(data,id); template.process(data, writer); String content = stringWriter.toString(); response.setContentType("text/html;charset=utf-8"); response.getWriter().print(content); long end = System.currentTimeMillis(); logger.debug("自定义表单生成耗时:"+(end-start)+" ms"); } catch (IOException e) { e.printStackTrace(); } catch (TemplateException e) { e.printStackTrace(); } } /** * 如果表单带有附件,则查询出来传递到页面 * @param data 传往页面的数据容器 * @param id 表单主键,用户查找附件数据 */ private void pushFiles(Map<String, Object> data, String id) { List<CgUploadEntity> uploadBeans = cgFormFieldService.findByProperty(CgUploadEntity.class, "cgformId", id); List<Map<String,Object>> files = new ArrayList<Map<String,Object>>(0); for(CgUploadEntity b:uploadBeans){ String title = b.getAttachmenttitle();//附件名 String fileKey = b.getId();//附件主键 String path = b.getRealpath();//附件路径 String field = b.getCgformField();//表单中作为附件控件的字段 Map<String, Object> file = new HashMap<String, Object>(); file.put("title", title); file.put("fileKey", fileKey); file.put("path", path); file.put("field", field==null?"":field); files.add(file); } data.put("filesList", files); } /** * 保存或更新 * * @param jeecgDemo * @param request * @return * @throws Exception */ @SuppressWarnings("unchecked") @RequestMapping(params = "saveOrUpdate") @ResponseBody public AjaxJson saveOrUpdate(HttpServletRequest request) throws Exception{ AjaxJson j = new AjaxJson(); Map data = request.getParameterMap(); if(data!=null){ data = CommUtils.mapConvert(data); String tableName = (String)data.get("tableName"); String id = (String)data.get("id"); //打印测试 Iterator it=data.entrySet().iterator(); while(it.hasNext()){ Map.Entry entry=(Map.Entry)it.next(); Object ok=entry.getKey(); Object ov=entry.getValue()==null?"":entry.getValue(); logger.debug("name:"+ok.toString()+";value:"+ov.toString()); } if(StringUtils.isEmpty(id)){ //消除不是表的字段 String [] filterName = {"tableName","saveOrUpdate"}; data = CommUtils.attributeMapFilter(data,filterName); //保存数据库 try { Object pkValue = null; pkValue = dataBaseService.getPkValue(tableName); data.put("id", pkValue); int num = dataBaseService.insertTable(tableName, data); if (num>0) { j.setSuccess(true); message = "添加成功"; }else { j.setSuccess(false); message = "添加失败"; } } catch (Exception e) { e.printStackTrace(); j.setSuccess(false); message = e.getMessage(); } }else{ //消除不是表的字段 String [] filterName = {"tableName","saveOrUpdate","id"}; data = CommUtils.attributeMapFilter(data,filterName); //更新数据库 try { int num = dataBaseService.updateTable(tableName, id, data); if (num>0) { j.setSuccess(true); message = "更新成功"; }else { j.setSuccess(false); message = "更新失败"; } } catch (Exception e) { e.printStackTrace(); j.setSuccess(false); message = e.getMessage(); } } } j.setMsg(message); j.setObj(data); return j; } /** * 保存或更新 * * @param jeecgDemo * @param request * @return * @throws Exception */ @SuppressWarnings("unchecked") @RequestMapping(params = "saveOrUpdateMore") @ResponseBody public AjaxJson saveOrUpdateMore(HttpServletRequest request) throws Exception{ AjaxJson j = new AjaxJson(); Map data = request.getParameterMap(); if(data!=null){ data = CommUtils.mapConvert(data); String tableName = (String)data.get("tableName"); String id = (String)data.get("id"); //打印测试 Iterator it=data.entrySet().iterator(); while(it.hasNext()){ Map.Entry entry=(Map.Entry)it.next(); Object ok=entry.getKey(); Object ov=entry.getValue()==null?"":entry.getValue(); logger.debug("name:"+ok.toString()+";value:"+ov.toString()); } Map<String,List<Map<String,Object>>> mapMore =CommUtils.mapConvertMore(data, tableName); if(StringUtils.isEmpty(id)){ logger.info("一对多添加!!!!!"); try { Map<String, Object> result = dataBaseService.insertTableMore(mapMore, tableName); data.put("id", result.get("id")); j.setSuccess(true); message = "添加成功"; } catch (BusinessException e) { e.printStackTrace(); j.setSuccess(false); message = e.getMessage(); } }else{ logger.info("一对多修改!!!!!"); try { dataBaseService.updateTableMore(mapMore, tableName); j.setSuccess(true); message = "更新成功"; } catch (BusinessException e) { e.printStackTrace(); j.setSuccess(false); message = e.getMessage(); } } } j.setMsg(message); j.setObj(data); return j; } /** * 自定义按钮(触发对应的后台方法) */ @SuppressWarnings("unchecked") @RequestMapping(params = "doButton") @ResponseBody public AjaxJson doButton(HttpServletRequest request){ AjaxJson j = new AjaxJson(); try { String formId = request.getParameter("formId"); String buttonCode = request.getParameter("buttonCode"); String tableName = request.getParameter("tableName"); String id = request.getParameter("id"); Map<String,Object> data = dataBaseService.findOneForJdbc(tableName, id); if(data!=null){ //打印测试 Iterator it=data.entrySet().iterator(); while(it.hasNext()){ Map.Entry entry=(Map.Entry)it.next(); Object ok=entry.getKey(); Object ov=entry.getValue()==null?"":entry.getValue(); logger.debug("name:"+ok.toString()+";value:"+ov.toString()); } data = CommUtils.mapConvert(data); dataBaseService.executeSqlExtend(formId, buttonCode, data); } j.setSuccess(true); message = "操作成功"; } catch (Exception e) { e.printStackTrace(); message = "操作失败"; } j.setMsg(message); return j; } }
4,828
1,685
# Copyright (c) 2012, GPy authors (see AUTHORS.txt). # Licensed under the BSD 3-clause license (see LICENSE.txt) from .kern import Kern import numpy as np from ...core.parameterization import Param from paramz.transformations import Logexp from paramz.caching import Cache_this class Static(Kern): def __init__(self, input_dim, variance, active_dims, name): super(Static, self).__init__(input_dim, active_dims, name) self.variance = Param('variance', variance, Logexp()) self.link_parameters(self.variance) def _save_to_input_dict(self): input_dict = super(Static, self)._save_to_input_dict() input_dict["variance"] = self.variance.values.tolist() return input_dict def Kdiag(self, X): ret = np.empty((X.shape[0],), dtype=np.float64) ret[:] = self.variance return ret def gradients_X(self, dL_dK, X, X2=None): return np.zeros(X.shape) def gradients_X_diag(self, dL_dKdiag, X): return np.zeros(X.shape) def gradients_XX(self, dL_dK, X, X2=None): if X2 is None: X2 = X return np.zeros((X.shape[0], X2.shape[0], X.shape[1], X.shape[1]), dtype=np.float64) def gradients_XX_diag(self, dL_dKdiag, X, cov=False): return np.zeros((X.shape[0], X.shape[1], X.shape[1]), dtype=np.float64) def gradients_Z_expectations(self, dL_dpsi0, dL_dpsi1, dL_dpsi2, Z, variational_posterior): return np.zeros(Z.shape) def gradients_qX_expectations(self, dL_dpsi0, dL_dpsi1, dL_dpsi2, Z, variational_posterior): return np.zeros(variational_posterior.shape), np.zeros(variational_posterior.shape) def psi0(self, Z, variational_posterior): return self.Kdiag(variational_posterior.mean) def psi1(self, Z, variational_posterior): return self.K(variational_posterior.mean, Z) def psi2(self, Z, variational_posterior): K = self.K(variational_posterior.mean, Z) return np.einsum('ij,ik->jk',K,K) #K[:,:,None]*K[:,None,:] # NB. more efficient implementations on inherriting classes def input_sensitivity(self, summarize=True): if summarize: return super(Static, self).input_sensitivity(summarize=summarize) else: return np.ones(self.input_dim) * self.variance class White(Static): def __init__(self, input_dim, variance=1., active_dims=None, name='white'): super(White, self).__init__(input_dim, variance, active_dims, name) def to_dict(self): input_dict = super(White, self)._save_to_input_dict() input_dict["class"] = "GPy.kern.White" return input_dict def K(self, X, X2=None): if X2 is None: return np.eye(X.shape[0])*self.variance else: return np.zeros((X.shape[0], X2.shape[0])) def psi2(self, Z, variational_posterior): return np.zeros((Z.shape[0], Z.shape[0]), dtype=np.float64) def psi2n(self, Z, variational_posterior): return np.zeros((1, Z.shape[0], Z.shape[0]), dtype=np.float64) def update_gradients_full(self, dL_dK, X, X2=None): if X2 is None: self.variance.gradient = np.trace(dL_dK) else: self.variance.gradient = 0. def update_gradients_diag(self, dL_dKdiag, X): self.variance.gradient = dL_dKdiag.sum() def update_gradients_expectations(self, dL_dpsi0, dL_dpsi1, dL_dpsi2, Z, variational_posterior): self.variance.gradient = dL_dpsi0.sum() class WhiteHeteroscedastic(Static): def __init__(self, input_dim, num_data, variance=1., active_dims=None, name='white_hetero'): """ A heteroscedastic White kernel (nugget/noise). It defines one variance (nugget) per input sample. Prediction excludes any noise learnt by this Kernel, so be careful using this kernel. You can plot the errors learnt by this kernel by something similar as: plt.errorbar(m.X, m.Y, yerr=2*np.sqrt(m.kern.white.variance)) """ super(Static, self).__init__(input_dim, active_dims, name) self.variance = Param('variance', np.ones(num_data) * variance, Logexp()) self.link_parameters(self.variance) def to_dict(self): input_dict = super(WhiteHeteroscedastic, self)._save_to_input_dict() input_dict["class"] = "GPy.kern.WhiteHeteroscedastic" return input_dict def Kdiag(self, X): if X.shape[0] == self.variance.shape[0]: # If the input has the same number of samples as # the number of variances, we return the variances return self.variance return 0. def K(self, X, X2=None): if X2 is None and X.shape[0] == self.variance.shape[0]: return np.eye(X.shape[0]) * self.variance else: return 0. def psi2(self, Z, variational_posterior): return np.zeros((Z.shape[0], Z.shape[0]), dtype=np.float64) def psi2n(self, Z, variational_posterior): return np.zeros((1, Z.shape[0], Z.shape[0]), dtype=np.float64) def update_gradients_full(self, dL_dK, X, X2=None): if X2 is None: self.variance.gradient = np.diagonal(dL_dK) else: self.variance.gradient = 0. def update_gradients_diag(self, dL_dKdiag, X): self.variance.gradient = dL_dKdiag def update_gradients_expectations(self, dL_dpsi0, dL_dpsi1, dL_dpsi2, Z, variational_posterior): self.variance.gradient = dL_dpsi0 class Bias(Static): def __init__(self, input_dim, variance=1., active_dims=None, name='bias'): super(Bias, self).__init__(input_dim, variance, active_dims, name) def to_dict(self): input_dict = super(Bias, self)._save_to_input_dict() input_dict["class"] = "GPy.kern.Bias" return input_dict @staticmethod def _build_from_input_dict(kernel_class, input_dict): useGPU = input_dict.pop('useGPU', None) return Bias(**input_dict) def K(self, X, X2=None): shape = (X.shape[0], X.shape[0] if X2 is None else X2.shape[0]) return np.full(shape, self.variance, dtype=np.float64) def update_gradients_full(self, dL_dK, X, X2=None): self.variance.gradient = dL_dK.sum() def update_gradients_diag(self, dL_dKdiag, X): self.variance.gradient = dL_dKdiag.sum() def psi2(self, Z, variational_posterior): return np.full((Z.shape[0], Z.shape[0]), self.variance*self.variance*variational_posterior.shape[0], dtype=np.float64) def psi2n(self, Z, variational_posterior): ret = np.empty((variational_posterior.mean.shape[0], Z.shape[0], Z.shape[0]), dtype=np.float64) ret[:] = self.variance*self.variance return ret def update_gradients_expectations(self, dL_dpsi0, dL_dpsi1, dL_dpsi2, Z, variational_posterior): if dL_dpsi2.ndim == 2: self.variance.gradient = (dL_dpsi0.sum() + dL_dpsi1.sum() + 2.*self.variance*dL_dpsi2.sum()*variational_posterior.shape[0]) else: self.variance.gradient = (dL_dpsi0.sum() + dL_dpsi1.sum() + 2.*self.variance*dL_dpsi2.sum()) class Fixed(Static): def __init__(self, input_dim, covariance_matrix, variance=1., active_dims=None, name='fixed'): """ :param input_dim: the number of input dimensions :type input_dim: int :param variance: the variance of the kernel :type variance: float """ super(Fixed, self).__init__(input_dim, variance, active_dims, name) self.fixed_K = covariance_matrix def K(self, X, X2): if X2 is None: return self.variance * self.fixed_K else: return np.zeros((X.shape[0], X2.shape[0])) def Kdiag(self, X): return self.variance * self.fixed_K.diagonal() def update_gradients_full(self, dL_dK, X, X2=None): if X2 is None: self.variance.gradient = np.einsum('ij,ij', dL_dK, self.fixed_K) else: self.variance.gradient = 0 def update_gradients_diag(self, dL_dKdiag, X): self.variance.gradient = np.einsum('i,i', dL_dKdiag, np.diagonal(self.fixed_K)) def psi2(self, Z, variational_posterior): return np.zeros((Z.shape[0], Z.shape[0]), dtype=np.float64) def psi2n(self, Z, variational_posterior): return np.zeros((1, Z.shape[0], Z.shape[0]), dtype=np.float64) def update_gradients_expectations(self, dL_dpsi0, dL_dpsi1, dL_dpsi2, Z, variational_posterior): self.variance.gradient = dL_dpsi0.sum() class Precomputed(Fixed): def __init__(self, input_dim, covariance_matrix, variance=1., active_dims=None, name='precomputed'): """ Class for precomputed kernels, indexed by columns in X Usage example: import numpy as np from GPy.models import GPClassification from GPy.kern import Precomputed from sklearn.cross_validation import LeaveOneOut n = 10 d = 100 X = np.arange(n).reshape((n,1)) # column vector of indices y = 2*np.random.binomial(1,0.5,(n,1))-1 X0 = np.random.randn(n,d) k = np.dot(X0,X0.T) kern = Precomputed(1,k) # k is a n x n covariance matrix cv = LeaveOneOut(n) ypred = y.copy() for train, test in cv: m = GPClassification(X[train], y[train], kernel=kern) m.optimize() ypred[test] = 2*(m.predict(X[test])[0]>0.5)-1 :param input_dim: the number of input dimensions :type input_dim: int :param variance: the variance of the kernel :type variance: float """ assert input_dim==1, "Precomputed only implemented in one dimension. Use multiple Precomputed kernels to have more dimensions by making use of active_dims" super(Precomputed, self).__init__(input_dim, covariance_matrix, variance, active_dims, name) @Cache_this(limit=2) def _index(self, X, X2): if X2 is None: i1 = i2 = X.astype('int').flat else: i1, i2 = X.astype('int').flat, X2.astype('int').flat return self.fixed_K[i1,:][:,i2] def K(self, X, X2=None): return self.variance * self._index(X, X2) def Kdiag(self, X): return self.variance * self._index(X,None).diagonal() def update_gradients_full(self, dL_dK, X, X2=None): self.variance.gradient = np.einsum('ij,ij', dL_dK, self._index(X, X2)) def update_gradients_diag(self, dL_dKdiag, X): self.variance.gradient = np.einsum('i,ii', dL_dKdiag, self._index(X, None))
5,005
6,098
<gh_stars>1000+ package hex.anovaglm; import hex.DataInfo; import hex.ModelBuilder; import hex.ModelBuilderHelper; import hex.ModelCategory; import hex.glm.GLM; import hex.glm.GLMModel; import water.DKV; import water.Key; import water.Scope; import water.exceptions.H2OModelBuilderIllegalArgumentException; import water.fvec.Frame; import water.fvec.Vec; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static hex.anovaglm.ANOVAGLMUtils.*; import static hex.gam.MatrixFrameUtils.GamUtils.keepFrameKeys; import static hex.glm.GLMModel.GLMParameters; import static hex.glm.GLMModel.GLMParameters.Family.*; import static water.util.ArrayUtils.flat; public class ANOVAGLM extends ModelBuilder<ANOVAGLMModel, ANOVAGLMModel.ANOVAGLMParameters, ANOVAGLMModel.ANOVAGLMModelOutput> { public int _numberOfModels = 4;// (A, A*B), (B, A*B), (A, B), (A, B, A*B) public int _numberOfPredCombo = 3; public int _numberOfPredictors = 3; // A, B, interaction of A and B DataInfo _dinfo; String[][] _predictComboNames; // store single predictors, predictor interaction columns int[] _degreeOfFreedom; String[] _modelNames; // store model description String[] _predNamesIndividual; // store individual column names public String[][] _transformedColNames; // store expanded names for single predictors, predictor interactions. public int[] _predictorColumnStart; public ANOVAGLM(boolean startup_once) { super(new ANOVAGLMModel.ANOVAGLMParameters(), startup_once); } public ANOVAGLM(ANOVAGLMModel.ANOVAGLMParameters parms) { super(parms); init(false); } public ANOVAGLM(ANOVAGLMModel.ANOVAGLMParameters parms, Key<ANOVAGLMModel> key) { super(parms, key); init(false); } @Override protected int nModelsInParallel(int folds) { // disallow nfold cross-validation return nModelsInParallel(1, 2); } @Override protected ANOVAGLMDriver trainModelImpl() { return new ANOVAGLMDriver(); } @Override public ModelCategory[] can_build() { return new ModelCategory[]{ModelCategory.Regression, ModelCategory.Binomial, ModelCategory.Multinomial, ModelCategory.Ordinal}; } @Override public boolean isSupervised() { return true; } @Override public boolean haveMojo() { return false; } @Override public boolean havePojo() { return false; } public BuilderVisibility buildVisibility() { return BuilderVisibility.Experimental; } public void init(boolean expensive) { super.init(expensive); if (expensive) { initValidateAnovaGLMParameters(); } } /*** * Init and validate ANOVAGLMParameters. */ private void initValidateAnovaGLMParameters() { if (_parms._link == null) _parms._link = GLMModel.GLMParameters.Link.family_default; _dinfo = new DataInfo(_train.clone(), _valid, 1, true, DataInfo.TransformType.NONE, DataInfo.TransformType.NONE, _parms.missingValuesHandling() == GLMModel.GLMParameters.MissingValuesHandling.Skip, _parms.imputeMissing(), _parms.makeImputer(), false, hasWeightCol(), hasOffsetCol(), hasFoldCol(), null); _numberOfPredictors = _dinfo._nums + _dinfo._cats; if (_numberOfPredictors < 2) error("predictors", " there must be at least two predictors."); if (_parms._highest_interaction_term == 0) _parms._highest_interaction_term = _numberOfPredictors; if (_parms._highest_interaction_term < 1 || _parms._highest_interaction_term > _numberOfPredictors) error("highest_interaction_term", " must be >= 1 or <= number of predictors."); if (!(gaussian.equals(_parms._family) || tweedie.equals(_parms._family) || poisson.equals(_parms._family))) { _parms._compute_p_values = false; _parms._remove_collinear_columns = false; } if (nclasses() > 2) error("family", " multinomial and ordinal are not supported at this point."); _numberOfPredCombo = calculatePredComboNumber(_numberOfPredictors, _parms._highest_interaction_term); _numberOfModels = _numberOfPredCombo + 1; _predNamesIndividual = extractPredNames(_dinfo, _numberOfPredictors); _predictComboNames = generatePredictorCombos(_predNamesIndividual, _parms._highest_interaction_term); _transformedColNames = new String[_numberOfPredCombo][]; _predictorColumnStart = new int[_numberOfPredCombo]; _degreeOfFreedom = new int[_numberOfPredCombo]; generatePredictorNames(_predictComboNames, _transformedColNames, _predictorColumnStart, _degreeOfFreedom, _dinfo); _modelNames = generateModelNames(_predictComboNames); if (error_count() > 0) throw H2OModelBuilderIllegalArgumentException.makeFromBuilder(ANOVAGLM.this); } private class ANOVAGLMDriver extends Driver { String[] _allTransformedColNames; // flatten new column names Key<Frame> _transformedColsKey; // store transformed column frame key Frame[] _trainingFrames; // store generated frames GLMParameters[] _glmParams; // store GLMParameters needed to generate all the data GLM[] _glmBuilder; // store GLM Builders to be build in parallel GLM[] _glmResults; Frame _completeTransformedFrame; // store transformed frame public final void buildModel() { ANOVAGLMModel model = null; try { _dinfo = new DataInfo(_completeTransformedFrame, _valid, 1, false, DataInfo.TransformType.NONE, DataInfo.TransformType.NONE, _parms.missingValuesHandling() == GLMModel.GLMParameters.MissingValuesHandling.Skip, _parms.imputeMissing(), _parms.makeImputer(), false, hasWeightCol(), hasOffsetCol(), hasFoldCol(), null); model = new ANOVAGLMModel(dest(), _parms, new ANOVAGLMModel.ANOVAGLMModelOutput(ANOVAGLM.this, _dinfo)); model.write_lock(_job); if (_parms._save_transformed_framekeys) { model._output._transformed_columns_key = _transformedColsKey; } _trainingFrames = buildTrainingFrames(_transformedColsKey, _numberOfModels, _transformedColNames, _parms); // build up training frames _glmParams = buildGLMParameters(_trainingFrames, _parms); _job.update(1, "calling GLM to build GLM models ..."); _glmBuilder = buildGLMBuilders(_glmParams); _glmResults = ModelBuilderHelper.trainModelsParallel(_glmBuilder, _parms._nparallelism); // set to 4 according to Michalk model._output._glmModels = extractGLMModels(_glmResults); model._output.copyGLMCoeffs(_modelNames); fillModelMetrics(model, model._output._glmModels[_numberOfPredCombo], _trainingFrames[_numberOfPredCombo]); // take full model metrics as our model metrics model.fillOutput(combineAndFlat(_predictComboNames), _degreeOfFreedom); _job.update(0, "Completed GLM model building. Extracting metrics from GLM models and building" + " ANOVAGLM outputs"); model.update(_job); } finally { final List<Key> keep = new ArrayList<>(); int numFrame2Delete = _parms._save_transformed_framekeys ? (_trainingFrames.length - 1) : _trainingFrames.length; removeFromDKV(_trainingFrames, numFrame2Delete); if (model != null) { if (_parms._save_transformed_framekeys) keepFrameKeys(keep, _transformedColsKey); else DKV.remove(_transformedColsKey); Scope.untrack(keep.toArray(new Key[keep.size()])); model.update(_job); model.unlock(_job); } } } /*** * This method will transform the training frame such that the constraints on the GLM parameters will be satisfied. * Refer to ANOVAGLMTutorial https://h2oai.atlassian.net/browse/PUBDEV-8088 section III.II. */ void generateTransformedColumns() { _allTransformedColNames = flat(_transformedColNames); List<String> expandedColNames = new ArrayList<>(Arrays.asList(_allTransformedColNames)); if (hasWeightCol()) expandedColNames.add(_parms._weights_column); if (hasOffsetCol()) expandedColNames.add(_parms._offset_column); expandedColNames.add(_parms._response_column); GenerateTransformColumns gtc = new GenerateTransformColumns(_transformedColNames, _parms, _dinfo, _predNamesIndividual.length, _predictComboNames); gtc.doAll(expandedColNames.size(), Vec.T_NUM, _dinfo._adaptedFrame); _completeTransformedFrame = gtc.outputFrame(Key.make(), expandedColNames.toArray(new String[0]), null); if (_train.vec(_parms._response_column).isCategorical() && !_completeTransformedFrame.vec(_parms._response_column).isCategorical()) _completeTransformedFrame.replace(_completeTransformedFrame.numCols()-1, _completeTransformedFrame.vec(_parms._response_column).toCategoricalVec()).remove(); _transformedColsKey = _completeTransformedFrame._key; // contains transformed predicts, weight/offset and response columns DKV.put(_completeTransformedFrame); } @Override public void computeImpl() { init(true); if (error_count() > 0) throw H2OModelBuilderIllegalArgumentException.makeFromBuilder(ANOVAGLM.this); generateTransformedColumns(); _job.update(0, "Finished transforming training frame"); buildModel(); } } }
3,533
7,073
<filename>atest/testresources/testlibs/objecttoreturn.py class ObjectToReturn: def __init__(self, name): self.name = name def __str__(self): return self.name def exception(self, name, msg=""): try: exception = getattr(__builtins__, name) except AttributeError: # __builtins__ is sometimes a dict, go figure exception = __builtins__[name] raise exception(msg)
183
1,227
/* * Copyright 2018 <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 com.mascotcapsule.micro3d.v3; import java.io.IOException; import java.io.InputStream; import javax.microedition.util.ContextHolder; public class Texture { protected boolean isModel; public Texture(byte[] b, boolean isForModel) { if (b == null) { throw new RuntimeException(); } this.isModel = isForModel; } public Texture(String name, boolean isForModel) throws IOException { if (name == null) { throw new NullPointerException(); } InputStream is = ContextHolder.getResourceAsStream(null, name); if (is == null) { throw new IOException(); } this.isModel = isForModel; } public final void dispose() { } }
385
372
<filename>lwbase/include/lw/rbtree.h /* Editor Settings: expandtabs and use 4 spaces for indentation * ex: set softtabstop=4 tabstop=8 expandtab shiftwidth=4: * * -*- mode: c, c-basic-offset: 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: * * rbtree.h * * Abstract: * * BeyondTrust Base Library (LwBase) * * Red Black Tree * * Authors: <NAME> (<EMAIL>) */ #ifndef __LW_RBTREE_H__ #define __LW_RBTREE_H__ #include <lw/types.h> #include <lw/attrs.h> #include <lw/ntstatus.h> LW_BEGIN_EXTERN_C typedef enum { LWRTL_TREE_TRAVERSAL_TYPE_PRE_ORDER = 0, LWRTL_TREE_TRAVERSAL_TYPE_IN_ORDER, LWRTL_TREE_TRAVERSAL_TYPE_POST_ORDER } LWRTL_TREE_TRAVERSAL_TYPE; typedef int (*PFN_LWRTL_RB_TREE_COMPARE)( PVOID pKey1, PVOID pKey2); typedef VOID (*PFN_LWRTL_RB_TREE_FREE_KEY)(PVOID pKey); typedef VOID (*PFN_LWRTL_RB_TREE_FREE_DATA)(PVOID pData); typedef NTSTATUS (*PFN_LWRTL_RB_TREE_VISIT)( PVOID pKey, PVOID pData, PVOID pUserData, PBOOLEAN pbContinue ); typedef struct LWRTL_RB_TREE *PLWRTL_RB_TREE; NTSTATUS LwRtlRBTreeCreate( PFN_LWRTL_RB_TREE_COMPARE pfnRBTreeCompare, PFN_LWRTL_RB_TREE_FREE_KEY pfnRBTreeFreeKey, PFN_LWRTL_RB_TREE_FREE_DATA pfnRBTreeFreeData, PLWRTL_RB_TREE* ppRBTree ); // Returns STATUS_NOT_FOUND and sets *ppItem to NULL if the key is not in the // tree. NTSTATUS LwRtlRBTreeFind( PLWRTL_RB_TREE pRBTree, PVOID pKey, PVOID* ppItem ); NTSTATUS LwRtlRBTreeAdd( PLWRTL_RB_TREE pRBTree, PVOID pKey, PVOID pData ); NTSTATUS LwRtlRBTreeTraverse( PLWRTL_RB_TREE pRBTree, LWRTL_TREE_TRAVERSAL_TYPE traversalType, PFN_LWRTL_RB_TREE_VISIT pfnVisit, PVOID pUserData ); NTSTATUS LwRtlRBTreeRemove( PLWRTL_RB_TREE pRBTree, PVOID pKey); VOID LwRtlRBTreeRemoveAll( PLWRTL_RB_TREE pRBTree ); VOID LwRtlRBTreeFree( PLWRTL_RB_TREE pRBTree ); LW_END_EXTERN_C #endif /* __LW_RBTREE_H__ */ /* local variables: mode: c c-basic-offset: 4 indent-tabs-mode: nil tab-width: 4 end: */
1,535
1,852
<gh_stars>1000+ // // CPDocument.h // ReferencedProject // // Created by <NAME> on 22/10/12. // Copyright (c) 2012 CocoaPods. All rights reserved. // #import <Cocoa/Cocoa.h> @interface CPDocument : NSPersistentDocument @end
93
5,169
<reponame>Gantios/Specs { "name": "D2PDatePicker", "version": "0.1.1", "summary": "Elegant and Easy-to-Use iOS Swift Date Picker", "description": "Elegant and Easy-to-Use iOS Swift Date Picker made with love by DI2PRA", "homepage": "https://github.com/di2pra/D2PDatePicker", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "di2pra": "<EMAIL>" }, "source": { "git": "https://github.com/di2pra/D2PDatePicker.git", "tag": "0.1.1" }, "social_media_url": "https://twitter.com/di2pra", "platforms": { "ios": "8.0" }, "source_files": "D2PDatePicker/Classes/**/*", "resource_bundles": { "D2PDatePicker": [ "D2PDatePicker/Assets/*.{xcassets}" ] }, "pushed_with_swift_version": "4" }
353
945
<gh_stars>100-1000 #include <vnl/io/vnl_io_vector.hxx> VNL_IO_VECTOR_INSTANTIATE(int);
45
335
package moze_intel.projecte.rendering; import net.minecraft.client.renderer.RenderState; import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.client.renderer.vertex.VertexFormat; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; public class PERenderType extends RenderType { //Ignored private PERenderType(String name, VertexFormat format, int drawMode, int bufferSize, boolean useDelegate, boolean needsSorting, Runnable setupTask, Runnable clearTask) { super(name, format, drawMode, bufferSize, useDelegate, needsSorting, setupTask, clearTask); } public static RenderType spriteRenderer(ResourceLocation resourceLocation) { RenderType.State state = RenderType.State.getBuilder() .texture(new RenderState.TextureState(resourceLocation, false, false))//Texture state .lightmap(LIGHTMAP_DISABLED)//disableLighting .alpha(HALF_ALPHA)//alpha .build(true); return makeType("sprite_renderer", DefaultVertexFormats.POSITION_TEX, GL11.GL_QUADS, 256, true, false, state); } public static RenderType yeuRenderer(ResourceLocation resourceLocation) { RenderType.State state = RenderType.State.getBuilder() .texture(new RenderState.TextureState(resourceLocation, false, false))//Texture state .lightmap(LIGHTMAP_DISABLED)//disableLighting .alpha(HALF_ALPHA)//alpha .cull(CULL_DISABLED) .build(true); return makeType("yeu_renderer", DefaultVertexFormats.POSITION_COLOR_TEX, GL11.GL_QUADS, 256, true, false, state); } public static RenderType transmutationOverlay() { RenderType.State state = RenderType.State.getBuilder() .transparency(TRANSLUCENT_TRANSPARENCY)//enableBled/blendFunc(SourceFactor.SRC_ALPHA, DestFactor.ONE_MINUS_SRC_ALPHA) .texture(NO_TEXTURE)//disableTexture .cull(CULL_DISABLED)//disableCull .lightmap(LIGHTMAP_DISABLED)//disableLighting .writeMask(COLOR_WRITE)//depthMask(false) .layer(POLYGON_OFFSET_LAYERING)//Offset it so that can render properly .build(true); return makeType("transmutation_overlay", DefaultVertexFormats.POSITION_COLOR, GL11.GL_QUADS, 256, true, false, state); } }
769
364
<filename>doc/quickbook/oglplus/quickref/client/scissor_test.hpp /* * Copyright 2014-2015 <NAME>. 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) */ //[oglplus_client_ScissorTestState namespace client { class ScissorTestState { __SettingStackIndexed< __SettingStack<__context_ScissorRectangle, ...>, __context_ScissorRectangle, __ViewportIndex> Scissor; /*< Indexed set of stacks managing the scissor rectangles for the individual viewports. >*/ }; } // namespace client //]
231
826
<reponame>julescmay/LuxCore<filename>deps/opencolorio-2.0.0/src/iccProfileReader.h /* The ICC Software License, Version 0.2 Copyright (c) 2003-2010 The International Color Consortium. 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. In the absence of prior written permission, the names "ICC" and "The International Color Consortium" must not be used to imply that the ICC organization endorses or promotes products derived from this software. THIS SOFTWARE IS PROVIDED ``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 INTERNATIONAL COLOR CONSORTIUM OR ITS CONTRIBUTING MEMBERS 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 software consists of voluntary contributions made by many individuals on behalf of the The International Color Consortium. Membership in the ICC is encouraged when this software is used for commercial purposes. For more information on The International Color Consortium, please see <http://www.color.org/>. */ /* This code has been copied and modified from http://sampleicc.sourceforge.net/ This is the minimal amount of code needed to read icc profiles. Modifications Copyright Contributors to the OpenColorIO Project. */ #ifndef INCLUDED_SAMPLEICC_PROFILEREADER_H #define INCLUDED_SAMPLEICC_PROFILEREADER_H #include <vector> #include <algorithm> #include <cstdio> #include <iostream> #include <sstream> // Before including http://www.color.org/icProfileHeader.h // make sure types will be properly defined. // There has just been one edit to icProfileHeader.h in order to // remove a comment within a comment. #if !defined(_WIN32) // non-PC, perhaps Mac, Linux #include <stdint.h> #define ICCUINT32 uint32_t #define ICCINT32 int32_t #define ICUINT32TYPE uint32_t #define ICINT32TYPE int32_t #endif #include "icProfileHeader.h" namespace SampleICC { void Swap8(icUInt8Number & a, icUInt8Number & b) { icUInt8Number tmp = a; a = b; b = tmp; } void Swap64Array(void *pVoid, icInt32Number num) { icUInt8Number *ptr = (icUInt8Number*)pVoid; while (num > 0) { Swap8(ptr[0], ptr[7]); Swap8(ptr[1], ptr[6]); Swap8(ptr[2], ptr[5]); Swap8(ptr[3], ptr[4]); ptr += 8; num--; } } void Swap32Array(void *pVoid, icInt32Number num) { icUInt8Number *ptr = (icUInt8Number*)pVoid; while (num > 0) { Swap8(ptr[0], ptr[3]); Swap8(ptr[1], ptr[2]); ptr += 4; num--; } } void Swap16Array(void *pVoid, icInt32Number num) { icUInt8Number *ptr = (icUInt8Number*)pVoid; while (num > 0) { Swap8(ptr[0], ptr[1]); ptr += 2; num--; } } float icFtoD(icS15Fixed16Number num) { return (float)((double)num / 65536.0); } icInt32Number Read8(std::istream & istream, void *pBuf, icInt32Number num) { if (!istream.good()) return 0; char * pBufChar = (char *)pBuf; istream.read(pBufChar, num); if (!istream.good()) return 0; return (icInt32Number)num; } icInt32Number Read64(std::istream & istream, void * pBuf64, icInt32Number num) { num = Read8(istream, pBuf64, num << 3) >> 3; Swap64Array(pBuf64, num); return num; } icInt32Number Read32(std::istream & istream, void * pBuf32, icInt32Number num) { num = Read8(istream, pBuf32, num << 2) >> 2; Swap32Array(pBuf32, num); return num; } icInt32Number Read16(std::istream & istream, void *pBuf16, icInt32Number num) { num = Read8(istream, pBuf16, num << 1) >> 1; Swap16Array(pBuf16, num); return num; } icInt32Number Read16Float(std::istream & istream, void *pBufFloat, icInt32Number num) { float * ptr = (float*)pBufFloat; icUInt16Number tmp; icInt32Number i; for (i = 0; i < num; ++i) { if (Read16(istream, &tmp, 1) != 1) break; *ptr = (float)((float)tmp / 65535.0f); ptr++; } return i; } class IccTypeReader { public: IccTypeReader() {} virtual ~IccTypeReader() {} virtual bool Read(std::istream & /* istream */, icUInt32Number /* size */) { return false; } virtual bool IsParametricCurve() const { return false; } static IccTypeReader * Create(icTagTypeSignature sigType); }; // Note, the textDescriptionType is from the v2 spec (ICC.1:2001-04, pg 60). It is not included // in the v4 spec (ICC.1:2010) but it is still found in many v4 profiles. class IccTextDescriptionTypeReader : public IccTypeReader { public: IccTextDescriptionTypeReader() = default; virtual ~IccTextDescriptionTypeReader() = default; virtual bool Read(std::istream & istream, icUInt32Number size) { mText.clear(); // Note that tag size include sig that has already been read. if (sizeof(icSigProfileDescriptionTag) + sizeof(icUInt32Number) + // reserved sizeof(icUInt32Number) > size) { return false; } if (!istream.good()) { return false; } icUInt32Number reserved; // reserved if (!Read32(istream, &reserved, 1)) { return false; } // Read the size of the string. icUInt32Number textSize = 0; if (!Read32(istream, &textSize, 1)) { return false; } // Read the string itself. if (textSize) { mText.resize(textSize + 1); // Completed with '\0' if the string is smaller than the expected size. const icUInt32Number readTextSize = Read8(istream, (void*)mText.c_str(), textSize); if (readTextSize != textSize) { mText.clear(); return false; } else { // Removes extra '\0' if any. const std::string::size_type pos = mText.find('\0'); if (pos != std::string::npos) { mText.resize(pos); } } } return true; } inline const std::string & GetText() const { return mText; } private: std::string mText; }; // Custom multi localized unicode reader to only find the one string following // the heuristic described below i.e. flavor the USA / English string. class IccMultiLocalizedUnicodeTypeReader : public IccTypeReader { public: IccMultiLocalizedUnicodeTypeReader() = default; virtual ~IccMultiLocalizedUnicodeTypeReader() = default; virtual bool Read(std::istream & istream, icUInt32Number size) { mText.clear(); // Note that tag size include sig that has already been read. if (sizeof(icTagTypeSignature) + (sizeof(icUInt32Number) * 3) > size) { return false; } if (!istream.good()) { return false; } icUInt32Number reserved, nNumRec, nRecSize; if (!Read32(istream, &reserved, 1) || !Read32(istream, &nNumRec, 1) || !Read32(istream, &nRecSize, 1)) { return false; } // Recognized version name records are 12 bytes each. if (nRecSize != 12) { return false; } icLanguageCode nLanguageCode; icCountryCode nRegionCode; icUInt32Number nLength, nOffset; // The heuristic for selecting the one string is: // 1) US region // 2) UK region // 3) First EN language // 4) First string of any kind // std::string foundCountryUSA; std::string foundContryUK; std::string foundLanguageEN; std::string foundFirstEntry; for (icUInt32Number i = 0; i < nNumRec; ++i) { if ( (4 * sizeof(icUInt32Number) + (i+1) * 12) > size) { return false; } if (!Read16(istream, &nLanguageCode, 1) || !Read16(istream, &nRegionCode, 1) || !Read32(istream, &nLength, 1) || !Read32(istream, &nOffset, 1)) { return false; } if ((nOffset + nLength) > size) { return false; } const icUInt32Number nNumChar = nLength / sizeof(icUInt16Number); std::vector<icUInt16Number> unicodeStr(nNumChar, 0); // Completed with '\0' if the string is smaller than the expected size. const icUInt32Number readTextSize = Read16(istream, (void*)&unicodeStr[0], nNumChar); if (readTextSize != nNumChar) { return false; } else { std::string str(nNumChar + 1, '\0'); for (std::vector<icUInt16Number>::size_type idx = 0; idx < unicodeStr.size(); ++idx) { // As only the English language is supported the Basic Latin character set // is enough for all the English characters. str[idx] = static_cast<icUInt8Number>(unicodeStr[idx]); } // Removes extra '\0' if any. const std::string::size_type pos = str.find('\0'); if (pos != std::string::npos) { str.resize(pos); } // As the order of the (country, language) is unknown, read all the strings // before selecting the right one. if (nRegionCode == icCountryCodeUSA) { // As soon as the US is found stop. foundCountryUSA = str; break; } if (nRegionCode == icCountryCodeUnitedKingdom && foundContryUK.empty()) { foundContryUK = str; } if (nLanguageCode == icLanguageCodeEnglish && foundLanguageEN.empty()) { foundLanguageEN = str; } if (i == 0) { foundFirstEntry = str; } } } if (mText.empty()) { if (!foundCountryUSA.empty()) { mText = foundCountryUSA; } else if (!foundContryUK.empty()) { mText = foundContryUK; } else if (!foundLanguageEN.empty()) { mText = foundLanguageEN; } else { mText = foundFirstEntry; } } return true; } inline const std::string & GetText() const { return mText; } private: std::string mText; }; class IccXYZArrayTypeReader : public IccTypeReader { public: IccXYZArrayTypeReader() {} virtual bool Read(std::istream & istream, icUInt32Number size) { // Tag size include sig that has already been read. if (sizeof(icTagTypeSignature) + sizeof(icUInt32Number) + sizeof(icXYZNumber) > size || !istream.good()) return false; icUInt32Number sizeComp = (icUInt32Number)((size - 2 * sizeof(icUInt32Number)) / sizeof(icXYZNumber)); // only used to read single XYZ if (sizeComp != 1) return false; icUInt32Number res; // reserved if (!Read32(istream, &res, 1)) return false; icUInt32Number num32 = (icUInt32Number)(sizeComp * sizeof(icXYZNumber) / sizeof(icUInt32Number)); if ((icUInt32Number)Read32(istream, &mXYZ, num32) != num32) return false; return true; } const icXYZNumber & GetXYZ() const { return mXYZ; } private: icXYZNumber mXYZ; }; class IccParametricCurveTypeReader : public IccTypeReader { public: IccParametricCurveTypeReader() : mnNumParam(0), mParam(NULL) {} ~IccParametricCurveTypeReader() { if (mParam) delete[] mParam; } virtual bool IsParametricCurve() const { return true; } virtual bool Read(std::istream & istream, icUInt32Number size) { // Tag size include sig that has already been read. icUInt16Number functionType; icUInt16Number res16; icUInt32Number res32; icUInt32Number nHdrSize = (icUInt32Number)( sizeof(icTagTypeSignature) + sizeof(icUInt32Number) + 2 * sizeof(icUInt16Number)); if (nHdrSize > size) return false; if (nHdrSize + sizeof(icS15Fixed16Number) > size) return false; if (!istream.good()) return false; if (!Read32(istream, &res32, 1) || !Read16(istream, &functionType, 1) || !Read16(istream, &res16, 1)) return false; if (0 != functionType) { // unsupported function type return false; } if (!mnNumParam) { mnNumParam = (icUInt16Number)((size - nHdrSize) / sizeof(icS15Fixed16Number)); mParam = new icS15Fixed16Number[mnNumParam]; } if (mnNumParam) { if (nHdrSize + mnNumParam * sizeof(icS15Fixed16Number) > size) return false; if (!Read32(istream, mParam, 1)) { return false; } } return true; } const icS15Fixed16Number * GetParam() const { return mParam; } icUInt16Number GetNumParam() const { return mnNumParam; } private: icUInt16Number mnNumParam; icS15Fixed16Number *mParam; }; class IccCurveTypeReader : public IccTypeReader { public: IccCurveTypeReader() {} virtual bool Read(std::istream & istream, icUInt32Number size) { // Tag size include sig that has already been read. if (sizeof(icTagTypeSignature) + sizeof(icUInt32Number) + sizeof(icUInt32Number) > size) return false; if (!istream.good()) return false; icUInt32Number res32; if (!Read32(istream, &res32, 1)) return false; icUInt32Number sizeData; if (!Read32(istream, &sizeData, 1)) return false; mCurve.resize(sizeData); if (sizeData) { if (sizeData != (icUInt32Number)Read16Float(istream, &(mCurve[0]), sizeData)) return false; } return true; } const std::vector<float> & GetCurve() const { return mCurve; } private: std::vector<float> mCurve; }; IccTypeReader * IccTypeReader::Create(icTagTypeSignature sigType) { if (icSigXYZArrayType == sigType) return new IccXYZArrayTypeReader(); else if (icSigParametricCurveType == sigType) return new IccParametricCurveTypeReader(); else if (icSigCurveType == sigType) return new IccCurveTypeReader(); else if (icSigTextDescriptionType == sigType) return new IccTextDescriptionTypeReader(); else if (icSigMultiLocalizedUnicodeType == sigType) return new IccMultiLocalizedUnicodeTypeReader(); return nullptr; } struct IccTagElement { IccTagElement() = default; icTag mTagInfo; IccTypeReader * mTagReader = nullptr; }; typedef std::vector<IccTagElement> TagVector; struct IccContent { struct FindSig { FindSig(const icTagSignature & sig) : mSig(sig) {} bool operator()(const IccTagElement & tag) { return tag.mTagInfo.sig == mSig; } private: FindSig() {} icTagSignature mSig; }; bool isMatrixShaper() const { return HasTag(icSigRedColorantTag) && HasTag(icSigGreenColorantTag) && HasTag(icSigBlueColorantTag) && HasTag(icSigRedTRCTag) && HasTag(icSigGreenTRCTag) && HasTag(icSigBlueTRCTag); } public: icHeader mHeader; TagVector mTags; ~IccContent() { TagVector::iterator it = mTags.begin(); TagVector::iterator itEnd = mTags.end(); while (it != itEnd) { if ((*it).mTagReader) { delete (*it).mTagReader; (*it).mTagReader = NULL; } ++it; } } TagVector::const_iterator FindTag(const icTagSignature & sig) const { return std::find_if(mTags.begin(), mTags.end(), FindSig(sig)); } TagVector::iterator FindTag(const icTagSignature & sig) { return std::find_if(mTags.begin(), mTags.end(), FindSig(sig)); } bool HasTag(const icTagSignature & sig) const { return FindTag(sig) != mTags.end(); } IccTypeReader * LoadTag(std::istream & istream, const icTagSignature & sig) { TagVector::iterator itTag = FindTag(sig); if (itTag == mTags.end()) return NULL; if ((*itTag).mTagReader == NULL) { istream.seekg((*itTag).mTagInfo.offset); if (istream.good()) { icTagTypeSignature sigType; if (Read32(istream, &sigType, 1)) { IccTypeReader * reader = IccTypeReader::Create(sigType); if (reader) { // Read if (reader->Read(istream, (*itTag).mTagInfo.size)) { // remember tag if read ok (*itTag).mTagReader = reader; } else { delete reader; } } } } } return (*itTag).mTagReader; } bool Validate(std::string & error) const { // Report critical issues. std::ostringstream message; switch (mHeader.deviceClass) { case icSigInputClass: case icSigDisplayClass: case icSigOutputClass: case icSigLinkClass: case icSigColorSpaceClass: case icSigAbstractClass: case icSigNamedColorClass: break; default: message << "Unknown profile class: "; message << mHeader.deviceClass; message << ". "; error = message.str(); return false; } switch (mHeader.renderingIntent) { case icPerceptual: case icRelativeColorimetric: case icSaturation: case icAbsoluteColorimetric: break; default: message << "Unknown rendering intent: "; message << mHeader.renderingIntent; message << ". "; error = message.str(); return false; } if (mTags.empty()) { message << "No tags present. "; error = message.str(); return false; } return true; } bool ValidateForOCIO(std::string & error) const { if (!Validate(error)) { return false; } std::ostringstream message; // Only the Matrix/TRC Model is supported for now if (!isMatrixShaper()) { message << "Only Matrix/TRC Model is supported. "; error = message.str(); return false; } // Matrix/TRC profiles only use the XYZ PCS if (mHeader.pcs != icSigXYZData) { message << "Unsupported ICC profile connection space. "; error = message.str(); return false; } if (mHeader.colorSpace != icSigRgbData) { message << "Unsupported ICC device color space. "; error = message.str(); return false; } return true; } }; } #endif
12,244
14,793
package me.chanjar.weixin.mp.bean.card.enums; /** * 商户提供服务类型 */ public enum BusinessServiceType { BIZ_SERVICE_DELIVER("外卖服务"), BIZ_SERVICE_FREE_PARK("停车位"), BIZ_SERVICE_WITH_PET("可带宠物"), BIZ_SERVICE_FREE_WIFI("可带宠物"); private String description; BusinessServiceType(String description) { this.description = description; } public String getDescription() { return description; } }
192
3,539
/* * If you are including the plugin into your code using static build, you * can simplify it by just including this file, which will include all the * related code in one step without you having to get involved in the detail. */ #define LWS_PLUGIN_STATIC #include "../crypto/chacha.c" #include "../crypto/ed25519.c" #include "../crypto/fe25519.c" #include "../crypto/ge25519.c" #include "../crypto/poly1305.c" #include "../crypto/sc25519.c" #include "../crypto/smult_curve25519_ref.c" #include "../kex-25519.c" #include "../sshd.c" #include "../telnet.c"
203
663
# (C) Datadog, Inc. 2018-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) from datadog_checks.base import PDHBaseCheck from .metrics import DEFAULT_COUNTERS class HypervCheck(PDHBaseCheck): def __init__(self, name, init_config, instances=None): super(HypervCheck, self).__init__(name, init_config, instances=instances, counter_list=DEFAULT_COUNTERS)
139