max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
1,338
<filename>src/tools/translation/stxtinfo/stxtinfo.cpp<gh_stars>1000+ /*****************************************************************************/ // stxtinfo // Written by <NAME>, OBOS Translation Kit Team // // Version: // // stxtinfo is a command line program for displaying text information about // Be styled text (the format that StyledEdit uses). StyledEdit stores the // styled text information as an attribute of the file and it is this // information that this program is concerned with. This format is outlined // in TranslatorFormats.h. // // This program prints out information from the "styles" attribute that // StyledEdit uses. If that information is not available, it attempts // to read the styles information from the contents of the file, assuming // that it is the format that BTranslationUtils::PutStyledText() writes // out. // // The intention of this program is to aid with the development and // debugging of the STXTTranslator. It may also be useful for debugging / // testing StyledEdit. // // This application and all source files used in its construction, except // where noted, are licensed under the MIT License, and have been written // and are: // // Copyright (c) 2003 OpenBeOS 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. /*****************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ByteOrder.h> #include <File.h> #include <TranslatorFormats.h> #include <Font.h> // for B_UNICODE_UTF8 #include <fs_attr.h> // for attr_info #define max(x,y) ((x > y) ? x : y) #define DATA_BUFFER_SIZE 64 struct StylesHeader { uint32 magic; // 41 6c 69 21 uint32 version; // 0 int32 count; }; struct Style { int32 offset; char family[64]; char style[64]; float size; float shear; // typically 90.0 uint16 face; // typically 0 uint8 red; uint8 green; uint8 blue; uint8 alpha; // 255 == opaque uint16 reserved; // 0 }; void PrintStyle(Style &style, int32 i) { style.offset = B_BENDIAN_TO_HOST_INT32(style.offset); style.size = B_BENDIAN_TO_HOST_FLOAT(style.size); style.shear = B_BENDIAN_TO_HOST_FLOAT(style.shear); style.face = B_BENDIAN_TO_HOST_INT16(style.face); style.reserved = B_BENDIAN_TO_HOST_INT16(style.reserved); printf("\nStyle %d:\n", static_cast<int>(i + 1)); printf("offset: %d\n", static_cast<int>(style.offset)); printf("family: %s\n", style.family); printf("style: %s\n", style.style); printf("size: %f\n", style.size); printf("shear: %f (typically 90.0)\n", style.shear); printf("face: %u (typically 0)\n", static_cast<unsigned int>(style.face)); printf("RGBA: (%u, %u, %u, %u)\n", static_cast<unsigned int>(style.red), static_cast<unsigned int>(style.blue), static_cast<unsigned int>(style.green), static_cast<unsigned int>(style.alpha)); printf("reserved: %u (should be 0)\n", static_cast<unsigned int>(style.reserved)); } bool PrintStylesAttribute(BFile &file) { const char *kAttrName = "styles"; attr_info info; if (file.GetAttrInfo(kAttrName, &info) != B_OK) return false; if (info.type != B_RAW_TYPE) { printf("Error: styles attribute is of the wrong type\n"); return false; } if (info.size < 160) { printf("Error: styles attribute is missing information\n"); return false; } uint8 *pflatRunArray = new uint8[info.size]; if (!pflatRunArray) { printf("Error: Not enough memory available to read styles attribute\n"); return false; } ssize_t amtread = file.ReadAttr(kAttrName, B_RAW_TYPE, 0, pflatRunArray, info.size); if (amtread != info.size) { printf("Error: Unable to read styles attribute\n"); return false; } // Check Styles StylesHeader stylesheader; memcpy(&stylesheader, pflatRunArray, sizeof(StylesHeader)); if (swap_data(B_UINT32_TYPE, &stylesheader, sizeof(StylesHeader), B_SWAP_BENDIAN_TO_HOST) != B_OK) { printf("Error: Unable to swap byte order of styles header\n"); return false; } // Print StylesHeader info printf("\"styles\" attribute data:\n\n"); printf("magic number: 0x%.8lx ", static_cast<unsigned long>(stylesheader.magic)); if (stylesheader.magic == 'Ali!') printf("(valid)\n"); else printf("(INVALID, should be 0x%.8lx)\n", static_cast<unsigned long>('Ali!')); printf("version: 0x%.8lx ", static_cast<unsigned long>(stylesheader.version)); if (stylesheader.version == 0) printf("(valid)\n"); else printf("(INVALID, should be 0x%.8lx)\n", 0UL); printf("number of styles: %d\n", static_cast<int>(stylesheader.count)); // Check and Print out each style Style *pstyle = reinterpret_cast<Style *>(pflatRunArray + sizeof(StylesHeader)); for (int32 i = 0; i < stylesheader.count; i++) PrintStyle(*(pstyle + i), i); delete[] pflatRunArray; pflatRunArray = NULL; return true; } bool PrintStxtInfo(BFile &file) { const uint32 kstxtsize = sizeof(TranslatorStyledTextStreamHeader); const uint32 ktxtsize = sizeof(TranslatorStyledTextTextHeader); const uint32 kstylsize = sizeof(TranslatorStyledTextStyleHeader); const uint32 kStyleSize = sizeof(Style); uint8 buffer[max(max(max(kstxtsize, ktxtsize), kstylsize), kStyleSize)]; // Check STXT Header status_t nread = 0; nread = file.Read(buffer, kstxtsize); if (nread != static_cast<status_t>(kstxtsize)) { printf("Error: Unable to read stream header\n"); return false; } TranslatorStyledTextStreamHeader stxtheader; memcpy(&stxtheader, buffer, kstxtsize); if (swap_data(B_UINT32_TYPE, &stxtheader, kstxtsize, B_SWAP_BENDIAN_TO_HOST) != B_OK) { printf("Error: Unable to swap byte order of stream header\n"); return false; } if (stxtheader.header.magic != B_STYLED_TEXT_FORMAT) { printf("Styled text magic number is incorrect, aborting.\n"); return false; } // Print Stream Header (STXT) printf("Stream Header (STXT section):\n\n"); printf("magic number: 0x%.8lx ", stxtheader.header.magic); if (stxtheader.header.magic == B_STYLED_TEXT_FORMAT) printf("(valid)\n"); else printf("(INVALID, should be 0x%.8lx)\n", static_cast<unsigned long>(B_STYLED_TEXT_FORMAT)); printf("header size: %u ", static_cast<unsigned int>(stxtheader.header.header_size)); if (stxtheader.header.header_size == kstxtsize) printf("(valid)\n"); else printf("(INVALID, should be %u)\n", static_cast<unsigned int>(kstxtsize)); printf("data size: %u ", static_cast<unsigned int>(stxtheader.header.data_size)); if (stxtheader.header.data_size == 0) printf("(valid)\n"); else printf("(INVALID, should be 0)\n"); printf("version: %d ", static_cast<int>(stxtheader.version)); if (stxtheader.version == 100) printf("(valid)\n"); else printf("(INVALID, should be 100)\n"); // Check the TEXT header TranslatorStyledTextTextHeader txtheader; if (file.Read(buffer, ktxtsize) != static_cast<ssize_t>(ktxtsize)) { printf("Error: Unable to read text header\n"); return false; } memcpy(&txtheader, buffer, ktxtsize); if (swap_data(B_UINT32_TYPE, &txtheader, ktxtsize, B_SWAP_BENDIAN_TO_HOST) != B_OK) { printf("Error: Unable to swap byte order of text header\n"); return false; } // Print Text Header (TEXT) printf("\nText Header (TEXT section):\n\n"); printf("magic number: 0x%.8lx ", txtheader.header.magic); if (txtheader.header.magic == 'TEXT') printf("(valid)\n"); else printf("(INVALID, should be 0x%.8lx)\n", static_cast<unsigned long>('TEXT')); printf("header size: %u ", static_cast<unsigned int>(txtheader.header.header_size)); if (stxtheader.header.header_size == ktxtsize) printf("(valid)\n"); else printf("(INVALID, should be %u)\n", static_cast<unsigned int>(ktxtsize)); printf("data size (bytes of text): %u\n", static_cast<unsigned int>(txtheader.header.data_size)); printf("character set: %d ", static_cast<int>(txtheader.charset)); if (txtheader.charset == B_UNICODE_UTF8) printf("(valid)\n"); else printf("(INVALID, should be %d)\n", B_UNICODE_UTF8); // Skip the text data off_t seekresult, pos; pos = stxtheader.header.header_size + txtheader.header.header_size + txtheader.header.data_size; seekresult = file.Seek(txtheader.header.data_size, SEEK_CUR); if (seekresult < pos) { printf("Error: Unable to seek past text data. " \ "Text data could be missing\n"); return false; } if (seekresult > pos) { printf("Error: File position is beyond expected value\n"); return false; } // Check the STYL header (not all STXT files have this) ssize_t read = 0; TranslatorStyledTextStyleHeader stylheader; read = file.Read(buffer, kstylsize); if (read != static_cast<ssize_t>(kstylsize) && read != 0) { printf("Error: Unable to read entire style header\n"); return false; } // If there is no STYL header (and no errors) if (read != static_cast<ssize_t>(kstylsize)) { printf("\nFile contains no Style Header (STYL section)\n"); return false; } memcpy(&stylheader, buffer, kstylsize); if (swap_data(B_UINT32_TYPE, &stylheader, kstylsize, B_SWAP_BENDIAN_TO_HOST) != B_OK) { printf("Error: Unable to swap byte order of style header\n"); return false; } // Print Style Header (STYL) printf("\nStyle Header (STYL section):\n\n"); printf("magic number: 0x%.8lx ", stylheader.header.magic); if (stylheader.header.magic == 'STYL') printf("(valid)\n"); else printf("(INVALID, should be 0x%.8lx)\n", static_cast<unsigned long>('STYL')); printf("header size: %u ", static_cast<unsigned int>(stylheader.header.header_size)); if (stylheader.header.header_size == kstylsize) printf("(valid)\n"); else printf("(INVALID, should be %u)\n", static_cast<unsigned int>(kstylsize)); printf("data size: %u\n", static_cast<unsigned int>(stylheader.header.data_size)); printf("apply offset: %u (usually 0)\n", static_cast<unsigned int>(stylheader.apply_offset)); printf("apply length: %u (usually the text data size)\n", static_cast<unsigned int>(stylheader.apply_length)); // Check Styles StylesHeader stylesheader; read = file.Read(buffer, sizeof(StylesHeader)); if (read != sizeof(StylesHeader)) { printf("Error: Unable to read Styles header\n"); return false; } memcpy(&stylesheader, buffer, sizeof(StylesHeader)); if (swap_data(B_UINT32_TYPE, &stylesheader, sizeof(StylesHeader), B_SWAP_BENDIAN_TO_HOST) != B_OK) { printf("Error: Unable to swap byte order of styles header\n"); return false; } // Print StylesHeader info printf("\nStyles Header (Ali! section):\n\n"); printf("magic number: 0x%.8lx ", static_cast<unsigned long>(stylesheader.magic)); if (stylesheader.magic == 'Ali!') printf("(valid)\n"); else printf("(INVALID, should be 0x%.8lx)\n", static_cast<unsigned long>('Ali!')); printf("version: 0x%.8lx ", static_cast<unsigned long>(stylesheader.version)); if (stylesheader.version == 0) printf("(valid)\n"); else printf("(INVALID, should be 0x%.8lx)\n", 0UL); printf("number of styles: %d\n", static_cast<int>(stylesheader.count)); // Check and Print out each style for (int32 i = 0; i < stylesheader.count; i++) { Style style; read = file.Read(&style, sizeof(Style)); if (read != sizeof(Style)) { printf("Error: Unable to read style %d\n", static_cast<int>(i + 1)); return false; } PrintStyle(style, i); } return true; } int main(int argc, char **argv) { printf("\n"); if (argc == 2) { BFile file(argv[1], B_READ_ONLY); if (file.InitCheck() != B_OK) printf("Error opening %s\n", argv[1]); else { printf("Be styled text information for: %s\n\n", argv[1]); if (PrintStylesAttribute(file) == false) { printf("Unable to read styles attribute, attempting to read " \ "style information from file...\n\n"); PrintStxtInfo(file); } } } else { printf("stxtinfo - reports information about a Be styled text file\n"); printf("\nUsage:\n"); printf("stxtinfo filename.stxt\n"); } printf("\n"); return 0; }
4,784
1,002
// Copyright (c) Microsoft Corporation. All rights reserved. // // Licensed under the MIT License. See LICENSE.txt in the project root for license information. #include "pch.h" #include "CanvasControl.h" #include "RecreatableDeviceManager.impl.h" #include "BaseControlAdapter.h" using namespace ABI::Microsoft::Graphics::Canvas::UI::Xaml; using namespace ABI::Microsoft::Graphics::Canvas; using namespace ABI::Windows::ApplicationModel::Core; using namespace ABI::Windows::ApplicationModel; using namespace ABI::Microsoft::UI::Dispatching; using namespace ABI::Windows::Graphics::Display; using namespace ABI::Microsoft::UI::Xaml::Media; using namespace ABI::Microsoft::UI::Xaml; IFACEMETHODIMP CanvasDrawEventArgsFactory::Create( ICanvasDrawingSession* drawingSession, ICanvasDrawEventArgs** drawEventArgs) { return ExceptionBoundary( [&] { CheckAndClearOutPointer(drawEventArgs); auto newCanvasDrawEventArgs = Make<CanvasDrawEventArgs>(drawingSession); CheckMakeResult(newCanvasDrawEventArgs); ThrowIfFailed(newCanvasDrawEventArgs.CopyTo(drawEventArgs)); }); } CanvasDrawEventArgs::CanvasDrawEventArgs(ICanvasDrawingSession* drawingSession) : m_drawingSession(drawingSession) {} IFACEMETHODIMP CanvasDrawEventArgs::get_DrawingSession(ICanvasDrawingSession** value) { return ExceptionBoundary( [&] { CheckAndClearOutPointer(value); ComPtr<ICanvasDrawingSession> drawingSession = m_drawingSession.EnsureNotClosed(); ThrowIfFailed(drawingSession.CopyTo(value)); }); } // // Warning C4250 is incorrectly triggered when we use virtual inheritance with // pure-virtual functions. In this case we have the functions defined in // IImageControlMixInAdapter that are implemented by ImageControlMixInAdapter. // The inheritance graph looks like this: // // /-- BaseControlAdapter -- ICanvasControlAdapter --\ // / \ // CanvasControlAdapter -- IImageControlMixInAdapter // \ / // \-- ImageControlMixInAdapter ---------------------/ // // The warning is only relevant if the functions from IImageControlMixInAdapter // are non-pure. // #pragma warning(disable: 4250) class CanvasControlAdapter : public BaseControlAdapter<CanvasControlTraits> , public ImageControlMixInAdapter { ComPtr<ICanvasImageSourceFactory> m_canvasImageSourceFactory; public: CanvasControlAdapter() { auto& module = Module<InProc>::GetModule(); ComPtr<IActivationFactory> imageSourceActivationFactory; ThrowIfFailed(module.GetActivationFactory( HStringReference(RuntimeClass_Microsoft_Graphics_Canvas_UI_Xaml_CanvasImageSource).Get(), &imageSourceActivationFactory)); ThrowIfFailed(imageSourceActivationFactory.As(&m_canvasImageSourceFactory)); } virtual RegisteredEvent AddCompositionRenderingCallback(IEventHandler<IInspectable*>* handler) override { return RegisteredEvent( GetCompositionTargetStatics(), &ICompositionTargetStatics::add_Rendering, &ICompositionTargetStatics::remove_Rendering, handler); } virtual ComPtr<CanvasImageSource> CreateCanvasImageSource(ICanvasDevice* device, float width, float height, float dpi, CanvasAlphaMode alphaMode) override { ComPtr<ICanvasResourceCreator> resourceCreator; ThrowIfFailed(device->QueryInterface(resourceCreator.GetAddressOf())); ComPtr<ICanvasImageSource> imageSource; ThrowIfFailed(m_canvasImageSourceFactory->CreateWithWidthAndHeightAndDpiAndAlphaMode( resourceCreator.Get(), width, height, dpi, alphaMode, &imageSource)); // Since we know that CanvasImageSourceFactory will only ever return // CanvasImageSource instances, we can be certain that the // ICanvasImageSource we get back is actually a CanvasImageSource. return static_cast<CanvasImageSource*>(imageSource.Get()); } }; #pragma warning(default: 4250) class CanvasControlFactory : public AgileActivationFactory<>, private LifespanTracker<CanvasControlFactory> { std::weak_ptr<CanvasControlAdapter> m_adapter; public: IFACEMETHODIMP ActivateInstance(IInspectable** obj) override { return ExceptionBoundary( [&] { CheckAndClearOutPointer(obj); auto adapter = m_adapter.lock(); if (!adapter) m_adapter = adapter = std::make_shared<CanvasControlAdapter>(); auto control = Make<CanvasControl>(adapter); CheckMakeResult(control); ThrowIfFailed(control.CopyTo(obj)); }); } }; CanvasControl::CanvasControl( std::shared_ptr<ICanvasControlAdapter> adapter) : BaseControlWithDrawHandler(adapter, true) , ImageControlMixIn(As<IUserControl>(GetComposableBase()).Get(), adapter.get()) , m_needToHookCompositionRendering(false) { } void CanvasControl::RegisterEventHandlers() { ImageControlMixIn::RegisterEventHandlers<CanvasControl>(GetAdapter().get()); } void CanvasControl::UnregisterEventHandlers() { if (m_renderingEventRegistration) { m_renderingEventRegistration.Release(); m_needToHookCompositionRendering = true; } ImageControlMixIn::UnregisterEventHandlers(); } IFACEMETHODIMP CanvasControl::Invalidate() { return ExceptionBoundary( [&] { Changed(ChangeReason::Other); }); } HRESULT CanvasControl::OnCompositionRendering(IInspectable*, IInspectable*) { return ExceptionBoundary( [&] { if (!IsLoaded()) return; auto lock = Lock(m_renderingEventMutex); m_renderingEventRegistration.Release(); lock.unlock(); if (!IsVisible()) return; try { DrawControl(); } catch (HResultException const& e) { // Sometimes, the XAML SurfaceImageSource gets into a state // where it returns E_SURFACE_CONTENTS_LOST, even though it // probably shouldn't. We handle this case by recreating the // SurfaceImageSource and retrying the draw. If it doesn't work // the second time we'll allow the error to bubble out. if (e.GetHr() == E_SURFACE_CONTENTS_LOST) { GetCurrentRenderTarget()->Target = nullptr; // force the SiS to get recreated on the next draw DrawControl(); } else { // Rethrow other errors. throw; } } }); } void CanvasControl::DrawControl() { RunWithRenderTarget( [=](CanvasImageSource* target, ICanvasDevice*, Color const& clearColor, bool callDrawHandlers) { if (!target) return; Draw(target, clearColor, callDrawHandlers, false); }); } void CanvasControl::CreateOrUpdateRenderTarget( ICanvasDevice* device, CanvasAlphaMode newAlphaMode, float newDpi, Size newSize, RenderTarget* renderTarget) { bool needsCreate = (renderTarget->Target == nullptr); needsCreate |= (renderTarget->AlphaMode != newAlphaMode); needsCreate |= (renderTarget->Dpi != newDpi); needsCreate |= (renderTarget->Size != newSize); if (!needsCreate) return; if (newSize.Width <= 0 || newSize.Height <= 0) { // Zero-sized controls don't have image sources *renderTarget = RenderTarget{}; SetImageSource(nullptr); } else { renderTarget->Target = GetAdapter()->CreateCanvasImageSource( device, newSize.Width, newSize.Height, newDpi, newAlphaMode); renderTarget->AlphaMode = newAlphaMode; renderTarget->Dpi = newDpi; renderTarget->Size = newSize; SetImageSource(As<IImageSource>(renderTarget->Target).Get()); } } ComPtr<CanvasDrawEventArgs> CanvasControl::CreateDrawEventArgs(ICanvasDrawingSession* drawingSession, bool) { auto drawEventArgs = Make<CanvasDrawEventArgs>(drawingSession); CheckMakeResult(drawEventArgs); return drawEventArgs; } void CanvasControl::Changed(ChangeReason) { if (!IsLoaded()) return; // Are we on the UI thread? boolean hasThreadAccess; // // IWindow will not be available in Xaml island scenarios, so prefer // IDependencyObject for getting the dispatcher. // ComPtr<IDispatcherQueue> dispatcher; auto control = GetControl(); if (auto dependencyObject = MaybeAs<IDependencyObject>(control)) { ThrowIfFailed(dependencyObject->get_DispatcherQueue(dispatcher.ReleaseAndGetAddressOf())); } else { ThrowIfFailed(GetWindow()->get_DispatcherQueue(dispatcher.ReleaseAndGetAddressOf())); } if (dispatcher) { ThrowIfFailed(As<IDispatcherQueue2>(dispatcher)->get_HasThreadAccess(&hasThreadAccess)); } else { // Running in the designer. assert(GetAdapter()->IsDesignModeEnabled()); hasThreadAccess = true; } if (hasThreadAccess) { // Do the work immediately. ChangedImpl(); } else { // Marshal back to the UI thread. WeakRef weakSelf = AsWeak(this); auto callback = Callback<AddFtmBase<IDispatcherQueueHandler>::Type>([weakSelf]() mutable { return ExceptionBoundary([&] { auto strongSelf = LockWeakRef<ICanvasControl>(weakSelf); auto self = static_cast<CanvasControl*>(strongSelf.Get()); if (self) { self->ChangedImpl(); } }); }); CheckMakeResult(callback); boolean result = true; dispatcher->TryEnqueueWithPriority(ABI::Microsoft::UI::Dispatching::DispatcherQueuePriority_Normal, callback.Get(), &result); } } void CanvasControl::ChangedImpl() { // // This is called on the UI thread (Changed() makes sure of it) // auto lock = Lock(m_renderingEventMutex); if (m_renderingEventRegistration) return; m_needToHookCompositionRendering = true; if (!IsVisible()) return; HookCompositionRenderingIfNecessary(lock); } void CanvasControl::Loaded() { RegisterEventHandlers(); } void CanvasControl::Unloaded() { UnregisterEventHandlers(); } void CanvasControl::ApplicationSuspending(ISuspendingEventArgs*) { Trim(); } void CanvasControl::ApplicationResuming() { } void CanvasControl::HookCompositionRenderingIfNecessary(Lock const& renderingEventLock) { MustOwnLock(renderingEventLock); if (m_renderingEventRegistration) return; if (!m_needToHookCompositionRendering) return; m_renderingEventRegistration = GetAdapter()->AddCompositionRenderingCallback( this, &CanvasControl::OnCompositionRendering); m_needToHookCompositionRendering = false; } void CanvasControl::WindowVisibilityChanged() { auto lock = Lock(m_renderingEventMutex); if (IsVisible()) { HookCompositionRenderingIfNecessary(lock); } else { if (m_renderingEventRegistration) { // // The window is invisible. This means that // OnCompositionRendering() will not do anything. However, XAML // will run composition if any handlers are registered on the // rendering event. Since we want to avoid the system doing // unnecessary work we take steps to unhook the event when we're // not making good use of it. // m_renderingEventRegistration.Release(); m_needToHookCompositionRendering = true; } } } ActivatableClassWithFactory(CanvasDrawEventArgs, CanvasDrawEventArgsFactory); ActivatableClassWithFactory(CanvasControl, CanvasControlFactory);
5,318
1,005
#ifndef TACO_UTIL_BENCHMARK_H #define TACO_UTIL_BENCHMARK_H #include <chrono> #include <algorithm> #include <iostream> #include <numeric> #include <vector> #include <cmath> #include "taco/error.h" using namespace std; namespace taco { namespace util { struct TimeResults { double mean; double stdev; double median; int size; friend std::ostream& operator<<(std::ostream& os, const TimeResults& t) { if (t.size == 1) { return os << t.mean; } else { return os << " mean: " << t.mean << endl << " stdev: " << t.stdev << endl << " median: " << t.median; } } }; typedef std::chrono::time_point<std::chrono::steady_clock> TimePoint; /// Monotonic timer that can be called multiple times and that computes /// statistics such as mean and median from the calls. class Timer { public: void start() { begin = std::chrono::steady_clock::now(); } void stop() { auto end = std::chrono::steady_clock::now(); auto diff = std::chrono::duration<double, std::milli>(end - begin).count(); times.push_back(diff); } // Compute mean, standard deviation and median TimeResults getResult() { int repeat = static_cast<int>(times.size()); TimeResults result; double mean=0.0; // times = ends - begins sort(times.begin(), times.end()); // remove 10% worst and best cases const int truncate = static_cast<int>(repeat * 0.1); mean = accumulate(times.begin() + truncate, times.end() - truncate, 0.0); int size = repeat - 2 * truncate; result.size = size; mean = mean/size; result.mean = mean; vector<double> diff(size); transform(times.begin() + truncate, times.end() - truncate, diff.begin(), [mean](double x) { return x - mean; }); double sq_sum = inner_product(diff.begin(), diff.end(), diff.begin(), 0.0); result.stdev = std::sqrt(sq_sum / size); result.median = (size % 2) ? times[size/2] : (times[size/2-1] + times[size/2]) / 2; return result; } double clear_cache() { double ret = 0.0; if (!dummyA) { dummyA = (double*)(malloc(dummySize*sizeof(double))); dummyB = (double*)(malloc(dummySize*sizeof(double))); } for (int i=0; i< 100; i++) { dummyA[rand() % dummySize] = rand()/RAND_MAX; dummyB[rand() % dummySize] = rand()/RAND_MAX; } for (int i=0; i<dummySize; i++) { ret += dummyA[i] * dummyB[i]; } return ret; } protected: vector<double> times; TimePoint begin; private: int dummySize = 3000000; double* dummyA = NULL; double* dummyB = NULL; }; /// Monotonic timer that prints results as it goes. class LapTimer { public: LapTimer(string timerName = "") : timerGroup(true), isTiming(false) { if (timerName != "") { std::cout << timerName << std::endl; } } void start(const string& name) { this->timingName = name; taco_iassert(!isTiming) << "Called PrintTimer::start twice in a row"; isTiming = true; begin = std::chrono::steady_clock::now(); } void lap(const string& name) { auto end = std::chrono::steady_clock::now(); taco_iassert(isTiming) << "lap timer that hasn't been started"; if (timerGroup) { std::cout << " "; } auto diff = std::chrono::duration<double, std::milli>(end - begin).count(); std::cout << timingName << ": " << diff << " ms" << std::endl; this->timingName = name; begin = std::chrono::steady_clock::now(); } void stop() { auto end = std::chrono::steady_clock::now(); taco_iassert(isTiming) << "Called PrintTimer::stop without first calling start"; if (timerGroup) { std::cout << " "; } auto diff = std::chrono::duration<double, std::milli>(end - begin).count(); std::cout << timingName << ": " << diff << " ms" << std::endl; isTiming = false; } private: bool timerGroup; string timingName; TimePoint begin; bool isTiming; }; }} #define TACO_TIME_REPEAT(CODE, REPEAT, RES, COLD) { \ taco::util::Timer timer; \ for(int i=0; i<REPEAT; i++) { \ if(COLD) \ timer.clear_cache(); \ timer.start(); \ CODE; \ timer.stop(); \ } \ RES = timer.getResult(); \ } #endif
2,088
1,350
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. package com.azure.search.documents.indexes.implementation.models; import com.azure.core.annotation.Immutable; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; /** Describes an error condition for the Azure Cognitive Search API. */ @Immutable public final class SearchError { /* * One of a server-defined set of error codes. */ @JsonProperty(value = "code", access = JsonProperty.Access.WRITE_ONLY) private String code; /* * A human-readable representation of the error. */ @JsonProperty(value = "message", required = true, access = JsonProperty.Access.WRITE_ONLY) private String message; /* * An array of details about specific errors that led to this reported * error. */ @JsonProperty(value = "details", access = JsonProperty.Access.WRITE_ONLY) private List<SearchError> details; /** * Creates an instance of SearchError class. * * @param message the message value to set. */ @JsonCreator public SearchError( @JsonProperty(value = "message", required = true, access = JsonProperty.Access.WRITE_ONLY) String message) { this.message = message; } /** * Get the code property: One of a server-defined set of error codes. * * @return the code value. */ public String getCode() { return this.code; } /** * Get the message property: A human-readable representation of the error. * * @return the message value. */ public String getMessage() { return this.message; } /** * Get the details property: An array of details about specific errors that led to this reported error. * * @return the details value. */ public List<SearchError> getDetails() { return this.details; } }
744
373
/* * #%L * ACS AEM Commons Bundle * %% * Copyright (C) 2017 Adobe * %% * 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% */ package com.adobe.acs.commons.mcp.model; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.stream.Collectors; import javax.annotation.PostConstruct; import javax.inject.Inject; import javax.jcr.Node; import javax.jcr.RepositoryException; import org.apache.commons.io.IOUtils; import org.apache.jackrabbit.commons.JcrUtils; import org.apache.sling.api.resource.ModifiableValueMap; import org.apache.sling.api.resource.PersistenceException; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.api.resource.ResourceUtil; import org.apache.sling.api.wrappers.ValueMapDecorator; import org.apache.sling.models.annotations.Model; import org.apache.sling.models.annotations.injectorspecific.ChildResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.adobe.acs.commons.mcp.ProcessInstance; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; /** * Stores the reports into a single blob in the repository. This is more * efficient compared to the GenericReport, and should be used furtheron. * */ @Model(adaptables = Resource.class) public class GenericBlobReport extends AbstractReport { @ChildResource Resource blobreport; @Inject String name; @Inject List<String> columns; private static final Logger LOG = LoggerFactory.getLogger(GenericBlobReport.class); public static final String BLOB_REPORT_RESOURCE_TYPE = ProcessInstance.RESOURCE_TYPE + "/process-blob-report"; public String getResourceType() { return BLOB_REPORT_RESOURCE_TYPE; } @PostConstruct public void init() { // read all data from the blob and store it in the properties of the // AbstractReport columnsData = columns; nameData = name; ObjectMapper mapper = new ObjectMapper(); try (InputStream is = blobreport.adaptTo(InputStream.class)) { JsonNode array = mapper.readTree(is); if (!array.isArray()) { LOG.error("blobreport does not contain a JSON array, not reading any data from {}", blobreport.getPath()); } else { for (JsonNode ar : array) { Map<String, Object> map = new HashMap<>(); for (String c : columns) { if (ar.has(c) && ar.get(c) != null) { map.put(c, ar.get(c).asText()); } } getRows().add(new ValueMapDecorator(map)); } } } catch (IOException e) { LOG.error("Problems during de-serialization of report (path={})", blobreport.getPath(), e); } } @Override public void persist(ResourceResolver rr, String path) throws PersistenceException, RepositoryException { // persist all data to the blob ModifiableValueMap jcrContent = ResourceUtil.getOrCreateResource(rr, path, getResourceType(), null, false) .adaptTo(ModifiableValueMap.class); jcrContent.put("jcr:primaryType", "nt:unstructured"); jcrContent.put("columns", getColumns().toArray(new String[0])); jcrContent.put("name", getName()); ObjectMapper mapper = new ObjectMapper(); ArrayNode jsonRows = new ArrayNode(JsonNodeFactory.instance); for (Map<String, Object> row : rowsData) { // First strip out null values Map<String, Object> properties = row.entrySet().stream().filter(e -> e.getValue() != null) .collect(Collectors.toMap(Entry::getKey, Entry::getValue)); JsonNode elem = mapper.convertValue(properties, JsonNode.class); jsonRows.add(elem); } Node parent = rr.getResource(path).adaptTo(Node.class); if (parent != null) { try { String jsonString = mapper.writeValueAsString(jsonRows); try (InputStream is = IOUtils.toInputStream(jsonString, Charset.defaultCharset())) { JcrUtils.putFile(parent, "blobreport", "text/json", is); rr.commit(); } } catch (JsonProcessingException ex) { throw new PersistenceException("Cannot convert Json to String", ex); } catch (IOException ioe) { throw new PersistenceException("Cannot close inputstream for report", ioe); } } else { LOG.error("{} is not a JCR path, cannot persist report", path); } } }
2,279
4,409
/* * Copyright 2002-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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.jwt.crypto.sign; import org.junit.Test; import org.springframework.security.jwt.codec.Codecs; import java.math.BigInteger; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.Security; import java.security.Signature; import java.security.interfaces.ECPrivateKey; import java.security.interfaces.ECPublicKey; import java.security.spec.ECGenParameterSpec; /** * Tests for {@link EllipticCurveVerifier}. * * @author <NAME> */ public class EllipticCurveVerifierTests { private final static String P256_CURVE = "P-256"; private final static String P384_CURVE = "P-384"; private final static String P521_CURVE = "P-521"; private final static String SHA256_ECDSA_ALG = "SHA256withECDSA"; private final static String SHA384_ECDSA_ALG = "SHA384withECDSA"; private final static String SHA512_ECDSA_ALG = "SHA512withECDSA"; static { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); } @Test(expected = IllegalArgumentException.class) public void constructorWhenUnsupportedCurveThenThrowIllegalArgumentException() { new EllipticCurveVerifier(BigInteger.ONE, BigInteger.ONE, "unsupported-curve", SHA256_ECDSA_ALG); } @Test public void verifyWhenP256CurveAndSignatureMatchesThenVerificationPasses() throws Exception { this.verifyWhenSignatureMatchesThenVerificationPasses(P256_CURVE, SHA256_ECDSA_ALG); } @Test(expected = InvalidSignatureException.class) public void verifyWhenP256CurveAndSignatureDoesNotMatchThenThrowInvalidSignatureException() throws Exception { this.verifyWhenSignatureDoesNotMatchThenThrowInvalidSignatureException(P256_CURVE, SHA256_ECDSA_ALG); } @Test public void verifyWhenP384CurveAndSignatureMatchesThenVerificationPasses() throws Exception { this.verifyWhenSignatureMatchesThenVerificationPasses(P384_CURVE, SHA384_ECDSA_ALG); } @Test(expected = InvalidSignatureException.class) public void verifyWhenP384CurveAndSignatureDoesNotMatchThenThrowInvalidSignatureException() throws Exception { this.verifyWhenSignatureDoesNotMatchThenThrowInvalidSignatureException(P384_CURVE, SHA384_ECDSA_ALG); } @Test public void verifyWhenP521CurveAndSignatureMatchesThenVerificationPasses() throws Exception { this.verifyWhenSignatureMatchesThenVerificationPasses(P521_CURVE, SHA512_ECDSA_ALG); } @Test(expected = InvalidSignatureException.class) public void verifyWhenP521CurveAndSignatureDoesNotMatchThenThrowInvalidSignatureException() throws Exception { this.verifyWhenSignatureDoesNotMatchThenThrowInvalidSignatureException(P521_CURVE, SHA512_ECDSA_ALG); } @Test(expected = InvalidSignatureException.class) public void verifyWhenSignatureAlgorithmNotSameAsVerificationAlgorithmThenThrowInvalidSignatureException() throws Exception { KeyPair keyPair = this.generateKeyPair(P256_CURVE); ECPublicKey publicKey = (ECPublicKey) keyPair.getPublic(); ECPrivateKey privateKey = (ECPrivateKey) keyPair.getPrivate(); byte[] data = "Some data".getBytes(); byte[] jwsSignature = Codecs.b64UrlEncode(this.generateJwsSignature(data, SHA256_ECDSA_ALG, privateKey)); EllipticCurveVerifier verifier = new EllipticCurveVerifier( publicKey.getW().getAffineX(), publicKey.getW().getAffineY(), P256_CURVE, SHA512_ECDSA_ALG); verifier.verify(data, Codecs.b64UrlDecode(jwsSignature)); } private void verifyWhenSignatureMatchesThenVerificationPasses(String curve, String algorithm) throws Exception { KeyPair keyPair = this.generateKeyPair(curve); ECPublicKey publicKey = (ECPublicKey) keyPair.getPublic(); ECPrivateKey privateKey = (ECPrivateKey) keyPair.getPrivate(); byte[] data = "Some data".getBytes(); byte[] jwsSignature = Codecs.b64UrlEncode(this.generateJwsSignature(data, algorithm, privateKey)); EllipticCurveVerifier verifier = new EllipticCurveVerifier( publicKey.getW().getAffineX(), publicKey.getW().getAffineY(), curve, algorithm); verifier.verify(data, Codecs.b64UrlDecode(jwsSignature)); } private void verifyWhenSignatureDoesNotMatchThenThrowInvalidSignatureException(String curve, String algorithm) throws Exception { KeyPair keyPair = this.generateKeyPair(curve); ECPublicKey publicKey = (ECPublicKey) keyPair.getPublic(); ECPrivateKey privateKey = (ECPrivateKey) keyPair.getPrivate(); byte[] data = "Some data".getBytes(); byte[] jwsSignature = Codecs.b64UrlEncode(this.generateJwsSignature(data, algorithm, privateKey)); EllipticCurveVerifier verifier = new EllipticCurveVerifier( publicKey.getW().getAffineX(), publicKey.getW().getAffineY(), curve, algorithm); verifier.verify("Data not matching signature".getBytes(), Codecs.b64UrlDecode(jwsSignature)); } private KeyPair generateKeyPair(String curve) throws Exception { ECGenParameterSpec ecGenParameterSpec = new ECGenParameterSpec(curve); KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("ECDSA"); keyPairGenerator.initialize(ecGenParameterSpec); return keyPairGenerator.generateKeyPair(); } private byte[] generateJwsSignature(byte[] data, String algorithm, ECPrivateKey privateKey) throws Exception { Signature signature = Signature.getInstance(algorithm); signature.initSign(privateKey); signature.update(data); byte[] jcaSignature = signature.sign();// DER-encoded signature, according to JCA spec (sequence of two integers - R + S) int jwsSignatureLength = -1; if (SHA256_ECDSA_ALG.equals(algorithm)) { jwsSignatureLength = 64; } else if (SHA384_ECDSA_ALG.equals(algorithm)) { jwsSignatureLength = 96; } else if (SHA512_ECDSA_ALG.equals(algorithm)) { jwsSignatureLength = 132; } return EllipticCurveSignatureHelper.transcodeSignatureToJWS(jcaSignature, jwsSignatureLength); } }
2,113
3,986
/* * Copyright (C) 2018 xuexiangjys(<EMAIL>) * * 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.xuexiang.xuidemo.fragment.components.refresh.smartrefresh; import android.widget.AbsListView; import com.scwang.smartrefresh.layout.api.RefreshLayout; import com.xuexiang.xpage.annotation.Page; import com.xuexiang.xuidemo.DemoDataProvider; import com.xuexiang.xuidemo.R; import com.xuexiang.xuidemo.adapter.SimpleRecyclerAdapter; import com.xuexiang.xuidemo.base.BaseFragment; import com.xuexiang.xuidemo.utils.XToastUtils; /** * @author xuexiang * @since 2018/12/6 下午5:57 */ @Page(name = "下拉刷新基础用法\n上拉加载、下拉刷新、自动刷新和点击事件") public class RefreshBasicFragment extends BaseFragment { private SimpleRecyclerAdapter mAdapter; /** * 布局的资源id * * @return */ @Override protected int getLayoutId() { return R.layout.fragment_refresh_basic; } /** * 初始化控件 */ @Override protected void initViews() { AbsListView listView = findViewById(R.id.listView); listView.setAdapter(mAdapter = new SimpleRecyclerAdapter()); final RefreshLayout refreshLayout = findViewById(R.id.refreshLayout); refreshLayout.setEnableAutoLoadMore(true);//开启自动加载功能(非必须) //下拉刷新 refreshLayout.setOnRefreshListener(refreshLayout12 -> refreshLayout12.getLayout().postDelayed(() -> { mAdapter.refresh(DemoDataProvider.getDemoData()); refreshLayout12.finishRefresh(); refreshLayout12.resetNoMoreData();//setNoMoreData(false); }, 2000)); //上拉加载 refreshLayout.setOnLoadMoreListener(refreshLayout1 -> refreshLayout1.getLayout().postDelayed(() -> { if (mAdapter.getItemCount() > 30) { XToastUtils.toast("数据全部加载完毕"); refreshLayout1.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件 } else { mAdapter.loadMore(DemoDataProvider.getDemoData()); refreshLayout1.finishLoadMore(); } }, 2000)); //触发自动刷新 refreshLayout.autoRefresh(); //item 点击测试 mAdapter.setOnItemClickListener((itemView, position) -> XToastUtils.toast("点击:" + position)); mAdapter.setOnItemLongClickListener((itemView, position) -> XToastUtils.toast("长按:" + position)); // //点击测试 // RefreshFooter footer = refreshLayout.getRefreshFooter(); // if (footer != null) { // refreshLayout.getRefreshFooter().getView().findViewById(ClassicsFooter.ID_TEXT_TITLE).setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // XToastUtils.toast("已经到底了!"); // } // }); // } } }
1,540
3,012
<gh_stars>1000+ /** @file Copyright (c) 2011 - 2013, Intel Corporation. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #ifndef __LINUX_BZIMAGE_H__ #define __LINUX_BZIMAGE_H__ #define BOOTSIG 0x1FE #define SETUP_HDR 0x53726448 /* 0x53726448 == "HdrS" */ #define E820_RAM 1 #define E820_RESERVED 2 #define E820_ACPI 3 #define E820_NVS 4 #define E820_UNUSABLE 5 #pragma pack(1) struct setup_header { UINT8 setup_secs; /* Sectors for setup code */ UINT16 root_flags; UINT32 sys_size; UINT16 ram_size; UINT16 video_mode; UINT16 root_dev; UINT16 signature; /* Boot signature */ UINT16 jump; UINT32 header; UINT16 version; UINT16 su_switch; UINT16 setup_seg; UINT16 start_sys; UINT16 kernel_ver; UINT8 loader_id; UINT8 load_flags; UINT16 movesize; UINT32 code32_start; /* Start of code loaded high */ UINT32 ramdisk_start; /* Start of initial ramdisk */ UINT32 ramdisk_len; /* Length of initial ramdisk */ UINT32 bootsect_kludge; UINT16 heap_end; UINT8 ext_loader_ver; /* Extended boot loader version */ UINT8 ext_loader_type; /* Extended boot loader ID */ UINT32 cmd_line_ptr; /* 32-bit pointer to the kernel command line */ UINT32 ramdisk_max; /* Highest legal initrd address */ UINT32 kernel_alignment; /* Physical addr alignment required for kernel */ UINT8 relocatable_kernel; /* Whether kernel is relocatable or not */ UINT8 min_alignment; UINT16 xloadflags; UINT32 cmdline_size; UINT32 hardware_subarch; UINT64 hardware_subarch_data; UINT32 payload_offset; UINT32 payload_length; UINT64 setup_data; UINT64 pref_address; UINT32 init_size; UINT32 handover_offset; }; struct efi_info { UINT32 efi_loader_signature; UINT32 efi_systab; UINT32 efi_memdesc_size; UINT32 efi_memdesc_version; UINT32 efi_memmap; UINT32 efi_memmap_size; UINT32 efi_systab_hi; UINT32 efi_memmap_hi; }; struct e820_entry { UINT64 addr; /* start of memory segment */ UINT64 size; /* size of memory segment */ UINT32 type; /* type of memory segment */ }; struct screen_info { UINT8 orig_x; /* 0x00 */ UINT8 orig_y; /* 0x01 */ UINT16 ext_mem_k; /* 0x02 */ UINT16 orig_video_page; /* 0x04 */ UINT8 orig_video_mode; /* 0x06 */ UINT8 orig_video_cols; /* 0x07 */ UINT8 flags; /* 0x08 */ UINT8 unused2; /* 0x09 */ UINT16 orig_video_ega_bx; /* 0x0a */ UINT16 unused3; /* 0x0c */ UINT8 orig_video_lines; /* 0x0e */ UINT8 orig_video_isVGA; /* 0x0f */ UINT16 orig_video_points; /* 0x10 */ /* VESA graphic mode -- linear frame buffer */ UINT16 lfb_width; /* 0x12 */ UINT16 lfb_height; /* 0x14 */ UINT16 lfb_depth; /* 0x16 */ UINT32 lfb_base; /* 0x18 */ UINT32 lfb_size; /* 0x1c */ UINT16 cl_magic, cl_offset; /* 0x20 */ UINT16 lfb_linelength; /* 0x24 */ UINT8 red_size; /* 0x26 */ UINT8 red_pos; /* 0x27 */ UINT8 green_size; /* 0x28 */ UINT8 green_pos; /* 0x29 */ UINT8 blue_size; /* 0x2a */ UINT8 blue_pos; /* 0x2b */ UINT8 rsvd_size; /* 0x2c */ UINT8 rsvd_pos; /* 0x2d */ UINT16 vesapm_seg; /* 0x2e */ UINT16 vesapm_off; /* 0x30 */ UINT16 pages; /* 0x32 */ UINT16 vesa_attributes; /* 0x34 */ UINT32 capabilities; /* 0x36 */ UINT8 _reserved[6]; /* 0x3a */ }; struct boot_params { struct screen_info screen_info; UINT8 apm_bios_info[0x14]; UINT8 _pad2[4]; UINT64 tboot_addr; UINT8 ist_info[0x10]; UINT8 _pad3[16]; UINT8 hd0_info[16]; UINT8 hd1_info[16]; UINT8 sys_desc_table[0x10]; UINT8 olpc_ofw_header[0x10]; UINT8 _pad4[128]; UINT8 edid_info[0x80]; struct efi_info efi_info; UINT32 alt_mem_k; UINT32 scratch; UINT8 e820_entries; UINT8 eddbuf_entries; UINT8 edd_mbr_sig_buf_entries; UINT8 _pad6[6]; struct setup_header hdr; UINT8 _pad7[0x290-0x1f1-sizeof (struct setup_header)]; UINT32 edd_mbr_sig_buffer[16]; struct e820_entry e820_map[128]; UINT8 _pad8[48]; UINT8 eddbuf[0x1ec]; UINT8 _pad9[276]; }; typedef struct { UINT16 limit; UINT64 *base; } dt_addr_t; #pragma pack() extern EFI_STATUS setup_graphics ( struct boot_params *buf ); #endif /* __LINUX_BZIMAGE_H__ */
3,038
1,133
{ "Hello": "Hola", "File": "Dossier", "Exit": "Surt", "Edit": "Edita", "Undo": "Desfés", "Redo": "Refés", "Cut": "Tallar", "Copy": "Copia", "Paste": "Enganxa", "Delete": "Suprimeix", "Select All": "Seleccionar tot", "View": "Veure", "Reload": "Recarregar", "Force Reload": "Força la recàrrega", "Toggle Developer Tools": "Commuta les eines per a desenvolupadors", "Reset Zoom": "Restableix el zoom", "Zoom In": "Ampliar", "Zoom Out": "Disminuir el zoom", "Toggle Fullscreen": "Commuta la pantalla completa", "Language": "Llenguatge", "Window": "Finestra", "Minimize": "Minimitzar", "Zoom": "Zoom", "Close": "Tanca", "Help": "Ajuda", "Learn More": "Aprèn més" }
310
5,964
<gh_stars>1000+ // Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef WTF_AddressSanitizer_h #define WTF_AddressSanitizer_h // TODO(sof): Add SyZyASan support? #if defined(ADDRESS_SANITIZER) #include <sanitizer/asan_interface.h> #else #define ASAN_POISON_MEMORY_REGION(addr, size) \ ((void)(addr), (void)(size)) #define ASAN_UNPOISON_MEMORY_REGION(addr, size) \ ((void)(addr), (void)(size)) #endif #if defined(LEAK_SANITIZER) #include <sanitizer/lsan_interface.h> #else #define __lsan_register_root_region(addr, size) ((void)(addr), (void)(size)) #define __lsan_unregister_root_region(addr, size) ((void)(addr), (void)(size)) #endif // TODO(sof): Have to handle (ADDRESS_SANITIZER && _WIN32) differently as it // uses both Clang (which supports the __attribute__ syntax) and CL (which doesn't) // as long as we use "clang-cl /fallback". This shouldn't be needed when Clang // handles all the code without falling back to CL. #if defined(ADDRESS_SANITIZER) && (!OS(WIN) || COMPILER(CLANG)) #define NO_SANITIZE_ADDRESS __attribute__((no_sanitize_address)) #if ENABLE(LAZY_SWEEPING) #define NO_LAZY_SWEEP_SANITIZE_ADDRESS NO_SANITIZE_ADDRESS #else #define NO_LAZY_SWEEP_SANITIZE_ADDRESS #endif #else #define NO_SANITIZE_ADDRESS #define NO_LAZY_SWEEP_SANITIZE_ADDRESS #endif #endif // WTF_AddressSanitizer_h
549
1,217
namespace My { template <class T> inline void SafeRelease(T **ppInterfaceToRelease) { if (*ppInterfaceToRelease != nullptr) { (*ppInterfaceToRelease)->Release(); (*ppInterfaceToRelease) = nullptr; } } } // namespace My
88
796
package tech.salroid.filmy.fragment; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.app.ActivityOptionsCompat; import androidx.core.util.Pair; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import tech.salroid.filmy.R; import tech.salroid.filmy.activities.CharacterDetailsActivity; import tech.salroid.filmy.activities.FullCrewActivity; import tech.salroid.filmy.custom_adapter.CrewAdapter; import tech.salroid.filmy.customs.BreathingProgress; import tech.salroid.filmy.data_classes.CrewDetailsData; import tech.salroid.filmy.parser.MovieDetailsActivityParseWork; /* * Filmy Application for Android * Copyright (c) 2016 <NAME> (http://github.com/webianks). * * 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. */ public class CrewFragment extends Fragment implements View.OnClickListener, CrewAdapter.ClickListener { @BindView(R.id.crew_more) TextView more; @BindView(R.id.crew_recycler) RecyclerView crew_recycler; @BindView(R.id.card_holder) TextView card_holder; @BindView(R.id.breathingProgressFragment) BreathingProgress breathingProgress; @BindView(R.id.detail_fragment_views_layout) RelativeLayout relativeLayout; private String jsonCrew; private String movieId, movieTitle; public static CrewFragment newInstance(String movieId, String movieTitle) { CrewFragment fragment = new CrewFragment(); Bundle args = new Bundle(); args.putString("movie_id", movieId); args.putString("movie_title", movieTitle); fragment.setArguments(args); return fragment; } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.crew_fragment, container, false); ButterKnife.bind(this, view); crew_recycler.setLayoutManager(new LinearLayoutManager(getActivity())); crew_recycler.setNestedScrollingEnabled(false); crew_recycler.setVisibility(View.INVISIBLE); more.setOnClickListener(this); return view; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle savedBundle = getArguments(); if (savedBundle != null) { movieId = savedBundle.getString("movie_id"); movieTitle = savedBundle.getString("movie_title"); } } public void parseCrewOutput(String crewResult) { MovieDetailsActivityParseWork par = new MovieDetailsActivityParseWork(getActivity(), crewResult); List<CrewDetailsData> crewList = par.parse_crew(); jsonCrew = crewResult; CrewAdapter crewAdapter = new CrewAdapter(getActivity(), crewList, true); crewAdapter.setClickListener(this); crew_recycler.setAdapter(crewAdapter); if (crewList.size() > 4) { more.setVisibility(View.VISIBLE); } else if (crewList.size() == 0) { more.setVisibility(View.INVISIBLE); card_holder.setVisibility(View.INVISIBLE); } else { more.setVisibility(View.INVISIBLE); } breathingProgress.setVisibility(View.GONE); crew_recycler.setVisibility(View.VISIBLE); relativeLayout.setMinimumHeight(0); } @Override public void onClick(View view) { if (view.getId() == R.id.crew_more) { Log.d("webi", "" + movieTitle); if (jsonCrew != null && movieTitle != null) { Intent intent = new Intent(getActivity(), FullCrewActivity.class); intent.putExtra("crew_json", jsonCrew); intent.putExtra("toolbar_title", movieTitle); startActivity(intent); } } } @Override public void itemClicked(CrewDetailsData setterGetter, int position, View view) { Intent intent = new Intent(getActivity(), CharacterDetailsActivity.class); intent.putExtra("id", setterGetter.getCrewId()); if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) { Pair<View, String> p1 = Pair.create(view.findViewById(R.id.crew_poster), "profile"); Pair<View, String> p2 = Pair.create(view.findViewById(R.id.crew_name), "name"); ActivityOptionsCompat options = ActivityOptionsCompat. makeSceneTransitionAnimation(getActivity(), p1, p2); startActivity(intent, options.toBundle()); } else { startActivity(intent); } } }
2,086
2,151
<gh_stars>1000+ /* * Copyright 2006 The Android Open Source Project * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkCoreBlitters.h" #include "SkColorData.h" #include "SkShader.h" #include "SkXfermodePriv.h" SkA8_Coverage_Blitter::SkA8_Coverage_Blitter(const SkPixmap& device, const SkPaint& paint) : SkRasterBlitter(device) { SkASSERT(nullptr == paint.getShader()); SkASSERT(paint.isSrcOver()); SkASSERT(nullptr == paint.getColorFilter()); } void SkA8_Coverage_Blitter::blitAntiH(int x, int y, const SkAlpha antialias[], const int16_t runs[]) { uint8_t* device = fDevice.writable_addr8(x, y); SkDEBUGCODE(int totalCount = 0;) for (;;) { int count = runs[0]; SkASSERT(count >= 0); if (count == 0) { return; } if (antialias[0]) { memset(device, antialias[0], count); } runs += count; antialias += count; device += count; SkDEBUGCODE(totalCount += count;) } SkASSERT(fDevice.width() == totalCount); } void SkA8_Coverage_Blitter::blitH(int x, int y, int width) { memset(fDevice.writable_addr8(x, y), 0xFF, width); } void SkA8_Coverage_Blitter::blitV(int x, int y, int height, SkAlpha alpha) { if (0 == alpha) { return; } uint8_t* dst = fDevice.writable_addr8(x, y); const size_t dstRB = fDevice.rowBytes(); while (--height >= 0) { *dst = alpha; dst += dstRB; } } void SkA8_Coverage_Blitter::blitRect(int x, int y, int width, int height) { uint8_t* dst = fDevice.writable_addr8(x, y); const size_t dstRB = fDevice.rowBytes(); while (--height >= 0) { memset(dst, 0xFF, width); dst += dstRB; } } void SkA8_Coverage_Blitter::blitMask(const SkMask& mask, const SkIRect& clip) { if (SkMask::kA8_Format != mask.fFormat) { this->INHERITED::blitMask(mask, clip); return; } int x = clip.fLeft; int y = clip.fTop; int width = clip.width(); int height = clip.height(); uint8_t* dst = fDevice.writable_addr8(x, y); const uint8_t* src = mask.getAddr8(x, y); const size_t srcRB = mask.fRowBytes; const size_t dstRB = fDevice.rowBytes(); while (--height >= 0) { memcpy(dst, src, width); dst += dstRB; src += srcRB; } } const SkPixmap* SkA8_Coverage_Blitter::justAnOpaqueColor(uint32_t*) { return nullptr; }
1,195
903
<filename>trunk/win/Source/Includes/QtIncludes/include/QtGui/qabstracttextdocumentlayout.h #include "../../src/gui/text/qabstracttextdocumentlayout.h"
54
777
<gh_stars>100-1000 // Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/media/router/issue_manager.h" #include <algorithm> #include "base/memory/ptr_util.h" #include "content/public/browser/browser_thread.h" namespace media_router { IssueManager::IssueManager() : top_issue_(nullptr) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); } IssueManager::~IssueManager() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); } void IssueManager::AddIssue(const IssueInfo& issue_info) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); auto it = std::find_if(issues_.begin(), issues_.end(), [&issue_info](const std::unique_ptr<Issue>& issue) { return issue_info == issue->info(); }); if (it != issues_.end()) return; issues_.push_back(base::MakeUnique<Issue>(issue_info)); MaybeUpdateTopIssue(); } void IssueManager::ClearIssue(const Issue::Id& issue_id) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); issues_.erase( std::remove_if(issues_.begin(), issues_.end(), [&issue_id](const std::unique_ptr<Issue>& issue) { return issue_id == issue->id(); }), issues_.end()); MaybeUpdateTopIssue(); } void IssueManager::RegisterObserver(IssuesObserver* observer) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK(observer); DCHECK(!issues_observers_.HasObserver(observer)); issues_observers_.AddObserver(observer); MaybeUpdateTopIssue(); if (top_issue_) observer->OnIssue(*top_issue_); } void IssueManager::UnregisterObserver(IssuesObserver* observer) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); issues_observers_.RemoveObserver(observer); } void IssueManager::MaybeUpdateTopIssue() { const Issue* new_top_issue = nullptr; if (!issues_.empty()) { // Select the first blocking issue in the list of issues. // If there are none, simply select the first issue in the list. auto it = std::find_if(issues_.begin(), issues_.end(), [](const std::unique_ptr<Issue>& issue) { return issue->info().is_blocking; }); if (it == issues_.end()) it = issues_.begin(); new_top_issue = it->get(); } // If we've found a new top issue, then report it via the observer. if (new_top_issue != top_issue_) { top_issue_ = new_top_issue; for (auto& observer : issues_observers_) { if (top_issue_) observer.OnIssue(*top_issue_); else observer.OnIssuesCleared(); } } } } // namespace media_router
1,112
2,232
<reponame>JLimperg/lean /* Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: <NAME> */ #include "kernel/instantiate.h" #include "library/vm/vm_name.h" #include "library/vm/vm_level.h" #include "library/vm/vm_expr.h" #include "library/vm/vm_list.h" #include "library/vm/vm_nat.h" #include "library/vm/vm_option.h" #include "library/vm/vm_task.h" namespace lean { /* inductive reducibility_hint | opaque : reducibility_hint | abbrev : reducibility_hint | regular : nat → bool → reducibility_hint */ vm_obj to_obj(reducibility_hints const & h) { switch (h.get_kind()) { case reducibility_hints::Opaque: return mk_vm_simple(0); case reducibility_hints::Abbreviation: return mk_vm_simple(1); case reducibility_hints::Regular: return mk_vm_constructor(2, mk_vm_nat(h.get_height()), mk_vm_bool(h.use_self_opt())); } lean_unreachable(); } reducibility_hints to_reducibility_hints(vm_obj const & o) { switch (cidx(o)) { case 0: return reducibility_hints::mk_opaque(); case 1: return reducibility_hints::mk_abbreviation(); case 2: return reducibility_hints::mk_regular(force_to_unsigned(cfield(o, 0), 0), to_bool(cfield(o, 1))); } lean_unreachable(); } struct vm_declaration : public vm_external { declaration m_val; vm_declaration(declaration const & v):m_val(v) {} virtual ~vm_declaration() {} virtual void dealloc() override { this->~vm_declaration(); get_vm_allocator().deallocate(sizeof(vm_declaration), this); } virtual vm_external * ts_clone(vm_clone_fn const &) override { return new vm_declaration(m_val); } virtual vm_external * clone(vm_clone_fn const &) override { return new (get_vm_allocator().allocate(sizeof(vm_declaration))) vm_declaration(m_val); } }; bool is_declaration(vm_obj const & o) { return is_external(o) && dynamic_cast<vm_declaration*>(to_external(o)); } declaration const & to_declaration(vm_obj const & o) { lean_vm_check(dynamic_cast<vm_declaration*>(to_external(o))); return static_cast<vm_declaration*>(to_external(o))->m_val; } vm_obj to_obj(declaration const & n) { return mk_vm_external(new (get_vm_allocator().allocate(sizeof(vm_declaration))) vm_declaration(n)); } vm_obj declaration_defn(vm_obj const & n, vm_obj const & ls, vm_obj const & type, vm_obj const & value, vm_obj const & hints, vm_obj const & trusted) { return to_obj(mk_definition(to_name(n), to_list_name(ls), to_expr(type), to_expr(value), to_reducibility_hints(hints), to_bool(trusted))); } vm_obj declaration_thm(vm_obj const & n, vm_obj const & ls, vm_obj const & type, vm_obj const & value) { return to_obj(mk_theorem(to_name(n), to_list_name(ls), to_expr(type), to_expr_task(value))); } vm_obj declaration_cnst(vm_obj const & n, vm_obj const & ls, vm_obj const & type, vm_obj const & trusted) { return to_obj(mk_constant_assumption(to_name(n), to_list_name(ls), to_expr(type), to_bool(trusted))); } vm_obj declaration_ax(vm_obj const & n, vm_obj const & ls, vm_obj const & type) { return to_obj(mk_axiom(to_name(n), to_list_name(ls), to_expr(type))); } unsigned declaration_cases_on(vm_obj const & o, buffer<vm_obj> & data) { declaration const & d = to_declaration(o); data.push_back(to_obj(d.get_name())); data.push_back(to_obj(d.get_univ_params())); data.push_back(to_obj(d.get_type())); if (d.is_theorem()) { data.push_back(to_obj(d.get_value_task())); return 1; } else if (d.is_axiom()) { return 3; } else if (d.is_definition()) { data.push_back(to_obj(d.get_value())); data.push_back(to_obj(d.get_hints())); data.push_back(mk_vm_bool(d.is_trusted())); return 0; } else { lean_assert(d.is_constant_assumption()); data.push_back(mk_vm_bool(d.is_trusted())); return 2; } } /* /- Instantiate a universe polymorphic declaration type with the given universes. -/ meta_constant declaration.instantiate_type_univ_params : declaration → list level → option expr */ vm_obj declaration_instantiate_type_univ_params(vm_obj const & _d, vm_obj const & _ls) { declaration const & d = to_declaration(_d); list<level> const & ls = to_list_level(_ls); if (d.get_num_univ_params() != length(ls)) return mk_vm_none(); else return mk_vm_some(to_obj(instantiate_type_univ_params(d, ls))); } /* /- Instantiate a universe polymorphic declaration type with the given universes. -/ meta_constant declaration.instantiate_value_univ_params : declaration → list level → option expr */ vm_obj declaration_instantiate_value_univ_params(vm_obj const & _d, vm_obj const & _ls) { declaration const & d = to_declaration(_d); list<level> const & ls = to_list_level(_ls); if (!d.is_definition() || d.get_num_univ_params() != length(ls)) return mk_vm_none(); else return mk_vm_some(to_obj(instantiate_value_univ_params(d, ls))); } void initialize_vm_declaration() { DECLARE_VM_BUILTIN(name({"declaration", "defn"}), declaration_defn); DECLARE_VM_BUILTIN(name({"declaration", "thm"}), declaration_thm); DECLARE_VM_BUILTIN(name({"declaration", "cnst"}), declaration_cnst); DECLARE_VM_BUILTIN(name({"declaration", "ax"}), declaration_ax); DECLARE_VM_BUILTIN(name({"declaration", "instantiate_type_univ_params"}), declaration_instantiate_type_univ_params); DECLARE_VM_BUILTIN(name({"declaration", "instantiate_value_univ_params"}), declaration_instantiate_value_univ_params); DECLARE_VM_CASES_BUILTIN(name({"declaration", "cases_on"}), declaration_cases_on); } void finalize_vm_declaration() { } }
2,354
471
<filename>corehq/form_processor/submission_post.py import logging from collections import namedtuple from ddtrace import tracer from django.db import IntegrityError from django.http import ( HttpRequest, HttpResponse, HttpResponseForbidden, ) from django.conf import settings from django.urls import reverse from django.utils.translation import ugettext as _ import sys from casexml.apps.case.xform import close_extension_cases from casexml.apps.phone.restore_caching import AsyncRestoreTaskIdCache, RestorePayloadPathCache import couchforms from casexml.apps.case.exceptions import PhoneDateValueError, IllegalCaseId, UsesReferrals, InvalidCaseIndex, \ CaseValueError from corehq.apps.receiverwrapper.rate_limiter import report_submission_usage from corehq.const import OPENROSA_VERSION_3 from corehq.middleware import OPENROSA_VERSION_HEADER from corehq.toggles import ASYNC_RESTORE, SUMOLOGIC_LOGS, NAMESPACE_OTHER from corehq.apps.cloudcare.const import DEVICE_ID as FORMPLAYER_DEVICE_ID from corehq.apps.commtrack.exceptions import MissingProductId from corehq.apps.domain_migration_flags.api import any_migrations_in_progress from corehq.apps.users.models import CouchUser from corehq.apps.users.permissions import has_permission_to_view_report from corehq.form_processor.exceptions import PostSaveError, XFormSaveError from corehq.form_processor.interfaces.dbaccessors import FormAccessors from corehq.form_processor.interfaces.processor import FormProcessorInterface from corehq.form_processor.parsers.form import process_xform_xml from corehq.form_processor.system_action import SYSTEM_ACTION_XMLNS, handle_system_action from corehq.form_processor.utils.metadata import scrub_meta from corehq.form_processor.submission_process_tracker import unfinished_submission from corehq.util.metrics.load_counters import form_load_counter from corehq.util.global_request import get_request from corehq.util.timer import TimingContext from couchforms import openrosa_response from couchforms.const import DEVICE_LOG_XMLNS from couchforms.models import DefaultAuthContext, UnfinishedSubmissionStub from couchforms.signals import successful_form_received from couchforms.util import legacy_notification_assert from couchforms.openrosa_response import OpenRosaResponse, ResponseNature from dimagi.utils.logging import notify_exception, log_signal_errors from phonelog.utils import process_device_log, SumoLogicLog from celery.task.control import revoke as revoke_celery_task CaseStockProcessingResult = namedtuple( 'CaseStockProcessingResult', 'case_result, case_models, stock_result' ) class FormProcessingResult(namedtuple('FormProcessingResult', 'response xform cases ledgers submission_type')): @property def case(self): assert len(self.cases) == 1 return self.cases[0] class SubmissionPost(object): def __init__(self, instance=None, attachments=None, auth_context=None, domain=None, app_id=None, build_id=None, path=None, location=None, submit_ip=None, openrosa_headers=None, last_sync_token=None, received_on=None, date_header=None, partial_submission=False, case_db=None, force_logs=False, timing_context=None): assert domain, "'domain' is required" assert instance, instance assert not isinstance(instance, HttpRequest), instance self.domain = domain self.app_id = app_id self.build_id = build_id # get_location has good default self.location = location or couchforms.get_location() self.received_on = received_on self.date_header = date_header self.submit_ip = submit_ip self.last_sync_token = last_sync_token self.openrosa_headers = openrosa_headers or {} self.instance = instance self.attachments = attachments or {} self.auth_context = auth_context or DefaultAuthContext() self.path = path self.interface = FormProcessorInterface(domain) self.formdb = FormAccessors(domain) self.partial_submission = partial_submission # always None except in the case where a system form is being processed as part of another submission # e.g. for closing extension cases self.case_db = case_db if case_db: assert case_db.domain == domain self.force_logs = force_logs self.is_openrosa_version3 = self.openrosa_headers.get(OPENROSA_VERSION_HEADER, '') == OPENROSA_VERSION_3 self.track_load = form_load_counter("form_submission", domain) self.timing_context = timing_context or TimingContext() def _set_submission_properties(self, xform): # attaches shared properties of the request to the document. # used on forms and errors xform.submit_ip = self.submit_ip xform.path = self.path xform.openrosa_headers = self.openrosa_headers xform.last_sync_token = self.last_sync_token if self.received_on: xform.received_on = self.received_on if self.date_header: xform.date_header = self.date_header xform.app_id = self.app_id xform.build_id = self.build_id xform.export_tag = ["domain", "xmlns"] xform.partial_submission = self.partial_submission return xform def _handle_known_error(self, error, instance, xforms): # errors we know about related to the content of the form # log the error and respond with a success code so that the phone doesn't # keep trying to send the form xforms[0] = _transform_instance_to_error(self.interface, error, instance) # this is usually just one document, but if an edit errored we want # to save the deprecated form as well self.interface.save_processed_models(xforms) def _handle_basic_failure_modes(self): if any_migrations_in_progress(self.domain): # keep submissions on the phone # until ready to start accepting again return HttpResponse(status=503) if not self.auth_context.is_valid(): return HttpResponseForbidden('Bad auth') def _post_process_form(self, xform): self._set_submission_properties(xform) found_old = scrub_meta(xform) legacy_notification_assert(not found_old, 'Form with old metadata submitted', xform.form_id) def _get_success_message(self, instance, cases=None): ''' Formplayer requests get a detailed success message pointing to the form/case affected. All other requests get a generic message. Message is formatted with markdown. ''' if not instance.metadata or instance.metadata.deviceID != FORMPLAYER_DEVICE_ID: return ' √ ' messages = [] user = CouchUser.get_by_user_id(instance.user_id) if not user or not user.is_web_user(): return _('Form successfully saved!') from corehq.apps.export.views.list import CaseExportListView, FormExportListView from corehq.apps.export.views.utils import can_view_case_exports, can_view_form_exports from corehq.apps.reports.views import CaseDataView, FormDataView form_link = case_link = form_export_link = case_export_link = None form_view = 'corehq.apps.reports.standard.inspect.SubmitHistory' if has_permission_to_view_report(user, instance.domain, form_view): form_link = reverse(FormDataView.urlname, args=[instance.domain, instance.form_id]) case_view = 'corehq.apps.reports.standard.cases.basic.CaseListReport' if cases and has_permission_to_view_report(user, instance.domain, case_view): if len(cases) == 1: case_link = reverse(CaseDataView.urlname, args=[instance.domain, cases[0].case_id]) else: case_link = ", ".join(["[{}]({})".format( c.name, reverse(CaseDataView.urlname, args=[instance.domain, c.case_id]) ) for c in cases]) if can_view_form_exports(user, instance.domain): form_export_link = reverse(FormExportListView.urlname, args=[instance.domain]) if cases and can_view_case_exports(user, instance.domain): case_export_link = reverse(CaseExportListView.urlname, args=[instance.domain]) # Start with generic message messages.append(_('Form successfully saved!')) # Add link to form/case if possible if form_link and case_link: if len(cases) == 1: messages.append( _("You submitted [this form]({}), which affected [this case]({}).") .format(form_link, case_link)) else: messages.append( _("You submitted [this form]({}), which affected these cases: {}.") .format(form_link, case_link)) elif form_link: messages.append(_("You submitted [this form]({}).").format(form_link)) elif case_link: if len(cases) == 1: messages.append(_("Your form affected [this case]({}).").format(case_link)) else: messages.append(_("Your form affected these cases: {}.").format(case_link)) # Add link to all form/case exports if form_export_link and case_export_link: messages.append( _("Click to export your [case]({}) or [form]({}) data.") .format(case_export_link, form_export_link)) elif form_export_link: messages.append(_("Click to export your [form data]({}).").format(form_export_link)) elif case_export_link: messages.append(_("Click to export your [case data]({}).").format(case_export_link)) return "\n\n".join(messages) def run(self): self.track_load() with self.timing_context("process_xml"): report_submission_usage(self.domain) failure_response = self._handle_basic_failure_modes() if failure_response: return FormProcessingResult(failure_response, None, [], [], 'known_failures') result = process_xform_xml(self.domain, self.instance, self.attachments, self.auth_context.to_json()) submitted_form = result.submitted_form self._post_process_form(submitted_form) self._invalidate_caches(submitted_form) if submitted_form.is_submission_error_log: logging.info('Processing form %s as a submission error', submitted_form.form_id) self.formdb.save_new_form(submitted_form) response = None try: xml = self.instance.decode() except UnicodeDecodeError: pass else: if 'log_subreport' in xml: response = self.get_exception_response_and_log( 'Badly formed device log', submitted_form, self.path ) if not response: response = self.get_exception_response_and_log( 'Problem receiving submission', submitted_form, self.path ) return FormProcessingResult(response, None, [], [], 'submission_error_log') if submitted_form.xmlns == SYSTEM_ACTION_XMLNS: logging.info('Processing form %s as a system action', submitted_form.form_id) with self.timing_context("process_system_action"): return self.handle_system_action(submitted_form) if submitted_form.xmlns == DEVICE_LOG_XMLNS: logging.info('Processing form %s as a device log', submitted_form.form_id) with self.timing_context("process_device_log"): return self.process_device_log(submitted_form) # Begin Normal Form Processing self._log_form_details(submitted_form) cases = [] ledgers = [] submission_type = 'unknown' openrosa_kwargs = {} with result.get_locked_forms() as xforms: if len(xforms) > 1: self.track_load(len(xforms) - 1) if self.case_db: case_db_cache = self.case_db case_db_cache.cached_xforms.extend(xforms) else: case_db_cache = self.interface.casedb_cache( domain=self.domain, lock=True, deleted_ok=True, xforms=xforms, load_src="form_submission", ) with case_db_cache as case_db: instance = xforms[0] if instance.is_duplicate: with self.timing_context("process_duplicate"), tracer.trace('submission.process_duplicate'): submission_type = 'duplicate' existing_form = xforms[1] stub = UnfinishedSubmissionStub.objects.filter( domain=instance.domain, xform_id=existing_form.form_id ).first() result = None if stub: from corehq.form_processor.reprocess import reprocess_unfinished_stub_with_form result = reprocess_unfinished_stub_with_form(stub, existing_form, lock=False) elif existing_form.is_error: from corehq.form_processor.reprocess import reprocess_form result = reprocess_form(existing_form, lock_form=False) if result and result.error: submission_type = 'error' openrosa_kwargs['error_message'] = result.error if existing_form.is_error: openrosa_kwargs['error_nature'] = ResponseNature.PROCESSING_FAILURE else: openrosa_kwargs['error_nature'] = ResponseNature.POST_PROCESSING_FAILURE else: self.interface.save_processed_models([instance]) elif not instance.is_error: submission_type = 'normal' try: case_stock_result = self.process_xforms_for_cases(xforms, case_db, self.timing_context) except (IllegalCaseId, UsesReferrals, MissingProductId, PhoneDateValueError, InvalidCaseIndex, CaseValueError) as e: self._handle_known_error(e, instance, xforms) submission_type = 'error' openrosa_kwargs['error_nature'] = ResponseNature.PROCESSING_FAILURE except Exception as e: # handle / log the error and reraise so the phone knows to resubmit # note that in the case of edit submissions this won't flag the previous # submission as having been edited. this is intentional, since we should treat # this use case as if the edit "failed" handle_unexpected_error(self.interface, instance, e) raise else: instance.initial_processing_complete = True openrosa_kwargs['error_message'] = self.save_processed_models(case_db, xforms, case_stock_result) if openrosa_kwargs['error_message']: openrosa_kwargs['error_nature'] = ResponseNature.POST_PROCESSING_FAILURE cases = case_stock_result.case_models ledgers = case_stock_result.stock_result.models_to_save openrosa_kwargs['success_message'] = self._get_success_message(instance, cases=cases) elif instance.is_error: submission_type = 'error' self._log_form_completion(instance, submission_type) response = self._get_open_rosa_response(instance, **openrosa_kwargs) return FormProcessingResult(response, instance, cases, ledgers, submission_type) def _log_form_details(self, form): attachments = form.attachments if hasattr(form, 'attachments') else {} logging.info('Received Form %s with %d attachments', form.form_id, len(attachments)) for index, (name, attachment) in enumerate(attachments.items()): attachment_msg = 'Form %s, Attachment %s: %s' attachment_props = [form.form_id, index, name] if hasattr(attachment, 'has_size') and attachment.has_size(): attachment_msg = attachment_msg + ' (%d bytes)' attachment_props.append(attachment.raw_content.size) logging.info(attachment_msg, *attachment_props) def _log_form_completion(self, form, submission_type): # Orig_id doesn't exist on all couch forms, only XFormError and XFormDeprecated if hasattr(form, 'orig_id') and form.orig_id is not None: logging.info('Finished %s processing for Form %s with original id %s', submission_type, form.form_id, form.orig_id) else: logging.info('Finished %s processing for Form %s', submission_type, form.form_id) def _conditionally_send_device_logs_to_sumologic(self, instance): url = getattr(settings, 'SUMOLOGIC_URL', None) if url and SUMOLOGIC_LOGS.enabled(instance.form_data.get('device_id'), NAMESPACE_OTHER): SumoLogicLog(self.domain, instance).send_data(url) def _invalidate_caches(self, xform): for device_id in {None, xform.metadata.deviceID if xform.metadata else None}: self._invalidate_restore_payload_path_cache(xform, device_id) if ASYNC_RESTORE.enabled(self.domain): self._invalidate_async_restore_task_id_cache(xform, device_id) def _invalidate_restore_payload_path_cache(self, xform, device_id): """invalidate cached initial restores""" restore_payload_path_cache = RestorePayloadPathCache( domain=self.domain, user_id=xform.user_id, sync_log_id=xform.last_sync_token, device_id=device_id, ) restore_payload_path_cache.invalidate() def _invalidate_async_restore_task_id_cache(self, xform, device_id): async_restore_task_id_cache = AsyncRestoreTaskIdCache( domain=self.domain, user_id=xform.user_id, sync_log_id=self.last_sync_token, device_id=device_id, ) task_id = async_restore_task_id_cache.get_value() if task_id is not None: revoke_celery_task(task_id) async_restore_task_id_cache.invalidate() @tracer.wrap(name='submission.save_models') def save_processed_models(self, case_db, xforms, case_stock_result): instance = xforms[0] try: with self.timing_context("save_models"), unfinished_submission(instance) as unfinished_submission_stub: try: self.interface.save_processed_models( xforms, case_stock_result.case_models, case_stock_result.stock_result ) except PostSaveError: # mark the stub as saved if there's a post save error # but re-raise the error so that the re-processing queue picks it up unfinished_submission_stub.submission_saved() raise else: unfinished_submission_stub.submission_saved() with self.timing_context("post_save_actions"): self.do_post_save_actions(case_db, xforms, case_stock_result) except PostSaveError: return "Error performing post save operations" @staticmethod @tracer.wrap(name='submission.post_save_actions') def do_post_save_actions(case_db, xforms, case_stock_result): instance = xforms[0] case_db.clear_changed() try: case_stock_result.case_result.commit_dirtiness_flags() case_stock_result.stock_result.finalize() SubmissionPost._fire_post_save_signals(instance, case_stock_result.case_models) close_extension_cases( case_db, case_stock_result.case_models, "SubmissionPost-%s-close_extensions" % instance.form_id ) except PostSaveError: raise except Exception: notify_exception(get_request(), "Error performing post save actions during form processing", { 'domain': instance.domain, 'form_id': instance.form_id, }) raise PostSaveError @staticmethod @tracer.wrap(name='submission.process_cases_and_stock') def process_xforms_for_cases(xforms, case_db, timing_context=None): from casexml.apps.case.xform import process_cases_with_casedb from corehq.apps.commtrack.processing import process_stock timing_context = timing_context or TimingContext() instance = xforms[0] with timing_context("process_cases"): case_result = process_cases_with_casedb(xforms, case_db) with timing_context("process_ledgers"): stock_result = process_stock(xforms, case_db) stock_result.populate_models() modified_on_date = instance.received_on if getattr(instance, 'edited_on', None) and instance.edited_on > instance.received_on: modified_on_date = instance.edited_on with timing_context("check_cases_before_save"): cases = case_db.get_cases_for_saving(modified_on_date) return CaseStockProcessingResult( case_result=case_result, case_models=cases, stock_result=stock_result, ) def get_response(self): return self.run().response @staticmethod def _fire_post_save_signals(instance, cases): from casexml.apps.case.signals import case_post_save error_message = "Error occurred during form submission post save (%s)" error_details = {'domain': instance.domain, 'form_id': instance.form_id} results = successful_form_received.send_robust(None, xform=instance) has_errors = log_signal_errors(results, error_message, error_details) for case in cases: results = case_post_save.send_robust(case.__class__, case=case) has_errors |= log_signal_errors(results, error_message, error_details) if has_errors: raise PostSaveError def _get_open_rosa_response(self, instance, success_message=None, error_message=None, error_nature=None): if self.is_openrosa_version3: instance_ok = instance.is_normal or instance.is_duplicate has_error = error_message or error_nature if instance_ok and not has_error: response = openrosa_response.get_openarosa_success_response(message=success_message) else: error_message = error_message or instance.problem response = self.get_v3_error_response(error_message, error_nature) else: if instance.is_normal: response = openrosa_response.get_openarosa_success_response() else: response = self.get_v2_submit_error_response(instance) # this hack is required for ODK response["Location"] = self.location # this is a magic thing that we add response['X-CommCareHQ-FormID'] = instance.form_id return response @staticmethod def get_v2_submit_error_response(doc): return OpenRosaResponse( message=doc.problem, nature=ResponseNature.SUBMIT_ERROR, status=201, ).response() @staticmethod def get_v3_error_response(message, nature): """Returns a 422(Unprocessable Entity) response - if nature == 'processing_failure' the mobile device will quarantine this form and not retry it - any other value of `nature` will result in the form being marked as a failure and retrying """ return OpenRosaResponse( message=message, nature=nature, status=422, ).response() @staticmethod def get_exception_response_and_log(msg, error_instance, path): logging.warning( msg, extra={ 'submission_path': path, 'form_id': error_instance.form_id, 'error_message': error_instance.problem } ) # This are generally badly formed XML resulting from file corruption, encryption errors # or other errors on the device which can not be recovered from. # To prevent retries of these errors we submit a 422 response with `processing_failure` nature. return OpenRosaResponse( message="There was an error processing the form: %s" % error_instance.problem, nature=ResponseNature.PROCESSING_FAILURE, status=422, ).response() @tracer.wrap(name='submission.handle_system_action') def handle_system_action(self, form): handle_system_action(form, self.auth_context) self.interface.save_processed_models([form]) response = HttpResponse(status=201) return FormProcessingResult(response, form, [], [], 'system-action') @tracer.wrap(name='submission.process_device_log') def process_device_log(self, device_log_form): self._conditionally_send_device_logs_to_sumologic(device_log_form) ignore_device_logs = settings.SERVER_ENVIRONMENT in settings.NO_DEVICE_LOG_ENVS if self.force_logs or not ignore_device_logs: try: process_device_log(self.domain, device_log_form, self.force_logs) except Exception as e: notify_exception(None, "Error processing device log", details={ 'xml': self.instance, 'domain': self.domain }) e.sentry_capture = False raise response = self._get_open_rosa_response(device_log_form) return FormProcessingResult(response, device_log_form, [], [], 'device-log') def _transform_instance_to_error(interface, exception, instance): error_message = '{}: {}'.format(type(exception).__name__, str(exception)) return interface.xformerror_from_xform_instance(instance, error_message) def handle_unexpected_error(interface, instance, exception): instance = _transform_instance_to_error(interface, exception, instance) notify_submission_error(instance, instance.problem, sys.exc_info()) try: FormAccessors(interface.domain).save_new_form(instance) except IntegrityError: # handle edge case where saving duplicate form fails instance = interface.xformerror_from_xform_instance(instance, instance.problem, with_new_id=True) FormAccessors(interface.domain).save_new_form(instance) except XFormSaveError: # try a simple save instance.save() def notify_submission_error(instance, message, exec_info=None): from corehq.util.global_request.api import get_request exec_info = exec_info or sys.exc_info() domain = getattr(instance, 'domain', '---') details = { 'domain': domain, 'error form ID': instance.form_id, } request = get_request() notify_exception(request, message, details=details, exec_info=exec_info)
12,275
1,350
[{"id":"PNA1","type":"alpha","calc":false,"value":""},{"id":"L1B","type":"number","calc":false,"value":""},{"id":"ADD1","type":"alpha","calc":false,"value":""},{"id":"QDIV","type":"number","calc":false,"value":""},{"id":"CITY","type":"alpha","calc":false,"value":""},{"id":"STP2","type":"alpha","calc":false,"value":""},{"id":"ST2","type":"alpha","calc":false,"value":""},{"id":"ZIP","type":"zip","calc":false,"value":""},{"id":"PPH","type":"phone","calc":false,"value":""},{"id":"L1C","type":"number","calc":false,"value":""},{"id":"L2C","type":"number","calc":false,"value":""},{"id":"PYID","type":"mask","calc":false,"value":""},{"id":"L2D","type":"number","calc":false,"value":""},{"id":"SSN","type":"ssn","calc":false,"value":""},{"id":"L1CTX","type":"number","calc":false,"value":""},{"id":"NAME","type":"alpha","calc":false,"value":""},{"id":"L1D","type":"number","calc":false,"value":""},{"id":"L2","type":"alpha","calc":false,"value":""},{"id":"L1E","type":"number","calc":false,"value":""},{"id":"RADD","type":"alpha","calc":false,"value":""},{"id":"TAX","type":"number","calc":false,"value":""},{"id":"CTRY","type":"alpha","calc":false,"value":""},{"id":"RCITY","type":"alpha","calc":false,"value":""},{"id":"STP","type":"alpha","calc":false,"value":""},{"id":"ZIP2","type":"zip","calc":false,"value":""},{"id":"L5","type":"number","calc":false,"value":""},{"id":"L6","type":"number","calc":false,"value":""},{"id":"EX2","type":"number","calc":false,"value":""},{"id":"EX4","type":"number","calc":false,"value":""},{"id":"ACCT","type":"alpha","calc":false,"value":""},{"id":"STATEID","type":"alpha","calc":false,"value":""},{"id":"STWH","type":"number","calc":false,"value":""},{"id":"STAT2","type":"alpha","calc":false,"value":""},{"id":"STATEID2","type":"alpha","calc":false,"value":""},{"id":"STWH2","type":"number","calc":false,"value":""}]
578
666
<reponame>tgolsson/appJar import sys sys.path.append("../../") from appJar import gui def validate(action, index, value_if_allowed, prior_value, text, validation_type, trigger_type, widget_name): if action == "1": if text in '0123456789.-+': try: if len(str(value_if_allowed)) == 1 and value_if_allowed in '.-': return True elif len(str(value_if_allowed)) == 2 and value_if_allowed == '-.': return True else: float(value_if_allowed) return True except ValueError: app.bell() return False else: app.bell() return False else: return True with gui() as app: ent = app.entry('e1') validator = (app.topLevel.register(validate), '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W') ent.config(validate='key', validatecommand=validator)
510
568
<reponame>JanStoltman/CompositeAndroid package com.pascalwelsch.compositeandroid.core; import java.util.Stack; public class AbstractPlugin<T, D> { final public Stack<NamedSuperCall> mSuperListeners = new Stack<>(); private D mDelegate; private T mOriginal; public final void addToDelegate(final D delegate, final T original) { mDelegate = delegate; mOriginal = original; onAddedToDelegate(); } public D getCompositeDelegate() { return mDelegate; } public T getOriginal() { return mOriginal; } public final void removeFromDelegate() { mDelegate = null; mOriginal = null; onRemovedFromDelegated(); } public void verifyMethodCalledFromDelegate(final String method) { if (mSuperListeners.isEmpty()) { throw new IllegalStateException("Do not call " + method + " on a ActivityPlugin directly. You have to call mDelegate." + method + " or the call order of the plugins would be mixed up."); } final String superListener = mSuperListeners.peek().getMethodName(); if (!superListener.equals(method)) { throw new IllegalStateException("You may have called " + method + " from " + superListener + " instead of calling getOriginal()." + method + ". Do not call " + method + " on a ActivityPlugin directly. You have to call mDelegate." + method + " or the call order of the plugins would be mixed up."); } } /** * callback when this plugin was added to a delegate. {@link #getOriginal()} and {@link * #getCompositeDelegate()} are now set */ protected void onAddedToDelegate() { } /** * callback when this plugin was removed from the delegate. {@link #getOriginal()} and {@link * #getCompositeDelegate()} are now {@code null} */ protected void onRemovedFromDelegated() { } }
804
998
<reponame>ADMTec/VoxelPlugin<gh_stars>100-1000 // Copyright 2021 Phyronnaz #pragma once #include "CoreMinimal.h" #include "VoxelAssets/VoxelDataAsset.h" #include "VoxelAssets/VoxelDataAssetData.inl" #include "VoxelGenerators/VoxelGeneratorHelpers.h" class FVoxelDataAssetInstance : public TVoxelGeneratorInstanceHelper<FVoxelDataAssetInstance, UVoxelDataAsset> { public: using Super = TVoxelGeneratorInstanceHelper<FVoxelDataAssetInstance, UVoxelDataAsset>; const TVoxelSharedRef<const FVoxelDataAssetData> Data; const bool bSubtractiveAsset; const FIntVector PositionOffset; float Tolerance = 0.f; public: FVoxelDataAssetInstance(UVoxelDataAsset& Asset) : Super(&Asset) , Data(Asset.GetData()) , bSubtractiveAsset(Asset.bSubtractiveAsset) , PositionOffset(Asset.PositionOffset) , Tolerance(Asset.Tolerance) { } //~ Begin FVoxelGeneratorInstance Interface virtual void Init(const FVoxelGeneratorInit& InitStruct) override { if (InitStruct.RenderType == EVoxelRenderType::Cubic) { Tolerance = FMath::Max(Tolerance, 0.1f); } } v_flt GetValueImpl(v_flt X, v_flt Y, v_flt Z, int32 LOD, const FVoxelItemStack& Items) const { X -= PositionOffset.X; Y -= PositionOffset.Y; Z -= PositionOffset.Z; return Data->GetInterpolatedValue(X, Y, Z, bSubtractiveAsset ? FVoxelValue::Full() : FVoxelValue::Empty(), Tolerance); } FVoxelMaterial GetMaterialImpl(v_flt X, v_flt Y, v_flt Z, int32 LOD, const FVoxelItemStack& Items) const { X -= PositionOffset.X; Y -= PositionOffset.Y; Z -= PositionOffset.Z; if (Data->HasMaterials()) { return Data->GetInterpolatedMaterial(X, Y, Z, Tolerance); } else { return FVoxelMaterial::Default(); } } TVoxelRange<v_flt> GetValueRangeImpl(const FVoxelIntBox& Bounds, int32 LOD, const FVoxelItemStack& Items) const { if (Bounds.Intersect(GetLocalBounds())) { return { -1, 1 }; } else { return bSubtractiveAsset ? -1 : 1; } } virtual void GetValues(TVoxelQueryZone<FVoxelValue>& QueryZone, int32 LOD, const FVoxelItemStack& Items) const override { for (VOXEL_QUERY_ZONE_ITERATE(QueryZone, X)) { for (VOXEL_QUERY_ZONE_ITERATE(QueryZone, Y)) { for (VOXEL_QUERY_ZONE_ITERATE(QueryZone, Z)) { const FVoxelValue Value = Data->GetValue( X - PositionOffset.X, Y - PositionOffset.Y, Z - PositionOffset.Z, bSubtractiveAsset ? FVoxelValue::Full() : FVoxelValue::Empty()); QueryZone.Set(X, Y, Z, Value); } } } } virtual FVector GetUpVector(v_flt X, v_flt Y, v_flt Z) const override final { return FVector::UpVector; } //~ End FVoxelGeneratorInstance Interface private: FORCEINLINE FVoxelIntBox GetLocalBounds() const { return FVoxelIntBox(PositionOffset, PositionOffset + Data->GetSize()); } };
1,279
432
/* * Copyright (c) 2019 <NAME> <<EMAIL>>. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE 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. */ #include <sys/cdefs.h> __FBSDID("$FreeBSD$"); #include <assert.h> #include <err.h> #include <errno.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "fstyp.h" /* * https://developer.apple.com/library/archive/technotes/tn/tn1150.html */ #define VOL_HDR_OFF 1024 typedef uint32_t hfsp_cat_nodeid; typedef struct hfsp_ext_desc { uint32_t ex_startBlock; uint32_t ex_blockCount; } hfsp_ext_desc; typedef struct hfsp_fork_data { uint64_t fd_logicalSz; uint32_t fd_clumpSz; uint32_t fd_totalBlocks; hfsp_ext_desc fd_extents[8]; } hfsp_fork_data; struct hfsp_vol_hdr { char hp_signature[2]; uint16_t hp_version; uint32_t hp_attributes; uint32_t hp_lastMounted; uint32_t hp_journalInfoBlock; /* Creation / etc dates. */ uint32_t hp_create; uint32_t hp_modify; uint32_t hp_backup; uint32_t hp_checked; /* Stats */ uint32_t hp_files; uint32_t hp_folders; /* Parameters */ uint32_t hp_blockSize; uint32_t hp_totalBlocks; uint32_t hp_freeBlocks; uint32_t hp_nextAlloc; uint32_t hp_rsrcClumpSz; uint32_t hp_dataClumpSz; hfsp_cat_nodeid hp_nextCatID; uint32_t hp_writeCount; uint64_t hp_encodingsBM; uint32_t hp_finderInfo[8]; hfsp_fork_data hp_allocationFile; hfsp_fork_data hp_extentsFile; hfsp_fork_data hp_catalogFile; hfsp_fork_data hp_attributesFile; hfsp_fork_data hp_startupFile; }; _Static_assert(sizeof(struct hfsp_vol_hdr) == 512, ""); int fstyp_hfsp(FILE *fp, char *label, size_t size, const char *devpath) { struct hfsp_vol_hdr *hdr; int retval; retval = 1; hdr = read_buf(fp, VOL_HDR_OFF, sizeof(*hdr)); if (hdr == NULL) goto fail; if ((strncmp(hdr->hp_signature, "H+", 2) != 0 || hdr->hp_version != 4) && (strncmp(hdr->hp_signature, "HX", 2) != 0 || hdr->hp_version != 5)) goto fail; /* This is an HFS+ volume. */ retval = 0; /* No label support yet. */ fail: free(hdr); return (retval); }
1,315
503
/** * Yona, 21c Project Hosting SW * <p> * Copyright Yona & Yobi Authors & NAVER Corp. * https://yona.io **/ package models.support; import com.avaje.ebean.annotation.Sql; import play.db.ebean.Model; import javax.persistence.Entity; @Entity @Sql public class IssueLabelAggregate extends Model { private static final long serialVersionUID = -8843323869004757091L; public Long issueId; public Long issueLabelId; }
152
448
// // AVDConfig.h // AliPlayerSDK // // Created by shiping.csp on 2018/11/16. // Copyright © 2018 com.alibaba.AliyunPlayer. All rights reserved. // #ifndef AVDConfig_h #define AVDConfig_h #import <Foundation/Foundation.h> OBJC_EXPORT @interface AVDConfig : NSObject /** @brief 最大超时时间 默认15000毫秒 */ /**** @brief Maximum timeout time. Default: 15000 milliseconds. */ @property (nonatomic, assign) int timeoutMs; /** @brief 最大连接超时时间 默认5000毫秒 */ /**** @brief Maximum connection timeout time. Default: 5000 milliseconds. */ @property (nonatomic, assign) int connnectTimoutMs; /** @brief 请求referer */ /**** @brief Request Referer. */ @property (nonatomic, copy) NSString *referer; /** @brief user Agent */ /**** @brief UserAgent. */ @property (nonatomic, copy) NSString *userAgent; /** @brief httpProxy代理 */ /**** @brief HTTP proxy. */ @property (nonatomic, copy) NSString *httpProxy; @end #endif /* AVDConfig_h */
384
364
<reponame>matus-chochlik/oglplus // File implement/oglplus/enums/context_profile_bit_def.ipp // // Automatically generated file, DO NOT modify manually. // Edit the source 'source/enums/oglplus/context_profile_bit.txt' // or the 'source/enums/make_enum.py' script instead. // // Copyright 2010-2019 <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 // #ifdef OGLPLUS_LIST_NEEDS_COMMA # undef OGLPLUS_LIST_NEEDS_COMMA #endif #if defined GL_CONTEXT_CORE_PROFILE_BIT # ifdef OGLPLUS_LIST_NEEDS_COMMA OGLPLUS_ENUM_CLASS_COMMA # endif # if defined Core # pragma push_macro("Core") # undef Core OGLPLUS_ENUM_CLASS_VALUE(Core, GL_CONTEXT_CORE_PROFILE_BIT) # pragma pop_macro("Core") # else OGLPLUS_ENUM_CLASS_VALUE(Core, GL_CONTEXT_CORE_PROFILE_BIT) # endif # ifndef OGLPLUS_LIST_NEEDS_COMMA # define OGLPLUS_LIST_NEEDS_COMMA 1 # endif #endif #if defined GL_CONTEXT_COMPATIBILITY_PROFILE_BIT # ifdef OGLPLUS_LIST_NEEDS_COMMA OGLPLUS_ENUM_CLASS_COMMA # endif # if defined Compatibility # pragma push_macro("Compatibility") # undef Compatibility OGLPLUS_ENUM_CLASS_VALUE(Compatibility, GL_CONTEXT_COMPATIBILITY_PROFILE_BIT) # pragma pop_macro("Compatibility") # else OGLPLUS_ENUM_CLASS_VALUE(Compatibility, GL_CONTEXT_COMPATIBILITY_PROFILE_BIT) # endif # ifndef OGLPLUS_LIST_NEEDS_COMMA # define OGLPLUS_LIST_NEEDS_COMMA 1 # endif #endif #ifdef OGLPLUS_LIST_NEEDS_COMMA # undef OGLPLUS_LIST_NEEDS_COMMA #endif
637
2,996
// Copyright 2021 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.engine.core.modes.loadProcesses; import org.terasology.engine.context.Context; import org.terasology.engine.core.modes.SingleStepLoadProcess; import org.terasology.engine.logic.console.Console; import org.terasology.engine.logic.console.ConsoleImpl; public class InitialiseCommandSystem extends SingleStepLoadProcess { private Context context; public InitialiseCommandSystem(Context context) { this.context = context; } @Override public String getMessage() { return "Initialising Command System..."; } @Override public boolean step() { context.put(Console.class, new ConsoleImpl(context)); return true; } @Override public int getExpectedCost() { return 1; } }
295
14,668
// Copyright 2021 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/browser/ui/webui/history_clusters/history_clusters_handler.h" #include "base/memory/raw_ptr.h" #include "base/test/scoped_feature_list.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/webui/history/history_ui.h" #include "chrome/browser/ui/webui/history_clusters/history_clusters.mojom.h" #include "chrome/common/webui_url_constants.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "components/history_clusters/core/features.h" #include "content/public/test/browser_test.h" #include "content/public/test/browser_test_utils.h" namespace history_clusters { class HistoryClustersHandlerBrowserTest : public InProcessBrowserTest { public: HistoryClustersHandlerBrowserTest() { feature_list_.InitWithFeatures({history_clusters::internal::kJourneys}, {}); } ~HistoryClustersHandlerBrowserTest() override = default; void SetUpOnMainThread() override { EXPECT_TRUE(ui_test_utils::NavigateToURL( browser(), GURL(chrome::kChromeUIHistoryClustersURL))); EXPECT_TRUE(content::WaitForLoadStop( browser()->tab_strip_model()->GetActiveWebContents())); handler_ = browser() ->tab_strip_model() ->GetActiveWebContents() ->GetWebUI() ->GetController() ->template GetAs<HistoryUI>() ->GetHistoryClustersHandlerForTesting(); } protected: raw_ptr<HistoryClustersHandler> handler_; private: base::test::ScopedFeatureList feature_list_; }; // Tests whether the handler opens all the given URLs in the same tab group and // and in the expected order. IN_PROC_BROWSER_TEST_F(HistoryClustersHandlerBrowserTest, OpenVisitUrlsInTabGroup) { auto* tab_strip_model = browser()->tab_strip_model(); ASSERT_EQ(1, tab_strip_model->GetTabCount()); std::vector<mojom::URLVisitPtr> visits; auto visit1 = mojom::URLVisit::New(); visit1->normalized_url = GURL("https://foo"); visits.push_back(std::move(visit1)); auto visit2 = mojom::URLVisit::New(); visit2->normalized_url = GURL("https://bar"); visits.push_back(std::move(visit2)); handler_->OpenVisitUrlsInTabGroup(std::move(visits)); ASSERT_EQ(3, tab_strip_model->GetTabCount()); ASSERT_EQ(tab_strip_model->GetTabGroupForTab(1).value(), tab_strip_model->GetTabGroupForTab(2).value()); ASSERT_EQ(GURL("https://foo"), tab_strip_model->GetWebContentsAt(1)->GetVisibleURL()); ASSERT_EQ(GURL("https://bar"), tab_strip_model->GetWebContentsAt(2)->GetVisibleURL()); } } // namespace history_clusters
1,097
1,705
{ "active": true, "synopsis": "This release introduces support for Amazon EventBridge schema registry, making it easy to discover and write code for events in EventBridge.", "generate-client-constructors": true }
54
1,475
<reponame>mhansonp/geode /* * 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.geode.internal.cache; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Test; import org.apache.geode.distributed.internal.membership.InternalDistributedMember; public class TxCallbackEventFactoryImplTest { private TxCallbackEventFactoryImpl factory; private InternalRegion region; private FilterRoutingInfo routingInfo; private EntryEventImpl entryEvent; @Before public void setup() { factory = new TxCallbackEventFactoryImpl(); region = mock(InternalRegion.class); routingInfo = mock(FilterRoutingInfo.class); entryEvent = mock(EntryEventImpl.class); } @Test public void setLocalFilterInfoNotInvokedIfNoFilterRoutingInfoAvailable() { factory.setLocalFilterInfo(region, null, entryEvent); verify(entryEvent, never()).setLocalFilterInfo(any()); } @Test public void setLocalFilterInfoInvokedIfFoundMatchingFilterInfo() { InternalDistributedMember member = mock(InternalDistributedMember.class); FilterRoutingInfo.FilterInfo localRouting = mock(FilterRoutingInfo.FilterInfo.class); when(region.getMyId()).thenReturn(member); when(routingInfo.getFilterInfo(member)).thenReturn(localRouting); factory.setLocalFilterInfo(region, routingInfo, entryEvent); verify(entryEvent).setLocalFilterInfo(localRouting); } }
665
373
<filename>src/light.hpp<gh_stars>100-1000 /*------------------------------------------------------------------------------- BARONY File: light.hpp Desc: prototypes for light.cpp, light-related types and prototypes Copyright 2013-2016 (c) Turning Wheel LLC, all rights reserved. See LICENSE for details. -------------------------------------------------------------------------------*/ #pragma once typedef struct light_t { Sint32 x, y; Sint32 radius; Sint32 intensity; Sint32* tiles; // a pointer to the light's location in a list node_t* node; } light_t; light_t* lightSphereShadow(Sint32 x, Sint32 y, Sint32 radius, Sint32 intensity); light_t* lightSphere(Sint32 x, Sint32 y, Sint32 radius, Sint32 intensity); light_t* newLight(Sint32 x, Sint32 y, Sint32 radius, Sint32 intensity);
242
403
<gh_stars>100-1000 /* * Camunda Platform REST API * OpenApi Spec for Camunda Platform REST API. * * The version of the OpenAPI document: 7.16.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package com.camunda.consulting.openapi.client.handler; import com.camunda.consulting.openapi.client.model.CorrelationMessageDto; import com.camunda.consulting.openapi.client.model.ExceptionDto; import com.camunda.consulting.openapi.client.model.MessageCorrelationResultWithVariableDto; import org.junit.Test; import org.junit.Ignore; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * API tests for MessageApi */ @Ignore public class MessageApiTest { private final MessageApi api = new MessageApi(); /** * Correlate * * Correlates a message to the process engine to either trigger a message start event or an intermediate message catching event. Internally this maps to the engine&#39;s message correlation builder methods &#x60;MessageCorrelationBuilder#correlateWithResult()&#x60; and &#x60;MessageCorrelationBuilder#correlateAllWithResult()&#x60;. For more information about the correlation behavior, see the [Message Events](https://docs.camunda.org/manual/7.16/bpmn20/events/message-events/) section of the [BPMN 2.0 Implementation Reference](https://docs.camunda.org/manual/7.16/reference/bpmn20/). * * @throws ApiException * if the Api call fails */ @Test public void deliverMessageTest() { CorrelationMessageDto correlationMessageDto = null; List<MessageCorrelationResultWithVariableDto> response = api.deliverMessage(correlationMessageDto); // TODO: test validations } }
623
530
<reponame>meghasfdc/jmc<gh_stars>100-1000 /* * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * The contents of this file are subject to the terms of either the Universal Permissive License * v 1.0 as shown at http://oss.oracle.com/licenses/upl * * or the following license: * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions * and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials provided with * the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to * endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.openjdk.jmc.joverflow.stats; import org.openjdk.jmc.joverflow.descriptors.CollectionDescriptors; import org.openjdk.jmc.joverflow.heap.model.JavaClass; import org.openjdk.jmc.joverflow.heap.model.JavaHeapObject; import org.openjdk.jmc.joverflow.heap.model.JavaLazyReadObject; import org.openjdk.jmc.joverflow.heap.model.JavaObject; import org.openjdk.jmc.joverflow.heap.model.JavaObjectArray; import org.openjdk.jmc.joverflow.heap.model.JavaThing; import org.openjdk.jmc.joverflow.heap.model.JavaValueArray; import org.openjdk.jmc.joverflow.heap.model.Snapshot; import org.openjdk.jmc.joverflow.heap.parser.HprofParsingCancelledException; import org.openjdk.jmc.joverflow.support.ProblemRecorder; import org.openjdk.jmc.joverflow.util.FastStack; /** * The heap scanner impl-n that scans a heap dump in depth-first order starting from GC roots. It * takes an instance of ProblemChecker, that should implement methods that check objects given to it * for problems and other interesting properties. */ class DepthFirstHeapScaner extends HeapScaner { private final ProblemChecker objHandler; private final FastStack<JavaThing[]> fieldsOrArrayElsStack; private final InterimRefChainStack refChain; // When this is true, getNextObjToScan() tries to find the next object to // scan such that it's located in the heap dump close to the previously // scanned object. That may reduce the number of page swaps in CachedReadBuffer // by 3-5%, thus reducing the number of disk reads and ultimately time. // However, for smaller heap dumps this may result in a significant increase // in CPU cycles with no benefit. We probably need to turn this option on // adaptively, when it becomes clear that page swapping takes too much time. private boolean optimizeForLocality = false; DepthFirstHeapScaner(Snapshot snapshot, ProblemChecker objHandler, ProblemRecorder problemRecorder, CollectionDescriptors colDescriptors) { super(snapshot, new InterimRefChainStack(problemRecorder, colDescriptors)); this.refChain = (InterimRefChainStack) getRefChain(); this.objHandler = objHandler; fieldsOrArrayElsStack = new FastStack<>(256); } /** * Scans all of the objects reachable from obj in depth-first order. We don't use recursion here * (which is easier to write and understand), because for long reference chains, such as those * found in linked lists, deep recursion can lead to StackOverflowError. */ @Override protected void scanObjectsFromRootObj(JavaHeapObject obj) { while (obj != null) { if (obj.setVisitedIfNot()) { currentProcessedObjNo++; if (cancelled) { throw new HprofParsingCancelledException.Runtime(); } JavaClass clazz = obj.getClazz(); refChain.push(obj); if (clazz.isString()) { objHandler.handleString((JavaObject) obj); refChain.pop(); } else { if (obj instanceof JavaObject) { JavaObject javaObj = (JavaObject) obj; // Note that in principle the call below could be replaced with the variant // with false boolean arg, which will initialize only reference fields. This // would speed up field parsing in JavaObject and field scanning below, but // may cause problems in other parts of the system, that expect JavaObjects // to have all fields set properly - like checking for all-zero fields. JavaThing[] fields = javaObj.getFields(); objHandler.handleInstance(javaObj, fields); // Nullify various fields like those for auxiliary linked list in LinkedHashMap, // so that scanObjectFields does not have problems with long lists, etc. int[] bannedFieldIndices = clazz.getBannedFieldIndices(); if (bannedFieldIndices != null) { for (int bannedFieldIdx : bannedFieldIndices) { fields[bannedFieldIdx] = null; } } refChain.pushIndexContainer(new TwoHandIndexContainer()); fieldsOrArrayElsStack.push(fields); } else if (obj instanceof JavaClass) { JavaThing[] staticFields = ((JavaClass) obj).getStaticValues(); refChain.pushIndexContainer(new TwoHandIndexContainer()); fieldsOrArrayElsStack.push(staticFields); } else if (obj instanceof JavaObjectArray) { JavaObjectArray objArray = (JavaObjectArray) obj; JavaHeapObject[] elements = objArray.getElements(); objHandler.handleObjectArray(objArray, elements); refChain.pushIndexContainer(new TwoHandIndexContainer()); fieldsOrArrayElsStack.push(elements); } else { objHandler.handleValueArray((JavaValueArray) obj); refChain.pop(); } } } // Now determine the next object to scan obj = getNextObjToScan(obj); } } /** * Most of the complexity in this method is due to experimental functionality where we try to * find next object to scan that is close enough to the current object inside the hep dump, in * order to minimize our disk cache misses. */ private JavaHeapObject getNextObjToScan(JavaHeapObject oldObj) { long oldObjOfsInFile = -1; JavaHeapObject obj = null; while (!fieldsOrArrayElsStack.isEmpty()) { JavaThing[] fieldsOrElements = fieldsOrArrayElsStack.peek(); TwoHandIndexContainer curIdxContainer = (TwoHandIndexContainer) refChain.getCurrentIndexContainer(); int nextIdx = curIdxContainer.incrementAndGetBase(); while (nextIdx < fieldsOrElements.length) { JavaThing objThing = fieldsOrElements[nextIdx]; // Ignore null, primitive and already visited fields if (objThing != null && objThing instanceof JavaHeapObject) { obj = (JavaHeapObject) objThing; if (!obj.isVisited()) { if (optimizeForLocality && (obj instanceof JavaLazyReadObject)) { oldObjOfsInFile = (oldObj instanceof JavaLazyReadObject) ? ((JavaLazyReadObject) oldObj).getObjOfsInFile() : -1; if (oldObjOfsInFile != -1) { curIdxContainer.setBase(nextIdx - 1); break; // We'll attempt to look for a closer located object } } curIdxContainer.setBase(nextIdx); curIdxContainer.set(nextIdx); return obj; } else { obj = null; } } nextIdx++; } if (obj == null) { // Fields or elements of the top object exhausted fieldsOrArrayElsStack.pop(); refChain.pop2(); // Pop the index holder and object continue; } // Look through the next few elements to see if any of them is closer to old obj long curObjOfsInFile = ((JavaLazyReadObject) obj).getObjOfsInFile(); long minDistance = Math.abs(curObjOfsInFile - oldObjOfsInFile); int bestIdx = nextIdx; int nCheckedFields = 0; nextIdx++; while (nextIdx < fieldsOrElements.length && nCheckedFields < 8) { JavaThing objThing = fieldsOrElements[nextIdx]; if (objThing != null && objThing instanceof JavaHeapObject) { obj = (JavaHeapObject) objThing; if (!obj.isVisited()) { if (!(obj instanceof JavaLazyReadObject)) { curIdxContainer.set(nextIdx); return obj; } nCheckedFields++; curObjOfsInFile = ((JavaLazyReadObject) obj).getObjOfsInFile(); long distance = Math.abs(curObjOfsInFile - oldObjOfsInFile); if (distance < minDistance) { bestIdx = nextIdx; minDistance = distance; } } } nextIdx++; } curIdxContainer.set(bestIdx); return (JavaHeapObject) fieldsOrElements[bestIdx]; } return obj; } }
3,186
21,684
// Copyright 2010-2014 RethinkDB, all rights reserved. #ifndef CONTAINERS_ARCHIVE_BUFFER_STREAM_HPP_ #define CONTAINERS_ARCHIVE_BUFFER_STREAM_HPP_ #include <string.h> #include "containers/archive/archive.hpp" // Reads from a buffer without taking ownership over it class buffer_read_stream_t : public read_stream_t { public: // Note: These are implemented in the header file because inlining them in // combination with `deserialize_varint_uint64()` yields significant performance // gains due to its frequent use in datum_string_t and other datum // deserialization functions. (measured on GCC 4.8) // If we end up compiling with whole-program link-time optimization some day, // we can probably move this back to a .cc file. explicit buffer_read_stream_t(const char *buf, size_t size, int64_t offset = 0) : pos_(offset), buf_(buf), size_(size) { guarantee(pos_ >= 0); guarantee(static_cast<uint64_t>(pos_) <= size_); } virtual ~buffer_read_stream_t() { } virtual MUST_USE int64_t read(void *p, int64_t n) { int64_t num_left = size_ - pos_; int64_t num_to_read = n < num_left ? n : num_left; memcpy(p, buf_ + pos_, num_to_read); pos_ += num_to_read; return num_to_read; } int64_t tell() const { return pos_; } private: int64_t pos_; const char *buf_; size_t size_; DISABLE_COPYING(buffer_read_stream_t); }; #endif // CONTAINERS_ARCHIVE_BUFFER_STREAM_HPP_
582
5,937
<reponame>txlos/wpf // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //----------------------------------------------------------------------------- // // // Description: // Effect resource header. // //----------------------------------------------------------------------------- MtExtern(CMilEffectDuce); // Class: CMilEffectDuce class CMilEffectDuce : public CMilSlaveResource { friend class CResourceFactory; friend class CMilPixelShaderDuce; private: CComposition* m_pCompositionNoRef; protected: DECLARE_METERHEAP_CLEAR(ProcessHeap, Mt(CMilEffectDuce)); CMilEffectDuce(__in_ecount(1) CComposition* pComposition) { m_pCompositionNoRef = pComposition; } CMilEffectDuce() { } public: __override virtual bool IsOfType(MIL_RESOURCE_TYPE type) const { return type == TYPE_EFFECT; } virtual HRESULT ApplyEffect( __in CContextState *pContextState, __in CHwSurfaceRenderTarget *pDestRT, __in_ecount(1) CMILMatrix *pScaleTransform, __in CD3DDeviceLevel1 *pDevice, UINT uIntermediateWidth, UINT uIntermediateHeight, __in_opt CHwTextureRenderTarget *pImplicitInputNoRef ) = 0; virtual HRESULT TransformBoundsForInflation(__inout CMilRectF *bounds) = 0; virtual HRESULT GetLocalSpaceClipBounds( __in CRectF<CoordinateSpace::LocalRendering> unclippedBoundsLocalSpace, __in CRectF<CoordinateSpace::PageInPixels> clip, __in const CMatrix<CoordinateSpace::LocalRendering,CoordinateSpace::PageInPixels> *pWorldTransform, __out CRectF<CoordinateSpace::LocalRendering> *pClippedBoundsLocalSpace ); virtual ShaderEffectShaderRenderMode::Enum GetShaderRenderMode(); virtual HRESULT ApplyEffectSw( __in CContextState *pContextState, __in CSwRenderTargetSurface *pDestRT, __in CMILMatrix *pScaleTransform, UINT uIntermediateWidth, UINT uIntermediateHeight, __in_opt IWGXBitmap *pImplicitInput ) = 0; virtual HRESULT PrepareSoftwarePass( __in const CMatrix<CoordinateSpace::RealizationSampling,CoordinateSpace::DeviceHPC> *pRealizationSamplingToDevice, __inout CPixelShaderState *pPixelShaderState, __deref_out CPixelShaderCompiler **ppPixelShaderCompiler ) = 0; virtual bool UsesImplicitInput() { return true; } virtual byte GetShaderMajorVersion() { // // Used when checking for ps_3_0 support when running a ps_3_0 pixel shader. // By default, a shader is not a ps_3_0 pixel shader. // return 2; } protected: __out CComposition *GetCompositionDeviceNoRef() { Assert(m_pCompositionNoRef != NULL); return m_pCompositionNoRef; } static HRESULT CreateIntermediateRT( __in CD3DDeviceLevel1 *pD3DDevice, __in UINT uWidth, __in UINT uHeight, __in D3DFORMAT d3dfmtTarget, __out CD3DVidMemOnlyTexture **ppVidMemOnlyTexture ); static HRESULT SetupVertexTransform( __in const CContextState *pContextState, __in CD3DDeviceLevel1 *pDevice, float destinationWidth, float destinationHeight, bool passToFinalDestination ); static HRESULT SetSamplerState( __in CD3DDeviceLevel1 *pDevice, UINT uSamplerRegister, bool setAddressMode, bool useBilinear ); // // Hw Pixel Shader Cache // HRESULT GetHwPixelShaderEffectFromCache( __in CD3DDeviceLevel1 *pDevice, __in UINT cacheIndex, __in bool forceRecreation, __in_bcount(sizeInBytes) BYTE *pPixelShaderByteCode, __in UINT sizeInBytes, __out_opt CHwPixelShaderEffect **ppPixelShaderEffect); void ReleasePixelShaderEffectFromCache(__in UINT cacheIndex); HRESULT SetPixelShaderCacheCapacity(__in UINT cacheSize); static HRESULT LockResource( __in UINT resourceId, __deref_out_bcount(*pSizeInBytes) BYTE **ppResource, __out UINT *pSizeInBytes ); };
1,780
32,544
<gh_stars>1000+ package com.baeldung.xmlhtml.pojo.jaxb.html.elements; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlValue; public class Meta { private String title; public String getTitle() { return title; } @XmlAttribute(name = "title") public void setTitle(String title) { this.title = title; } private String value; @XmlValue public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
229
592
/****************************************************************************** Copyright (c) 2018, <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: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ #include <towr/initialization/gait_generator.h> #include <towr_ros/towr_ros_interface.h> namespace towr { /** * @brief An example application of using TOWR together with ROS. * * Build your own application with your own formulation using the building * blocks provided in TOWR and following the example below. */ class TowrRosApp : public TowrRosInterface { public: /** * @brief Sets the feet to nominal position on flat ground and base above. */ void SetTowrInitialState() override { auto nominal_stance_B = formulation_.model_.kinematic_model_->GetNominalStanceInBase(); double z_ground = 0.0; formulation_.initial_ee_W_ = nominal_stance_B; std::for_each(formulation_.initial_ee_W_.begin(), formulation_.initial_ee_W_.end(), [&](Vector3d& p){ p.z() = z_ground; } // feet at 0 height ); formulation_.initial_base_.lin.at(kPos).z() = - nominal_stance_B.front().z() + z_ground; } /** * @brief Sets the parameters required to formulate the TOWR problem. */ Parameters GetTowrParameters(int n_ee, const TowrCommandMsg& msg) const override { Parameters params; // Instead of manually defining the initial durations for each foot and // step, for convenience we use a GaitGenerator with some predefined gaits // for a variety of robots (walk, trot, pace, ...). auto gait_gen_ = GaitGenerator::MakeGaitGenerator(n_ee); auto id_gait = static_cast<GaitGenerator::Combos>(msg.gait); gait_gen_->SetCombo(id_gait); for (int ee=0; ee<n_ee; ++ee) { params.ee_phase_durations_.push_back(gait_gen_->GetPhaseDurations(msg.total_duration, ee)); params.ee_in_contact_at_start_.push_back(gait_gen_->IsInContactAtStart(ee)); } // Here you can also add other constraints or change parameters // params.constraints_.push_back(Parameters::BaseRom); // increases optimization time, but sometimes helps find a solution for // more difficult terrain. if (msg.optimize_phase_durations) params.OptimizePhaseDurations(); return params; } /** * @brief Sets the paramters for IPOPT. */ void SetIpoptParameters(const TowrCommandMsg& msg) override { // the HA-L solvers are alot faster, so consider installing and using solver_->SetOption("linear_solver", "mumps"); // ma27, ma57 // Analytically defining the derivatives in IFOPT as we do it, makes the // problem a lot faster. However, if this becomes too difficult, we can also // tell IPOPT to just approximate them using finite differences. However, // this uses numerical derivatives for ALL constraints, there doesn't yet // exist an option to turn on numerical derivatives for only some constraint // sets. solver_->SetOption("jacobian_approximation", "exact"); // finite difference-values // This is a great to test if the analytical derivatives implemented in are // correct. Some derivatives that are correct are still flagged, showing a // deviation of 10e-4, which is fine. What to watch out for is deviations > 10e-2. // solver_->SetOption("derivative_test", "first-order"); solver_->SetOption("max_cpu_time", 40.0); solver_->SetOption("print_level", 5); if (msg.play_initialization) solver_->SetOption("max_iter", 0); else solver_->SetOption("max_iter", 3000); } }; } // namespace towr int main(int argc, char *argv[]) { ros::init(argc, argv, "my_towr_ros_app"); towr::TowrRosApp towr_app; ros::spin(); return 1; }
1,626
4,036
/** * * Copyright 2003-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Adapted from the Java Servlet API version 2.4 as available at * http://search.maven.org/remotecontent?filepath=javax/servlet/servlet-api/2.4/servlet-api-2.4-sources.jar * Only relevant stubs of this file have been retained for test purposes. */ package javax.servlet; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.Enumeration; import java.util.Set; public interface ServletContext { public ServletContext getContext(String uripath); public int getMajorVersion(); public int getMinorVersion(); public String getMimeType(String file); public Set getResourcePaths(String path); public URL getResource(String path) throws MalformedURLException; public InputStream getResourceAsStream(String path); public RequestDispatcher getRequestDispatcher(String path); public RequestDispatcher getNamedDispatcher(String name); public Servlet getServlet(String name) throws ServletException; public Enumeration getServlets(); public Enumeration getServletNames(); public void log(String msg); public void log(Exception exception, String msg); public void log(String message, Throwable throwable); public String getRealPath(String path); public String getServerInfo(); public String getInitParameter(String name); public Enumeration getInitParameterNames(); public Object getAttribute(String name); public Enumeration getAttributeNames(); public void setAttribute(String name, Object object); public void removeAttribute(String name); public String getServletContextName(); }
656
2,743
<filename>cpp/include/cuml/explainer/tree_shap.hpp /* * Copyright (c) 2021, NVIDIA CORPORATION. * * 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 <cstddef> #include <cstdint> #include <cuml/ensemble/treelite_defs.hpp> #include <memory> namespace ML { namespace Explainer { // An abstract class representing an opaque handle to path information // extracted from a tree model. The implementation in tree_shap.cu will // define an internal class that inherits from this abtract class. class TreePathInfo { public: enum class ThresholdTypeEnum : std::uint8_t { kFloat, kDouble }; virtual ThresholdTypeEnum GetThresholdType() const = 0; }; std::unique_ptr<TreePathInfo> extract_path_info(ModelHandle model); void gpu_treeshap(const TreePathInfo* path_info, const float* data, std::size_t n_rows, std::size_t n_cols, float* out_preds); } // namespace Explainer } // namespace ML
498
383
<reponame>BrettRD/fuse /* * Software License Agreement (BSD License) * * Copyright (c) 2021, Locus Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef FUSE_TUTORIALS_RANGE_CONSTRAINT_H #define FUSE_TUTORIALS_RANGE_CONSTRAINT_H #include <fuse_core/constraint.h> #include <fuse_core/macros.h> #include <fuse_variables/point_2d_landmark.h> #include <fuse_variables/position_2d_stamped.h> #include <boost/serialization/access.hpp> #include <boost/serialization/base_object.hpp> #include <boost/serialization/export.hpp> #include <ceres/cost_function.h> #include <ostream> #include <string> namespace fuse_tutorials { /** * @brief Implements a range-only measurement constraint between the robot and a beacon. * * The main purpose for this constraint is to demonstrate how to write your own cost constraint classes. * * For the purposes of this tutorial, let's imagine that you have developed some new robotic sensor that is capable * of measuring the distance to some sort of beacon, but does not provide any information about the bearing/heading * to that beacon. None of the fuse packages provide such a sensor model, so you need to develop one yourself. * * The "sensor model" class provides an interface to ROS, allowing sensor messages to be received. The sensor model * class also acts as a "factory" (in a programming sense) that creates new sensor constraints for each received * sensor measurement. The constraint class does a number of things: * - Represents a single measurement, and likely holds the actual measured value * - Defines exactly which variable instances are involved in this measurement model * - Defines any robust loss function that should be applied to the computed costs * - Generates instances of a Ceres Solver cost function that implements the desired sensor measurement model * * This range-only constraint will use the mathematical model defined in the RangeCostFunctor, and Ceres Solver's * automatic differentiation system to create a Ceres Solver cost function. */ class RangeConstraint : public fuse_core::Constraint { public: // There are some boilerplate types and functions that must be implemented for each constraint, such as shared pointer // typedefs and clone() methods. These are formulaic, but the derived type is needed for their proper implementation. // A few different macro options are provided to make implementing this boilerplate code easy. FUSE_CONSTRAINT_DEFINITIONS(RangeConstraint); /** * @brief Default constructor * * A default constructor is required to support the serialize/deserialize functionality. */ RangeConstraint() = default; /** * @brief Create a range-only constraint between the provided robot position and the beacon position * * This is the constructor that will be used from within the RangeSensorModel. It accepts references to the variables * involved with this specific measurement -- the robot position at the time the measurement was sampled, and the * beacon that was measured. * * Note that, when measuring subset of dimensions, empty axis vectors are permitted. This signifies, e.g., that you * don't want to measure any of the quantities in that variable. * * The mean is given as a vector. The first components (if any) will be dictated, both in content and in ordering, by * the value of the \p linear_indices. The final component (if any) is dictated by the \p angular_indices. * The covariance matrix follows the same ordering. * * @param[in] source - The name of the sensor that generated this constraint. This is largely information to aid in * debugging or visualizing the system. If multiple sensors of the same type exist, being able to * disambiguate the constraints from sensor1 versus sensor2 is useful. * @param[in] robot_position - The 2D position of the robot at the time the measurement was sampled * @param[in] beacon_position - The 2D position of the sampled beacon * @param[in] z - The distance measured between the robot and beacon by our new sensor * @param[in] sigma - The uncertainty of measured distance */ RangeConstraint( const std::string& source, const fuse_variables::Position2DStamped& robot_position, const fuse_variables::Point2DLandmark& beacon_position, const double z, const double sigma); /** * @brief Print a human-readable description of the constraint to the provided stream. * * This is required by the fuse_core::Constraint base class, but is largely just for debugging and visualization. * * @param[out] stream - The stream to write to. Defaults to stdout. */ void print(std::ostream& stream = std::cout) const override; /** * @brief Construct an instance of this constraint's cost function * * This is the most important operation of a Constraint -- to create a Ceres Solver CostFunction object that is then * optimized by the Ceres Solver least-squares solver. This implementation uses the RangeCostFunctor and the Ceres * Solver AutoDiffCostFunction class to automatically compute the cost function Jacobians. This is also where the * sizes of the input variables and output cost array is defined. * * @return A base pointer to an instance of a derived Ceres Solver CostFunction. Ownership of the CostFunction object * is transferred Ceres Solver; Ceres Solver will delete the CostFunction object when it is done. Also note * that the fuse project guarantees the derived Constraint object will outlive the Ceres Solver CostFunction * object. */ ceres::CostFunction* costFunction() const override; private: // Allow Boost Serialization access to private methods and members friend class boost::serialization::access; /** * @brief The Boost Serialize method that serializes all of the data members in to/out of the archive * * Implementing the serialize() function allows the derived Constraint object to be written to disk, and retrieved * again at a later date. In particular, the Graph classes make use of this feature, allowing a full graph to be * saved to disk and recalled later. This is extraordinarily useful in debugging and replaying. It is highly * recommended that the serialize() method be implemented properly. And for most things, it is trivial to implement. * See the Boost Serialization documentation for more details: * https://www.boost.org/doc/libs/1_77_0/libs/serialization/doc/index.html * * @param[in/out] archive - The archive object that holds the serialized class members * @param[in] version - The version of the archive being read/written. Generally unused. */ template <class Archive> void serialize(Archive& archive, const unsigned int /* version */) { archive& boost::serialization::base_object<fuse_core::Constraint>(*this); archive& sigma_; archive& z_; } double sigma_ { 0.0 }; //!< The standard deviation of the range measurement double z_ { 0.0 }; //!< The measured range to the beacon }; } // namespace fuse_tutorials // This is part of the serialization requirement. Boost needs to be told this class is serializable. BOOST_CLASS_EXPORT_KEY(fuse_tutorials::RangeConstraint); #endif // FUSE_TUTORIALS_RANGE_CONSTRAINT_H
2,473
435
<reponame>luigidcsoares/psychec T f() { const int* x; int* y; x = y; return 0; }
56
797
<gh_stars>100-1000 /* The MIT License (MIT) Copyright (c) 2015 <NAME> and 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 com.intellij.lang.jsgraphql.types.execution.directives; import com.google.common.collect.ImmutableMap; import com.intellij.lang.jsgraphql.types.Internal; import com.intellij.lang.jsgraphql.types.execution.ValuesResolver; import com.intellij.lang.jsgraphql.types.language.Directive; import com.intellij.lang.jsgraphql.types.schema.GraphQLArgument; import com.intellij.lang.jsgraphql.types.schema.GraphQLCodeRegistry; import com.intellij.lang.jsgraphql.types.schema.GraphQLDirective; import com.intellij.lang.jsgraphql.types.schema.GraphQLSchema; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * This turns AST directives into runtime directives with resolved types and so on */ @Internal public class DirectivesResolver { private final ValuesResolver valuesResolver = new ValuesResolver(); public DirectivesResolver() { } public Map<String, GraphQLDirective> resolveDirectives(List<Directive> directives, GraphQLSchema schema, Map<String, Object> variables) { GraphQLCodeRegistry codeRegistry = schema.getCodeRegistry(); Map<String, GraphQLDirective> directiveMap = new LinkedHashMap<>(); directives.forEach(directive -> { GraphQLDirective protoType = schema.getDirective(directive.getName()); if (protoType != null) { GraphQLDirective newDirective = protoType.transform(builder -> buildArguments(builder, codeRegistry, protoType, directive, variables)); directiveMap.put(newDirective.getName(), newDirective); } }); return ImmutableMap.copyOf(directiveMap); } private void buildArguments(GraphQLDirective.Builder directiveBuilder, GraphQLCodeRegistry codeRegistry, GraphQLDirective protoType, Directive fieldDirective, Map<String, Object> variables) { Map<String, Object> argumentValues = valuesResolver.getArgumentValues(codeRegistry, protoType.getArguments(), fieldDirective.getArguments(), variables); directiveBuilder.clearArguments(); protoType.getArguments().forEach(protoArg -> { if (argumentValues.containsKey(protoArg.getName())) { Object argValue = argumentValues.get(protoArg.getName()); GraphQLArgument newArgument = protoArg.transform(argBuilder -> argBuilder.value(argValue)); directiveBuilder.argument(newArgument); } else { // this means they can ask for the argument default value because the argument on the directive // object is present - but null GraphQLArgument newArgument = protoArg.transform(argBuilder -> argBuilder.value(null)); directiveBuilder.argument(newArgument); } }); } }
1,317
827
/* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. Camunda licenses this file to you under the Apache License, * Version 2.0; 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.camunda.bpm.example.spring.soap; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.PropertyException; import javax.xml.namespace.QName; import javax.xml.transform.dom.DOMResult; import javax.xml.ws.Endpoint; import org.apache.cxf.binding.soap.SoapFault; import org.apache.cxf.jaxws.EndpointImpl; import org.camunda.bpm.engine.HistoryService; import org.camunda.bpm.engine.ProcessEngine; import org.camunda.bpm.engine.RuntimeService; import org.camunda.bpm.engine.TaskService; import org.camunda.bpm.engine.history.HistoricVariableInstance; import org.camunda.bpm.engine.runtime.ProcessInstance; import org.camunda.bpm.engine.variable.value.ObjectValue; import org.camunda.bpm.engine.variable.value.StringValue; import org.camunda.bpm.engine.variable.value.TypedValue; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.w3c.dom.Element; import com.camunda.bpm.example.spring.soap.v1.BankCustomerServicePortType; import com.camunda.bpm.example.spring.soap.v1.BankException; import com.camunda.bpm.example.spring.soap.v1.BankException_Exception; import com.camunda.bpm.example.spring.soap.v1.BankRequestHeader; import com.camunda.bpm.example.spring.soap.v1.GetAccountsRequest; import com.camunda.bpm.example.spring.soap.v1.GetAccountsResponse; /** * This class tests three async processes. */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:/spring/engine.xml", "classpath:/spring/beans.xml" }) @ActiveProfiles("webservice") public class BankCustomerProcessTest { @Autowired protected RuntimeService runtimeService; @Autowired protected TaskService taskService; @Autowired protected HistoryService historyService; @Autowired protected ProcessEngine processEngine; @Mock protected BankCustomerServicePortType serviceMock; @Value("${bankcustomer.service}") protected String bankCustomerServiceAddress; protected EndpointImpl endpoint; @Before public void initMocks() throws Exception { MockitoAnnotations.initMocks(this); // wrap the evaluator mock in proxy BankCustomerServicePortType serviceInterface = ServiceProxy.newInstance(serviceMock); // publish the mock endpoint = (EndpointImpl) Endpoint.create(serviceInterface); // we have to use the following CXF dependent code, to specify qname, so that it resource locator finds it QName serviceName = new QName("http://soap.spring.example.bpm.camunda.com/v1", "BankCustomerServicePortType"); endpoint.setServiceName(serviceName); endpoint.publish(bankCustomerServiceAddress); } @After public void closeMocks() { reset(serviceMock); if (endpoint != null) { endpoint.stop(); } } @Test public void process_inputJaxbObjectInProcess_javaObjectPassedToService() throws Exception { // add mock response GetAccountsResponse mockResponse = new GetAccountsResponse(); List<String> accountList = mockResponse.getAccount(); accountList.add("1234"); accountList.add("5678"); when(serviceMock.getAccounts(any(GetAccountsRequest.class), any(BankRequestHeader.class))).thenReturn(mockResponse); String customerNumber = "123456789"; String secret = "abc"; // invoke process (async behaviour) Map<String, Object> variables = new HashMap<>(); variables.put("customerNumber", customerNumber); variables.put("secret", secret); ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("process", variables); // wait until all jobs complete assertTrue(waitUntilNoActiveJobs(processEngine, 1000)); // validate that mock called verifyRequest(customerNumber, secret); // verify that all serialization types are application/xml (kind of important) verifySerializationFormat(processInstance, "application/xml"); // verify that we got our response GetAccountsResponse response = (GetAccountsResponse) historyService.createHistoricVariableInstanceQuery() .processInstanceId(processInstance.getProcessInstanceId()) .variableName("accounts") .singleResult() .getValue(); assertThat(response.getAccount().size(), is(2)); } @Test public void call_serviceWithSoapFault_soapFaultException() throws Exception { // add mock response GetAccountsResponse mockResponse = new GetAccountsResponse(); List<String> accountList = mockResponse.getAccount(); accountList.add("1234"); accountList.add("5678"); String errorCode = "myErrorCode"; String errorMessage = "myErrorMessage"; SoapFault fault = createFault(errorCode, errorMessage); when(serviceMock.getAccounts(any(GetAccountsRequest.class), any(BankRequestHeader.class))).thenThrow(fault); String customerNumber = "123456789"; String secret = "abc"; // invoke process (async behaviour) Map<String, Object> variables = new HashMap<>(); variables.put("customerNumber", customerNumber); variables.put("secret", secret); ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("process", variables); // wait until all jobs complete assertTrue(waitUntilNoActiveJobs(processEngine, 1000)); // validate that mock called verifyRequest(customerNumber, secret); Assert.assertNull(historyService.createHistoricVariableInstanceQuery() .processInstanceId(processInstance.getProcessInstanceId()) .variableName("accounts") .singleResult()); } /** * construct soap fault */ protected SoapFault createFault(String errorCode, String errorMessage) throws JAXBException, PropertyException { BankException exception = new BankException(); exception.setCode(errorCode); exception.setMessage(errorMessage); QName qName = SoapFault.FAULT_CODE_SERVER; SoapFault fault = new SoapFault("message", qName); Element detail = fault.getOrCreateDetail(); JAXBContext context = JAXBContext.newInstance(BankException.class); DOMResult result = new DOMResult(); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); marshaller.marshal( new JAXBElement<BankException>(new QName("http://soap.spring.example.bpm.camunda.com/v1", "bankException"), BankException.class, exception), result); detail.appendChild(detail.getOwnerDocument().importNode(result.getNode().getFirstChild(), true)); return fault; } protected void verifySerializationFormat(ProcessInstance processInstance, String format) { List<HistoricVariableInstance> list = historyService.createHistoricVariableInstanceQuery() .processInstanceId(processInstance.getProcessInstanceId()) .list(); for (HistoricVariableInstance item : list) { if (item.getName().equals("request") || item.getName().equals("accounts")) { TypedValue typedValue = item.getTypedValue(); if (typedValue instanceof ObjectValue) { ObjectValue objectValue = (ObjectValue) typedValue; assertThat(item.getName(), objectValue.getSerializationDataFormat(), is(format)); } else if (!(typedValue instanceof StringValue)) { Assert.fail(); } } } } protected void verifyRequest(String customerNumber, String secret) throws Exception { ArgumentCaptor<GetAccountsRequest> argument1 = ArgumentCaptor.forClass(GetAccountsRequest.class); ArgumentCaptor<BankRequestHeader> argument2 = ArgumentCaptor.forClass(BankRequestHeader.class); verify(serviceMock, times(1)).getAccounts(argument1.capture(), argument2.capture()); GetAccountsRequest request = argument1.getValue(); assertThat(request.getCustomerNumber(), is(customerNumber)); BankRequestHeader header = argument2.getValue(); assertThat(header.getSecret(), is(secret)); } public boolean waitUntilNoActiveJobs(ProcessEngine processEngine, long wait) throws InterruptedException { long timeout = System.currentTimeMillis() + wait; while (System.currentTimeMillis() < timeout) { long jobs = processEngine.getManagementService().createJobQuery().active().count(); if (jobs == 0) { return true; } System.out.println("Waiting for " + jobs + " jobs"); Thread.sleep(50); } return false; } /** * Utility class to wrap the webservice implementation in a mock. */ public static class ServiceProxy implements InvocationHandler { protected Object obj; public static <T> T newInstance(T obj) { ServiceProxy proxy = new ServiceProxy(obj); Class<?> clazz = obj.getClass(); T res = (T) Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), proxy); return res; } ServiceProxy(Object obj) { this.obj = obj; } @Override public Object invoke(Object proxy, Method m, Object[] args) throws Exception { try { return m.invoke(obj, args); } catch (Exception e) { if (e.getCause() instanceof org.apache.cxf.binding.soap.SoapFault) { throw (Exception) e.getCause(); } throw new RuntimeException(e.getMessage(), e); } } } }
3,581
4,081
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.job.plan.transform.format; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.mockito.Mockito.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.powermock.api.mockito.PowerMockito.mockStatic; import static org.powermock.api.mockito.PowerMockito.verifyStatic; import static org.powermock.api.mockito.PowerMockito.when; import alluxio.client.ReadType; import alluxio.conf.PropertyKey; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.security.UserGroupInformation; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; @RunWith(PowerMockRunner.class) @PrepareForTest({JobPath.class, UserGroupInformation.class}) public class JobPathTest { @Before public void before() throws Exception { mockStatic(UserGroupInformation.class); when(UserGroupInformation.getCurrentUser()).thenReturn(null); } @Test public void testCache() throws Exception { mockStatic(JobPath.class); Configuration conf = new Configuration(); JobPath jobPath = new JobPath("foo", "bar", "/baz"); when(JobPath.fileSystemGet(any(), any())).thenAnswer((p) -> mock(FileSystem.class)); FileSystem fileSystem = jobPath.getFileSystem(conf); verifyStatic(JobPath.class, times(1)); JobPath.fileSystemGet(any(), any()); assertEquals(fileSystem, jobPath.getFileSystem(conf)); verifyStatic(JobPath.class, times(1)); JobPath.fileSystemGet(any(), any()); conf.set(PropertyKey.USER_FILE_READ_TYPE_DEFAULT.toString(), ReadType.NO_CACHE.toString()); FileSystem newFileSystem = jobPath.getFileSystem(conf); assertNotEquals(fileSystem, newFileSystem); verifyStatic(JobPath.class, times(2)); JobPath.fileSystemGet(any(), any()); conf.set("foo", "bar"); assertEquals(newFileSystem, jobPath.getFileSystem(conf)); verifyStatic(JobPath.class, times(2)); JobPath.fileSystemGet(any(), any()); jobPath = new JobPath("foo", "bar", "/bar"); assertEquals(newFileSystem, jobPath.getFileSystem(conf)); verifyStatic(JobPath.class, times(2)); JobPath.fileSystemGet(any(), any()); jobPath = new JobPath("foo", "baz", "/bar"); assertNotEquals(newFileSystem, jobPath.getFileSystem(conf)); verifyStatic(JobPath.class, times(3)); JobPath.fileSystemGet(any(), any()); jobPath = new JobPath("bar", "bar", "/bar"); assertNotEquals(newFileSystem, jobPath.getFileSystem(conf)); verifyStatic(JobPath.class, times(4)); JobPath.fileSystemGet(any(), any()); } }
1,096
12,718
<filename>compiler-rt/lib/sanitizer_common/sanitizer_freebsd.h //===-- sanitizer_freebsd.h -------------------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file is a part of Sanitizer runtime. It contains FreeBSD-specific // definitions. // //===----------------------------------------------------------------------===// #ifndef SANITIZER_FREEBSD_H #define SANITIZER_FREEBSD_H #include "sanitizer_internal_defs.h" // x86-64 FreeBSD 9.2 and older define 'ucontext_t' incorrectly in // 32-bit mode. #if SANITIZER_FREEBSD && (SANITIZER_WORDSIZE == 32) #include <osreldate.h> #if __FreeBSD_version <= 902001 // v9.2 #include <link.h> #include <sys/param.h> #include <ucontext.h> namespace __sanitizer { typedef unsigned long long __xuint64_t; typedef __int32_t __xregister_t; typedef struct __xmcontext { __xregister_t mc_onstack; __xregister_t mc_gs; __xregister_t mc_fs; __xregister_t mc_es; __xregister_t mc_ds; __xregister_t mc_edi; __xregister_t mc_esi; __xregister_t mc_ebp; __xregister_t mc_isp; __xregister_t mc_ebx; __xregister_t mc_edx; __xregister_t mc_ecx; __xregister_t mc_eax; __xregister_t mc_trapno; __xregister_t mc_err; __xregister_t mc_eip; __xregister_t mc_cs; __xregister_t mc_eflags; __xregister_t mc_esp; __xregister_t mc_ss; int mc_len; int mc_fpformat; int mc_ownedfp; __xregister_t mc_flags; int mc_fpstate[128] __aligned(16); __xregister_t mc_fsbase; __xregister_t mc_gsbase; __xregister_t mc_xfpustate; __xregister_t mc_xfpustate_len; int mc_spare2[4]; } xmcontext_t; typedef struct __xucontext { sigset_t uc_sigmask; xmcontext_t uc_mcontext; struct __ucontext *uc_link; stack_t uc_stack; int uc_flags; int __spare__[4]; } xucontext_t; struct xkinfo_vmentry { int kve_structsize; int kve_type; __xuint64_t kve_start; __xuint64_t kve_end; __xuint64_t kve_offset; __xuint64_t kve_vn_fileid; __uint32_t kve_vn_fsid; int kve_flags; int kve_resident; int kve_private_resident; int kve_protection; int kve_ref_count; int kve_shadow_count; int kve_vn_type; __xuint64_t kve_vn_size; __uint32_t kve_vn_rdev; __uint16_t kve_vn_mode; __uint16_t kve_status; int _kve_ispare[12]; char kve_path[PATH_MAX]; }; typedef struct { __uint32_t p_type; __uint32_t p_offset; __uint32_t p_vaddr; __uint32_t p_paddr; __uint32_t p_filesz; __uint32_t p_memsz; __uint32_t p_flags; __uint32_t p_align; } XElf32_Phdr; struct xdl_phdr_info { Elf_Addr dlpi_addr; const char *dlpi_name; const XElf32_Phdr *dlpi_phdr; Elf_Half dlpi_phnum; unsigned long long int dlpi_adds; unsigned long long int dlpi_subs; size_t dlpi_tls_modid; void *dlpi_tls_data; }; typedef int (*__xdl_iterate_hdr_callback)(struct xdl_phdr_info *, size_t, void *); typedef int xdl_iterate_phdr_t(__xdl_iterate_hdr_callback, void *); #define xdl_iterate_phdr(callback, param) \ (((xdl_iterate_phdr_t *)dl_iterate_phdr)((callback), (param))) } // namespace __sanitizer #endif // __FreeBSD_version <= 902001 #endif // SANITIZER_FREEBSD && (SANITIZER_WORDSIZE == 32) #endif // SANITIZER_FREEBSD_H
1,489
1,338
<reponame>Kirishikesan/haiku<gh_stars>1000+ /* * Copyright 2008-2011, <NAME>, <EMAIL>. * Copyright 2008-2017, <NAME>, <EMAIL>. * Distributed under the terms of the MIT License. */ #include "IORequest.h" #include <string.h> #include <arch/debug.h> #include <debug.h> #include <heap.h> #include <kernel.h> #include <team.h> #include <thread.h> #include <util/AutoLock.h> #include <vm/vm.h> #include <vm/VMAddressSpace.h> #include "dma_resources.h" //#define TRACE_IO_REQUEST #ifdef TRACE_IO_REQUEST # define TRACE(x...) dprintf(x) #else # define TRACE(x...) ; #endif // partial I/O operation phases enum { PHASE_READ_BEGIN = 0, PHASE_READ_END = 1, PHASE_DO_ALL = 2 }; struct virtual_vec_cookie { uint32 vec_index; generic_size_t vec_offset; area_id mapped_area; void* physical_page_handle; addr_t virtual_address; virtual_vec_cookie() : vec_index(0), vec_offset(0), mapped_area(-1), physical_page_handle(NULL), virtual_address((addr_t)-1) { } void PutPhysicalPageIfNeeded() { if (virtual_address != (addr_t)-1) { vm_put_physical_page(virtual_address, physical_page_handle); virtual_address = (addr_t)-1; } } }; // #pragma mark - IORequestChunk::IORequestChunk() : fParent(NULL), fStatus(1) { } IORequestChunk::~IORequestChunk() { } // #pragma mark - IOBuffer* IOBuffer::Create(uint32 count, bool vip) { size_t size = sizeof(IOBuffer) + sizeof(generic_io_vec) * (count - 1); IOBuffer* buffer = (IOBuffer*)(malloc_etc(size, vip ? HEAP_PRIORITY_VIP : 0)); if (buffer == NULL) return NULL; buffer->fCapacity = count; buffer->fVecCount = 0; buffer->fUser = false; buffer->fPhysical = false; buffer->fVIP = vip; buffer->fMemoryLocked = false; return buffer; } void IOBuffer::Delete() { free_etc(this, fVIP ? HEAP_PRIORITY_VIP : 0); } void IOBuffer::SetVecs(generic_size_t firstVecOffset, generic_size_t lastVecSize, const generic_io_vec* vecs, uint32 count, generic_size_t length, uint32 flags) { memcpy(fVecs, vecs, sizeof(generic_io_vec) * count); if (count > 0 && firstVecOffset > 0) { fVecs[0].base += firstVecOffset; fVecs[0].length -= firstVecOffset; } if (lastVecSize > 0) fVecs[count - 1].length = lastVecSize; fVecCount = count; fLength = length; fPhysical = (flags & B_PHYSICAL_IO_REQUEST) != 0; fUser = !fPhysical && IS_USER_ADDRESS(vecs[0].base); #if KDEBUG generic_size_t actualLength = 0; for (size_t i = 0; i < fVecCount; i++) actualLength += fVecs[i].length; ASSERT(actualLength == fLength); #endif } status_t IOBuffer::GetNextVirtualVec(void*& _cookie, iovec& vector) { virtual_vec_cookie* cookie = (virtual_vec_cookie*)_cookie; if (cookie == NULL) { cookie = new(malloc_flags(fVIP ? HEAP_PRIORITY_VIP : 0)) virtual_vec_cookie; if (cookie == NULL) return B_NO_MEMORY; _cookie = cookie; } // recycle a potential previously mapped page cookie->PutPhysicalPageIfNeeded(); if (cookie->vec_index >= fVecCount) return B_BAD_INDEX; if (!fPhysical) { vector.iov_base = (void*)(addr_t)fVecs[cookie->vec_index].base; vector.iov_len = fVecs[cookie->vec_index++].length; return B_OK; } if (cookie->vec_index == 0 && (fVecCount > 1 || fVecs[0].length > B_PAGE_SIZE)) { void* mappedAddress; addr_t mappedSize; // TODO: This is a potential violation of the VIP requirement, since // vm_map_physical_memory_vecs() allocates memory without special flags! cookie->mapped_area = vm_map_physical_memory_vecs( VMAddressSpace::KernelID(), "io buffer mapped physical vecs", &mappedAddress, B_ANY_KERNEL_ADDRESS, &mappedSize, B_KERNEL_READ_AREA | B_KERNEL_WRITE_AREA, fVecs, fVecCount); if (cookie->mapped_area >= 0) { vector.iov_base = mappedAddress; vector.iov_len = mappedSize; return B_OK; } else ktrace_printf("failed to map area: %s\n", strerror(cookie->mapped_area)); } // fallback to page wise mapping generic_io_vec& currentVec = fVecs[cookie->vec_index]; generic_addr_t address = currentVec.base + cookie->vec_offset; size_t pageOffset = address % B_PAGE_SIZE; // TODO: This is a potential violation of the VIP requirement, since // vm_get_physical_page() may allocate memory without special flags! status_t result = vm_get_physical_page(address - pageOffset, &cookie->virtual_address, &cookie->physical_page_handle); if (result != B_OK) return result; generic_size_t length = min_c(currentVec.length - cookie->vec_offset, B_PAGE_SIZE - pageOffset); vector.iov_base = (void*)(cookie->virtual_address + pageOffset); vector.iov_len = length; cookie->vec_offset += length; if (cookie->vec_offset >= currentVec.length) { cookie->vec_index++; cookie->vec_offset = 0; } return B_OK; } void IOBuffer::FreeVirtualVecCookie(void* _cookie) { virtual_vec_cookie* cookie = (virtual_vec_cookie*)_cookie; if (cookie->mapped_area >= 0) delete_area(cookie->mapped_area); cookie->PutPhysicalPageIfNeeded(); free_etc(cookie, fVIP ? HEAP_PRIORITY_VIP : 0); } status_t IOBuffer::LockMemory(team_id team, bool isWrite) { if (fMemoryLocked) { panic("memory already locked!"); return B_BAD_VALUE; } for (uint32 i = 0; i < fVecCount; i++) { status_t status = lock_memory_etc(team, (void*)(addr_t)fVecs[i].base, fVecs[i].length, isWrite ? 0 : B_READ_DEVICE); if (status != B_OK) { _UnlockMemory(team, i, isWrite); return status; } } fMemoryLocked = true; return B_OK; } void IOBuffer::_UnlockMemory(team_id team, size_t count, bool isWrite) { for (uint32 i = 0; i < count; i++) { unlock_memory_etc(team, (void*)(addr_t)fVecs[i].base, fVecs[i].length, isWrite ? 0 : B_READ_DEVICE); } } void IOBuffer::UnlockMemory(team_id team, bool isWrite) { if (!fMemoryLocked) { panic("memory not locked"); return; } _UnlockMemory(team, fVecCount, isWrite); fMemoryLocked = false; } void IOBuffer::Dump() const { kprintf("IOBuffer at %p\n", this); kprintf(" origin: %s\n", fUser ? "user" : "kernel"); kprintf(" kind: %s\n", fPhysical ? "physical" : "virtual"); kprintf(" length: %" B_PRIuGENADDR "\n", fLength); kprintf(" capacity: %" B_PRIuSIZE "\n", fCapacity); kprintf(" vecs: %" B_PRIuSIZE "\n", fVecCount); for (uint32 i = 0; i < fVecCount; i++) { kprintf(" [%" B_PRIu32 "] %#" B_PRIxGENADDR ", %" B_PRIuGENADDR "\n", i, fVecs[i].base, fVecs[i].length); } } // #pragma mark - bool IOOperation::Finish() { TRACE("IOOperation::Finish()\n"); if (fStatus == B_OK) { if (fParent->IsWrite()) { TRACE(" is write\n"); if (fPhase == PHASE_READ_BEGIN) { TRACE(" phase read begin\n"); // repair phase adjusted vec fDMABuffer->VecAt(fSavedVecIndex).length = fSavedVecLength; // partial write: copy partial begin to bounce buffer bool skipReadEndPhase; status_t error = _CopyPartialBegin(true, skipReadEndPhase); if (error == B_OK) { // We're done with the first phase only (read in begin). // Get ready for next phase... fPhase = HasPartialEnd() && !skipReadEndPhase ? PHASE_READ_END : PHASE_DO_ALL; _PrepareVecs(); ResetStatus(); // TODO: Is there a race condition, if the request is // aborted at the same time? return false; } SetStatus(error); } else if (fPhase == PHASE_READ_END) { TRACE(" phase read end\n"); // repair phase adjusted vec generic_io_vec& vec = fDMABuffer->VecAt(fSavedVecIndex); vec.base += vec.length - fSavedVecLength; vec.length = fSavedVecLength; // partial write: copy partial end to bounce buffer status_t error = _CopyPartialEnd(true); if (error == B_OK) { // We're done with the second phase only (read in end). // Get ready for next phase... fPhase = PHASE_DO_ALL; ResetStatus(); // TODO: Is there a race condition, if the request is // aborted at the same time? return false; } SetStatus(error); } } } if (fParent->IsRead() && UsesBounceBuffer()) { TRACE(" read with bounce buffer\n"); // copy the bounce buffer segments to the final location uint8* bounceBuffer = (uint8*)fDMABuffer->BounceBufferAddress(); phys_addr_t bounceBufferStart = fDMABuffer->PhysicalBounceBufferAddress(); phys_addr_t bounceBufferEnd = bounceBufferStart + fDMABuffer->BounceBufferSize(); const generic_io_vec* vecs = fDMABuffer->Vecs(); uint32 vecCount = fDMABuffer->VecCount(); status_t error = B_OK; // We iterate through the vecs we have read, moving offset (the device // offset) as we go. If [offset, offset + vec.length) intersects with // [startOffset, endOffset) we copy to the final location. off_t offset = fOffset; const off_t startOffset = fOriginalOffset; const off_t endOffset = fOriginalOffset + fOriginalLength; for (uint32 i = 0; error == B_OK && i < vecCount; i++) { const generic_io_vec& vec = vecs[i]; generic_addr_t base = vec.base; generic_size_t length = vec.length; if (offset < startOffset) { // If the complete vector is before the start offset, skip it. if (offset + (off_t)length <= startOffset) { offset += length; continue; } // The vector starts before the start offset, but intersects // with it. Skip the part we aren't interested in. generic_size_t diff = startOffset - offset; offset += diff; base += diff; length -= diff; } if (offset + (off_t)length > endOffset) { // If we're already beyond the end offset, we're done. if (offset >= endOffset) break; // The vector extends beyond the end offset -- cut it. length = endOffset - offset; } if (base >= bounceBufferStart && base < bounceBufferEnd) { error = fParent->CopyData( bounceBuffer + (base - bounceBufferStart), offset, length); } offset += length; } if (error != B_OK) SetStatus(error); } return true; } /*! Note: SetPartial() must be called first! */ status_t IOOperation::Prepare(IORequest* request) { if (fParent != NULL) fParent->RemoveOperation(this); fParent = request; fTransferredBytes = 0; // set initial phase fPhase = PHASE_DO_ALL; if (fParent->IsWrite()) { // Copy data to bounce buffer segments, save the partial begin/end vec, // which will be copied after their respective read phase. if (UsesBounceBuffer()) { TRACE(" write with bounce buffer\n"); uint8* bounceBuffer = (uint8*)fDMABuffer->BounceBufferAddress(); phys_addr_t bounceBufferStart = fDMABuffer->PhysicalBounceBufferAddress(); phys_addr_t bounceBufferEnd = bounceBufferStart + fDMABuffer->BounceBufferSize(); const generic_io_vec* vecs = fDMABuffer->Vecs(); uint32 vecCount = fDMABuffer->VecCount(); generic_size_t vecOffset = 0; uint32 i = 0; off_t offset = fOffset; off_t endOffset = fOffset + fLength; if (HasPartialBegin()) { // skip first block generic_size_t toSkip = fBlockSize; while (toSkip > 0) { if (vecs[i].length <= toSkip) { toSkip -= vecs[i].length; i++; } else { vecOffset = toSkip; break; } } offset += fBlockSize; } if (HasPartialEnd()) { // skip last block generic_size_t toSkip = fBlockSize; while (toSkip > 0) { if (vecs[vecCount - 1].length <= toSkip) { toSkip -= vecs[vecCount - 1].length; vecCount--; } else break; } endOffset -= fBlockSize; } for (; i < vecCount; i++) { const generic_io_vec& vec = vecs[i]; generic_addr_t base = vec.base + vecOffset; generic_size_t length = vec.length - vecOffset; vecOffset = 0; if (base >= bounceBufferStart && base < bounceBufferEnd) { if (offset + (off_t)length > endOffset) length = endOffset - offset; status_t error = fParent->CopyData(offset, bounceBuffer + (base - bounceBufferStart), length); if (error != B_OK) return error; } offset += length; } } if (HasPartialBegin()) fPhase = PHASE_READ_BEGIN; else if (HasPartialEnd()) fPhase = PHASE_READ_END; _PrepareVecs(); } ResetStatus(); if (fParent != NULL) fParent->AddOperation(this); return B_OK; } void IOOperation::SetOriginalRange(off_t offset, generic_size_t length) { fOriginalOffset = fOffset = offset; fOriginalLength = fLength = length; } void IOOperation::SetRange(off_t offset, generic_size_t length) { fOffset = offset; fLength = length; } off_t IOOperation::Offset() const { return fPhase == PHASE_READ_END ? fOffset + fLength - fBlockSize : fOffset; } generic_size_t IOOperation::Length() const { return fPhase == PHASE_DO_ALL ? fLength : fBlockSize; } generic_io_vec* IOOperation::Vecs() const { switch (fPhase) { case PHASE_READ_END: return fDMABuffer->Vecs() + fSavedVecIndex; case PHASE_READ_BEGIN: case PHASE_DO_ALL: default: return fDMABuffer->Vecs(); } } uint32 IOOperation::VecCount() const { switch (fPhase) { case PHASE_READ_BEGIN: return fSavedVecIndex + 1; case PHASE_READ_END: return fDMABuffer->VecCount() - fSavedVecIndex; case PHASE_DO_ALL: default: return fDMABuffer->VecCount(); } } void IOOperation::SetPartial(bool partialBegin, bool partialEnd) { TRACE("partial begin %d, end %d\n", partialBegin, partialEnd); fPartialBegin = partialBegin; fPartialEnd = partialEnd; } bool IOOperation::IsWrite() const { return fParent->IsWrite() && fPhase == PHASE_DO_ALL; } bool IOOperation::IsRead() const { return fParent->IsRead(); } void IOOperation::_PrepareVecs() { // we need to prepare the vecs for consumption by the drivers if (fPhase == PHASE_READ_BEGIN) { generic_io_vec* vecs = fDMABuffer->Vecs(); uint32 vecCount = fDMABuffer->VecCount(); generic_size_t vecLength = fBlockSize; for (uint32 i = 0; i < vecCount; i++) { generic_io_vec& vec = vecs[i]; if (vec.length >= vecLength) { fSavedVecIndex = i; fSavedVecLength = vec.length; vec.length = vecLength; break; } vecLength -= vec.length; } } else if (fPhase == PHASE_READ_END) { generic_io_vec* vecs = fDMABuffer->Vecs(); uint32 vecCount = fDMABuffer->VecCount(); generic_size_t vecLength = fBlockSize; for (int32 i = vecCount - 1; i >= 0; i--) { generic_io_vec& vec = vecs[i]; if (vec.length >= vecLength) { fSavedVecIndex = i; fSavedVecLength = vec.length; vec.base += vec.length - vecLength; vec.length = vecLength; break; } vecLength -= vec.length; } } } status_t IOOperation::_CopyPartialBegin(bool isWrite, bool& singleBlockOnly) { generic_size_t relativeOffset = OriginalOffset() - fOffset; generic_size_t length = fBlockSize - relativeOffset; singleBlockOnly = length >= OriginalLength(); if (singleBlockOnly) length = OriginalLength(); TRACE("_CopyPartialBegin(%s, single only %d)\n", isWrite ? "write" : "read", singleBlockOnly); if (isWrite) { return fParent->CopyData(OriginalOffset(), (uint8*)fDMABuffer->BounceBufferAddress() + relativeOffset, length); } else { return fParent->CopyData( (uint8*)fDMABuffer->BounceBufferAddress() + relativeOffset, OriginalOffset(), length); } } status_t IOOperation::_CopyPartialEnd(bool isWrite) { TRACE("_CopyPartialEnd(%s)\n", isWrite ? "write" : "read"); const generic_io_vec& lastVec = fDMABuffer->VecAt(fDMABuffer->VecCount() - 1); off_t lastVecPos = fOffset + fLength - fBlockSize; uint8* base = (uint8*)fDMABuffer->BounceBufferAddress() + (lastVec.base + lastVec.length - fBlockSize - fDMABuffer->PhysicalBounceBufferAddress()); // NOTE: this won't work if we don't use the bounce buffer contiguously // (because of boundary alignments). generic_size_t length = OriginalOffset() + OriginalLength() - lastVecPos; if (isWrite) return fParent->CopyData(lastVecPos, base, length); return fParent->CopyData(base, lastVecPos, length); } void IOOperation::Dump() const { kprintf("io_operation at %p\n", this); kprintf(" parent: %p\n", fParent); kprintf(" status: %s\n", strerror(fStatus)); kprintf(" dma buffer: %p\n", fDMABuffer); kprintf(" offset: %-8" B_PRIdOFF " (original: %" B_PRIdOFF ")\n", fOffset, fOriginalOffset); kprintf(" length: %-8" B_PRIuGENADDR " (original: %" B_PRIuGENADDR ")\n", fLength, fOriginalLength); kprintf(" transferred: %" B_PRIuGENADDR "\n", fTransferredBytes); kprintf(" block size: %" B_PRIuGENADDR "\n", fBlockSize); kprintf(" saved vec index: %u\n", fSavedVecIndex); kprintf(" saved vec length: %u\n", fSavedVecLength); kprintf(" r/w: %s\n", IsWrite() ? "write" : "read"); kprintf(" phase: %s\n", fPhase == PHASE_READ_BEGIN ? "read begin" : fPhase == PHASE_READ_END ? "read end" : fPhase == PHASE_DO_ALL ? "do all" : "unknown"); kprintf(" partial begin: %s\n", fPartialBegin ? "yes" : "no"); kprintf(" partial end: %s\n", fPartialEnd ? "yes" : "no"); kprintf(" bounce buffer: %s\n", fUsesBounceBuffer ? "yes" : "no"); set_debug_variable("_parent", (addr_t)fParent); set_debug_variable("_buffer", (addr_t)fDMABuffer); } // #pragma mark - IORequest::IORequest() : fIsNotified(false), fFinishedCallback(NULL), fFinishedCookie(NULL), fIterationCallback(NULL), fIterationCookie(NULL) { mutex_init(&fLock, "I/O request lock"); fFinishedCondition.Init(this, "I/O request finished"); } IORequest::~IORequest() { mutex_lock(&fLock); DeleteSubRequests(); if (fBuffer != NULL) fBuffer->Delete(); mutex_destroy(&fLock); } /* static */ IORequest* IORequest::Create(bool vip) { return vip ? new(malloc_flags(HEAP_PRIORITY_VIP)) IORequest : new(std::nothrow) IORequest; } status_t IORequest::Init(off_t offset, generic_addr_t buffer, generic_size_t length, bool write, uint32 flags) { ASSERT(offset >= 0); generic_io_vec vec; vec.base = buffer; vec.length = length; return Init(offset, &vec, 1, length, write, flags); } status_t IORequest::Init(off_t offset, generic_size_t firstVecOffset, generic_size_t lastVecSize, const generic_io_vec* vecs, size_t count, generic_size_t length, bool write, uint32 flags) { ASSERT(offset >= 0); fBuffer = IOBuffer::Create(count, (flags & B_VIP_IO_REQUEST) != 0); if (fBuffer == NULL) return B_NO_MEMORY; fBuffer->SetVecs(firstVecOffset, lastVecSize, vecs, count, length, flags); fOwner = NULL; fOffset = offset; fLength = length; fRelativeParentOffset = 0; fTransferSize = 0; fFlags = flags; Thread* thread = thread_get_current_thread(); fTeam = thread->team->id; fThread = thread->id; fIsWrite = write; fPartialTransfer = false; fSuppressChildNotifications = false; // these are for iteration fVecIndex = 0; fVecOffset = 0; fRemainingBytes = length; fPendingChildren = 0; fStatus = 1; return B_OK; } status_t IORequest::CreateSubRequest(off_t parentOffset, off_t offset, generic_size_t length, IORequest*& _subRequest) { ASSERT(parentOffset >= fOffset && length <= fLength && parentOffset - fOffset <= (off_t)(fLength - length)); // find start vec generic_size_t vecOffset = parentOffset - fOffset; generic_io_vec* vecs = fBuffer->Vecs(); int32 vecCount = fBuffer->VecCount(); int32 startVec = 0; for (; startVec < vecCount; startVec++) { const generic_io_vec& vec = vecs[startVec]; if (vecOffset < vec.length) break; vecOffset -= vec.length; } // count vecs generic_size_t currentVecOffset = vecOffset; int32 endVec = startVec; generic_size_t remainingLength = length; for (; endVec < vecCount; endVec++) { const generic_io_vec& vec = vecs[endVec]; if (vec.length - currentVecOffset >= remainingLength) break; remainingLength -= vec.length - currentVecOffset; currentVecOffset = 0; } // create subrequest IORequest* subRequest = Create((fFlags & B_VIP_IO_REQUEST) != 0); if (subRequest == NULL) return B_NO_MEMORY; status_t error = subRequest->Init(offset, vecOffset, remainingLength, vecs + startVec, endVec - startVec + 1, length, fIsWrite, fFlags & ~B_DELETE_IO_REQUEST); if (error != B_OK) { delete subRequest; return error; } subRequest->fRelativeParentOffset = parentOffset - fOffset; subRequest->fTeam = fTeam; subRequest->fThread = fThread; _subRequest = subRequest; subRequest->SetParent(this); MutexLocker _(fLock); fChildren.Add(subRequest); fPendingChildren++; TRACE("IORequest::CreateSubRequest(): request: %p, subrequest: %p\n", this, subRequest); return B_OK; } void IORequest::DeleteSubRequests() { while (IORequestChunk* chunk = fChildren.RemoveHead()) delete chunk; fPendingChildren = 0; } void IORequest::SetFinishedCallback(io_request_finished_callback callback, void* cookie) { fFinishedCallback = callback; fFinishedCookie = cookie; } void IORequest::SetIterationCallback(io_request_iterate_callback callback, void* cookie) { fIterationCallback = callback; fIterationCookie = cookie; } io_request_finished_callback IORequest::FinishedCallback(void** _cookie) const { if (_cookie != NULL) *_cookie = fFinishedCookie; return fFinishedCallback; } status_t IORequest::Wait(uint32 flags, bigtime_t timeout) { MutexLocker locker(fLock); if (IsFinished() && fIsNotified) return Status(); ConditionVariableEntry entry; fFinishedCondition.Add(&entry); locker.Unlock(); status_t error = entry.Wait(flags, timeout); if (error != B_OK) return error; return Status(); } void IORequest::NotifyFinished() { TRACE("IORequest::NotifyFinished(): request: %p\n", this); MutexLocker locker(fLock); if (fStatus == B_OK && !fPartialTransfer && RemainingBytes() > 0) { // The request is not really done yet. If it has an iteration callback, // call it. if (fIterationCallback != NULL) { ResetStatus(); locker.Unlock(); bool partialTransfer = false; status_t error = fIterationCallback(fIterationCookie, this, &partialTransfer); if (error == B_OK && !partialTransfer) return; // Iteration failed, which means we're responsible for notifying the // requests finished. locker.Lock(); fStatus = error; fPartialTransfer = true; } } ASSERT(!fIsNotified); ASSERT(fPendingChildren == 0); ASSERT(fChildren.IsEmpty() || dynamic_cast<IOOperation*>(fChildren.Head()) == NULL); // unlock the memory if (fBuffer->IsMemoryLocked()) fBuffer->UnlockMemory(fTeam, fIsWrite); // Cache the callbacks before we unblock waiters and unlock. Any of the // following could delete this request, so we don't want to touch it // once we have started telling others that it is done. IORequest* parent = fParent; io_request_finished_callback finishedCallback = fFinishedCallback; void* finishedCookie = fFinishedCookie; status_t status = fStatus; generic_size_t lastTransferredOffset = fRelativeParentOffset + fTransferSize; bool partialTransfer = status != B_OK || fPartialTransfer; bool deleteRequest = (fFlags & B_DELETE_IO_REQUEST) != 0; // unblock waiters fIsNotified = true; fFinishedCondition.NotifyAll(); locker.Unlock(); // notify callback if (finishedCallback != NULL) { finishedCallback(finishedCookie, this, status, partialTransfer, lastTransferredOffset); } // notify parent if (parent != NULL) { parent->SubRequestFinished(this, status, partialTransfer, lastTransferredOffset); } if (deleteRequest) delete this; } /*! Returns whether this request or any of it's ancestors has a finished or notification callback. Used to decide whether NotifyFinished() can be called synchronously. */ bool IORequest::HasCallbacks() const { if (fFinishedCallback != NULL || fIterationCallback != NULL) return true; return fParent != NULL && fParent->HasCallbacks(); } void IORequest::SetStatusAndNotify(status_t status) { MutexLocker locker(fLock); if (fStatus != 1) return; fStatus = status; locker.Unlock(); NotifyFinished(); } void IORequest::OperationFinished(IOOperation* operation, status_t status, bool partialTransfer, generic_size_t transferEndOffset) { TRACE("IORequest::OperationFinished(%p, %#" B_PRIx32 "): request: %p\n", operation, status, this); MutexLocker locker(fLock); fChildren.Remove(operation); operation->SetParent(NULL); if (status != B_OK || partialTransfer) { if (fTransferSize > transferEndOffset) fTransferSize = transferEndOffset; fPartialTransfer = true; } if (status != B_OK && fStatus == 1) fStatus = status; if (--fPendingChildren > 0) return; // last child finished // set status, if not done yet if (fStatus == 1) fStatus = B_OK; } void IORequest::SubRequestFinished(IORequest* request, status_t status, bool partialTransfer, generic_size_t transferEndOffset) { TRACE("IORequest::SubrequestFinished(%p, %#" B_PRIx32 ", %d, %" B_PRIuGENADDR "): request: %p\n", request, status, partialTransfer, transferEndOffset, this); MutexLocker locker(fLock); if (status != B_OK || partialTransfer) { if (fTransferSize > transferEndOffset) fTransferSize = transferEndOffset; fPartialTransfer = true; } if (status != B_OK && fStatus == 1) fStatus = status; if (--fPendingChildren > 0 || fSuppressChildNotifications) return; // last child finished // set status, if not done yet if (fStatus == 1) fStatus = B_OK; locker.Unlock(); NotifyFinished(); } void IORequest::SetUnfinished() { MutexLocker _(fLock); ResetStatus(); } void IORequest::SetTransferredBytes(bool partialTransfer, generic_size_t transferredBytes) { TRACE("%p->IORequest::SetTransferredBytes(%d, %" B_PRIuGENADDR ")\n", this, partialTransfer, transferredBytes); MutexLocker _(fLock); fPartialTransfer = partialTransfer; fTransferSize = transferredBytes; } void IORequest::SetSuppressChildNotifications(bool suppress) { fSuppressChildNotifications = suppress; } void IORequest::Advance(generic_size_t bySize) { TRACE("IORequest::Advance(%" B_PRIuGENADDR "): remaining: %" B_PRIuGENADDR " -> %" B_PRIuGENADDR "\n", bySize, fRemainingBytes, fRemainingBytes - bySize); fRemainingBytes -= bySize; fTransferSize += bySize; generic_io_vec* vecs = fBuffer->Vecs(); uint32 vecCount = fBuffer->VecCount(); while (fVecIndex < vecCount && vecs[fVecIndex].length - fVecOffset <= bySize) { bySize -= vecs[fVecIndex].length - fVecOffset; fVecOffset = 0; fVecIndex++; } fVecOffset += bySize; } IORequest* IORequest::FirstSubRequest() { return dynamic_cast<IORequest*>(fChildren.Head()); } IORequest* IORequest::NextSubRequest(IORequest* previous) { if (previous == NULL) return NULL; return dynamic_cast<IORequest*>(fChildren.GetNext(previous)); } void IORequest::AddOperation(IOOperation* operation) { MutexLocker locker(fLock); TRACE("IORequest::AddOperation(%p): request: %p\n", operation, this); fChildren.Add(operation); fPendingChildren++; } void IORequest::RemoveOperation(IOOperation* operation) { MutexLocker locker(fLock); fChildren.Remove(operation); operation->SetParent(NULL); } status_t IORequest::CopyData(off_t offset, void* buffer, size_t size) { return _CopyData(buffer, offset, size, true); } status_t IORequest::CopyData(const void* buffer, off_t offset, size_t size) { return _CopyData((void*)buffer, offset, size, false); } status_t IORequest::ClearData(off_t offset, generic_size_t size) { if (size == 0) return B_OK; if (offset < fOffset || offset + (off_t)size > fOffset + (off_t)fLength) { panic("IORequest::ClearData(): invalid range: (%" B_PRIdOFF ", %" B_PRIuGENADDR ")", offset, size); return B_BAD_VALUE; } // If we can, we directly copy from/to the virtual buffer. The memory is // locked in this case. status_t (*clearFunction)(generic_addr_t, generic_size_t, team_id); if (fBuffer->IsPhysical()) { clearFunction = &IORequest::_ClearDataPhysical; } else { clearFunction = fBuffer->IsUser() && fTeam != team_get_current_team_id() ? &IORequest::_ClearDataUser : &IORequest::_ClearDataSimple; } // skip bytes if requested generic_io_vec* vecs = fBuffer->Vecs(); generic_size_t skipBytes = offset - fOffset; generic_size_t vecOffset = 0; while (skipBytes > 0) { if (vecs[0].length > skipBytes) { vecOffset = skipBytes; break; } skipBytes -= vecs[0].length; vecs++; } // clear vector-wise while (size > 0) { generic_size_t toClear = min_c(size, vecs[0].length - vecOffset); status_t error = clearFunction(vecs[0].base + vecOffset, toClear, fTeam); if (error != B_OK) return error; size -= toClear; vecs++; vecOffset = 0; } return B_OK; } status_t IORequest::_CopyData(void* _buffer, off_t offset, size_t size, bool copyIn) { if (size == 0) return B_OK; uint8* buffer = (uint8*)_buffer; if (offset < fOffset || offset + (off_t)size > fOffset + (off_t)fLength) { panic("IORequest::_CopyData(): invalid range: (%" B_PRIdOFF ", %lu)", offset, size); return B_BAD_VALUE; } // If we can, we directly copy from/to the virtual buffer. The memory is // locked in this case. status_t (*copyFunction)(void*, generic_addr_t, size_t, team_id, bool); if (fBuffer->IsPhysical()) { copyFunction = &IORequest::_CopyPhysical; } else { copyFunction = fBuffer->IsUser() && fTeam != team_get_current_team_id() ? &IORequest::_CopyUser : &IORequest::_CopySimple; } // skip bytes if requested generic_io_vec* vecs = fBuffer->Vecs(); generic_size_t skipBytes = offset - fOffset; generic_size_t vecOffset = 0; while (skipBytes > 0) { if (vecs[0].length > skipBytes) { vecOffset = skipBytes; break; } skipBytes -= vecs[0].length; vecs++; } // copy vector-wise while (size > 0) { generic_size_t toCopy = min_c(size, vecs[0].length - vecOffset); status_t error = copyFunction(buffer, vecs[0].base + vecOffset, toCopy, fTeam, copyIn); if (error != B_OK) return error; buffer += toCopy; size -= toCopy; vecs++; vecOffset = 0; } return B_OK; } /* static */ status_t IORequest::_CopySimple(void* bounceBuffer, generic_addr_t external, size_t size, team_id team, bool copyIn) { TRACE(" IORequest::_CopySimple(%p, %#" B_PRIxGENADDR ", %lu, %d)\n", bounceBuffer, external, size, copyIn); if (IS_USER_ADDRESS(external)) { status_t status = B_OK; if (copyIn) status = user_memcpy(bounceBuffer, (void*)(addr_t)external, size); else status = user_memcpy((void*)(addr_t)external, bounceBuffer, size); if (status < B_OK) return status; return B_OK; } if (copyIn) memcpy(bounceBuffer, (void*)(addr_t)external, size); else memcpy((void*)(addr_t)external, bounceBuffer, size); return B_OK; } /* static */ status_t IORequest::_CopyPhysical(void* bounceBuffer, generic_addr_t external, size_t size, team_id team, bool copyIn) { if (copyIn) return vm_memcpy_from_physical(bounceBuffer, external, size, false); return vm_memcpy_to_physical(external, bounceBuffer, size, false); } /* static */ status_t IORequest::_CopyUser(void* _bounceBuffer, generic_addr_t _external, size_t size, team_id team, bool copyIn) { uint8* bounceBuffer = (uint8*)_bounceBuffer; uint8* external = (uint8*)(addr_t)_external; while (size > 0) { static const int32 kEntryCount = 8; physical_entry entries[kEntryCount]; uint32 count = kEntryCount; status_t error = get_memory_map_etc(team, external, size, entries, &count); if (error != B_OK && error != B_BUFFER_OVERFLOW) { panic("IORequest::_CopyUser(): Failed to get physical memory for " "user memory %p\n", external); return B_BAD_ADDRESS; } for (uint32 i = 0; i < count; i++) { const physical_entry& entry = entries[i]; error = _CopyPhysical(bounceBuffer, entry.address, entry.size, team, copyIn); if (error != B_OK) return error; size -= entry.size; bounceBuffer += entry.size; external += entry.size; } } return B_OK; } /*static*/ status_t IORequest::_ClearDataSimple(generic_addr_t external, generic_size_t size, team_id team) { memset((void*)(addr_t)external, 0, (size_t)size); return B_OK; } /*static*/ status_t IORequest::_ClearDataPhysical(generic_addr_t external, generic_size_t size, team_id team) { return vm_memset_physical((phys_addr_t)external, 0, (phys_size_t)size); } /*static*/ status_t IORequest::_ClearDataUser(generic_addr_t _external, generic_size_t size, team_id team) { uint8* external = (uint8*)(addr_t)_external; while (size > 0) { static const int32 kEntryCount = 8; physical_entry entries[kEntryCount]; uint32 count = kEntryCount; status_t error = get_memory_map_etc(team, external, size, entries, &count); if (error != B_OK && error != B_BUFFER_OVERFLOW) { panic("IORequest::_ClearDataUser(): Failed to get physical memory " "for user memory %p\n", external); return B_BAD_ADDRESS; } for (uint32 i = 0; i < count; i++) { const physical_entry& entry = entries[i]; error = _ClearDataPhysical(entry.address, entry.size, team); if (error != B_OK) return error; size -= entry.size; external += entry.size; } } return B_OK; } void IORequest::Dump() const { kprintf("io_request at %p\n", this); kprintf(" owner: %p\n", fOwner); kprintf(" parent: %p\n", fParent); kprintf(" status: %s\n", strerror(fStatus)); kprintf(" mutex: %p\n", &fLock); kprintf(" IOBuffer: %p\n", fBuffer); kprintf(" offset: %" B_PRIdOFF "\n", fOffset); kprintf(" length: %" B_PRIuGENADDR "\n", fLength); kprintf(" transfer size: %" B_PRIuGENADDR "\n", fTransferSize); kprintf(" relative offset: %" B_PRIuGENADDR "\n", fRelativeParentOffset); kprintf(" pending children: %" B_PRId32 "\n", fPendingChildren); kprintf(" flags: %#" B_PRIx32 "\n", fFlags); kprintf(" team: %" B_PRId32 "\n", fTeam); kprintf(" thread: %" B_PRId32 "\n", fThread); kprintf(" r/w: %s\n", fIsWrite ? "write" : "read"); kprintf(" partial transfer: %s\n", fPartialTransfer ? "yes" : "no"); kprintf(" finished cvar: %p\n", &fFinishedCondition); kprintf(" iteration:\n"); kprintf(" vec index: %" B_PRIu32 "\n", fVecIndex); kprintf(" vec offset: %" B_PRIuGENADDR "\n", fVecOffset); kprintf(" remaining bytes: %" B_PRIuGENADDR "\n", fRemainingBytes); kprintf(" callbacks:\n"); kprintf(" finished %p, cookie %p\n", fFinishedCallback, fFinishedCookie); kprintf(" iteration %p, cookie %p\n", fIterationCallback, fIterationCookie); kprintf(" children:\n"); IORequestChunkList::ConstIterator iterator = fChildren.GetIterator(); while (iterator.HasNext()) { kprintf(" %p\n", iterator.Next()); } set_debug_variable("_parent", (addr_t)fParent); set_debug_variable("_mutex", (addr_t)&fLock); set_debug_variable("_buffer", (addr_t)fBuffer); set_debug_variable("_cvar", (addr_t)&fFinishedCondition); }
13,791
1,338
#include "exceptions.h" ExceptionBase::ExceptionBase() {} ExceptionBase::~ExceptionBase() {} ExceptionA::ExceptionA() {} ExceptionA::~ExceptionA() {} ExceptionB::ExceptionB() {} ExceptionB::~ExceptionB() {} VirtualExceptionBase::VirtualExceptionBase() {} VirtualExceptionBase::~VirtualExceptionBase() {} VirtualExceptionA::VirtualExceptionA() {} VirtualExceptionA::~VirtualExceptionA() {} VirtualExceptionB::VirtualExceptionB() {} VirtualExceptionB::~VirtualExceptionB() {} void throwBase() { throw ExceptionBase(); } void throwA() { throw ExceptionA(); } void throwB() { throw ExceptionB(); } void throwVirtualBase() { throw VirtualExceptionBase(); } void throwVirtualA() { throw VirtualExceptionA(); } void throwVirtualB() { throw VirtualExceptionB(); } void throwInt() { throw int(7); }
256
368
/* Plugin-SDK (Grand Theft Auto San Andreas) header file Authors: GTA Community. See more here https://github.com/DK22Pac/plugin-sdk Do not delete this comment block. Respect others' work! */ #pragma once #include "PluginBase.h" #include "CTaskSimple.h" class PLUGIN_API CTaskSimpleHoldEntity : public CTaskSimple { protected: CTaskSimpleHoldEntity(plugin::dummy_func_t a) : CTaskSimple(a) {} public: }; //VALIDATE_SIZE(CTaskSimpleHoldEntity, 0x);
171
322
<reponame>WanpengQian/ConcurrencyFreaks /****************************************************************************** * Copyright (c) 2015, <NAME>, <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: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Concurrency Freaks nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> 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. ****************************************************************************** */ package com.concurrencyfreaks.cow; import java.util.TreeMap; /** * <h1> TreeMap with a Copy-On-Write with Mutation Queue (Lock-Free) </h1> * * TODO: * * @author <NAME> * @author <NAME> * */ public class CopyOnWriteMQLFTreeMap<K,V> extends COWMutationQLF<K, V, K, CopyOnWriteMQLFTreeMap.CopyableTreeMap<K,V>>{ public static class CopyableTreeMap<K,V> extends TreeMap<K,V> implements IShallowCopy { private static final long serialVersionUID = -3775955588768508232L; public CopyableTreeMap() { super(); } public CopyableTreeMap(CopyableTreeMap<K,V> tree) { super(tree); } @Override public Object copyOf() { return new CopyableTreeMap<K,V>(this); } } public CopyOnWriteMQLFTreeMap() { super(new CopyableTreeMap<K,V>()); } /** * There is a volatile load in ref.get() * * Progress Condition: Wait-Free Population Oblivious * * @param key * @return */ public V get(Object key) { return combinedRef.instance.get(key); } public boolean containsKey(Object key) { return combinedRef.instance.containsKey(key); } public V put(K key, V value) { return applyMutation(key, value, null, (K _key, V _value, K _nop, TreeMap<K,V> tree) -> tree.put(_key, _value)); } public V remove(K key) { return applyMutation(key, null, null, (K _key, V _value, K _nop, TreeMap<K,V> tree) -> tree.remove(_key)); } }
1,146
577
<gh_stars>100-1000 # -*- coding: utf-8 -*- # Author: <NAME> # License: MIT import warnings warnings.filterwarnings("ignore") import sys from ..utils import print_sys from . import bi_pred_dataset, multi_pred_dataset from ..metadata import dataset_names class TestMultiPred(bi_pred_dataset.DataLoader): """Summary Attributes: entity1_name (str): Description entity2_name (str): Description two_types (bool): Description """ def __init__(self, name, path='./data', label_name=None, print_stats=False): """Summary Args: name (TYPE): Description path (str, optional): Description label_name (None, optional): Description print_stats (bool, optional): Description """ super().__init__(name, path, label_name, print_stats, dataset_names=dataset_names["test_multi_pred"]) self.entity1_name = 'Antibody' self.entity2_name = 'Antigen' self.two_types = True if print_stats: self.print_stats() print('Done!', flush=True, file=sys.stderr)
522
2,206
/* ****************************************************************************** * * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://www.apache.org/licenses/LICENSE-2.0. * * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ // // @author <EMAIL> // #include <system/op_boilerplate.h> #if NOT_EXCLUDED(OP_skipgram) #include <ops/declarable/CustomOperations.h> #include <ops/declarable/helpers/sg_cb.h> namespace sd { namespace ops { CONFIGURABLE_OP_IMPL(skipgram, 12, 12, true, 0, 0) { auto target = INPUT_VARIABLE(0); auto ngStarter = INPUT_VARIABLE(1); // required part auto indices = INPUT_VARIABLE(2); auto codes = INPUT_VARIABLE(3); auto syn0 = INPUT_VARIABLE(4); auto syn1 = INPUT_VARIABLE(5); auto syn1neg = INPUT_VARIABLE(6); auto expTable = INPUT_VARIABLE(7); auto negTable = INPUT_VARIABLE(8); auto alpha = INPUT_VARIABLE(9); auto randomValue = INPUT_VARIABLE(10); auto inferenceVector = INPUT_VARIABLE(11); // auto neu1e = INPUT_VARIABLE(12); auto numWorkers = block.numI() > 0 ? INT_ARG(0) : omp_get_max_threads(); auto nsRounds = block.numI() > 1 ? INT_ARG(1) : 0; auto isInference = block.numB() > 0 ? B_ARG(0) : false; auto isPreciseMode = block.numB() > 1 ? B_ARG(1) : false; REQUIRE_TRUE(block.isInplace(), 0, "SkipGram: this operation requires inplace execution only"); REQUIRE_TRUE(syn0->dataType() == syn1->dataType() && syn0->dataType() == syn1neg->dataType(), 0, "SkipGram: all syn tables must have the same data type"); REQUIRE_TRUE(syn0->dataType() == expTable->dataType(), 0, "SkipGram: expTable must have the same data type as syn0 table"); sd::ops::helpers::skipgram(*syn0, *syn1, *syn1neg, *expTable, *negTable, *target, *ngStarter, nsRounds, *indices, *codes, *alpha, *randomValue, *inferenceVector, isPreciseMode, numWorkers); return sd::Status::OK; } DECLARE_TYPES(skipgram) { getOpDescriptor() ->setAllowedInputTypes(0, sd::DataType::INT32) ->setAllowedInputTypes(1, sd::DataType::INT32) ->setAllowedInputTypes(2, sd::DataType::INT32) ->setAllowedInputTypes(3, sd::DataType::INT8) ->setAllowedInputTypes(4, {ALL_FLOATS}) ->setAllowedInputTypes(5, {ALL_FLOATS}) ->setAllowedInputTypes(6, {ALL_FLOATS}) ->setAllowedInputTypes(7, {ALL_FLOATS}) ->setAllowedInputTypes(8, {ALL_FLOATS}) ->setAllowedInputTypes(9, {ALL_FLOATS}) ->setAllowedInputTypes(10, sd::DataType::INT64) ->setAllowedInputTypes(11, {ALL_FLOATS}) ->setAllowedOutputTypes(sd::DataType::ANY); } /* DECLARE_SHAPE_FN(skipgram) { return SHAPELIST(ShapeBuilders::createScalarShapeInfo(DataType::INT8, block.getWorkspace())); } */ } // namespace ops } // namespace sd #endif
1,262
1,090
package com.uber.okbuck.extension; import java.util.Set; import javax.annotation.Nullable; public class TestExtension { /** Enable generation of robolectric test rules. */ public boolean robolectric = false; /** * Choose only a specific subset of robolectric API levels to download. Default is all api levels */ @Nullable public Set<String> robolectricApis = null; /** Enable generation of espresso test rules. */ public boolean espresso = false; /** Enable generation of espresso test rules on android libraries. */ public boolean espressoForLibraries = false; /** Enable creation of integrationTest rules for modules with `integrationTest` folder */ public boolean enableIntegrationTests = false; }
193
910
/* * Copyright (C) 2017, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.github.megatronking.svg.generator.svg.parser.attribute; import com.github.megatronking.svg.generator.svg.model.Line; import com.github.megatronking.svg.generator.svg.model.SvgConstants; import com.github.megatronking.svg.generator.svg.parser.SvgNodeAbstractAttributeParser; import org.dom4j.DocumentException; import org.dom4j.Element; /** * Build line's field values from attributes of the svg element. * * @author <NAME> * @since 2016/11/22 19:00 */ public class LineAttributeParser extends SvgNodeAbstractAttributeParser<Line> { @Override public void parse(Element element, Line line) throws DocumentException { super.parse(element, line); line.x1 = parseFloat(element, SvgConstants.ATTR_X1); line.y1 = parseFloat(element, SvgConstants.ATTR_Y1); line.x2 = parseFloat(element, SvgConstants.ATTR_X2); line.y2 = parseFloat(element, SvgConstants.ATTR_Y2); line.toPath(); } }
549
444
<reponame>BartoszMilewski/Okasaki<filename>Queue/Qtest.cpp #include "Queue.h" void test() { Queue<int> q; auto q1 = q.pushed_back(1); q1.printq(); auto q2 = q1.pushed_back(2); q1.printq(); q2.printq(); auto q3 = q2.pushed_back(3); q1.printq(); q2.printq(); q3.printq(); std::cout << "--Popping\n\n"; std::cout << "pop " << q3.front() << std::endl; auto q4 = q3.popped_front(); q4.printq(); std::cout << "pop " << q4.front() << std::endl; auto q5 = q4.popped_front(); q5.printq(); std::cout << "pop " << q5.front() << std::endl; auto q6 = q5.popped_front(); q6.printq(); } void main() { test(); }
349
348
{"nom":"Chennevières-sur-Marne","circ":"4ème circonscription","dpt":"Val-de-Marne","inscrits":10309,"abs":5807,"votants":4502,"blancs":49,"nuls":24,"exp":4429,"res":[{"nuance":"MDM","nom":"Mme <NAME>","voix":1833},{"nuance":"LR","nom":"Mme <NAME>","voix":887},{"nuance":"FI","nom":"Mme <NAME>","voix":527},{"nuance":"FN","nom":"M. <NAME>","voix":507},{"nuance":"SOC","nom":"M. <NAME>","voix":173},{"nuance":"COM","nom":"Mme <NAME>","voix":123},{"nuance":"ECO","nom":"M. <NAME>","voix":109},{"nuance":"DIV","nom":"Mme <NAME>","voix":81},{"nuance":"DLF","nom":"Mme <NAME>","voix":65},{"nuance":"DIV","nom":"M. <NAME>","voix":45},{"nuance":"ECO","nom":"Mme <NAME>","voix":41},{"nuance":"DIV","nom":"Mme <NAME>","voix":19},{"nuance":"EXG","nom":"Mme <NAME>","voix":19},{"nuance":"REG","nom":"Mme <NAME>","voix":0}]}
332
1,304
<filename>tests/base/test_multitenancy.py # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import os import tempfile import pytest from treq.testing import StubTreq from rasa_nlu import config from rasa_nlu.config import RasaNLUModelConfig from rasa_nlu.data_router import DataRouter from rasa_nlu.model import Trainer from rasa_nlu.server import RasaNLU from tests.utilities import ResponseTest @pytest.fixture(scope="module") def app(component_builder): """Use IResource interface of Klein to mock Rasa HTTP server. :param component_builder: :return: """ if "TRAVIS_BUILD_DIR" in os.environ: root_dir = os.environ["TRAVIS_BUILD_DIR"] else: root_dir = os.getcwd() _, nlu_log_file = tempfile.mkstemp(suffix="_rasa_nlu_logs.json") train_models(component_builder, os.path.join(root_dir, "data/examples/rasa/demo-rasa.json")) router = DataRouter(os.path.join(root_dir, "test_projects")) rasa = RasaNLU(router, logfile=nlu_log_file, testing=True) return StubTreq(rasa.app.resource()) @pytest.mark.parametrize("response_test", [ ResponseTest( "http://dummy-uri/parse?q=food&project=test_project_mitie", {"entities": [], "intent": "affirm", "text": "food"} ), ResponseTest( "http://dummy-uri/parse?q=food&project=test_project_mitie_sklearn", {"entities": [], "intent": "restaurant_search", "text": "food"} ), ResponseTest( "http://dummy-uri/parse?q=food&project=test_project_spacy_sklearn", {"entities": [], "intent": "restaurant_search", "text": "food"} ), ]) @pytest.inlineCallbacks def test_get_parse(app, response_test): response = yield app.get(response_test.endpoint) rjs = yield response.json() assert response.code == 200 assert all(prop in rjs for prop in ['entities', 'intent', 'text']) @pytest.mark.parametrize("response_test", [ ResponseTest( "http://dummy-uri/parse?q=food", {"error": "No project found with name 'default'."} ), ResponseTest( "http://dummy-uri/parse?q=food&project=umpalumpa", {"error": "No project found with name 'umpalumpa'."} ) ]) @pytest.inlineCallbacks def test_get_parse_invalid_model(app, response_test): response = yield app.get(response_test.endpoint) rjs = yield response.json() assert response.code == 404 assert rjs.get("error").startswith(response_test.expected_response["error"]) @pytest.mark.parametrize("response_test", [ ResponseTest( "http://dummy-uri/parse", {"entities": [], "intent": "affirm", "text": "food"}, payload={"q": "food", "project": "test_project_mitie"} ), ResponseTest( "http://dummy-uri/parse", {"entities": [], "intent": "restaurant_search", "text": "food"}, payload={"q": "food", "project": "test_project_mitie_sklearn"} ), ResponseTest( "http://dummy-uri/parse", {"entities": [], "intent": "restaurant_search", "text": "food"}, payload={"q": "food", "project": "test_project_spacy_sklearn"} ), ]) @pytest.inlineCallbacks def test_post_parse(app, response_test): response = yield app.post(response_test.endpoint, json=response_test.payload) rjs = yield response.json() assert response.code == 200 assert all(prop in rjs for prop in ['entities', 'intent', 'text']) @pytest.inlineCallbacks def test_post_parse_specific_model(app): status = yield app.get("http://dummy-uri/status") sjs = yield status.json() project = sjs["available_projects"]["test_project_spacy_sklearn"] model = project["available_models"][0] query = ResponseTest("http://dummy-uri/parse", {"entities": [], "intent": "affirm", "text": "food"}, payload={"q": "food", "project": "test_project_spacy_sklearn", "model": model}) response = yield app.post(query.endpoint, json=query.payload) assert response.code == 200 # check that that model now is loaded in the server status = yield app.get("http://dummy-uri/status") sjs = yield status.json() project = sjs["available_projects"]["test_project_spacy_sklearn"] assert model in project["loaded_models"] @pytest.mark.parametrize("response_test", [ ResponseTest( "http://dummy-uri/parse", {"error": "No project found with name 'default'."}, payload={"q": "food"} ), ResponseTest( "http://dummy-uri/parse", {"error": "No project found with name 'umpalumpa'."}, payload={"q": "food", "project": "umpalumpa"} ), ]) @pytest.inlineCallbacks def test_post_parse_invalid_model(app, response_test): response = yield app.post(response_test.endpoint, json=response_test.payload) rjs = yield response.json() assert response.code == 404 assert rjs.get("error").startswith(response_test.expected_response["error"]) def train_models(component_builder, data): # Retrain different multitenancy models def train(cfg_name, project_name): from rasa_nlu.train import create_persistor from rasa_nlu import training_data cfg = config.load(cfg_name) trainer = Trainer(cfg, component_builder) training_data = training_data.load_data(data) trainer.train(training_data) trainer.persist("test_projects", project_name=project_name) train("sample_configs/config_spacy.yml", "test_project_spacy_sklearn") train("sample_configs/config_mitie.yml", "test_project_mitie") train("sample_configs/config_mitie_sklearn.yml", "test_project_mitie_sklearn")
2,434
454
<filename>vertx-gaia/vertx-tp/src/main/java/io/vertx/tp/error/WallItemSizeException.java package io.vertx.tp.error; import io.vertx.up.eon.em.AuthWall; import io.vertx.up.exception.UpException; public class WallItemSizeException extends UpException { public WallItemSizeException(final Class<?> clazz, final AuthWall wall, final Integer size) { super(clazz, wall.key(), size); } @Override public int getCode() { return -40076; } }
244
575
// 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. package org.chromium.chrome.browser.toolbar.top; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnLongClickListener; import android.view.ViewStub; import androidx.annotation.VisibleForTesting; import org.chromium.base.CallbackController; import org.chromium.base.supplier.ObservableSupplier; import org.chromium.base.supplier.OneshotSupplier; import org.chromium.base.supplier.Supplier; import org.chromium.chrome.R; import org.chromium.chrome.browser.layouts.LayoutStateProvider; import org.chromium.chrome.browser.tabmodel.IncognitoStateProvider; import org.chromium.chrome.browser.tabmodel.TabModelSelector; import org.chromium.chrome.browser.theme.ThemeColorProvider; import org.chromium.chrome.browser.toolbar.ButtonData; import org.chromium.chrome.browser.toolbar.TabCountProvider; import org.chromium.chrome.browser.toolbar.TabSwitcherButtonCoordinator; import org.chromium.chrome.browser.toolbar.TabSwitcherButtonView; import org.chromium.chrome.browser.toolbar.menu_button.MenuButtonCoordinator; import org.chromium.chrome.browser.user_education.UserEducationHelper; import org.chromium.chrome.features.start_surface.StartSurfaceConfiguration; import org.chromium.chrome.features.start_surface.StartSurfaceState; import org.chromium.ui.modelutil.PropertyModel; import org.chromium.ui.modelutil.PropertyModelChangeProcessor; /** * The controller for the StartSurfaceToolbar. This class handles all interactions that the * StartSurfaceToolbar has with the outside world. Lazily creates the tab toolbar the first time * it's needed. */ public class StartSurfaceToolbarCoordinator { private final StartSurfaceToolbarMediator mToolbarMediator; private final ViewStub mStub; private final PropertyModel mPropertyModel; private PropertyModelChangeProcessor mPropertyModelChangeProcessor; private StartSurfaceToolbarView mView; private TabModelSelector mTabModelSelector; private TabSwitcherButtonCoordinator mTabSwitcherButtonCoordinator; private TabSwitcherButtonView mTabSwitcherButtonView; private TabCountProvider mTabCountProvider; private ThemeColorProvider mThemeColorProvider; private OnClickListener mTabSwitcherClickListener; private OnLongClickListener mTabSwitcherLongClickListener; private MenuButtonCoordinator mMenuButtonCoordinator; private CallbackController mCallbackController = new CallbackController(); StartSurfaceToolbarCoordinator(ViewStub startSurfaceToolbarStub, UserEducationHelper userEducationHelper, OneshotSupplier<LayoutStateProvider> layoutStateProviderSupplier, ObservableSupplier<Boolean> identityDiscStateSupplier, ThemeColorProvider provider, MenuButtonCoordinator menuButtonCoordinator, Supplier<ButtonData> identityDiscButtonSupplier, boolean isGridTabSwitcherEnabled, ObservableSupplier<Boolean> homepageEnabledSupplier, ObservableSupplier<Boolean> startSurfaceAsHomepageSupplier, ObservableSupplier<Boolean> homepageManagedByPolicySupplier, OnClickListener homeButtonOnClickHandler, boolean isTabGroupsAndroidContinuationEnabled) { mStub = startSurfaceToolbarStub; layoutStateProviderSupplier.onAvailable( mCallbackController.makeCancelable(this::setLayoutStateProvider)); mPropertyModel = new PropertyModel.Builder(StartSurfaceToolbarProperties.ALL_KEYS) .with(StartSurfaceToolbarProperties.INCOGNITO_SWITCHER_VISIBLE, !StartSurfaceConfiguration .START_SURFACE_HIDE_INCOGNITO_SWITCH_NO_TAB.getValue()) .with(StartSurfaceToolbarProperties.IN_START_SURFACE_MODE, false) .with(StartSurfaceToolbarProperties.MENU_IS_VISIBLE, true) .with(StartSurfaceToolbarProperties.IS_VISIBLE, true) .with(StartSurfaceToolbarProperties.GRID_TAB_SWITCHER_ENABLED, isGridTabSwitcherEnabled) .build(); mToolbarMediator = new StartSurfaceToolbarMediator(mPropertyModel, (iphCommandBuilder) -> { // TODO(crbug.com/865801): Replace the null check with an assert after fixing or // removing the ShareButtonControllerTest that necessitated it. if (mView == null) return; userEducationHelper.requestShowIPH( iphCommandBuilder.setAnchorView(mView.getIdentityDiscView()).build()); }, StartSurfaceConfiguration.START_SURFACE_HIDE_INCOGNITO_SWITCH_NO_TAB.getValue(), StartSurfaceConfiguration.HOME_BUTTON_ON_GRID_TAB_SWITCHER.getValue(), menuButtonCoordinator, identityDiscStateSupplier, identityDiscButtonSupplier, homepageEnabledSupplier, startSurfaceAsHomepageSupplier, homepageManagedByPolicySupplier, homeButtonOnClickHandler, StartSurfaceConfiguration.shouldShowNewSurfaceFromHomeButton(), isTabGroupsAndroidContinuationEnabled); mThemeColorProvider = provider; mMenuButtonCoordinator = menuButtonCoordinator; } /** * Cleans up any code and removes observers as necessary. */ void destroy() { mToolbarMediator.destroy(); if (mTabSwitcherButtonCoordinator != null) mTabSwitcherButtonCoordinator.destroy(); if (mMenuButtonCoordinator != null) { mMenuButtonCoordinator.destroy(); mMenuButtonCoordinator = null; } if (mCallbackController != null) { mCallbackController.destroy(); mCallbackController = null; } mTabSwitcherButtonCoordinator = null; mTabSwitcherButtonView = null; mTabCountProvider = null; mThemeColorProvider = null; mTabSwitcherClickListener = null; mTabSwitcherLongClickListener = null; } /** * Sets the OnClickListener that will be notified when the New Tab button is pressed. * @param listener The callback that will be notified when the New Tab button is pressed. */ void setOnNewTabClickHandler(View.OnClickListener listener) { mToolbarMediator.setOnNewTabClickHandler(listener); } /** * Sets the current {@Link TabModelSelector} so the toolbar can pass it into buttons that need * access to it. */ void setTabModelSelector(TabModelSelector selector) { mTabModelSelector = selector; mToolbarMediator.setTabModelSelector(selector); } /** * Called when Start Surface mode is entered or exited. * @param inStartSurfaceMode Whether or not start surface mode should be shown or hidden. */ void setStartSurfaceMode(boolean inStartSurfaceMode) { if (!isInflated()) { inflate(); } mToolbarMediator.setStartSurfaceMode(inStartSurfaceMode); } /** * @param provider The provider used to determine incognito state. */ void setIncognitoStateProvider(IncognitoStateProvider provider) { mToolbarMediator.setIncognitoStateProvider(provider); } /** * Called when accessibility status changes. * @param enabled whether accessibility status is enabled. */ void onAccessibilityStatusChanged(boolean enabled) { mToolbarMediator.onAccessibilityStatusChanged(enabled); } /** * @param layoutStateProvider The {@link LayoutStateProvider} to observe layout state changes. */ private void setLayoutStateProvider(LayoutStateProvider layoutStateProvider) { assert layoutStateProvider != null; mToolbarMediator.setLayoutStateProvider(layoutStateProvider); } /** * @param tabCountProvider The {@link TabCountProvider} to update the tab switcher button. */ void setTabCountProvider(TabCountProvider tabCountProvider) { if (mTabSwitcherButtonCoordinator != null) { mTabSwitcherButtonCoordinator.setTabCountProvider(tabCountProvider); } else { mTabCountProvider = tabCountProvider; } mToolbarMediator.setTabCountProvider(tabCountProvider); } /** * @param onClickListener The {@link OnClickListener} for the tab switcher button. */ void setTabSwitcherListener(OnClickListener onClickListener) { if (mTabSwitcherButtonCoordinator != null) { mTabSwitcherButtonCoordinator.setTabSwitcherListener(onClickListener); } else { mTabSwitcherClickListener = onClickListener; } } /** * @param listener The {@link OnLongClickListener} for the tab switcher button. */ void setOnTabSwitcherLongClickHandler(OnLongClickListener listener) { if (mTabSwitcherButtonView != null) { mTabSwitcherButtonView.setOnLongClickListener(listener); } else { mTabSwitcherLongClickListener = listener; } } /** * Called when start surface state is changed. * @param newState The new {@link StartSurfaceState}. * @param shouldShowStartSurfaceToolbar Whether or not should show start surface toolbar. */ void onStartSurfaceStateChanged( @StartSurfaceState int newState, boolean shouldShowStartSurfaceToolbar) { mToolbarMediator.onStartSurfaceStateChanged(newState, shouldShowStartSurfaceToolbar); } /** * Triggered when the offset of start surface header view is changed. * @param verticalOffset The start surface header view's offset. */ void onStartSurfaceHeaderOffsetChanged(int verticalOffset) { mToolbarMediator.onStartSurfaceHeaderOffsetChanged(verticalOffset); } /** * @param toolbarHeight The height of start surface toolbar. * @return Whether or not toolbar layout view should be hidden. */ boolean shouldHideToolbarLayout(int toolbarHeight) { return mToolbarMediator.shouldHideToolbarLayout(toolbarHeight); } boolean isToolbarOnScreenTop() { return mToolbarMediator.isToolbarOnScreenTop(); } void onNativeLibraryReady() { mToolbarMediator.onNativeLibraryReady(); } /** * @param highlight If the new tab button should be highlighted. */ void setNewTabButtonHighlight(boolean highlight) { mToolbarMediator.setNewTabButtonHighlight(highlight); } private void inflate() { mStub.setLayoutResource(R.layout.start_top_toolbar); mView = (StartSurfaceToolbarView) mStub.inflate(); mMenuButtonCoordinator.setMenuButton(mView.findViewById(R.id.menu_button_wrapper)); mMenuButtonCoordinator.setVisibility( mPropertyModel.get(StartSurfaceToolbarProperties.MENU_IS_VISIBLE)); mPropertyModelChangeProcessor = PropertyModelChangeProcessor.create( mPropertyModel, mView, StartSurfaceToolbarViewBinder::bind); if (StartSurfaceConfiguration.shouldShowNewSurfaceFromHomeButton()) { mTabSwitcherButtonView = mView.findViewById(R.id.start_tab_switcher_button); if (mTabSwitcherLongClickListener != null) { mTabSwitcherButtonView.setOnLongClickListener(mTabSwitcherLongClickListener); mTabSwitcherLongClickListener = null; } mTabSwitcherButtonCoordinator = new TabSwitcherButtonCoordinator(mTabSwitcherButtonView); mTabSwitcherButtonCoordinator.setThemeColorProvider(mThemeColorProvider); if (mTabCountProvider != null) { mTabSwitcherButtonCoordinator.setTabCountProvider(mTabCountProvider); mTabCountProvider = null; } if (mTabSwitcherClickListener != null) { mTabSwitcherButtonCoordinator.setTabSwitcherListener(mTabSwitcherClickListener); mTabSwitcherClickListener = null; } } } private boolean isInflated() { return mView != null; } @VisibleForTesting public TabCountProvider getIncognitoToggleTabCountProviderForTesting() { return mPropertyModel.get(StartSurfaceToolbarProperties.INCOGNITO_TAB_COUNT_PROVIDER); } }
4,794
348
{"nom":"Villedieu","circ":"4ème circonscription","dpt":"Vaucluse","inscrits":412,"abs":178,"votants":234,"blancs":20,"nuls":11,"exp":203,"res":[{"nuance":"REM","nom":"<NAME>","voix":136},{"nuance":"EXD","nom":"<NAME>","voix":67}]}
91
32,544
<reponame>zeesh49/tutorials<gh_stars>1000+ package com.baeldung.jackson.bidirection; import java.util.ArrayList; import java.util.List; public class User { public int id; public String name; public List<Item> userItems; public User() { super(); } public User(final int id, final String name) { this.id = id; this.name = name; userItems = new ArrayList<Item>(); } public void addItem(final Item item) { userItems.add(item); } }
213
2,881
package com.salesmanager.core.model.content; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.persistence.TableGenerator; import javax.persistence.UniqueConstraint; import com.salesmanager.core.constants.SchemaConstant; import com.salesmanager.core.model.common.description.Description; import com.salesmanager.core.model.reference.language.Language; @Entity @Table(name="CONTENT_DESCRIPTION",uniqueConstraints={ @UniqueConstraint(columnNames={ "CONTENT_ID", "LANGUAGE_ID" }) } ) @TableGenerator(name = "description_gen", table = "SM_SEQUENCER", pkColumnName = "SEQ_NAME", valueColumnName = "SEQ_COUNT", pkColumnValue = "content_description_seq", allocationSize = SchemaConstant.DESCRIPTION_ID_ALLOCATION_SIZE, initialValue = SchemaConstant.DESCRIPTION_ID_START_VALUE) //@SequenceGenerator(name = "description_gen", sequenceName = "content_description_seq", allocationSize = SchemaConstant.DESCRIPTION_ID_SEQUENCE_START) public class ContentDescription extends Description implements Serializable { /** * */ private static final long serialVersionUID = 1L; @ManyToOne(targetEntity = Content.class) @JoinColumn(name = "CONTENT_ID", nullable = false) private Content content; @Column(name="SEF_URL", length=120) private String seUrl; @Column(name="META_KEYWORDS") private String metatagKeywords; @Column(name="META_TITLE") private String metatagTitle; public String getMetatagTitle() { return metatagTitle; } public void setMetatagTitle(String metatagTitle) { this.metatagTitle = metatagTitle; } @Column(name="META_DESCRIPTION") private String metatagDescription; public ContentDescription() { } public ContentDescription(String name, Language language) { this.setName(name); this.setLanguage(language); super.setId(0L); } public Content getContent() { return content; } public void setContent(Content content) { this.content = content; } public String getSeUrl() { return seUrl; } public void setSeUrl(String seUrl) { this.seUrl = seUrl; } public String getMetatagKeywords() { return metatagKeywords; } public void setMetatagKeywords(String metatagKeywords) { this.metatagKeywords = metatagKeywords; } public String getMetatagDescription() { return metatagDescription; } public void setMetatagDescription(String metatagDescription) { this.metatagDescription = metatagDescription; } }
888
854
<filename>solutions/LeetCode/C++/458.cpp __________________________________________________________________________________________________ sample 4 ms submission class Solution { public: int poorPigs(int buckets, int minutesToDie, int minutesToTest) { int t = (minutesToTest - 1) / minutesToDie + 1; if (buckets == 1) return 0; return log(buckets - 1) / log(t + 1) + 1; } }; __________________________________________________________________________________________________ sample 8136 kb submission class Solution { public: int poorPigs(int buckets, int minutesToDie, int minutesToTest) { int matrix_size = minutesToTest / minutesToDie + 1; int num_dimensions = 0; while (pow(matrix_size, num_dimensions) < buckets) ++num_dimensions; return num_dimensions; } }; __________________________________________________________________________________________________
269
794
#include "game/actions/CGActionProgressTimer.h" #include "game/CGProgressTimer.h" NS_CC_BEGIN #define kProgressTimerCast CGProgressTimer* // implementation of ProgressTo ProgressTo* ProgressTo::create(float duration, float percent) { ProgressTo *progressTo = new (std::nothrow) ProgressTo(); progressTo->initWithDuration(duration, percent); progressTo->autorelease(); return progressTo; } bool ProgressTo::initWithDuration(float duration, float percent) { if (ActionInterval::initWithDuration(duration)) { _to = percent; return true; } return false; } ProgressTo* ProgressTo::clone() const { // no copy constructor auto a = new (std::nothrow) ProgressTo(); a->initWithDuration(_duration, _to); a->autorelease(); return a; } ProgressTo* ProgressTo::reverse() const { CCASSERT(false, "reverse() not supported in ProgressTo"); return nullptr; } void ProgressTo::startWithTarget(CGSprite *target) { ActionInterval::startWithTarget(target); _from = ((kProgressTimerCast)(target))->getPercentage(); } void ProgressTo::update(float time) { ((kProgressTimerCast)(_target))->setPercentage(_from + (_to - _from) * time); } // implementation of ProgressFromTo ProgressFromTo* ProgressFromTo::create(float duration, float fromPercentage, float toPercentage) { ProgressFromTo *progressFromTo = new (std::nothrow) ProgressFromTo(); progressFromTo->initWithDuration(duration, fromPercentage, toPercentage); progressFromTo->autorelease(); return progressFromTo; } bool ProgressFromTo::initWithDuration(float duration, float fromPercentage, float toPercentage) { if (ActionInterval::initWithDuration(duration)) { _to = toPercentage; _from = fromPercentage; return true; } return false; } ProgressFromTo* ProgressFromTo::clone() const { // no copy constructor auto a = new (std::nothrow) ProgressFromTo(); a->initWithDuration(_duration, _from, _to); a->autorelease(); return a; } ProgressFromTo* ProgressFromTo::reverse() const { return ProgressFromTo::create(_duration, _to, _from); } void ProgressFromTo::startWithTarget(CGSprite *target) { ActionInterval::startWithTarget(target); } void ProgressFromTo::update(float time) { ((kProgressTimerCast)(_target))->setPercentage(_from + (_to - _from) * time); } NS_CC_END
839
2,542
/*++ (c) 2010 by Microsoft Corp. All Rights Reserved. ktlbase.cpp Description: Kernel Tempate Library (KTL) Implements global allocators and other system-wide entry points. History: raymcc 20-Aug-2010 Initial version. --*/ #include <ktl.h> // // Global data structures used by KSystem. // //* Grandfathered KtlSystemDefaultImp imp - may be removed class KtlSystemImp : public KtlSystemBase { public: static NTSTATUS Create( __out KtlSystemImp*& ResultSystem ); FAILABLE KtlSystemImp() : KtlSystemBase(KGuid()) { } ~KtlSystemImp() { } VOID Delete(__in ULONG TimeoutInMs = 5000); #if KTL_USER_MODE static KGlobalSpinLockStorage gs_GrandFatheredSingletonLock; #endif BOOLEAN _EnableVNetworking; }; KtlSystemImp* GrandFatheredKtlSystemSingleton = nullptr; #if KTL_USER_MODE KGlobalSpinLockStorage KtlSystemImp::gs_GrandFatheredSingletonLock; #endif NTSTATUS KtlSystemImp::Create( __out KtlSystemImp*& ResultSystem ) { ResultSystem = nullptr; ResultSystem = (KtlSystemImp*)ExAllocatePoolWithTag( #if KTL_USER_MODE // // Initial KTLSystem is created in the process heap - all other allocations are made in the // heap associated with KtlSystem. This heap is created in the KtlSystemBase constructor. // GetProcessHeap(), #endif NonPagedPool, sizeof(KtlSystemImp), KTL_TAG_BASE); NTSTATUS status; if (ResultSystem == nullptr) { status = STATUS_INSUFFICIENT_RESOURCES; } else { ResultSystem->KtlSystemImp::KtlSystemImp(); status = ResultSystem->Status(); if (!NT_SUCCESS(status)) { ResultSystem->KtlSystemImp::~KtlSystemImp(); #if KTL_USER_MODE ExFreePool( GetProcessHeap(), ResultSystem); #else ExFreePool(ResultSystem); #endif ResultSystem = nullptr; } else { // Grandfathered behavior ResultSystem->SetStrictAllocationChecks(FALSE); ResultSystem->Activate(KtlSystem::InfiniteTime); status = ResultSystem->Status(); if (!NT_SUCCESS(status)) { ResultSystem->Delete(); ResultSystem = nullptr; } } } return status; } VOID KtlSystemImp::Delete( __in ULONG TimeoutInMs ) { ULONG timeout = this->GetStrictAllocationChecks() ? TimeoutInMs : KtlSystem::InfiniteTime; this->Deactivate(timeout); this->KtlSystemImp::~KtlSystemImp(); #if KTL_USER_MODE ExFreePool( GetProcessHeap(), this); #else ExFreePool(this); #endif } NTSTATUS KtlSystem::Initialize( __in BOOLEAN EnableVNetworking, __out_opt KtlSystem* *const OptResultSystem ) { KFatal(GrandFatheredKtlSystemSingleton == nullptr); NTSTATUS status = KtlSystemImp::Create(GrandFatheredKtlSystemSingleton); if (!NT_SUCCESS(status)) { return status; } if (OptResultSystem != nullptr) { *OptResultSystem = GrandFatheredKtlSystemSingleton; } #if !defined(PLATFORM_UNIX) if (EnableVNetworking) { status = VNetwork::Startup(GlobalNonPagedAllocator()); } #endif GrandFatheredKtlSystemSingleton->_EnableVNetworking = EnableVNetworking; return status; } NTSTATUS KtlSystem::Initialize( __out_opt KtlSystem* *const OptResultSystem ) { return Initialize(TRUE, OptResultSystem); } VOID KtlSystem::Shutdown( __in ULONG TimeoutInMs ) { if (GrandFatheredKtlSystemSingleton != nullptr) { #if !defined(PLATFORM_UNIX) if (GrandFatheredKtlSystemSingleton->_EnableVNetworking) { VNetwork::Shutdown(); } #endif GrandFatheredKtlSystemSingleton->Delete(TimeoutInMs); GrandFatheredKtlSystemSingleton = nullptr; } } KtlSystem& KtlSystem::GetDefaultKtlSystem() { KAssert(GrandFatheredKtlSystemSingleton != nullptr); return *GrandFatheredKtlSystemSingleton; }
1,920
14,668
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/sync_device_info/device_count_metrics_provider.h" #include <algorithm> #include <map> #include <vector> #include "base/metrics/histogram_functions.h" #include "components/sync/protocol/sync_enums.pb.h" #include "components/sync_device_info/device_info_tracker.h" namespace syncer { using DeviceType = sync_pb::SyncEnums::DeviceType; DeviceCountMetricsProvider::DeviceCountMetricsProvider( const ProvideTrackersCallback& provide_trackers) : provide_trackers_(provide_trackers) {} DeviceCountMetricsProvider::~DeviceCountMetricsProvider() = default; void DeviceCountMetricsProvider::ProvideCurrentSessionData( metrics::ChromeUserMetricsExtension* uma_proto) { std::vector<const DeviceInfoTracker*> trackers; provide_trackers_.Run(&trackers); int max_total = 0; int max_desktop_count = 0; int max_phone_count = 0; int max_tablet_count = 0; for (auto* tracker : trackers) { std::map<DeviceType, int> count_by_type = tracker->CountActiveDevicesByType(); int total_devices = 0; int desktop_count = 0; int phone_count = 0; int tablet_count = 0; for (const auto& device_type_and_count : count_by_type) { total_devices += device_type_and_count.second; switch (device_type_and_count.first) { case sync_pb::SyncEnums_DeviceType_TYPE_CROS: case sync_pb::SyncEnums_DeviceType_TYPE_LINUX: case sync_pb::SyncEnums_DeviceType_TYPE_MAC: case sync_pb::SyncEnums_DeviceType_TYPE_WIN: desktop_count += device_type_and_count.second; break; case sync_pb::SyncEnums_DeviceType_TYPE_PHONE: phone_count += device_type_and_count.second; break; case sync_pb::SyncEnums_DeviceType_TYPE_TABLET: tablet_count += device_type_and_count.second; break; case sync_pb::SyncEnums_DeviceType_TYPE_OTHER: case sync_pb::SyncEnums_DeviceType_TYPE_UNSET: break; } } max_total = std::max(max_total, total_devices); max_desktop_count = std::max(max_desktop_count, desktop_count); max_phone_count = std::max(max_phone_count, phone_count); max_tablet_count = std::max(max_tablet_count, tablet_count); } base::UmaHistogramSparse("Sync.DeviceCount2", std::min(max_total, 100)); base::UmaHistogramSparse("Sync.DeviceCount2.Desktop", std::min(max_desktop_count, 100)); base::UmaHistogramSparse("Sync.DeviceCount2.Phone", std::min(max_phone_count, 100)); base::UmaHistogramSparse("Sync.DeviceCount2.Tablet", std::min(max_tablet_count, 100)); } } // namespace syncer
1,136
421
// System::Net::WebClient::OpenRead /* This program demonstrates the 'OpenRead' method of 'WebClient' class. It creates a URI to access a web resource. It then invokes 'OpenRead' tp obtain a 'Stream' instance which is used to retrieve the web page data. The data read from the stream is then displayed on the console. */ #using <System.dll> using namespace System; using namespace System::Net; using namespace System::IO; int main() { try { Console::Write( "\nPlease enter a URI (e.g. http://www.contoso.com): " ); String^ uriString = Console::ReadLine(); // <Snippet1> // Create a new WebClient instance. WebClient^ myWebClient = gcnew WebClient; // Download home page data. Console::WriteLine( "Accessing {0} ...", uriString ); // Open a stream to point to the data stream coming from the Web resource. Stream^ myStream = myWebClient->OpenRead( uriString ); Console::WriteLine( "\nDisplaying Data :\n" ); StreamReader^ sr = gcnew StreamReader( myStream ); Console::WriteLine( sr->ReadToEnd() ); // Close the stream. myStream->Close(); // </Snippet1> } catch ( WebException^ e ) { // Display the exception. Console::WriteLine( "Webresource access failed!!! WebException : {0}", e->Message ); } catch ( Exception^ e ) { // Display the exception. Console::WriteLine( "The following general exception was raised: {0}", e->Message ); } }
572
423
""" ============================================================================== Code for builder of a dynamic linear model ============================================================================== This piece of code provides the basic functionality for constructing the model of a dlm. It allows flexible modeling by users. User can add to, delete and view componets of a given dlm. Builder will finally assemble all the components to a final big model. """ # this class provide all the model building operations for constructing # customized model import numpy as np from pydlm.base.baseModel import baseModel from copy import deepcopy from pydlm.modeler.matrixTools import matrixTools as mt # The builder will be the main class for construting dlm # it featues two types of evaluation matrix and evaluation matrix # The static evaluation remains the same over time which is used to # record the trend and seasonality. # # The dynamic evaluation vector changes over time, it is basically # the other variables that might have impact on the time series # We need to update this vector as time going forward class builder: """ The main modeling part of a dynamic linear model. It allows the users to custemize their own model. User can add, delete any components like trend or seasonality to the builder, or view the existing components. Builder will finally assemble all components to a big model for further training and inference. Attributes: model: the model structure from @baseModel, stores all the necessary quantities initialized: indicates whether the model has been built staticComponents: stores all the static components (trend and seasonality) dynamicComponents: stores all the dynamic components componentIndex: the location of each component in the latent states statePrior: the prior mean of the latent state sysVarPrior: the prior of the covariance of the latent states noiseVar: the prior of the observation noise initialDegreeFreedom: the initial degree of freedom. discount: the discounting factor, please refer to @kalmanFilter for more details renewTerm: used for aiding the stability of the model. The renewTerm is computed according to the discount fact. When the filter goes over certain steps, the information contribution of the previous data has decayed to minimum. We then ignore those days and refit the time series starting from current - renewTerm. Thus, the effective sample size of the dlm is twice renewTerm. When discount = 1, there will be no renewTerm, since all the information will be passed along. renewDiscount: the minimum discount of seasonality component, or if there is no seasonality, this will be the minimum discount of all components. Used for computing renewTerm. Methods: add: add new component ls: list out all components delete: delete a specific component by its name initialize: assemble all the component to construt a big model updateEvaluation: update the valuation matrix of the big model """ # create members def __init__(self): # the basic model structure for running kalman filter self.model = None self.initialized = False # to store all components. Separate the two as the evaluation # for dynamic component needs update each iteration # (new) added the third category, which is dynamic but the # features can be automatically computed from the data # store all the static components, i.e., the evaluation vector # do not change over time self.staticComponents = {} # store all the dynamic components, i.e., the evaluation vector # changes over time self.dynamicComponents = {} # store all the components that are dynamic, but the evaluation # vector can be inferred directly from the main data instead # of other sources self.automaticComponents = {} # store the index (location in the latent states) of all components # can be used to extract information for each componnet self.componentIndex = {} # record the prior guess on the latent state and system covariance self.statePrior = None self.sysVarPrior = None self.noiseVar = None self.initialDegreeFreedom = 1 # record the discount factor for the model self.discount = None # renew term used to indicate the effective length of data, i.e., # for days before this length will have little impact on # the current result self.renewTerm = -1.0 self.renewDiscount = None # used for adjusting renewTerm # flag for determining whether the system info should be printed. self._printInfo = True # The function that allows the user to add components def add(self, component): """ Add a new model component to the builder. Args: component: a model component, any class implements @component class """ self.__add__(component) def __add__(self, component): if component.componentType == 'dynamic': if component.name in self.dynamicComponents: raise NameError('Please rename the component to a' + ' different name.') self.dynamicComponents[component.name] = component if component.componentType == 'autoReg' \ or component.componentType == 'longSeason': if component.name in self.automaticComponents: raise NameError('Please rename the component to a' + ' different name.') self.automaticComponents[component.name] = component if component.componentType == 'trend' \ or component.componentType == 'seasonality': if component.name in self.staticComponents: raise NameError('Please rename the component' + ' to a different name.') self.staticComponents[component.name] = component # we use seasonality's discount to adjust the renewTerm if component.componentType == 'seasonality': if self.renewDiscount is None: self.renewDiscount = 1.0 self.renewDiscount = min(self.renewDiscount, min(component.discount)) self.initialized = False return self # print all components to the client def ls(self): """ List out all the existing components to the model """ if len(self.staticComponents) > 0: print('The static components are') for name in self.staticComponents: comp = self.staticComponents[name] print(comp.name + ' (degree = ' + str(comp.d) + ')') print(' ') else: print('There is no static component.') print(' ') if len(self.dynamicComponents) > 0: print('The dynamic components are') for name in self.dynamicComponents: comp = self.dynamicComponents[name] print(comp.name + ' (dimension = ' + str(comp.d) + ')') print(' ') else: print('There is no dynamic component.') print(' ') if len(self.automaticComponents) > 0: print('The automatic components are') for name in self.automaticComponents: comp = self.automaticComponents[name] print(comp.name + ' (dimension = ' + str(comp.d) + ')') else: print('There is no automatic component.') # delete the componet that pointed out by the client def delete(self, name): """ Delete a specific component from dlm by its name. Args: name: the name of the component. Can be read from ls() """ if name in self.staticComponents: del self.staticComponents[name] elif name in self.dynamicComponents: del self.dynamicComponents[name] elif name in self.automaticComponents: del self.automaticComponents[name] else: raise NameError('Such component does not exisit!') self.initialized = False # initialize model for all the quantities # noise is the prior guess of the variance of the observed data # data is used by auto regressor. def initialize(self, data=[], noise=1): """ Initialize the model. It construct the baseModel by assembling all quantities from the components. Args: noise: the initial guess of the variance of the observation noise. """ if len(self.staticComponents) == 0 and \ len(self.dynamicComponents) == 0 and \ len(self.automaticComponents) == 0: raise NameError('The model must contain at least' + ' one component') # construct transition, evaluation, prior state, prior covariance if self._printInfo: print('Initializing models...') transition = None evaluation = None state = None sysVar = None self.discount = np.array([]) # first construct for the static components # the evaluation will be treated separately for static or dynamic # as the latter one will change over time currentIndex = 0 # used for compute the index for i in self.staticComponents: comp = self.staticComponents[i] transition = mt.matrixAddInDiag(transition, comp.transition) evaluation = mt.matrixAddByCol(evaluation, comp.evaluation) state = mt.matrixAddByRow(state, comp.meanPrior) sysVar = mt.matrixAddInDiag(sysVar, comp.covPrior) self.discount = np.concatenate((self.discount, comp.discount)) self.componentIndex[i] = (currentIndex, currentIndex + comp.d - 1) currentIndex += comp.d # if the model contains the dynamic part, we add the dynamic components if len(self.dynamicComponents) > 0: self.dynamicEvaluation = None for i in self.dynamicComponents: comp = self.dynamicComponents[i] comp.updateEvaluation(0) transition = mt.matrixAddInDiag(transition, comp.transition) evaluation = mt.matrixAddByCol(evaluation, comp.evaluation) state = mt.matrixAddByRow(state, comp.meanPrior) sysVar = mt.matrixAddInDiag(sysVar, comp.covPrior) self.discount = np.concatenate((self.discount, comp.discount)) self.componentIndex[i] = (currentIndex, currentIndex + comp.d - 1) currentIndex += comp.d # if the model contains the automatic dynamic part, we add # them to the builder if len(self.automaticComponents) > 0: self.automaticEvaluation = None for i in self.automaticComponents: comp = self.automaticComponents[i] comp.updateEvaluation(0, data) transition = mt.matrixAddInDiag(transition, comp.transition) evaluation = mt.matrixAddByCol(evaluation, comp.evaluation) state = mt.matrixAddByRow(state, comp.meanPrior) sysVar = mt.matrixAddInDiag(sysVar, comp.covPrior) self.discount = np.concatenate((self.discount, comp.discount)) self.componentIndex[i] = (currentIndex, currentIndex + comp.d - 1) currentIndex += comp.d self.statePrior = state self.sysVarPrior = sysVar self.noiseVar = np.matrix(noise) self.model = baseModel(transition=transition, evaluation=evaluation, noiseVar=np.matrix(noise), sysVar=sysVar, state=state, df=self.initialDegreeFreedom) self.model.initializeObservation() # compute the renew period if self.renewDiscount is None: self.renewDiscount = np.min(self.discount) if self.renewDiscount < 1.0 - 1e-8: self.renewTerm = np.log(0.001 * (1 - self.renewDiscount)) \ / np.log(self.renewDiscount) self.initialized = True if self._printInfo: print('Initialization finished.') # Initialize from another builder exported from other dlm class def initializeFromBuilder(self, data, exported_builder): # Copy the components self.staticComponents = deepcopy(exported_builder.staticComponents) self.automaticComponents = deepcopy(exported_builder.automaticComponents) self.dynamicComponents = deepcopy(exported_builder.dynamicComponents) self.componentIndex = deepcopy(exported_builder.componentIndex) self.discount = deepcopy(exported_builder.discount) self.initialDegreeFreedom = exported_builder.model.df # Copy the model states self.statePrior = deepcopy(exported_builder.statePrior) self.sysVarPrior = deepcopy(exported_builder.sysVarPrior) self.noiseVar = deepcopy(exported_builder.noiseVar) self.model = deepcopy(exported_builder.model) # update the evaluation to the current. self.updateEvaluation(step=0, data=data) self.model.initializeObservation() # compute the renew period if self.renewDiscount is None: self.renewDiscount = np.min(self.discount) if self.renewDiscount < 1.0 - 1e-8: self.renewTerm = np.log(0.001 * (1 - self.renewDiscount)) \ / np.log(self.renewDiscount) self.initialized = True if self._printInfo: print('Initialization finished.') # This function allows the model to update the dynamic evaluation vector, # so that the model can handle control variables # This function should be called only when dynamicComponents is not empty # data is used by auto regressor. def updateEvaluation(self, step, data): """ Update the evaluation matrix of the model to a specific date. It loops over all dynamic components and update their evaluation matrix and then reconstruct the model evaluation matrix by incorporating the new evaluations Arges: step: the date at which the evaluation matrix is needed. """ # if len(self.dynamicComponents) == 0 and \ # len(self.automaticComponents) == 0: # raise NameError('This shall only be used when there' + # ' are dynamic or automatic components!') # update the dynamic evaluation vector # We need first update all dynamic components by 1 step for i in self.dynamicComponents: comp = self.dynamicComponents[i] comp.updateEvaluation(step) self.model.evaluation[0, self.componentIndex[i][0]: (self.componentIndex[i][1] + 1)] = comp.evaluation for i in self.automaticComponents: comp = self.automaticComponents[i] comp.updateEvaluation(step, data) self.model.evaluation[0, self.componentIndex[i][0]: (self.componentIndex[i][1] + 1)] = comp.evaluation
6,598
5,166
<filename>javav2/example_code/personalize/src/main/java/com/example/personalize/FilterRecommendations.java<gh_stars>1000+ //snippet-sourcedescription:[FilterRecommendations.java demonstrates how use a filter when requesting recommendations] //snippet-keyword:[AWS SDK for Java v2] //snippet-keyword:[Code Sample] //snippet-service:[Amazon Personalize] //snippet-sourcetype:[full-example] //snippet-sourcedate:[7/13/2021] //snippet-sourceauthor:[seashman - AWS] /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package com.example.personalize; //snippet-start:[personalize.java2.filter_recommendations.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.personalizeruntime.model.PersonalizeRuntimeException; import software.amazon.awssdk.services.personalizeruntime.PersonalizeRuntimeClient; import software.amazon.awssdk.services.personalizeruntime.model.GetRecommendationsRequest; import software.amazon.awssdk.services.personalizeruntime.model.GetRecommendationsResponse; import software.amazon.awssdk.services.personalizeruntime.model.PredictedItem; import java.util.HashMap; import java.util.List; import java.util.Map; //snippet-end:[personalize.java2.filter_recommendations.import] /** * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. * * For information, see this documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class FilterRecommendations { public static void main(String[] args) { // This example shows how to use a filter with an expression that has // two placeholder parameters, and passes two values to the first and one to the second. // in the GetRecommendations request. // Your filter may not have the same number of parameters or you may not want to use two values. // Change the following code and the PersonalizeTest.java code based on the number of parameters // your expression uses and the values you want to pass. final String USAGE = "\n" + "Usage:\n" + " GetRecommendations <campaignArn> <userId> <filterArn> <parameter1Name> " + " <parameter1Value1> <parameter1Value2> <parameter2Name> <parameter2Value>\n\n" + "Where:\n" + " campaignArn - The Amazon Resource Name (ARN) of the campaign.\n\n" + " userId - The user ID to provide recommendations for." + " filterArn - The ARN of the filter to use." + " parameter1Name - The name of the first placeholder parameter in the filter." + " parameter1Value1 - The first value to pass to the first parameter." + " parameter1Value2 - The second value to pass to the first parameter." + " parameter2Name = The name of the second placeholder parameter in the filter." + " parameter2Value = The value to pass to the second parameter\n\n"; if (args.length != 8) { System.out.println(USAGE); System.exit(1); } String campaignArn = args[0]; String userId = args[1]; String filterArn = args[2]; String parameter1Name = args[3]; String parameter1Value1 = args[4]; String parameter1Value2 = args[5]; String parameter2Name = args[6]; String parameter2Value = args[7]; Region region = Region.US_EAST_1; PersonalizeRuntimeClient personalizeRuntimeClient = PersonalizeRuntimeClient.builder() .region(region) .build(); getFilteredRecs(personalizeRuntimeClient, campaignArn, userId, filterArn, parameter1Name, parameter1Value1, parameter1Value2, parameter2Name, parameter2Value); personalizeRuntimeClient.close(); } //snippet-start:[personalize.java2.filter_recommendations.main] public static void getFilteredRecs(PersonalizeRuntimeClient personalizeRuntimeClient, String campaignArn, String userId, String filterArn, String parameter1Name, String parameter1Value1, String parameter1Value2, String parameter2Name, String parameter2Value){ try { Map<String, String> filterValues = new HashMap<>(); filterValues.put(parameter1Name, String.format("\"%1$s\",\"%2$s\"", parameter1Value1, parameter1Value2)); filterValues.put(parameter2Name, String.format("\"%1$s\"", parameter2Value)); GetRecommendationsRequest recommendationsRequest = GetRecommendationsRequest.builder() .campaignArn(campaignArn) .numResults(20) .userId(userId) .filterArn(filterArn) .filterValues(filterValues) .build(); GetRecommendationsResponse recommendationsResponse = personalizeRuntimeClient.getRecommendations(recommendationsRequest); List<PredictedItem> items = recommendationsResponse.itemList(); for (PredictedItem item: items) { System.out.println("Item Id is : "+item.itemId()); System.out.println("Item score is : "+item.score()); } } catch (PersonalizeRuntimeException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } //snippet-end:[personalize.java2.filter_recommendations.main] }
2,475
333
<filename>src/main/java/com/alipay/api/response/AlipayCommerceOperationPointHistoryQueryResponse.java package com.alipay.api.response; import java.util.List; import com.alipay.api.internal.mapping.ApiField; import com.alipay.api.internal.mapping.ApiListField; import com.alipay.api.domain.PointLogInfo; import com.alipay.api.AlipayResponse; /** * ALIPAY API: alipay.commerce.operation.point.history.query response. * * @author auto create * @since 1.0, 2021-10-09 11:20:33 */ public class AlipayCommerceOperationPointHistoryQueryResponse extends AlipayResponse { private static final long serialVersionUID = 6311464953231821914L; /** * 是否存在下一页 */ @ApiField("has_next_page") private Boolean hasNextPage; /** * 分页数 */ @ApiField("page_number") private Long pageNumber; /** * 积分明细 */ @ApiField("point_amount") private Long pointAmount; /** * 详细数据 */ @ApiListField("point_log_list") @ApiField("point_log_info") private List<PointLogInfo> pointLogList; /** * 总分页数 */ @ApiField("total_pages") private Long totalPages; /** * 总数 */ @ApiField("total_size") private Long totalSize; public void setHasNextPage(Boolean hasNextPage) { this.hasNextPage = hasNextPage; } public Boolean getHasNextPage( ) { return this.hasNextPage; } public void setPageNumber(Long pageNumber) { this.pageNumber = pageNumber; } public Long getPageNumber( ) { return this.pageNumber; } public void setPointAmount(Long pointAmount) { this.pointAmount = pointAmount; } public Long getPointAmount( ) { return this.pointAmount; } public void setPointLogList(List<PointLogInfo> pointLogList) { this.pointLogList = pointLogList; } public List<PointLogInfo> getPointLogList( ) { return this.pointLogList; } public void setTotalPages(Long totalPages) { this.totalPages = totalPages; } public Long getTotalPages( ) { return this.totalPages; } public void setTotalSize(Long totalSize) { this.totalSize = totalSize; } public Long getTotalSize( ) { return this.totalSize; } }
899
471
package com.dtflys.test.mock; import org.mockserver.client.server.MockServerClient; import org.mockserver.junit.MockServerRule; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.response; /** * @author gongjun[<EMAIL>] * @since 2017-05-17 16:08 */ public class OAuth2MockServer extends MockServerRule { public final static String EXPECTED = "{\"status\": \"ok\"}"; public final static String TOKEN = "<KEY>"; public final static String TOKEN_JSON = "{" + "\"access_token\": \"" + TOKEN + "\"," + "\"expires_in\": \"1\"" + "}"; public final static String DEFINITION_TOKEN_JSON = "{\"token\":\"" + TOKEN + "\"}"; public final static Integer port = 5071; public OAuth2MockServer(Object target) { super(target, port); } public void initServer() { MockServerClient mockClient = new MockServerClient("localhost", port); mockClient.when( request() .withPath("/auth/oauth/token") .withMethod("POST") .withBody("client_id=password&client_secret=123456&scope=any&grant_type=password&username=root&password=<PASSWORD>") ).respond( response() .withStatusCode(200) .withBody(TOKEN_JSON) ); mockClient.when( request() .withPath("/auth/test/password") .withMethod("GET") .withHeader("Authorization", "Bearer " + TOKEN) ).respond( response() .withStatusCode(200) .withBody(EXPECTED) ); mockClient.when( request() .withPath("/auth/test/password_at_url") .withMethod("GET") .withQueryStringParameter("access_token", TOKEN) ).respond( response() .withStatusCode(200) .withBody(EXPECTED) ); mockClient.when( request() .withPath("/auth/oauth/client_credentials/token") .withMethod("POST") .withBody("client_id=client_credentials&client_secret=123456&scope=any&grant_type=client_credentials") ).respond( response() .withStatusCode(200) .withBody(TOKEN_JSON) ); mockClient.when( request() .withPath("/auth/test/client_credentials") .withMethod("GET") .withHeader("Authorization", "Bearer " + TOKEN) ).respond( response() .withStatusCode(200) .withBody(EXPECTED) ); mockClient.when( request() .withPath("/auth/test/client_credentials_at_url") .withMethod("GET") .withQueryStringParameter("access_token", TOKEN) ).respond( response() .withStatusCode(200) .withBody(EXPECTED) ); mockClient.when( request() .withPath("/auth/oauth/token/definition") .withMethod("POST") .withBody("client_id=password&client_secret=123456&scope=any&grant_type=password&username=root&password=<PASSWORD>") ).respond( response() .withStatusCode(200) .withBody(DEFINITION_TOKEN_JSON) ); } }
2,181
628
<gh_stars>100-1000 /* $info$ tags: ir|opts $end_info$ */ #include <FEXCore/Utils/BucketList.h> #include "Common/MathUtils.h" #include "Interface/IR/Passes/RegisterAllocationPass.h" #include "Interface/IR/Passes.h" #include <FEXCore/Core/CoreState.h> #include <FEXCore/Core/SignalDelegator.h> #include <FEXCore/IR/IR.h> #include <FEXCore/IR/IREmitter.h> #include <FEXCore/IR/IntrusiveIRList.h> #include <FEXCore/IR/RegisterAllocationData.h> #include <FEXCore/Utils/LogManager.h> #include <algorithm> #include <cstdint> #include <set> #include <stddef.h> #include <string.h> #include <strings.h> #include <unordered_map> #include <unordered_set> #include <utility> #include <vector> #define SRA_DEBUG(...) // printf(__VA_ARGS__) namespace { using FEXCore::IR::PhysicalRegister; constexpr uint32_t INVALID_REG = FEXCore::IR::InvalidReg; constexpr uint32_t INVALID_CLASS = FEXCore::IR::InvalidClass.Val; constexpr uint32_t DEFAULT_INTERFERENCE_LIST_COUNT = 122; constexpr uint32_t DEFAULT_INTERFERENCE_SPAN_COUNT = 30; constexpr uint32_t DEFAULT_NODE_COUNT = 8192; struct Register { bool Virtual; uint64_t Index; }; struct RegisterClass { uint32_t CountMask; uint32_t PhysicalCount; }; struct RegisterNode { struct VolatileHeader { uint32_t BlockID; uint32_t SpillSlot; RegisterNode *PhiPartner; } Head { ~0U, ~0U, nullptr }; FEXCore::BucketList<DEFAULT_INTERFERENCE_LIST_COUNT, uint32_t> Interferences; }; static_assert(sizeof(RegisterNode) == 128 * 4); constexpr size_t REGISTER_NODES_PER_PAGE = FEXCore::Core::PAGE_SIZE / sizeof(RegisterNode); struct RegisterSet { std::vector<RegisterClass> Classes; uint32_t ClassCount; uint32_t Conflicts[ 8 * 8 * 32 * 32]; }; struct LiveRange { uint32_t Begin{~0U}; uint32_t End{~0U}; uint32_t RematCost{0}; uint32_t PreWritten{0}; PhysicalRegister PrefferedRegister{PhysicalRegister::Invalid()}; bool Written{false}; bool Global{false}; }; struct SpillStackUnit { uint32_t Node; FEXCore::IR::RegisterClassType Class; LiveRange SpillRange; FEXCore::IR::OrderedNode *SpilledNode; }; struct RegisterGraph { std::unique_ptr<FEXCore::IR::RegisterAllocationData, FEXCore::IR::RegisterAllocationDataDeleter> AllocData; RegisterSet Set; std::vector<RegisterNode> Nodes{}; uint32_t NodeCount{}; std::vector<SpillStackUnit> SpillStack; std::unordered_map<uint32_t, std::unordered_set<uint32_t>> BlockPredecessors; std::unordered_map<uint32_t, std::unordered_set<uint32_t>> VisitedNodePredecessors; }; void ResetRegisterGraph(RegisterGraph *Graph, uint64_t NodeCount); RegisterGraph *AllocateRegisterGraph(uint32_t ClassCount) { RegisterGraph *Graph = new RegisterGraph{}; // Allocate the register set Graph->Set.ClassCount = ClassCount; Graph->Set.Classes.resize(ClassCount); // Allocate default nodes ResetRegisterGraph(Graph, DEFAULT_NODE_COUNT); return Graph; } void AllocatePhysicalRegisters(RegisterGraph *Graph, FEXCore::IR::RegisterClassType Class, uint32_t Count) { Graph->Set.Classes[Class].CountMask = (1 << Count) - 1; Graph->Set.Classes[Class].PhysicalCount = Count; } void SetConflict(RegisterGraph *Graph, PhysicalRegister RegAndClass, PhysicalRegister ConflictRegAndClass) { uint32_t Index = (ConflictRegAndClass.Class << 8) | RegAndClass.Raw; Graph->Set.Conflicts[Index] |= 1 << ConflictRegAndClass.Reg; } uint32_t GetConflicts(RegisterGraph *Graph, PhysicalRegister RegAndClass, FEXCore::IR::RegisterClassType ConflictClass) { uint32_t Index = (ConflictClass.Val << 8) | RegAndClass.Raw; return Graph->Set.Conflicts[Index]; } void VirtualAddRegisterConflict(RegisterGraph *Graph, FEXCore::IR::RegisterClassType ClassConflict, uint32_t RegConflict, FEXCore::IR::RegisterClassType Class, uint32_t Reg) { auto RegAndClass = PhysicalRegister(Class, Reg); auto RegAndClassConflict = PhysicalRegister(ClassConflict, RegConflict); // Conflict must go both ways SetConflict(Graph, RegAndClass, RegAndClassConflict); SetConflict(Graph, RegAndClassConflict, RegAndClass); } void FreeRegisterGraph(RegisterGraph *Graph) { delete Graph; } void ResetRegisterGraph(RegisterGraph *Graph, uint64_t NodeCount) { NodeCount = AlignUp(NodeCount, REGISTER_NODES_PER_PAGE); // Clear to free the Bucketlists which have unique_ptrs // Resize to our correct size Graph->Nodes.clear(); Graph->Nodes.resize(NodeCount); Graph->VisitedNodePredecessors.clear(); Graph->AllocData.reset((FEXCore::IR::RegisterAllocationData*)FEXCore::Allocator::malloc(FEXCore::IR::RegisterAllocationData::Size(NodeCount))); memset(&Graph->AllocData->Map[0], PhysicalRegister::Invalid().Raw, NodeCount); Graph->AllocData->MapCount = NodeCount; Graph->AllocData->IsShared = false; // not shared by default Graph->NodeCount = NodeCount; } void SetNodeClass(RegisterGraph *Graph, uint32_t Node, FEXCore::IR::RegisterClassType Class) { Graph->AllocData->Map[Node].Class = Class.Val; } void SetNodePartner(RegisterGraph *Graph, uint32_t Node, uint32_t Partner) { Graph->Nodes[Node].Head.PhiPartner = &Graph->Nodes[Partner]; } #if 0 bool IsConflict(RegisterGraph *Graph, PhysicalRegister RegAndClass, PhysicalRegister ConflictRegAndClass) { uint32_t Index = (ConflictRegAndClass.Class << 8) | RegAndClass.Raw; return (Graph->Set.Conflicts[Index] >> ConflictRegAndClass.Reg) & 1; } // PHI nodes currently unsupported /** * @brief Individual node interference check */ bool DoesNodeInterfereWithRegister(RegisterGraph *Graph, RegisterNode const *Node, PhysicalRegister RegAndClass) { // Walk the node's interference list and see if it interferes with this register return Node->Interferences.Find([Graph, RegAndClass](uint32_t InterferenceNodeId) { auto InterferenceRegAndClass = Graph->AllocData->Map[InterferenceNodeId]; return IsConflict(Graph, InterferenceRegAndClass, RegAndClass); }); } /** * @brief Node set walking for PHI node interference checking */ bool DoesNodeSetInterfereWithRegister(RegisterGraph *Graph, std::vector<RegisterNode*> const &Nodes, PhysicalRegister RegAndClass) { for (auto it : Nodes) { if (DoesNodeInterfereWithRegister(Graph, it, RegAndClass)) { return true; } } return false; } #endif FEXCore::IR::RegisterClassType GetRegClassFromNode(FEXCore::IR::IRListView *IR, FEXCore::IR::IROp_Header *IROp) { using namespace FEXCore; FEXCore::IR::RegisterClassType Class = IR::GetRegClass(IROp->Op); if (Class != FEXCore::IR::ComplexClass) return Class; // Complex register class handling switch (IROp->Op) { case IR::OP_LOADCONTEXT: { auto Op = IROp->C<IR::IROp_LoadContext>(); return Op->Class; break; } case IR::OP_LOADREGISTER: { auto Op = IROp->C<IR::IROp_LoadRegister>(); return Op->Class; break; } case IR::OP_LOADCONTEXTINDEXED: { auto Op = IROp->C<IR::IROp_LoadContextIndexed>(); return Op->Class; break; } case IR::OP_LOADMEM: case IR::OP_LOADMEMTSO: { auto Op = IROp->C<IR::IROp_LoadMem>(); return Op->Class; break; } case IR::OP_FILLREGISTER: { auto Op = IROp->C<IR::IROp_FillRegister>(); return Op->Class; break; } case IR::OP_PHIVALUE: { // Unwrap the PHIValue to get the class auto Op = IROp->C<IR::IROp_PhiValue>(); return GetRegClassFromNode(IR, IR->GetOp<IR::IROp_Header>(Op->Value)); } case IR::OP_PHI: { // Class is defined from the values passed in // All Phi nodes should have its class be the same (Validation should confirm this auto Op = IROp->C<IR::IROp_Phi>(); return GetRegClassFromNode(IR, IR->GetOp<IR::IROp_Header>(Op->PhiBegin)); } default: break; } // Unreachable return FEXCore::IR::InvalidClass; }; // Walk the IR and set the node classes void FindNodeClasses(RegisterGraph *Graph, FEXCore::IR::IRListView *IR) { for (auto [CodeNode, IROp] : IR->GetAllCode()) { // If the destination hasn't yet been set then set it now if (IROp->HasDest) { Graph->AllocData->Map[IR->GetID(CodeNode)] = PhysicalRegister(GetRegClassFromNode(IR, IROp), INVALID_REG); } else { //Graph->AllocData->Map[IR->GetID(CodeNode)] = PhysicalRegister::Invalid(); } } } } namespace FEXCore::IR { class ConstrainedRAPass final : public RegisterAllocationPass { public: ConstrainedRAPass(FEXCore::IR::Pass* _CompactionPass, bool OptimizeSRA); ~ConstrainedRAPass(); bool Run(IREmitter *IREmit) override; void AllocateRegisterSet(uint32_t RegisterCount, uint32_t ClassCount) override; void AddRegisters(FEXCore::IR::RegisterClassType Class, uint32_t RegisterCount) override; void AddRegisterConflict(FEXCore::IR::RegisterClassType ClassConflict, uint32_t RegConflict, FEXCore::IR::RegisterClassType Class, uint32_t Reg) override; /** * @brief Returns the register and class encoded together * Top 32bits is the class, lower 32bits is the register */ RegisterAllocationData* GetAllocationData() override; std::unique_ptr<RegisterAllocationData, RegisterAllocationDataDeleter> PullAllocationData() override; private: uint32_t SpillPointId; #define INFO_MAKE(id, Class) ((id) | (Class << 24)) #define INFO_IDCLASS(info) (info & 0xffff'ffff) #define INFO_ID(info) (info & 0xff'ffff) #define INFO_CLASS(info) (info & 0xff00'0000) std::vector<BucketList<DEFAULT_INTERFERENCE_SPAN_COUNT, uint32_t>> SpanStart; std::vector<BucketList<DEFAULT_INTERFERENCE_SPAN_COUNT, uint32_t>> SpanEnd; RegisterGraph *Graph; FEXCore::IR::Pass* CompactionPass; bool OptimizeSRA; void SpillOne(FEXCore::IR::IREmitter *IREmit); std::vector<LiveRange> LiveRanges; using BlockInterferences = std::vector<uint32_t>; std::unordered_map<uint32_t, BlockInterferences> LocalBlockInterferences; BlockInterferences GlobalBlockInterferences; void CalculateLiveRange(FEXCore::IR::IRListView *IR); void OptimizeStaticRegisters(FEXCore::IR::IRListView *IR); void CalculateBlockInterferences(FEXCore::IR::IRListView *IR); void CalculateBlockNodeInterference(FEXCore::IR::IRListView *IR); void CalculateNodeInterference(FEXCore::IR::IRListView *IR); void AllocateVirtualRegisters(); void CalculatePredecessors(FEXCore::IR::IRListView *IR); void RecursiveLiveRangeExpansion(FEXCore::IR::IRListView *IR, uint32_t Node, uint32_t DefiningBlockID, LiveRange *LiveRange, const std::unordered_set<uint32_t> &Predecessors, std::unordered_set<uint32_t> &VisitedPredecessors); FEXCore::IR::AllNodesIterator FindFirstUse(FEXCore::IR::IREmitter *IREmit, FEXCore::IR::OrderedNode* Node, FEXCore::IR::AllNodesIterator Begin, FEXCore::IR::AllNodesIterator End); FEXCore::IR::AllNodesIterator FindLastUseBefore(FEXCore::IR::IREmitter *IREmit, FEXCore::IR::OrderedNode* Node, FEXCore::IR::AllNodesIterator Begin, FEXCore::IR::AllNodesIterator End); uint32_t FindNodeToSpill(IREmitter *IREmit, RegisterNode *RegisterNode, uint32_t CurrentLocation, LiveRange const *OpLiveRange, int32_t RematCost = -1); uint32_t FindSpillSlot(uint32_t Node, FEXCore::IR::RegisterClassType RegisterClass); bool RunAllocateVirtualRegisters(IREmitter *IREmit); }; ConstrainedRAPass::ConstrainedRAPass(FEXCore::IR::Pass* _CompactionPass, bool _OptimizeSRA) : CompactionPass {_CompactionPass}, OptimizeSRA(_OptimizeSRA) { } ConstrainedRAPass::~ConstrainedRAPass() { FreeRegisterGraph(Graph); } void ConstrainedRAPass::AllocateRegisterSet(uint32_t RegisterCount, uint32_t ClassCount) { LOGMAN_THROW_A(RegisterCount <= INVALID_REG, "Up to %d regs supported", INVALID_REG); LOGMAN_THROW_A(ClassCount <= INVALID_CLASS, "Up to %d classes supported", INVALID_CLASS); Graph = AllocateRegisterGraph(ClassCount); // Add identity conflicts for (uint32_t Class = 0; Class < INVALID_CLASS; Class++) { for (uint32_t Reg = 0; Reg < INVALID_REG; Reg++) { AddRegisterConflict(RegisterClassType{Class}, Reg, RegisterClassType{Class}, Reg); } } } void ConstrainedRAPass::AddRegisters(FEXCore::IR::RegisterClassType Class, uint32_t RegisterCount) { LOGMAN_THROW_A(RegisterCount <= INVALID_REG, "Up to %d regs supported", INVALID_REG); AllocatePhysicalRegisters(Graph, Class, RegisterCount); } void ConstrainedRAPass::AddRegisterConflict(FEXCore::IR::RegisterClassType ClassConflict, uint32_t RegConflict, FEXCore::IR::RegisterClassType Class, uint32_t Reg) { VirtualAddRegisterConflict(Graph, ClassConflict, RegConflict, Class, Reg); } RegisterAllocationData* ConstrainedRAPass::GetAllocationData() { return Graph->AllocData.get(); } std::unique_ptr<RegisterAllocationData, RegisterAllocationDataDeleter> ConstrainedRAPass::PullAllocationData() { return std::move(Graph->AllocData); } void ConstrainedRAPass::RecursiveLiveRangeExpansion(FEXCore::IR::IRListView *IR, uint32_t Node, uint32_t DefiningBlockID, LiveRange *LiveRange, const std::unordered_set<uint32_t> &Predecessors, std::unordered_set<uint32_t> &VisitedPredecessors) { for (auto PredecessorId: Predecessors) { if (DefiningBlockID != PredecessorId && !VisitedPredecessors.contains(PredecessorId)) { // do the magic VisitedPredecessors.insert(PredecessorId); auto [_, IROp] = *IR->at(PredecessorId); auto Op = IROp->C<IROp_CodeBlock>(); LOGMAN_THROW_A(Op->Header.Op == OP_CODEBLOCK, "Block not defined by codeblock?"); LiveRange->Begin = std::min(LiveRange->Begin, Op->Begin.ID()); LiveRange->End = std::max(LiveRange->End, Op->Begin.ID()); LiveRange->Begin = std::min(LiveRange->Begin, Op->Last.ID()); LiveRange->End = std::max(LiveRange->End, Op->Last.ID()); RecursiveLiveRangeExpansion(IR, Node, DefiningBlockID, LiveRange, Graph->BlockPredecessors[PredecessorId], VisitedPredecessors); } } } void ConstrainedRAPass::CalculateLiveRange(FEXCore::IR::IRListView *IR) { using namespace FEXCore; size_t Nodes = IR->GetSSACount(); LiveRanges.clear(); LiveRanges.resize(Nodes); constexpr uint32_t DEFAULT_REMAT_COST = 1000; for (auto [BlockNode, BlockHeader] : IR->GetBlocks()) { uint32_t BlockNodeID = IR->GetID(BlockNode); for (auto [CodeNode, IROp] : IR->GetCode(BlockNode)) { uint32_t Node = IR->GetID(CodeNode); // If the destination hasn't yet been set then set it now if (IROp->HasDest) { LOGMAN_THROW_A(LiveRanges[Node].Begin == ~0U, "Node begin already defined?"); LiveRanges[Node].Begin = Node; // Default to ending right where after it starts LiveRanges[Node].End = Node + 1; } // Calculate remat cost switch (IROp->Op) { case IR::OP_CONSTANT: LiveRanges[Node].RematCost = 1; break; case IR::OP_LOADFLAG: case IR::OP_LOADCONTEXT: LiveRanges[Node].RematCost = 10; break; case IR::OP_LOADREGISTER: LiveRanges[Node].RematCost = 10; break; case IR::OP_LOADMEM: case IR::OP_LOADMEMTSO: LiveRanges[Node].RematCost = 100; break; case IR::OP_FILLREGISTER: LiveRanges[Node].RematCost = DEFAULT_REMAT_COST + 1; break; // We want PHI to be very expensive to spill case IR::OP_PHI: LiveRanges[Node].RematCost = DEFAULT_REMAT_COST * 10; break; default: LiveRanges[Node].RematCost = DEFAULT_REMAT_COST; break; } // Set this node's block ID Graph->Nodes[Node].Head.BlockID = BlockNodeID; // FillRegister's SSA arg is only there for verification, and we don't want it // to impact the live range. if (IROp->Op == OP_FILLREGISTER) continue; uint8_t NumArgs = IR::GetArgs(IROp->Op); for (uint8_t i = 0; i < NumArgs; ++i) { if (IROp->Args[i].IsInvalid()) continue; if (IR->GetOp<IROp_Header>(IROp->Args[i])->Op == OP_INLINECONSTANT) continue; if (IR->GetOp<IROp_Header>(IROp->Args[i])->Op == OP_INLINEENTRYPOINTOFFSET) continue; if (IR->GetOp<IROp_Header>(IROp->Args[i])->Op == OP_IRHEADER) continue; uint32_t ArgNode = IROp->Args[i].ID(); LOGMAN_THROW_A(LiveRanges[ArgNode].Begin != ~0U, "%%ssa%d used by %%ssa%d before defined?", ArgNode, Node); auto ArgNodeBlockID = Graph->Nodes[ArgNode].Head.BlockID; if (ArgNodeBlockID == BlockNodeID) { // Set the node end to be at least here LiveRanges[ArgNode].End = Node; } else { LiveRanges[ArgNode].Global = true; // Grow the live range to include this use LiveRanges[ArgNode].Begin = std::min(LiveRanges[ArgNode].Begin, Node); LiveRanges[ArgNode].End = std::max(LiveRanges[ArgNode].End, Node); // Can't spill this range, it is MB LiveRanges[ArgNode].RematCost = -1; // Include any blocks this value passes through in the live range RecursiveLiveRangeExpansion(IR, ArgNode, ArgNodeBlockID, &LiveRanges[ArgNode], Graph->BlockPredecessors[BlockNodeID], Graph->VisitedNodePredecessors[ArgNode]); } } if (IROp->Op == IR::OP_PHI) { // Special case the PHI op, all of the nodes in the argument need to have the same virtual register affinity // Walk through all of them and set affinities for each other auto Op = IROp->C<IR::IROp_Phi>(); auto NodeBegin = IR->at(Op->PhiBegin); uint32_t CurrentSourcePartner = Node; while (NodeBegin != NodeBegin.Invalid()) { auto [ValueNode, ValueHeader] = NodeBegin(); auto ValueOp = ValueHeader->CW<IROp_PhiValue>(); // Set the node partner to the current one // This creates a singly linked list of node partners to follow SetNodePartner(Graph, CurrentSourcePartner, ValueOp->Value.ID()); CurrentSourcePartner = ValueOp->Value.ID(); NodeBegin = IR->at(ValueOp->Next); } } } } } void ConstrainedRAPass::OptimizeStaticRegisters(FEXCore::IR::IRListView *IR) { // Helpers // Is an OP_STOREREGISTER eligible to write directly to the SRA reg? auto IsPreWritable = [](uint8_t Size, RegisterClassType StaticClass) { if (StaticClass == GPRFixedClass) { return Size == 8; } else if (StaticClass == FPRFixedClass) { return Size == 16; } else { LOGMAN_THROW_A(false, "Unexpected static class %d", StaticClass); } return false; // Unknown }; // Is an OP_LOADREGISTER eligible to read directly from the SRA reg? auto IsAliasable = [](uint8_t Size, RegisterClassType StaticClass, uint32_t Offset) { if (StaticClass == GPRFixedClass) { return (Size == 8 /*|| Size == 4*/) && ((Offset & 7) == 0); // We need more meta info to support not-size-of-reg } else if (StaticClass == FPRFixedClass) { return (Size == 16 /*|| Size == 8 || Size == 4*/) && ((Offset & 15) == 0); // We need more meta info to support not-size-of-reg } else { LOGMAN_THROW_A(false, "Unexpected static class %d", StaticClass); } return false; // Unknown }; // Get SRA Reg and Class from a Context offset auto GetRegAndClassFromOffset = [](uint32_t Offset) { auto beginGpr = offsetof(FEXCore::Core::CpuStateFrame, State.gregs[0]); auto endGpr = offsetof(FEXCore::Core::CpuStateFrame, State.gregs[17]); auto beginFpr = offsetof(FEXCore::Core::CpuStateFrame, State.xmm[0][0]); auto endFpr = offsetof(FEXCore::Core::CpuStateFrame, State.xmm[17][0]); if (Offset >= beginGpr && Offset < endGpr) { auto reg = (Offset - beginGpr) / 8; return PhysicalRegister(GPRFixedClass, reg); } else if (Offset >= beginFpr && Offset < endFpr) { auto reg = (Offset - beginFpr) / 16; return PhysicalRegister(FPRFixedClass, reg); } else { LOGMAN_THROW_A(false, "Unexpected Offset %d", Offset); return PhysicalRegister::Invalid(); } }; auto GprSize = Graph->Set.Classes[GPRFixedClass.Val].PhysicalCount; auto MapsSize = Graph->Set.Classes[GPRFixedClass.Val].PhysicalCount + Graph->Set.Classes[FPRFixedClass.Val].PhysicalCount; LiveRange* StaticMaps[MapsSize]; // Get a StaticMap entry from context offset auto GetStaticMapFromOffset = [&](uint32_t Offset) { auto beginGpr = offsetof(FEXCore::Core::CpuStateFrame, State.gregs[0]); auto endGpr = offsetof(FEXCore::Core::CpuStateFrame, State.gregs[17]); auto beginFpr = offsetof(FEXCore::Core::CpuStateFrame, State.xmm[0][0]); auto endFpr = offsetof(FEXCore::Core::CpuStateFrame, State.xmm[17][0]); if (Offset >= beginGpr && Offset < endGpr) { auto reg = (Offset - beginGpr) / 8; return &StaticMaps[reg]; } else if (Offset >= beginFpr && Offset < endFpr) { auto reg = (Offset - beginFpr) / 16; return &StaticMaps[GprSize + reg]; } else { LOGMAN_THROW_A(false, "Unexpected offset %d", Offset); return (LiveRange**)nullptr; } }; // Get a StaticMap entry from reg and class auto GetStaticMapFromReg = [&](IR::PhysicalRegister PhyReg) { if (PhyReg.Class == GPRFixedClass.Val) { return &StaticMaps[PhyReg.Reg]; } else if (PhyReg.Class == FPRFixedClass.Val) { return &StaticMaps[GprSize + PhyReg.Reg]; } else { LOGMAN_THROW_A(false, "Unexpected Class %d", PhyReg.Class); return (LiveRange**)nullptr; } }; //First pass: Mark pre-writes for (auto [BlockNode, BlockHeader] : IR->GetBlocks()) { for (auto [CodeNode, IROp] : IR->GetCode(BlockNode)) { uint32_t Node = IR->GetID(CodeNode); if (IROp->Op == OP_STOREREGISTER) { auto Op = IROp->C<IR::IROp_StoreRegister>(); //int -1 /*vreg*/ = (int)(Op->Offset / 8) - 1; if (IsPreWritable(IROp->Size, Op->StaticClass) && LiveRanges[Op->Value.ID()].PrefferedRegister.IsInvalid() && !LiveRanges[Op->Value.ID()].Global) { //pre-write and sra-allocate in the defining node - this might be undone if a read before the actual store happens SRA_DEBUG("Prewritting ssa%d (Store in ssa%d)\n", Op->Value.ID(), Node); LiveRanges[Op->Value.ID()].PrefferedRegister = GetRegAndClassFromOffset(Op->Offset); LiveRanges[Op->Value.ID()].PreWritten = Node; SetNodeClass(Graph, Op->Value.ID(), Op->StaticClass); } } } } // Second pass: // - Demote pre-writes if read after pre-write // - Mark read-aliases // - Demote read-aliases if SRA reg is written before the alias's last read for (auto [BlockNode, BlockHeader] : IR->GetBlocks()) { memset(StaticMaps, 0, MapsSize * sizeof(LiveRange*)); for (auto [CodeNode, IROp] : IR->GetCode(BlockNode)) { uint32_t Node = IR->GetID(CodeNode); // Check for read-after-write and demote if it happens uint8_t NumArgs = IR::GetArgs(IROp->Op); for (uint8_t i = 0; i < NumArgs; ++i) { if (IROp->Args[i].IsInvalid()) continue; if (IR->GetOp<IROp_Header>(IROp->Args[i])->Op == OP_INLINECONSTANT) continue; if (IR->GetOp<IROp_Header>(IROp->Args[i])->Op == OP_INLINEENTRYPOINTOFFSET) continue; if (IR->GetOp<IROp_Header>(IROp->Args[i])->Op == OP_IRHEADER) continue; uint32_t ArgNode = IROp->Args[i].ID(); // ACCESSED after write, let's not SRA this one if (LiveRanges[ArgNode].Written) { SRA_DEBUG("Demoting ssa%d because accessed after write in ssa%d\n", ArgNode, Node); LiveRanges[ArgNode].PrefferedRegister = PhysicalRegister::Invalid(); auto ArgNodeNode = IR->GetNode(IROp->Args[i]); SetNodeClass(Graph, ArgNode, GetRegClassFromNode(IR, ArgNodeNode->Op(IR->GetData()))); } } // This op defines a span if (IROp->HasDest) { // If this is a pre-write, update the StaticMap so we track writes if (!LiveRanges[Node].PrefferedRegister.IsInvalid()) { SRA_DEBUG("ssa%d is a pre-write\n", Node); auto StaticMap = GetStaticMapFromReg(LiveRanges[Node].PrefferedRegister); if ((*StaticMap)) { SRA_DEBUG("Markng ssa%ld as written because ssa%d writes to sra%d\n", (*StaticMap) - &LiveRanges[0], Node, -1 /*vreg*/); (*StaticMap)->Written = true; } (*StaticMap) = &LiveRanges[Node]; } // Opcode is an SRA read // Check if // - There is not a pre-write before this read. If there is one, demote to no pre-write // - Try to read-alias if possible if (IROp->Op == OP_LOADREGISTER) { auto Op = IROp->C<IR::IROp_LoadRegister>(); auto StaticMap = GetStaticMapFromOffset(Op->Offset); // Make sure there wasn't a store pre-written before this read if ((*StaticMap) && (*StaticMap)->PreWritten) { uint32_t ID = (*StaticMap) - &LiveRanges[0]; SRA_DEBUG("ssa%d cannot be a pre-write because ssa%d reads from sra%d before storereg", ID, Node, -1 /*vreg*/); (*StaticMap)->PrefferedRegister = PhysicalRegister::Invalid(); (*StaticMap)->PreWritten = 0; SetNodeClass(Graph, ID, Op->Class); } // if not sra-allocated and full size, sra-allocate if (!LiveRanges[Node].Global && LiveRanges[Node].PrefferedRegister.IsInvalid()) { // only full size reads can be aliased if (IsAliasable(IROp->Size, Op->StaticClass, Op->Offset)) { // We can only track a single active span. // Marking here as written is overly agressive, but // there might be write(s) later on the instruction stream if ((*StaticMap)) { SRA_DEBUG("Markng ssa%ld as written because ssa%d re-loads sra%d, and we can't track possible future writes\n", (*StaticMap) - &LiveRanges[0], Node, -1 /*vreg*/); (*StaticMap)->Written = true; } LiveRanges[Node].PrefferedRegister = GetRegAndClassFromOffset(Op->Offset); //0, 1, and so on (*StaticMap) = &LiveRanges[Node]; SetNodeClass(Graph, Node, Op->StaticClass); SRA_DEBUG("Marking ssa%d as allocated to sra%d\n", Node, -1 /*vreg*/); } } } } // OP is an OP_STOREREGISTER // - If there was a matching pre-write, clear the pre-write flag as the register is no longer pre-written // - Mark the SRA span as written, so that any further reads demote it from read-aliases if they happen if (IROp->Op == OP_STOREREGISTER) { auto Op = IROp->C<IR::IROp_StoreRegister>(); auto StaticMap = GetStaticMapFromOffset(Op->Offset); // if a read pending, it has been writting if ((*StaticMap)) { // writes to self don't invalidate the span if ((*StaticMap)->PreWritten != Node) { SRA_DEBUG("Markng ssa%d as written because ssa%d writes to sra%d with value ssa%d. Write size is %d\n", ID, Node, -1 /*vreg*/, Op->Value.ID(), IROp->Size); (*StaticMap)->Written = true; } } if (LiveRanges[Op->Value.ID()].PreWritten == Node) { // no longer pre-written LiveRanges[Op->Value.ID()].PreWritten = 0; SRA_DEBUG("Markng ssa%d as no longer pre-written as ssa%d is a storereg for sra%d\n", Op->Value.ID(), Node, -1 /*vreg*/); } } } } } void ConstrainedRAPass::CalculateBlockInterferences(FEXCore::IR::IRListView *IR) { using namespace FEXCore; for (auto [BlockNode, BlockHeader] : IR->GetBlocks()) { auto BlockIROp = BlockHeader->CW<FEXCore::IR::IROp_CodeBlock>(); LOGMAN_THROW_A(BlockIROp->Header.Op == IR::OP_CODEBLOCK, "IR type failed to be a code block"); BlockInterferences *BlockInterferenceVector = &LocalBlockInterferences.try_emplace(IR->GetID(BlockNode)).first->second; BlockInterferenceVector->reserve(BlockIROp->Last.ID() - BlockIROp->Begin.ID()); for (auto [CodeNode, IROp] : IR->GetCode(BlockNode)) { uint32_t Node = IR->GetID(CodeNode); LiveRange *NodeLiveRange = &LiveRanges[Node]; if (NodeLiveRange->Begin >= BlockIROp->Begin.ID() && NodeLiveRange->End <= BlockIROp->Last.ID()) { // If the live range of this node is FULLY inside of the block // Then add it to the block specific interference list BlockInterferenceVector->emplace_back(Node); } else { // If the live range is not fully inside the block then add it to the global interference list GlobalBlockInterferences.emplace_back(Node); } } } } void ConstrainedRAPass::CalculateBlockNodeInterference(FEXCore::IR::IRListView *IR) { #if 0 auto AddInterference = [&](uint32_t Node1, uint32_t Node2) { RegisterNode *Node = &Graph->Nodes[Node1]; Node->Interference.Set(Node2); Node->InterferenceList[Node->Head.InterferenceCount++] = Node2; }; auto CheckInterferenceNodeSizes = [&](uint32_t Node1, uint32_t MaxNewNodes) { RegisterNode *Node = &Graph->Nodes[Node1]; uint32_t NewListMax = Node->Head.InterferenceCount + MaxNewNodes; if (Node->InterferenceListSize <= NewListMax) { Node->InterferenceListSize = std::max(Node->InterferenceListSize * 2U, (uint32_t)AlignUp(NewListMax, DEFAULT_INTERFERENCE_LIST_COUNT)); Node->InterferenceList = reinterpret_cast<uint32_t*>(realloc(Node->InterferenceList, Node->InterferenceListSize * sizeof(uint32_t))); } }; using namespace FEXCore; for (auto [BlockNode, BlockHeader] : IR->GetBlocks()) { BlockInterferences *BlockInterferenceVector = &LocalBlockInterferences.try_emplace(IR->GetID(BlockNode)).first->second; std::vector<uint32_t> Interferences; Interferences.reserve(BlockInterferenceVector->size() + GlobalBlockInterferences.size()); for (auto [CodeNode, IROp] : IR->GetCode(BlockNode)) { uint32_t Node = IR->GetID(CodeNode); // Check for every interference with the local block's interference for (auto RHSNode : *BlockInterferenceVector) { if (!(LiveRanges[Node].Begin >= LiveRanges[RHSNode].End || LiveRanges[RHSNode].Begin >= LiveRanges[Node].End)) { Interferences.emplace_back(RHSNode); } } // Now check the global block interference vector for (auto RHSNode : GlobalBlockInterferences) { if (!(LiveRanges[Node].Begin >= LiveRanges[RHSNode].End || LiveRanges[RHSNode].Begin >= LiveRanges[Node].End)) { Interferences.emplace_back(RHSNode); } } CheckInterferenceNodeSizes(Node, Interferences.size()); for (auto RHSNode : Interferences) { AddInterference(Node, RHSNode); } for (auto RHSNode : Interferences) { AddInterference(RHSNode, Node); CheckInterferenceNodeSizes(RHSNode, 0); } Interferences.clear(); } } #endif } void ConstrainedRAPass::CalculateNodeInterference(FEXCore::IR::IRListView *IR) { auto AddInterference = [this](uint32_t Node1, uint32_t Node2) { RegisterNode *Node = &Graph->Nodes[Node1]; Node->Interferences.Append(Node2); }; uint32_t NodeCount = IR->GetSSACount(); // Now that we have all the live ranges calculated we need to add them to our interference graph auto GetClass = [](PhysicalRegister PhyReg) { if (PhyReg.Class == IR::GPRPairClass.Val) return IR::GPRClass.Val; else return (uint32_t)PhyReg.Class; }; // SpanStart/SpanEnd assume SSA id will fit in 24bits LOGMAN_THROW_A(NodeCount <= 0xff'ffff, "Block too large for Spans"); SpanStart.resize(NodeCount); SpanEnd.resize(NodeCount); for (uint32_t i = 0; i < NodeCount; ++i) { if (LiveRanges[i].Begin != ~0U) { LOGMAN_THROW_A(LiveRanges[i].Begin < LiveRanges[i].End , "Span must Begin before Ending"); auto Class = GetClass(Graph->AllocData->Map[i]); SpanStart[LiveRanges[i].Begin].Append(INFO_MAKE(i, Class)); SpanEnd[LiveRanges[i].End] .Append(INFO_MAKE(i, Class)); } } BucketList<32, uint32_t> Active; for (int OpNodeId = 0; OpNodeId < IR->GetSSACount(); OpNodeId++) { // Expire end intervals first SpanEnd[OpNodeId].Iterate([&](uint32_t EdgeInfo) { Active.Erase(INFO_IDCLASS(EdgeInfo)); }); // Add starting invervals SpanStart[OpNodeId].Iterate([&](uint32_t EdgeInfo) { // Starts here Active.Iterate([&](uint32_t ActiveInfo) { if (INFO_CLASS(ActiveInfo) == INFO_CLASS(EdgeInfo)) { AddInterference(INFO_ID(ActiveInfo), INFO_ID(EdgeInfo)); AddInterference(INFO_ID(EdgeInfo), INFO_ID(ActiveInfo)); } }); Active.Append(EdgeInfo); }); } LOGMAN_THROW_A(Active.Items[0] == 0, "Interference bug"); SpanStart.clear(); SpanEnd.clear(); } void ConstrainedRAPass::AllocateVirtualRegisters() { for (uint32_t i = 0; i < Graph->NodeCount; ++i) { RegisterNode *CurrentNode = &Graph->Nodes[i]; auto &CurrentRegAndClass = Graph->AllocData->Map[i]; if (CurrentRegAndClass == PhysicalRegister::Invalid()) continue; auto LiveRange = &LiveRanges[i]; FEXCore::IR::RegisterClassType RegClass = FEXCore::IR::RegisterClassType{CurrentRegAndClass.Class}; auto RegAndClass = PhysicalRegister::Invalid(); RegisterClass *RAClass = &Graph->Set.Classes[RegClass]; if (CurrentNode->Head.PhiPartner) { LOGMAN_MSG_A("Phi nodes not supported"); #if 0 // In the case that we have a list of nodes that need the same register allocated we need to do something special // We need to gather the data from the forward linked list and make sure they all match the virtual register std::vector<RegisterNode *> Nodes; auto CurrentPartner = CurrentNode; while (CurrentPartner) { Nodes.emplace_back(CurrentPartner); CurrentPartner = CurrentPartner->Head.PhiPartner; } for (uint32_t ri = 0; ri < RAClass->Count; ++ri) { uint64_t RegisterToCheck = (static_cast<uint64_t>(RegClass) << 32) + ri; if (!DoesNodeSetInterfereWithRegister(Graph, Nodes, RegisterToCheck)) { RegAndClass = RegisterToCheck; break; } } // If we failed to find a virtual register then allocate more space for them if (RegAndClass == ~0ULL) { RegAndClass = (static_cast<uint64_t>(RegClass.Val) << 32); RegAndClass |= INVALID_REG; } TopRAPressure[RegClass] = std::max((uint32_t)RegAndClass + 1, TopRAPressure[RegClass]); // Walk the partners and ensure they are all set to the same register now for (auto Partner : Nodes) { Partner->Head.RegAndClass = RegAndClass; } #endif } else { if (!LiveRange->PrefferedRegister.IsInvalid()) { RegAndClass = LiveRange->PrefferedRegister; } else { uint32_t RegisterConflicts = 0; CurrentNode->Interferences.Iterate([&](const uint32_t InterferenceNode) { RegisterConflicts |= GetConflicts(Graph, Graph->AllocData->Map[InterferenceNode], {RegClass}); }); RegisterConflicts = (~RegisterConflicts) & RAClass->CountMask; int Reg = ffs(RegisterConflicts); if (Reg != 0) { RegAndClass = PhysicalRegister({RegClass}, Reg-1); } } // If we failed to find a virtual register then use INVALID_REG and mark allocation as failed if (RegAndClass.IsInvalid()) { RegAndClass = IR::PhysicalRegister(RegClass, INVALID_REG); HadFullRA = false; SpillPointId = i; CurrentRegAndClass = RegAndClass; // Must spill and restart return; } CurrentRegAndClass = RegAndClass; } } } FEXCore::IR::AllNodesIterator ConstrainedRAPass::FindFirstUse(FEXCore::IR::IREmitter *IREmit, FEXCore::IR::OrderedNode* Node, FEXCore::IR::AllNodesIterator Begin, FEXCore::IR::AllNodesIterator End) { using namespace FEXCore::IR; uint32_t SearchID = IREmit->ViewIR().GetID(Node); while(1) { auto [RealNode, IROp] = Begin(); uint8_t NumArgs = FEXCore::IR::GetArgs(IROp->Op); for (uint8_t i = 0; i < NumArgs; ++i) { uint32_t ArgNode = IROp->Args[i].ID(); if (ArgNode == SearchID) { return Begin; } } // CodeLast is inclusive. So we still need to dump the CodeLast op as well if (Begin == End) { break; } ++Begin; } return AllNodesIterator::Invalid(); } FEXCore::IR::AllNodesIterator ConstrainedRAPass::FindLastUseBefore(FEXCore::IR::IREmitter *IREmit, FEXCore::IR::OrderedNode* Node, FEXCore::IR::AllNodesIterator Begin, FEXCore::IR::AllNodesIterator End) { auto CurrentIR = IREmit->ViewIR(); uint32_t SearchID = CurrentIR.GetID(Node); while (1) { using namespace FEXCore::IR; auto [RealNode, IROp] = End(); if (Node == RealNode) { // We walked back all the way to the definition of the IR op return End; } uint8_t NumArgs = FEXCore::IR::GetArgs(IROp->Op); for (uint8_t i = 0; i < NumArgs; ++i) { uint32_t ArgNode = IROp->Args[i].ID(); if (ArgNode == SearchID) { return End; } } // CodeLast is inclusive. So we still need to dump the CodeLast op as well if (Begin == End) { break; } --End; } return FEXCore::IR::AllNodesIterator::Invalid(); } uint32_t ConstrainedRAPass::FindNodeToSpill(IREmitter *IREmit, RegisterNode *RegisterNode, uint32_t CurrentLocation, LiveRange const *OpLiveRange, int32_t RematCost) { auto IR = IREmit->ViewIR(); uint32_t InterferenceIdToSpill = 0; uint32_t InterferenceFarthestNextUse = 0; IR::OrderedNodeWrapper NodeOpBegin = IR::OrderedNodeWrapper::WrapOffset(CurrentLocation * sizeof(IR::OrderedNode)); IR::OrderedNodeWrapper NodeOpEnd = IR::OrderedNodeWrapper::WrapOffset(OpLiveRange->End * sizeof(IR::OrderedNode)); auto NodeOpBeginIter = IR.at(NodeOpBegin); auto NodeOpEndIter = IR.at(NodeOpEnd); // Couldn't find register to spill // Be more aggressive if (InterferenceIdToSpill == 0) { RegisterNode->Interferences.Iterate([&](uint32_t InterferenceNode) { auto *InterferenceLiveRange = &LiveRanges[InterferenceNode]; if (InterferenceLiveRange->RematCost == -1 || (RematCost != -1 && InterferenceLiveRange->RematCost != RematCost)) { return; } //if ((RegisterNode->Head.RegAndClass>>32) != (InterferenceNode->Head.RegAndClass>>32)) // return; // If this node's live range fully encompasses the live range of the interference node // then spilling that interference node will not lower RA // | Our Node | Interference | // | ========================================== | // | 0 - Assign | | // | 1 | Assign | // | 2 | | // | 3 | Last Use | // | 4 | | // | 5 - Last Use | | // | Range - (0, 5] | (1, 3] | if (OpLiveRange->Begin <= InterferenceLiveRange->Begin && OpLiveRange->End >= InterferenceLiveRange->End) { return; } auto [InterferenceOrderedNode, _] = IR.at(InterferenceNode)(); auto InterferenceNodeOpBeginIter = IR.at(InterferenceLiveRange->Begin); auto InterferenceNodeOpEndIter = IR.at(InterferenceLiveRange->End); bool Found{}; // If the nodes live range is entirely encompassed by the interference node's range // then spilling that range will /potentially/ lower RA // Will only lower register pressure if the interference node does NOT have a use inside of // this live range's use // | Our Node | Interference | // | ========================================== | // | 0 | Assign | // | 1 - Assign | (No Use) | // | 2 | (No Use) | // | 3 - Last Use | (No Use) | // | 4 | | // | 5 | Last Use | // | Range - (1, 3] | (0, 5] | if (CurrentLocation > InterferenceLiveRange->Begin && OpLiveRange->End < InterferenceLiveRange->End) { // This will only save register pressure if the interference node // does NOT have a use inside of this this node's live range // Search only inside the source node's live range to see if there is a use auto FirstUseLocation = FindFirstUse(IREmit, InterferenceOrderedNode, NodeOpBeginIter, NodeOpEndIter); if (FirstUseLocation == IR::NodeIterator::Invalid()) { // Looks like there isn't a usage of this interference node inside our node's live range // This means it is safe to spill this node and it'll result in in lower RA // Proper calculation of cost to spill would be to calculate the two distances from // (Node->Begin - InterferencePrevUse) + (InterferenceNextUse - Node->End) // This would ensure something will spill earlier if its previous use and next use are farther away auto InterferenceNodeNextUse = FindFirstUse(IREmit, InterferenceOrderedNode, NodeOpBeginIter, InterferenceNodeOpEndIter); auto InterferenceNodePrevUse = FindLastUseBefore(IREmit, InterferenceOrderedNode, InterferenceNodeOpBeginIter, NodeOpBeginIter); LOGMAN_THROW_A(InterferenceNodeNextUse != IR::NodeIterator::Invalid(), "Couldn't find next usage of op"); // If there is no use of the interference op prior to our op then it only has initial definition if (InterferenceNodePrevUse == IR::NodeIterator::Invalid()) InterferenceNodePrevUse = InterferenceNodeOpBeginIter; uint32_t NextUseDistance = InterferenceNodeNextUse.ID() - CurrentLocation; if (NextUseDistance >= InterferenceFarthestNextUse) { Found = true; InterferenceIdToSpill = InterferenceNode; InterferenceFarthestNextUse = NextUseDistance; } } } }); } if (InterferenceIdToSpill == 0) { RegisterNode->Interferences.Iterate([&](uint32_t InterferenceNode) { auto *InterferenceLiveRange = &LiveRanges[InterferenceNode]; if (InterferenceLiveRange->RematCost == -1 || (RematCost != -1 && InterferenceLiveRange->RematCost != RematCost)) { return; } // If this node's live range fully encompasses the live range of the interference node // then spilling that interference node will not lower RA // | Our Node | Interference | // | ========================================== | // | 0 - Assign | | // | 1 | Assign | // | 2 | | // | 3 | Last Use | // | 4 | | // | 5 - Last Use | | // | Range - (0, 5] | (1, 3] | if (OpLiveRange->Begin <= InterferenceLiveRange->Begin && OpLiveRange->End >= InterferenceLiveRange->End) { return; } auto [InterferenceOrderedNode, _] = IR.at(InterferenceNode)(); auto InterferenceNodeOpEndIter = IR.at(InterferenceLiveRange->End); bool Found{}; // If the node's live range intersects the interference node // but the interference node only overlaps the beginning of our live range // then spilling the register will lower register pressure if there is not // a use of the interference register at the same node as assignment // (So we can spill just before current node assignment) // | Our Node | Interference | // | ========================================== | // | 0 | Assign | // | 1 - Assign | (No Use) | // | 2 | (No Use) | // | 3 | Last Use | // | 4 | | // | 5 - Last Use | | // | Range - (1, 5] | (0, 3] | if (!Found && CurrentLocation > InterferenceLiveRange->Begin && OpLiveRange->End > InterferenceLiveRange->End) { auto FirstUseLocation = FindFirstUse(IREmit, InterferenceOrderedNode, NodeOpBeginIter, NodeOpBeginIter); if (FirstUseLocation == IR::NodeIterator::Invalid()) { // This means that the assignment of our register doesn't use this interference node // So we are safe to spill this interference node before assignment of our current node auto InterferenceNodeNextUse = FindFirstUse(IREmit, InterferenceOrderedNode, NodeOpBeginIter, InterferenceNodeOpEndIter); uint32_t NextUseDistance = InterferenceNodeNextUse.ID() - CurrentLocation; if (NextUseDistance >= InterferenceFarthestNextUse) { Found = true; InterferenceIdToSpill = InterferenceNode; InterferenceFarthestNextUse = NextUseDistance; } } } // If the node's live range intersects the interference node // but the interference node only overlaps the end of our live range // then spilling the register will lower register pressure if there is // not a use of the interference register at the same node as the other node's // last use // | Our Node | Interference | // | ========================================== | // | 0 - Assign | | // | 1 | | // | 2 | Assign | // | 3 - Last Use | (No Use) | // | 4 | (No Use) | // | 5 | Last Use | // | Range - (1, 3] | (2, 5] | // XXX: This route has a bug in it so it is purposely disabled for now if (false && !Found && CurrentLocation <= InterferenceLiveRange->Begin && OpLiveRange->End <= InterferenceLiveRange->End) { auto FirstUseLocation = FindFirstUse(IREmit, InterferenceOrderedNode, NodeOpEndIter, NodeOpEndIter); if (FirstUseLocation == IR::NodeIterator::Invalid()) { // This means that the assignment of our the interference register doesn't overlap // with the final usage of our register, we can spill it and reduce usage auto InterferenceNodeNextUse = FindFirstUse(IREmit, InterferenceOrderedNode, NodeOpBeginIter, InterferenceNodeOpEndIter); uint32_t NextUseDistance = InterferenceNodeNextUse.ID() - CurrentLocation; if (NextUseDistance >= InterferenceFarthestNextUse) { Found = true; InterferenceIdToSpill = InterferenceNode; InterferenceFarthestNextUse = NextUseDistance; } } } }); } // If we are looking for a specific node then we can safely return not found if (RematCost != -1 && InterferenceIdToSpill == 0) { return ~0U; } // Heuristics failed to spill ? if (InterferenceIdToSpill == 0) { // Panic spill: Spill any value not used by the current op std::set<uint32_t> CurrentNodes; // Get all used nodes for current IR op { auto CurrentNode = IR.GetNode(NodeOpBegin); auto IROp = CurrentNode->Op(IR.GetData()); CurrentNodes.insert(NodeOpBegin.ID()); for (int i = 0; i < IROp->NumArgs; i++) { CurrentNodes.insert(IROp->Args[i].ID()); } } RegisterNode->Interferences.Find([&](uint32_t InterferenceNode) { auto *InterferenceLiveRange = &LiveRanges[InterferenceNode]; if (InterferenceLiveRange->RematCost == -1 || (RematCost != -1 && InterferenceLiveRange->RematCost != RematCost)) { return false; } if (!CurrentNodes.contains(InterferenceNode)) { InterferenceIdToSpill = InterferenceNode; LogMan::Msg::D("Panic spilling %%ssa%d, Live Range[%d, %d)", InterferenceIdToSpill, InterferenceLiveRange->Begin, InterferenceLiveRange->End); return true; } return false; }); } if (InterferenceIdToSpill == 0) { int j = 0; LogMan::Msg::D("node %%ssa%d, was dumped in to virtual reg %d. Live Range[%d, %d)", CurrentLocation, -1, OpLiveRange->Begin, OpLiveRange->End); RegisterNode->Interferences.Iterate([&](uint32_t InterferenceNode) { auto *InterferenceLiveRange = &LiveRanges[InterferenceNode]; LogMan::Msg::D("\tInt%d: %%ssa%d Remat: %d [%d, %d)", j++, InterferenceNode, InterferenceLiveRange->RematCost, InterferenceLiveRange->Begin, InterferenceLiveRange->End); }); } LOGMAN_THROW_A(InterferenceIdToSpill != 0, "Couldn't find Node to spill"); return InterferenceIdToSpill; } uint32_t ConstrainedRAPass::FindSpillSlot(uint32_t Node, FEXCore::IR::RegisterClassType RegisterClass) { RegisterNode *CurrentNode = &Graph->Nodes[Node]; LiveRange *NodeLiveRange = &LiveRanges[Node]; if (ReuseSpillSlots) { for (uint32_t i = 0; i < Graph->SpillStack.size(); ++i) { SpillStackUnit *SpillUnit = &Graph->SpillStack.at(i); if (NodeLiveRange->Begin <= SpillUnit->SpillRange.End && SpillUnit->SpillRange.Begin <= NodeLiveRange->End) { SpillUnit->SpillRange.Begin = std::min(SpillUnit->SpillRange.Begin, LiveRanges[Node].Begin); SpillUnit->SpillRange.End = std::max(SpillUnit->SpillRange.End, LiveRanges[Node].End); CurrentNode->Head.SpillSlot = i; return i; } } } // Couldn't find a spill slot so just make a new one auto StackItem = Graph->SpillStack.emplace_back(SpillStackUnit{Node, RegisterClass}); StackItem.SpillRange.Begin = NodeLiveRange->Begin; StackItem.SpillRange.End = NodeLiveRange->End; CurrentNode->Head.SpillSlot = SpillSlotCount; SpillSlotCount++; return CurrentNode->Head.SpillSlot; } void ConstrainedRAPass::SpillOne(FEXCore::IR::IREmitter *IREmit) { using namespace FEXCore; auto IR = IREmit->ViewIR(); auto LastCursor = IREmit->GetWriteCursor(); auto [CodeNode, IROp] = IR.at(SpillPointId)(); LOGMAN_THROW_A(IROp->HasDest, "Can't spill with no dest"); uint32_t Node = IR.GetID(CodeNode); RegisterNode *CurrentNode = &Graph->Nodes[Node]; auto &CurrentRegAndClass = Graph->AllocData->Map[Node]; LiveRange *OpLiveRange = &LiveRanges[Node]; // If this node is allocated above the number of physical registers we have then we need to search the interference list and spill the one // that is cheapest bool NeedsToSpill = CurrentRegAndClass.Reg == INVALID_REG; if (NeedsToSpill) { bool Spilled = false; // First let's just check for constants that we can just rematerialize instead of spilling uint32_t InterferenceNode = FindNodeToSpill(IREmit, CurrentNode, Node, OpLiveRange, 1); if (InterferenceNode != ~0U) { // We want to end the live range of this value here and continue it on first use auto [ConstantNode, _] = IR.at(InterferenceNode)(); auto ConstantIROp = IR.GetOp<IR::IROp_Constant>(ConstantNode); // First op post Spill auto NextIter = IR.at(CodeNode); auto FirstUseLocation = FindFirstUse(IREmit, ConstantNode, NextIter, NodeIterator::Invalid()); LOGMAN_THROW_A(FirstUseLocation != IR::NodeIterator::Invalid(), "At %%ssa%d Spilling Op %%ssa%d but Failure to find op use", Node, InterferenceNode); if (FirstUseLocation != IR::NodeIterator::Invalid()) { --FirstUseLocation; auto [FirstUseOrderedNode, _] = FirstUseLocation(); IREmit->SetWriteCursor(FirstUseOrderedNode); auto FilledConstant = IREmit->_Constant(ConstantIROp->Constant); IREmit->ReplaceUsesWithAfter(ConstantNode, FilledConstant, FirstUseLocation); Spilled = true; } } // If we didn't remat a constant then we need to do some real spilling if (!Spilled) { uint32_t InterferenceNode = FindNodeToSpill(IREmit, CurrentNode, Node, OpLiveRange); if (InterferenceNode != ~0U) { FEXCore::IR::RegisterClassType InterferenceRegClass = FEXCore::IR::RegisterClassType{Graph->AllocData->Map[InterferenceNode].Class}; uint32_t SpillSlot = FindSpillSlot(InterferenceNode, InterferenceRegClass); #if defined(ASSERTIONS_ENABLED) && ASSERTIONS_ENABLED RegisterNode *InterferenceRegisterNode = &Graph->Nodes[InterferenceNode]; LOGMAN_THROW_A(SpillSlot != ~0U, "Interference Node doesn't have a spill slot!"); //LOGMAN_THROW_A(InterferenceRegisterNode->Head.RegAndClass.Reg != INVALID_REG, "Interference node never assigned a register?"); LOGMAN_THROW_A(InterferenceRegClass != ~0U, "Interference node never assigned a register class?"); LOGMAN_THROW_A(InterferenceRegisterNode->Head.PhiPartner == nullptr, "We don't support spilling PHI nodes currently"); #endif // This is the op that we need to dump auto [InterferenceOrderedNode, InterferenceIROp] = IR.at(InterferenceNode)(); // This will find the last use of this definition // Walks from CodeBegin -> BlockBegin to find the last Use // Which this is walking backwards to find the first use auto LastUseIterator = FindLastUseBefore(IREmit, InterferenceOrderedNode, NodeIterator::Invalid(), IR.at(CodeNode)); if (LastUseIterator != AllNodesIterator::Invalid()) { auto [LastUseNode, LastUseIROp] = LastUseIterator(); // Set the write cursor to point of last usage IREmit->SetWriteCursor(LastUseNode); } else { // There is no last use -- use the definition as last use IREmit->SetWriteCursor(InterferenceOrderedNode); } // Actually spill the node now auto SpillOp = IREmit->_SpillRegister(InterferenceOrderedNode, SpillSlot, InterferenceRegClass); SpillOp.first->Header.Size = InterferenceIROp->Size; SpillOp.first->Header.ElementSize = InterferenceIROp->ElementSize; { // Search from the point of spilling to find the first use // Set the write cursor to the first location found and fill at that point auto FirstIter = IR.at(SpillOp.Node); // Just past the spill ++FirstIter; auto FirstUseLocation = FindFirstUse(IREmit, InterferenceOrderedNode, FirstIter, NodeIterator::Invalid()); LOGMAN_THROW_A(FirstUseLocation != NodeIterator::Invalid(), "At %%ssa%d Spilling Op %%ssa%d but Failure to find op use", Node, InterferenceNode); if (FirstUseLocation != IR::NodeIterator::Invalid()) { // We want to fill just before the first use --FirstUseLocation; auto [FirstUseOrderedNode, _] = FirstUseLocation(); IREmit->SetWriteCursor(FirstUseOrderedNode); auto FilledInterference = IREmit->_FillRegister(InterferenceOrderedNode, SpillSlot, InterferenceRegClass); FilledInterference.first->Header.Size = InterferenceIROp->Size; FilledInterference.first->Header.ElementSize = InterferenceIROp->ElementSize; IREmit->ReplaceUsesWithAfter(InterferenceOrderedNode, FilledInterference, FilledInterference); Spilled = true; } } } IREmit->SetWriteCursor(LastCursor); } } } bool ConstrainedRAPass::RunAllocateVirtualRegisters(FEXCore::IR::IREmitter *IREmit) { using namespace FEXCore; bool Changed = false; GlobalBlockInterferences.clear(); LocalBlockInterferences.clear(); auto IR = IREmit->ViewIR(); uint32_t SSACount = IR.GetSSACount(); ResetRegisterGraph(Graph, SSACount); FindNodeClasses(Graph, &IR); CalculateLiveRange(&IR); if (OptimizeSRA) OptimizeStaticRegisters(&IR); // Linear forward scan based interference calculation is faster for smaller blocks // Smarter block based interference calculation is faster for larger blocks /*if (SSACount >= 2048) { CalculateBlockInterferences(&IR); CalculateBlockNodeInterference(&IR); } else*/ { CalculateNodeInterference(&IR); } AllocateVirtualRegisters(); return Changed; } void ConstrainedRAPass::CalculatePredecessors(FEXCore::IR::IRListView *IR) { Graph->BlockPredecessors.clear(); for (auto [BlockNode, BlockIROp] : IR->GetBlocks()) { auto CodeBlock = BlockIROp->C<IROp_CodeBlock>(); auto IROp = IR->GetNode(IR->GetNode(CodeBlock->Last)->Header.Previous)->Op(IR->GetData()); if (IROp->Op == OP_JUMP) { auto Op = IROp->C<IROp_Jump>(); Graph->BlockPredecessors[Op->Target.ID()].insert(IR->GetID(BlockNode)); } else if (IROp->Op == OP_CONDJUMP) { auto Op = IROp->C<IROp_CondJump>(); Graph->BlockPredecessors[Op->TrueBlock.ID()].insert(IR->GetID(BlockNode)); Graph->BlockPredecessors[Op->FalseBlock.ID()].insert(IR->GetID(BlockNode)); } } } bool ConstrainedRAPass::Run(IREmitter *IREmit) { bool Changed = false; auto IR = IREmit->ViewIR(); SpillSlotCount = 0; Graph->SpillStack.clear(); CalculatePredecessors(&IR); while (1) { HadFullRA = true; // Virtual allocation pass runs the compaction pass per run Changed |= RunAllocateVirtualRegisters(IREmit); if (HadFullRA) { break; } SpillOne(IREmit); Changed = true; // We need to rerun compaction after spilling CompactionPass->Run(IREmit); } Graph->AllocData->SpillSlotCount = Graph->SpillStack.size(); return Changed; } std::unique_ptr<FEXCore::IR::RegisterAllocationPass> CreateRegisterAllocationPass(FEXCore::IR::Pass* CompactionPass, bool OptimizeSRA) { return std::make_unique<ConstrainedRAPass>(CompactionPass, OptimizeSRA); } }
25,088
327
package de.fhpotsdam.unfolding.examples.interaction.multitouch; import org.apache.log4j.Logger; import processing.core.PApplet; import TUIO.TuioClient; import TUIO.TuioCursor; import TUIO.TuioListener; import TUIO.TuioObject; import TUIO.TuioTime; import de.fhpotsdam.unfolding.UnfoldingMap; import de.fhpotsdam.unfolding.events.EventDispatcher; import de.fhpotsdam.unfolding.geo.Location; import de.fhpotsdam.unfolding.interactions.TuioCursorHandler; /** * Multitouch map with a simple button atop. A tap on the button does not affect the map. * * Creates a map and a handler for TUIO cursors, with this application acting as TUIO listener, and forwarding the TUIO * events to the handler. This allows reacting to other touch interactions in the application (e.g. map markers, or * other interface elements), as well. * * See simpler {@link MultitouchMapApp} if you want to use multitouch interaction for the map only. */ public class MultitouchMapExternalTuioApp extends PApplet implements TuioListener { public static Logger log = Logger.getLogger(MultitouchMapExternalTuioApp.class); UnfoldingMap map; EventDispatcher eventDispatcher; TuioCursorHandler tuioCursorHandler; TuioClient tuioClient; boolean activeButton = false; int buttonX = 50; int buttonY = 50; int buttonSize = 40; public static void main(String[] args) { String[] params = new String[] { "--present", "--bgcolor=#000000", "--hide-stop", "de.fhpotsdam.unfolding.examples.interaction.multitouch.MultitouchMapExternalTuioApp" }; PApplet.main(params); } public void settings() { size(800, 600, P2D); } public void setup() { map = new UnfoldingMap(this); map.setTweening(false); map.zoomAndPanTo(13, new Location(1.283f, 103.833f)); map.setPanningRestriction(new Location(1.283f, 103.833f), 30); eventDispatcher = new EventDispatcher(); tuioCursorHandler = new TuioCursorHandler(this, false, map); eventDispatcher.addBroadcaster(tuioCursorHandler); eventDispatcher.register(map, "pan"); eventDispatcher.register(map, "zoom"); tuioClient = tuioCursorHandler.getTuioClient(); tuioClient.addTuioListener(this); } public void draw() { map.draw(); // log.debug("map.center: " + map.getCenter()); if (activeButton) { fill(255, 0, 0, 150); } else { fill(255, 150); } noStroke(); ellipse(buttonX, buttonY, buttonSize, buttonSize); // tuioCursorHandler.drawCursors(); fill(255, 100); for (TuioCursor tcur : tuioClient.getTuioCursors()) { ellipse(tcur.getScreenX(width), tcur.getScreenY(height), 20, 20); } } @Override public void addTuioCursor(TuioCursor tuioCursor) { int x = tuioCursor.getScreenX(width); int y = tuioCursor.getScreenY(height); log.debug("Add " + tuioCursor.getCursorID() + ": " + x + ", " + y); if (dist(x, y, buttonX, buttonY) < buttonSize / 2) { activeButton = !activeButton; } else { tuioCursorHandler.addTuioCursor(tuioCursor); } } @Override public void updateTuioCursor(TuioCursor tuioCursor) { int x = tuioCursor.getScreenX(width); int y = tuioCursor.getScreenY(height); log.debug("Update " + tuioCursor.getCursorID() + ": " + x + ", " + y); tuioCursorHandler.updateTuioCursor(tuioCursor); } @Override public void removeTuioCursor(TuioCursor tuioCursor) { log.debug("Remove " + tuioCursor.getCursorID()); tuioCursorHandler.removeTuioCursor(tuioCursor); } @Override public void addTuioObject(TuioObject arg0) { // No objects used } @Override public void refresh(TuioTime arg0) { // Not used } @Override public void removeTuioObject(TuioObject arg0) { // No objects used } @Override public void updateTuioObject(TuioObject arg0) { // No objects used } }
1,391
12,278
<gh_stars>1000+ /////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 // // demo_xml_load.cpp // // (C) Copyright 2002-4 <NAME> - http://www.rrsd.com . // Use, modification and distribution is subject to 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 <iostream> #include <string> #include <boost/archive/tmpdir.hpp> #include <boost/archive/xml_iarchive.hpp> #include "demo_gps.hpp" void restore_schedule(bus_schedule &s, const char * filename) { // open the archive std::ifstream ifs(filename); assert(ifs.good()); boost::archive::xml_iarchive ia(ifs); // restore the schedule from the archive ia >> BOOST_SERIALIZATION_NVP(s); } int main(int argc, char *argv[]) { // make a new schedule bus_schedule new_schedule; std::string filename(boost::archive::tmpdir()); filename += "/demo_save.xml"; restore_schedule(new_schedule, filename.c_str()); // and display std::cout << "\nrestored schedule"; std::cout << new_schedule; return 0; }
432
377
/* * Licensed to the Technische Universität Darmstadt under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The Technische Universität Darmstadt * 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. * * 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 de.tudarmstadt.ukp.clarin.webanno.diag.repairs; import static de.tudarmstadt.ukp.clarin.webanno.api.WebAnnoConst.SPAN_TYPE; import static org.apache.uima.fit.util.CasUtil.getType; import static org.apache.uima.fit.util.CasUtil.select; import static org.apache.uima.fit.util.CasUtil.selectCovered; import static org.apache.uima.fit.util.FSUtil.getFeature; import static org.apache.uima.fit.util.FSUtil.setFeature; import java.util.ArrayList; import java.util.List; import org.apache.uima.cas.CAS; import org.apache.uima.cas.Type; import org.apache.uima.cas.text.AnnotationFS; import org.springframework.beans.factory.annotation.Autowired; import de.tudarmstadt.ukp.clarin.webanno.api.AnnotationSchemaService; import de.tudarmstadt.ukp.clarin.webanno.diag.repairs.Repair.Safe; import de.tudarmstadt.ukp.clarin.webanno.model.AnnotationLayer; import de.tudarmstadt.ukp.clarin.webanno.model.Project; import de.tudarmstadt.ukp.clarin.webanno.support.logging.LogMessage; @Safe(false) public class ReattachFeatureAttachedSpanAnnotationsAndDeleteExtrasRepair implements Repair { private @Autowired AnnotationSchemaService annotationService; @Override public void repair(Project aProject, CAS aCas, List<LogMessage> aMessages) { for (AnnotationLayer layer : annotationService.listAnnotationLayer(aProject)) { if (!(SPAN_TYPE.equals(layer.getType()) && layer.getAttachFeature() != null)) { continue; } Type attachType = getType(aCas, layer.getAttachType().getName()); String attachFeature = layer.getAttachFeature().getName(); int count = 0; // Go over the layer that has an attach feature (e.g. Token) and make sure that it is // filled // anno -> e.g. Lemma // attach -> e.g. Token for (AnnotationFS anno : select(aCas, getType(aCas, layer.getName()))) { // Here we fetch all annotations of the layer we attach to at the relevant position, // e.g. Token List<AnnotationFS> attachables = selectCovered(attachType, anno); if (attachables.size() > 1) { aMessages.add(LogMessage.error(this, "There is more than one attachable annotation for [%s] on layer [%s].", layer.getName(), attachType.getName())); } for (AnnotationFS attach : attachables) { AnnotationFS existing = getFeature(attach, attachFeature, AnnotationFS.class); // So there is an annotation to which we could attach and it does not yet have // an annotation attached, so we attach to it. if (existing == null) { setFeature(attach, attachFeature, anno); count++; } } } if (count > 0) { aMessages.add(LogMessage.info(this, "Reattached [%d] unattached spans on layer [%s].", count, layer.getName())); } // Go over the layer that is being attached to (e.g. Lemma) and ensure that if there // only exactly one annotation for each annotation in the layer that has the attach // feature (e.g. Token) - or short: ensure that there are not multiple Lemmas for a // single Token because such a thing is not valid in WebAnno. Layers that have an // attach feature cannot have stacking enabled! // // attach -> e.g. Token // candidates -> e.g. Lemma List<AnnotationFS> toDelete = new ArrayList<>(); for (AnnotationFS attach : select(aCas, attachType)) { List<AnnotationFS> candidates = selectCovered(getType(aCas, layer.getName()), attach); if (!candidates.isEmpty()) { // One of the candidates should already be attached AnnotationFS attachedCandidate = getFeature(attach, attachFeature, AnnotationFS.class); for (AnnotationFS candidate : candidates) { if (!candidate.equals(attachedCandidate)) { toDelete.add(candidate); } } } } // Delete those the extra candidates that are not properly attached if (!toDelete.isEmpty()) { toDelete.forEach(aCas::removeFsFromIndexes); aMessages.add( LogMessage.info(this, "Removed [%d] unattached stacked candidates [%s].", toDelete.size(), layer.getName())); } } } }
2,439
1,103
<gh_stars>1000+ /* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.core.schema; import com.netflix.hollow.api.error.IncompatibleSchemaException; import com.netflix.hollow.core.read.filter.HollowFilterConfig; import com.netflix.hollow.core.schema.HollowObjectSchema.FieldType; import org.junit.Assert; import org.junit.Test; public class HollowObjectSchemaTest { @Test public void findsCommonSchemas() { HollowObjectSchema s1 = new HollowObjectSchema("Test", 2, "F2"); s1.addField("F1", FieldType.INT); s1.addField("F2", FieldType.LONG); HollowObjectSchema s2 = new HollowObjectSchema("Test", 2, "F2"); s2.addField("F2", FieldType.LONG); s2.addField("F3", FieldType.STRING); HollowObjectSchema commonSchema = s1.findCommonSchema(s2); Assert.assertEquals(1, commonSchema.numFields()); Assert.assertEquals("F2", commonSchema.getFieldName(0)); Assert.assertEquals(FieldType.LONG, commonSchema.getFieldType(0)); Assert.assertEquals(s1.getPrimaryKey(), s2.getPrimaryKey()); Assert.assertEquals(s1.getPrimaryKey(), commonSchema.getPrimaryKey()); { HollowObjectSchema s3 = new HollowObjectSchema("Test", 2, "F3"); s3.addField("F2", FieldType.LONG); s3.addField("F3", FieldType.STRING); HollowObjectSchema c3 = s1.findCommonSchema(s3); Assert.assertNotEquals(s1.getPrimaryKey(), s3.getPrimaryKey()); Assert.assertNotEquals(s1.getPrimaryKey(), c3.getPrimaryKey()); Assert.assertNull(c3.getPrimaryKey()); } } @Test public void findCommonSchema_incompatible() { try { HollowObjectSchema s1 = new HollowObjectSchema("Test", 2, "F1"); s1.addField("F1", FieldType.INT); HollowObjectSchema s2 = new HollowObjectSchema("Test", 2, "F1"); s2.addField("F1", FieldType.STRING); s1.findCommonSchema(s2); Assert.fail("Expected IncompatibleSchemaException"); } catch (IncompatibleSchemaException e) { Assert.assertEquals("Test", e.getTypeName()); Assert.assertEquals("F1", e.getFieldName()); } } @Test public void findsUnionSchemas() { HollowObjectSchema s1 = new HollowObjectSchema("Test", 2, "F2"); s1.addField("F1", FieldType.INT); s1.addField("F2", FieldType.LONG); HollowObjectSchema s2 = new HollowObjectSchema("Test", 2, "F2"); s2.addField("F2", FieldType.LONG); s2.addField("F3", FieldType.STRING); HollowObjectSchema unionSchema = s1.findUnionSchema(s2); Assert.assertEquals(3, unionSchema.numFields()); Assert.assertEquals("F1", unionSchema.getFieldName(0)); Assert.assertEquals(FieldType.INT, unionSchema.getFieldType(0)); Assert.assertEquals("F2", unionSchema.getFieldName(1)); Assert.assertEquals(FieldType.LONG, unionSchema.getFieldType(1)); Assert.assertEquals("F3", unionSchema.getFieldName(2)); Assert.assertEquals(FieldType.STRING, unionSchema.getFieldType(2)); Assert.assertEquals(s1.getPrimaryKey(), s2.getPrimaryKey()); Assert.assertEquals(s1.getPrimaryKey(), unionSchema.getPrimaryKey()); { HollowObjectSchema s3 = new HollowObjectSchema("Test", 2, "F3"); s3.addField("F2", FieldType.LONG); s3.addField("F3", FieldType.STRING); HollowObjectSchema u3 = s1.findUnionSchema(s3); Assert.assertNotEquals(s1.getPrimaryKey(), u3.getPrimaryKey()); Assert.assertNotEquals(s1.getPrimaryKey(), u3.getPrimaryKey()); Assert.assertNull(u3.getPrimaryKey()); } } @Test public void filterSchema() { HollowObjectSchema s1 = new HollowObjectSchema("Test", 2, "F2"); s1.addField("F1", FieldType.INT); s1.addField("F2", FieldType.LONG); Assert.assertEquals(2, s1.numFields()); HollowFilterConfig filter = new HollowFilterConfig(); filter.addField("Test", "F2"); HollowObjectSchema s2 = s1.filterSchema(filter); Assert.assertEquals(1, s2.numFields()); Assert.assertEquals("F2", s2.getFieldName(0)); Assert.assertEquals(s1.getPrimaryKey(), s2.getPrimaryKey()); } @Test public void testEquals() { { HollowObjectSchema s1 = new HollowObjectSchema("Test", 2); s1.addField("F1", FieldType.INT); s1.addField("F2", FieldType.LONG); HollowObjectSchema s2 = new HollowObjectSchema("Test", 2); s2.addField("F1", FieldType.INT); s2.addField("F2", FieldType.LONG); Assert.assertEquals(s1, s2); } { HollowObjectSchema s1 = new HollowObjectSchema("Test", 2); s1.addField("F1", FieldType.INT); s1.addField("F2", FieldType.LONG); HollowObjectSchema s2 = new HollowObjectSchema("Test", 1); s2.addField("F1", FieldType.INT); Assert.assertNotEquals(s1, s2); } } @Test public void testEqualsWithPrimaryKey() { { HollowObjectSchema s1 = new HollowObjectSchema("Test", 2, "F2"); s1.addField("F1", FieldType.INT); s1.addField("F2", FieldType.LONG); HollowObjectSchema s2 = new HollowObjectSchema("Test", 2, "F2"); s2.addField("F1", FieldType.INT); s2.addField("F2", FieldType.LONG); Assert.assertEquals(s1, s2); Assert.assertEquals(s1.getPrimaryKey(), s2.getPrimaryKey()); } { HollowObjectSchema s1 = new HollowObjectSchema("Test", 2, "F1", "F2"); s1.addField("F1", FieldType.INT); s1.addField("F2", FieldType.LONG); HollowObjectSchema s2 = new HollowObjectSchema("Test", 2, "F1", "F2"); s2.addField("F1", FieldType.INT); s2.addField("F2", FieldType.LONG); Assert.assertEquals(s1, s2); Assert.assertEquals(s1.getPrimaryKey(), s2.getPrimaryKey()); } { HollowObjectSchema s1 = new HollowObjectSchema("Test", 2, "F1", "F2"); s1.addField("F1", FieldType.INT); s1.addField("F2", FieldType.LONG); HollowObjectSchema s2 = new HollowObjectSchema("Test", 2, "F1"); s2.addField("F1", FieldType.INT); s2.addField("F2", FieldType.LONG); Assert.assertNotEquals(s1, s2); Assert.assertNotEquals(s1.getPrimaryKey(), s2.getPrimaryKey()); } { HollowObjectSchema s1 = new HollowObjectSchema("Test", 2); s1.addField("F1", FieldType.INT); s1.addField("F2", FieldType.LONG); HollowObjectSchema s2 = new HollowObjectSchema("Test", 2, "F1"); s2.addField("F1", FieldType.INT); s2.addField("F2", FieldType.LONG); Assert.assertNotEquals(s1, s2); Assert.assertNotEquals(s1.getPrimaryKey(), s2.getPrimaryKey()); } } }
3,554
926
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys sys.path.append("../../") import unittest import time import numpy as np import paddle import paddle.fluid as fluid from paddleslim.prune import sensitivity import paddle.vision.transforms as T from paddle.static import InputSpec as Input from paddleslim.dygraph import L1NormFilterPruner class TestSensitivity(unittest.TestCase): def __init__(self, methodName='runTest', pruner=None, param_names=[]): super(TestSensitivity, self).__init__(methodName) self._pruner = pruner self._param_names = param_names transform = T.Compose([T.Transpose(), T.Normalize([127.5], [127.5])]) self.train_dataset = paddle.vision.datasets.MNIST( mode="train", backend="cv2", transform=transform) self.val_dataset = paddle.vision.datasets.MNIST( mode="test", backend="cv2", transform=transform) def _reader(): for data in self.val_dataset: yield data self.val_reader = _reader def runTest(self): dygraph_sen, params = self.dygraph_sen() static_sen = self.static_sen(params) all_right = True for _name, _value in dygraph_sen.items(): _losses = {} for _ratio, _loss in static_sen[_name].items(): _losses[round(_ratio, 2)] = _loss for _ratio, _loss in _value.items(): if not np.allclose(_losses[_ratio], _loss, atol=1e-2): print( f'static loss: {static_sen[_name][_ratio]}; dygraph loss: {_loss}' ) all_right = False self.assertTrue(all_right) def dygraph_sen(self): paddle.disable_static() net = paddle.vision.models.LeNet() optimizer = paddle.optimizer.Adam( learning_rate=0.001, parameters=net.parameters()) inputs = [Input([None, 1, 28, 28], 'float32', name='image')] labels = [Input([None, 1], 'int64', name='label')] model = paddle.Model(net, inputs, labels) model.prepare( optimizer, paddle.nn.CrossEntropyLoss(), paddle.metric.Accuracy(topk=(1, 5))) model.fit(self.train_dataset, epochs=1, batch_size=128, verbose=1) result = model.evaluate(self.val_dataset, batch_size=128, verbose=1) pruner = None if self._pruner == 'l1norm': pruner = L1NormFilterPruner(net, [1, 1, 28, 28]) elif self._pruner == 'fpgm': pruner = FPGMFilterPruner(net, [1, 1, 28, 28]) def eval_fn(): result = model.evaluate(self.val_dataset, batch_size=128) return result['acc_top1'] sen = pruner.sensitive( eval_func=eval_fn, sen_file="_".join(["./dygraph_sen_", str(time.time())]), #sen_file="sen.pickle", target_vars=self._param_names) params = {} for param in net.parameters(): params[param.name] = np.array(param.value().get_tensor()) print(f'dygraph sen: {sen}') return sen, params def static_sen(self, params): paddle.enable_static() main_program = fluid.Program() startup_program = fluid.Program() with fluid.unique_name.guard(): with fluid.program_guard(main_program, startup_program): input = fluid.data(name="image", shape=[None, 1, 28, 28]) label = fluid.data(name="label", shape=[None, 1], dtype="int64") model = paddle.vision.models.LeNet() out = model(input) acc_top1 = fluid.layers.accuracy(input=out, label=label, k=1) eval_program = main_program.clone(for_test=True) place = fluid.CUDAPlace(0) scope = fluid.global_scope() exe = fluid.Executor(place) exe.run(startup_program) val_reader = paddle.fluid.io.batch(self.val_reader, batch_size=128) def eval_func(program): feeder = fluid.DataFeeder( feed_list=['image', 'label'], place=place, program=program) acc_set = [] for data in val_reader(): acc_np = exe.run(program=program, feed=feeder.feed(data), fetch_list=[acc_top1]) acc_set.append(float(acc_np[0])) acc_val_mean = np.array(acc_set).mean() return acc_val_mean for _name, _value in params.items(): t = scope.find_var(_name).get_tensor() t.set(_value, place) print(f"static base: {eval_func(eval_program)}") criterion = None if self._pruner == 'l1norm': criterion = 'l1_norm' elif self._pruner == 'fpgm': criterion = 'geometry_median' sen = sensitivity( eval_program, place, self._param_names, eval_func, sensitivities_file="_".join( ["./sensitivities_file", str(time.time())]), criterion=criterion) return sen def add_cases(suite): suite.addTest( TestSensitivity( pruner="l1norm", param_names=["conv2d_0.w_0"])) def load_tests(loader, standard_tests, pattern): suite = unittest.TestSuite() add_cases(suite) return suite if __name__ == '__main__': unittest.main()
2,781
15,179
<filename>tests/unit/clients/test_helper.py import aiohttp import pytest from jina import Flow from jina.logging.logger import JinaLogger from jina.types.request import Request from jina.clients.request.helper import _new_data_request from jina.clients.base.helper import HTTPClientlet, WebsocketClientlet logger = JinaLogger('clientlet') @pytest.mark.asyncio async def test_http_clientlet(): with Flow(port_expose=12345, protocol='http').add(): async with HTTPClientlet( url='http://localhost:12345/post', logger=logger ) as iolet: request = _new_data_request('/', None, {'a': 'b'}) r = await iolet.send_message(request) response = Request(await r.json()) response = response.as_typed_request(response.request_type).as_response() assert response.header.exec_endpoint == '/' assert response.parameters == {'a': 'b'} @pytest.mark.asyncio async def test_websocket_clientlet(): with pytest.raises(aiohttp.ClientError): async with WebsocketClientlet( url='ws://localhost:12345', logger=logger ) as iolet: pass
477
393
<filename>OtrosLogViewer-app/src/main/java/pl/otros/logview/gui/actions/search/SearchAction.java /* * ****************************************************************************** * Copyright 2011 <NAME> * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package pl.otros.logview.gui.actions.search; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pl.otros.logview.accept.query.QueryAcceptCondition; import pl.otros.logview.accept.query.org.apache.log4j.rule.RuleException; import pl.otros.logview.api.OtrosApplication; import pl.otros.logview.api.StatusObserver; import pl.otros.logview.api.gui.Icons; import pl.otros.logview.api.gui.LogViewPanelWrapper; import pl.otros.logview.api.gui.OtrosAction; import pl.otros.logview.api.model.MarkerColors; import javax.swing.*; import javax.swing.text.BadLocationException; import javax.swing.text.StyledDocument; import java.awt.*; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.Optional; public class SearchAction extends OtrosAction { private static final Logger LOGGER = LoggerFactory.getLogger(SearchAction.class); public enum SearchMode { STRING_CONTAINS("String contains search"), REGEX("Regex search"), QUERY("Query search"); private final String name; SearchMode(String name) { this.name = name; } public String getName() { return name; } } private SearchMode searchMode = SearchMode.STRING_CONTAINS; private boolean markFound = false; private final SearchEngine searchEngine; private MarkerColors markerColors = MarkerColors.Aqua; private final SearchDirection searchDirection; private final SearchListener searchListener; public SearchAction(OtrosApplication otrosApplication, SearchDirection searchDirection, SearchListener searchListener) { super(otrosApplication); this.searchDirection = searchDirection; this.searchListener = searchListener; if (searchDirection.equals(SearchDirection.FORWARD)) { this.putValue(Action.NAME, "Next"); this.putValue(Action.SMALL_ICON, Icons.ARROW_DOWN); } else { this.putValue(Action.NAME, "Previous"); this.putValue(Action.SMALL_ICON, Icons.ARROW_UP); } searchEngine = new SearchEngine(); } @Override protected void actionPerformedHook(ActionEvent arg0) { StatusObserver statusObserver = getOtrosApplication().getStatusObserver(); String text = getOtrosApplication().getSearchField().getText().trim(); if (text.trim().length() == 0) { statusObserver.updateStatus("No search criteria", StatusObserver.LEVEL_WARNING); return; } performSearch(text, searchDirection); } public void performSearch(String text, SearchDirection direction) { searchListener.searchPerformed(searchMode, text); StatusObserver statusObserver = getOtrosApplication().getStatusObserver(); JTabbedPane jTabbedPane = getOtrosApplication().getJTabbedPane(); LogViewPanelWrapper lvPanel = (LogViewPanelWrapper) jTabbedPane.getSelectedComponent(); if (lvPanel == null) { return; } JTable table = lvPanel.getLogViewPanel().getTable(); NextRowProvider nextRowProvider = NextRowProviderFactory.getFilteredTableRow(table, direction); SearchContext context = new SearchContext(); context.setDataTableModel(lvPanel.getDataTableModel()); SearchMatcher searchMatcher = null; if (SearchMode.STRING_CONTAINS.equals(searchMode)) { searchMatcher = new StringContainsSearchMatcher(text); } else if (SearchMode.REGEX.equals(searchMode)) { try { searchMatcher = new RegexMatcher(text); } catch (Exception e) { statusObserver.updateStatus("Error in regular expression: " + e.getMessage(), StatusObserver.LEVEL_ERROR); return; } } else if (SearchMode.QUERY.equals(searchMode)) { QueryAcceptCondition acceptCondition; try { acceptCondition = new QueryAcceptCondition(text); searchMatcher = new AcceptConditionSearchMatcher(acceptCondition); } catch (RuleException e) { statusObserver.updateStatus("Wrong query rule: " + e.getMessage(), StatusObserver.LEVEL_ERROR); return; } } context.setSearchMatcher(searchMatcher); SearchResult searchNext = searchEngine.searchNext(context, nextRowProvider); if (searchNext.isFound()) { int row = table.convertRowIndexToView(searchNext.getRow()); Rectangle rect = table.getCellRect(row, 0, true); table.scrollRectToVisible(rect); table.clearSelection(); table.setRowSelectionInterval(row, row); statusObserver.updateStatus(String.format("Found at row %d", row), StatusObserver.LEVEL_NORMAL); if (markFound) { lvPanel.getDataTableModel().markRows(markerColors, table.convertRowIndexToModel(row)); } assert searchMatcher != null; scrollToSearchResult(searchMatcher.getFoundTextFragments(lvPanel.getDataTableModel().getLogData(table.convertRowIndexToModel(row))), lvPanel .getLogViewPanel().getLogDetailTextArea()); } else { statusObserver.updateStatus(String.format("\"%s\" not found", text), StatusObserver.LEVEL_WARNING); } } private void scrollToSearchResult(ArrayList<String> toHighlight, JTextPane textPane) { if (toHighlight.size() == 0) { return; } try { StyledDocument logDetailsDocument = textPane.getStyledDocument(); String text = logDetailsDocument.getText(0, logDetailsDocument.getLength()); String string = toHighlight.get(0); textPane.setCaretPosition(Math.max(text.indexOf(string), 0)); } catch (BadLocationException e) { LOGGER.warn("Cant scroll to content, wrong location: " + e.getMessage()); } } public boolean isMarkFound() { return markFound; } public void setMarkFound(boolean markFound) { this.markFound = markFound; } public MarkerColors getMarkerColors() { return markerColors; } public void setMarkerColors(MarkerColors markerColors) { this.markerColors = markerColors; } public void setSearchMode(SearchMode searchMode) { this.searchMode = searchMode; } public SearchMode getSearchMode() { return searchMode; } @Override public Optional<String> actionModeForStats() { return Optional.of(searchMode.name()); } }
2,324
421
<reponame>hamarb123/dotnet-api-docs //<snippet4> using namespace System; using namespace System::IO; public ref class ProcessFile { public: static void Main() { try { StreamReader^ sr = File::OpenText("data.txt"); Console::WriteLine("The first line of this file is {0}", sr->ReadLine()); } //<snippet5> catch (FileNotFoundException^ e) { Console::WriteLine("[Data File Missing] {0}", e); } //</snippet5> catch (Exception^ e) { Console::WriteLine("An error occurred: '{0}'", e); } } }; int main() { ProcessFile::Main(); } //</snippet4>
366
390
<filename>blueflood-core/src/main/java/com/rackspacecloud/blueflood/io/datastax/DLocatorIO.java /* * Copyright (c) 2016 Rackspace. * * 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.rackspacecloud.blueflood.io.datastax; import com.codahale.metrics.Timer; import com.datastax.driver.core.*; import com.datastax.driver.core.querybuilder.Insert; import com.datastax.driver.core.querybuilder.QueryBuilder; import com.datastax.driver.core.querybuilder.Select; import com.rackspacecloud.blueflood.cache.TenantTtlProvider; import com.rackspacecloud.blueflood.io.CassandraModel; import com.rackspacecloud.blueflood.io.Instrumentation; import com.rackspacecloud.blueflood.io.LocatorIO; import com.rackspacecloud.blueflood.rollup.Granularity; import com.rackspacecloud.blueflood.rollup.SlotKey; import com.rackspacecloud.blueflood.types.Locator; import com.rackspacecloud.blueflood.utils.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import static com.datastax.driver.core.querybuilder.QueryBuilder.bindMarker; import static com.datastax.driver.core.querybuilder.QueryBuilder.eq; import static com.datastax.driver.core.querybuilder.QueryBuilder.ttl; /** * This class uses the Datastax driver to read/write locators from * Cassandra metrics_locator Column Family. */ public class DLocatorIO implements LocatorIO { private static final Logger LOG = LoggerFactory.getLogger(DLocatorIO.class); private static final String KEY = "key"; private static final String COLUMN1 = "column1"; private static final String VALUE = "value"; private PreparedStatement getValue; private PreparedStatement putValue; /** * Constructor */ public DLocatorIO() { createPreparedStatements(); } /** * Create all prepared statements use in this class for metrics_locator */ private void createPreparedStatements() { // create a generic select statement for retrieving from metrics_locator Select.Where select = QueryBuilder .select() .all() .from( CassandraModel.CF_METRICS_LOCATOR_NAME ) .where( eq ( KEY, bindMarker() )); getValue = DatastaxIO.getSession().prepare( select ); // create a generic insert statement for inserting into metrics_locator Insert insert = QueryBuilder.insertInto( CassandraModel.CF_METRICS_LOCATOR_NAME) .using(ttl(TenantTtlProvider.LOCATOR_TTL)) .value(KEY, bindMarker()) .value(COLUMN1, bindMarker()) .value(VALUE, bindMarker()); putValue = DatastaxIO.getSession() .prepare(insert) .setConsistencyLevel( ConsistencyLevel.LOCAL_ONE ); } /** * Insert a locator with key = shard long value calculated using Util.getShard() * @param locator * @throws IOException */ @Override public void insertLocator(Locator locator) throws IOException { Session session = DatastaxIO.getSession(); Timer.Context timer = Instrumentation.getWriteTimerContext(CassandraModel.CF_METRICS_LOCATOR_NAME); try { // bound values and execute BoundStatement bs = getBoundStatementForLocator(locator); session.execute(bs); } finally { timer.stop(); } } // package protect so other classes in this package can call it BoundStatement getBoundStatementForLocator(Locator locator) { // get shard this locator would belong to long shard = (long) Util.getShard(locator.toString()); return putValue.bind(shard, locator.toString(), ""); } /** * Returns the locators for a shard, i.e. those that should be rolled up, for a given shard. * 'Should' means: * 1) A locator is capable of rollup. * 2) A locator has had new data in the past LOCATOR_TTL seconds. * * @param shard Number of the shard you want the locators for. 0-127 inclusive. * @return Collection of locators * @throws IOException */ @Override public Collection<Locator> getLocators(long shard) throws IOException { Timer.Context ctx = Instrumentation.getReadTimerContext(CassandraModel.CF_METRICS_LOCATOR_NAME); Session session = DatastaxIO.getSession(); Collection<Locator> locators = new ArrayList<Locator>(); try { // bind value BoundStatement bs = getValue.bind(shard); List<Row> results = session.execute(bs).all(); for ( Row row : results ) { if ( LOG.isTraceEnabled() ) { LOG.trace( "Read metrics_locators with shard " + shard + ": " + row.getString( KEY ) + row.getString( COLUMN1 )); } locators.add(Locator.createLocatorFromDbKey(row.getString(COLUMN1))); } // return results if (locators.size() == 0) { Instrumentation.markNotFound(CassandraModel.CF_METRICS_LOCATOR_NAME); return Collections.emptySet(); } else { return locators; } } finally { ctx.stop(); } } }
2,340
679
<reponame>Grosskopf/openoffice /************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ package com.sun.star.lib; import com.sun.star.bridge.XBridge; import com.sun.star.bridge.XBridgeFactory; import com.sun.star.bridge.XInstanceProvider; import com.sun.star.comp.helper.Bootstrap; import com.sun.star.connection.Acceptor; import com.sun.star.connection.Connector; import com.sun.star.connection.XAcceptor; import com.sun.star.connection.XConnection; import com.sun.star.connection.XConnector; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XComponentContext; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; public final class TestBed { public boolean execute(XInstanceProvider provider, boolean waitForServer, Class client, long wait) throws Exception { // assert client.isAssignableFrom(client) && wait >= 0; synchronized (lock) { server = new Server(provider); server.start(); server.waitAccepting(); } Process p = Runtime.getRuntime().exec(new String[] { "java", "-classpath", System.getProperty("java.class.path"), /* "-Xdebug", "-Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n", */ client.getName() }); pipe(p.getInputStream(), System.out, "CO> "); pipe(p.getErrorStream(), System.err, "CE> "); boolean clientDone = false; if (wait <= 0) { clientDone = p.waitFor() == CLIENT_DONE; } else { try { Thread.sleep(wait); } catch (InterruptedException e) { p.destroy(); throw e; } try { clientDone = p.exitValue() == CLIENT_DONE; } catch (IllegalThreadStateException e) { p.destroy(); } } boolean success = clientDone; if (waitForServer) { success &= server.waitDone(); } return success; } public void serverDone(boolean success) { synchronized (lock) { server.done(success); } } private void pipe(final InputStream in, final PrintStream out, final String prefix) { new Thread("Pipe: " + prefix) { public void run() { BufferedReader r = new BufferedReader(new InputStreamReader(in)); try { for (;;) { String s = r.readLine(); if (s == null) { break; } out.println(prefix + s); } } catch (java.io.IOException e) { e.printStackTrace(System.err); } } }.start(); } public static abstract class Client { protected abstract boolean run(XComponentContext context) throws Throwable; protected final String getConnectionDescription() { return connectionDescription; } protected final String getProtocolDescription() { return protocolDescription; } protected final XBridge getBridge(XComponentContext context) throws com.sun.star.uno.Exception { XConnector connector = Connector.create(context); XBridgeFactory factory = UnoRuntime.queryInterface( XBridgeFactory.class, context.getServiceManager().createInstanceWithContext( "com.sun.star.bridge.BridgeFactory", context)); System.out.println("Client: Connecting..."); XConnection connection = connector.connect(connectionDescription); System.out.println("Client: ...connected..."); XBridge bridge = factory.createBridge( "", protocolDescription, connection, null); System.out.println("Client: ...bridged."); return bridge; } protected final void execute() { int status = CLIENT_FAILED; try { if (run(Bootstrap.createInitialComponentContext(null))) { status = CLIENT_DONE; } } catch (Throwable e) { e.printStackTrace(System.err); } System.exit(status); } } private static final class Server extends Thread { public Server(XInstanceProvider provider) { super("Server"); // assert provider != null; this.provider = provider; } public void run() { try { XComponentContext context = Bootstrap.createInitialComponentContext(null); XAcceptor acceptor = Acceptor.create(context); XBridgeFactory factory = UnoRuntime.queryInterface( XBridgeFactory.class, context.getServiceManager().createInstanceWithContext( "com.sun.star.bridge.BridgeFactory", context)); System.out.println("Server: Accepting..."); synchronized (this) { state = ACCEPTING; notifyAll(); } for (;;) { XConnection connection = acceptor.accept( connectionDescription); System.out.println("Server: ...connected..."); XBridge bridge = factory.createBridge( "", protocolDescription, connection, provider); System.out.println("Server: ...bridged."); } } catch (Throwable e) { e.printStackTrace(System.err); } } public synchronized void waitAccepting() throws InterruptedException { while (state < ACCEPTING) { wait(); } } public synchronized boolean waitDone() throws InterruptedException { while (state <= ACCEPTING) { wait(); } return state == SUCCEEDED; } public synchronized void done(boolean success) { state = success ? SUCCEEDED : FAILED; notifyAll(); } private static final int INITIAL = 0; private static final int ACCEPTING = 1; private static final int FAILED = 2; private static final int SUCCEEDED = 3; private final XInstanceProvider provider; private int state = INITIAL; } private static final int TEST_SUCCEEDED = 0; private static final int TEST_FAILED = 1; private static final int TEST_ERROR = 2; private static final int CLIENT_FAILED = 0; private static final int CLIENT_DONE = 123; private static final String connectionDescription = "socket,host=localhost,port=12345"; private static final String protocolDescription = "urp"; private final Object lock = new Object(); private Server server = null; }
3,588
2,621
<reponame>SuperPokeS/Osiris<filename>Osiris/freetype/src/autofit/afblue.c /* This file has been generated by the Perl script `afblue.pl', */ /* using data from file `afblue.dat'. */ /**************************************************************************** * * afblue.c * * Auto-fitter data for blue strings (body). * * Copyright (C) 2013-2020 by * <NAME>, <NAME>, and <NAME>. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #include "aftypes.h" FT_LOCAL_ARRAY_DEF( char ) af_blue_strings[] = { /* */ '\xF0', '\x9E', '\xA4', '\x8C', ' ', '\xF0', '\x9E', '\xA4', '\x85', ' ', '\xF0', '\x9E', '\xA4', '\x88', ' ', '\xF0', '\x9E', '\xA4', '\x8F', ' ', '\xF0', '\x9E', '\xA4', '\x94', ' ', '\xF0', '\x9E', '\xA4', '\x9A', /* 𞤌 𞤅 𞤈 𞤏 𞤔 𞤚 */ '\0', '\xF0', '\x9E', '\xA4', '\x82', ' ', '\xF0', '\x9E', '\xA4', '\x96', /* 𞤂 𞤖 */ '\0', '\xF0', '\x9E', '\xA4', '\xAC', ' ', '\xF0', '\x9E', '\xA4', '\xAE', ' ', '\xF0', '\x9E', '\xA4', '\xBB', ' ', '\xF0', '\x9E', '\xA4', '\xBC', ' ', '\xF0', '\x9E', '\xA4', '\xBE', /* 𞤬 𞤮 𞤻 𞤼 𞤾 */ '\0', '\xF0', '\x9E', '\xA4', '\xA4', ' ', '\xF0', '\x9E', '\xA4', '\xA8', ' ', '\xF0', '\x9E', '\xA4', '\xA9', ' ', '\xF0', '\x9E', '\xA4', '\xAD', ' ', '\xF0', '\x9E', '\xA4', '\xB4', ' ', '\xF0', '\x9E', '\xA4', '\xB8', ' ', '\xF0', '\x9E', '\xA4', '\xBA', ' ', '\xF0', '\x9E', '\xA5', '\x80', /* 𞤤 𞤨 𞤩 𞤭 𞤴 𞤸 𞤺 𞥀 */ '\0', '\xD8', '\xA7', ' ', '\xD8', '\xA5', ' ', '\xD9', '\x84', ' ', '\xD9', '\x83', ' ', '\xD8', '\xB7', ' ', '\xD8', '\xB8', /* ا إ ل ك ط ظ */ '\0', '\xD8', '\xAA', ' ', '\xD8', '\xAB', ' ', '\xD8', '\xB7', ' ', '\xD8', '\xB8', ' ', '\xD9', '\x83', /* ت ث ط ظ ك */ '\0', '\xD9', '\x80', /* ـ */ '\0', '\xD4', '\xB1', ' ', '\xD5', '\x84', ' ', '\xD5', '\x92', ' ', '\xD5', '\x8D', ' ', '\xD4', '\xB2', ' ', '\xD4', '\xB3', ' ', '\xD4', '\xB4', ' ', '\xD5', '\x95', /* Ա Մ Ւ Ս Բ Գ Դ Օ */ '\0', '\xD5', '\x92', ' ', '\xD5', '\x88', ' ', '\xD4', '\xB4', ' ', '\xD5', '\x83', ' ', '\xD5', '\x87', ' ', '\xD5', '\x8D', ' ', '\xD5', '\x8F', ' ', '\xD5', '\x95', /* Ւ Ո Դ Ճ Շ Ս Տ Օ */ '\0', '\xD5', '\xA5', ' ', '\xD5', '\xA7', ' ', '\xD5', '\xAB', ' ', '\xD5', '\xB4', ' ', '\xD5', '\xBE', ' ', '\xD6', '\x86', ' ', '\xD5', '\xB3', /* ե է ի մ վ ֆ ճ */ '\0', '\xD5', '\xA1', ' ', '\xD5', '\xB5', ' ', '\xD6', '\x82', ' ', '\xD5', '\xBD', ' ', '\xD5', '\xA3', ' ', '\xD5', '\xB7', ' ', '\xD6', '\x80', ' ', '\xD6', '\x85', /* ա յ ւ ս գ շ ր օ */ '\0', '\xD5', '\xB0', ' ', '\xD5', '\xB8', ' ', '\xD5', '\xB3', ' ', '\xD5', '\xA1', ' ', '\xD5', '\xA5', ' ', '\xD5', '\xAE', ' ', '\xD5', '\xBD', ' ', '\xD6', '\x85', /* հ ո ճ ա ե ծ ս օ */ '\0', '\xD5', '\xA2', ' ', '\xD5', '\xA8', ' ', '\xD5', '\xAB', ' ', '\xD5', '\xAC', ' ', '\xD5', '\xB2', ' ', '\xD5', '\xBA', ' ', '\xD6', '\x83', ' ', '\xD6', '\x81', /* բ ը ի լ ղ պ փ ց */ '\0', '\xF0', '\x90', '\xAC', '\x80', ' ', '\xF0', '\x90', '\xAC', '\x81', ' ', '\xF0', '\x90', '\xAC', '\x90', ' ', '\xF0', '\x90', '\xAC', '\x9B', /* 𐬀 𐬁 𐬐 𐬛 */ '\0', '\xF0', '\x90', '\xAC', '\x80', ' ', '\xF0', '\x90', '\xAC', '\x81', /* 𐬀 𐬁 */ '\0', '\xEA', '\x9A', '\xA7', ' ', '\xEA', '\x9A', '\xA8', ' ', '\xEA', '\x9B', '\x9B', ' ', '\xEA', '\x9B', '\x89', ' ', '\xEA', '\x9B', '\x81', ' ', '\xEA', '\x9B', '\x88', ' ', '\xEA', '\x9B', '\xAB', ' ', '\xEA', '\x9B', '\xAF', /* ꚧ ꚨ ꛛ ꛉ ꛁ ꛈ ꛫ ꛯ */ '\0', '\xEA', '\x9A', '\xAD', ' ', '\xEA', '\x9A', '\xB3', ' ', '\xEA', '\x9A', '\xB6', ' ', '\xEA', '\x9B', '\xAC', ' ', '\xEA', '\x9A', '\xA2', ' ', '\xEA', '\x9A', '\xBD', ' ', '\xEA', '\x9B', '\xAF', ' ', '\xEA', '\x9B', '\xB2', /* ꚭ ꚳ ꚶ ꛬ ꚢ ꚽ ꛯ ꛲ */ '\0', '\xE0', '\xA6', '\x85', ' ', '\xE0', '\xA6', '\xA1', ' ', '\xE0', '\xA6', '\xA4', ' ', '\xE0', '\xA6', '\xA8', ' ', '\xE0', '\xA6', '\xAC', ' ', '\xE0', '\xA6', '\xAD', ' ', '\xE0', '\xA6', '\xB2', ' ', '\xE0', '\xA6', '\x95', /* অ ড ত ন ব ভ ল ক */ '\0', '\xE0', '\xA6', '\x87', ' ', '\xE0', '\xA6', '\x9F', ' ', '\xE0', '\xA6', '\xA0', ' ', '\xE0', '\xA6', '\xBF', ' ', '\xE0', '\xA7', '\x80', ' ', '\xE0', '\xA7', '\x88', ' ', '\xE0', '\xA7', '\x97', /* ই ট ঠ ি ী ৈ ৗ */ '\0', '\xE0', '\xA6', '\x93', ' ', '\xE0', '\xA6', '\x8F', ' ', '\xE0', '\xA6', '\xA1', ' ', '\xE0', '\xA6', '\xA4', ' ', '\xE0', '\xA6', '\xA8', ' ', '\xE0', '\xA6', '\xAC', ' ', '\xE0', '\xA6', '\xB2', ' ', '\xE0', '\xA6', '\x95', /* ও এ ড ত ন ব ল ক */ '\0', '\xE1', '\x9D', '\x90', ' ', '\xE1', '\x9D', '\x88', /* ᝐ ᝈ */ '\0', '\xE1', '\x9D', '\x85', ' ', '\xE1', '\x9D', '\x8A', ' ', '\xE1', '\x9D', '\x8E', /* ᝅ ᝊ ᝎ */ '\0', '\xE1', '\x9D', '\x82', ' ', '\xE1', '\x9D', '\x83', ' ', '\xE1', '\x9D', '\x89', ' ', '\xE1', '\x9D', '\x8C', /* ᝂ ᝃ ᝉ ᝌ */ '\0', '\xE1', '\x9D', '\x80', ' ', '\xE1', '\x9D', '\x83', ' ', '\xE1', '\x9D', '\x86', ' ', '\xE1', '\x9D', '\x89', ' ', '\xE1', '\x9D', '\x8B', ' ', '\xE1', '\x9D', '\x8F', ' ', '\xE1', '\x9D', '\x91', /* ᝀ ᝃ ᝆ ᝉ ᝋ ᝏ ᝑ */ '\0', '\xE1', '\x97', '\x9C', ' ', '\xE1', '\x96', '\xB4', ' ', '\xE1', '\x90', '\x81', ' ', '\xE1', '\x92', '\xA3', ' ', '\xE1', '\x91', '\xAB', ' ', '\xE1', '\x91', '\x8E', ' ', '\xE1', '\x94', '\x91', ' ', '\xE1', '\x97', '\xB0', /* ᗜ ᖴ ᐁ ᒣ ᑫ ᑎ ᔑ ᗰ */ '\0', '\xE1', '\x97', '\xB6', ' ', '\xE1', '\x96', '\xB5', ' ', '\xE1', '\x92', '\xA7', ' ', '\xE1', '\x90', '\x83', ' ', '\xE1', '\x91', '\x8C', ' ', '\xE1', '\x92', '\x8D', ' ', '\xE1', '\x94', '\x91', ' ', '\xE1', '\x97', '\xA2', /* ᗶ ᖵ ᒧ ᐃ ᑌ ᒍ ᔑ ᗢ */ '\0', '\xE1', '\x93', '\x93', ' ', '\xE1', '\x93', '\x95', ' ', '\xE1', '\x93', '\x80', ' ', '\xE1', '\x93', '\x82', ' ', '\xE1', '\x93', '\x84', ' ', '\xE1', '\x95', '\x84', ' ', '\xE1', '\x95', '\x86', ' ', '\xE1', '\x98', '\xA3', /* ᓓ ᓕ ᓀ ᓂ ᓄ ᕄ ᕆ ᘣ */ '\0', '\xE1', '\x95', '\x83', ' ', '\xE1', '\x93', '\x82', ' ', '\xE1', '\x93', '\x80', ' ', '\xE1', '\x95', '\x82', ' ', '\xE1', '\x93', '\x97', ' ', '\xE1', '\x93', '\x9A', ' ', '\xE1', '\x95', '\x86', ' ', '\xE1', '\x98', '\xA3', /* ᕃ ᓂ ᓀ ᕂ ᓗ ᓚ ᕆ ᘣ */ '\0', '\xE1', '\x90', '\xAA', ' ', '\xE1', '\x99', '\x86', ' ', '\xE1', '\xA3', '\x98', ' ', '\xE1', '\x90', '\xA2', ' ', '\xE1', '\x92', '\xBE', ' ', '\xE1', '\xA3', '\x97', ' ', '\xE1', '\x94', '\x86', /* ᐪ ᙆ ᣘ ᐢ ᒾ ᣗ ᔆ */ '\0', '\xE1', '\x99', '\x86', ' ', '\xE1', '\x97', '\xAE', ' ', '\xE1', '\x92', '\xBB', ' ', '\xE1', '\x90', '\x9E', ' ', '\xE1', '\x94', '\x86', ' ', '\xE1', '\x92', '\xA1', ' ', '\xE1', '\x92', '\xA2', ' ', '\xE1', '\x93', '\x91', /* ᙆ ᗮ ᒻ ᐞ ᔆ ᒡ ᒢ ᓑ */ '\0', '\xF0', '\x90', '\x8A', '\xA7', ' ', '\xF0', '\x90', '\x8A', '\xAB', ' ', '\xF0', '\x90', '\x8A', '\xAC', ' ', '\xF0', '\x90', '\x8A', '\xAD', ' ', '\xF0', '\x90', '\x8A', '\xB1', ' ', '\xF0', '\x90', '\x8A', '\xBA', ' ', '\xF0', '\x90', '\x8A', '\xBC', ' ', '\xF0', '\x90', '\x8A', '\xBF', /* 𐊧 𐊫 𐊬 𐊭 𐊱 𐊺 𐊼 𐊿 */ '\0', '\xF0', '\x90', '\x8A', '\xA3', ' ', '\xF0', '\x90', '\x8A', '\xA7', ' ', '\xF0', '\x90', '\x8A', '\xB7', ' ', '\xF0', '\x90', '\x8B', '\x80', ' ', '\xF0', '\x90', '\x8A', '\xAB', ' ', '\xF0', '\x90', '\x8A', '\xB8', ' ', '\xF0', '\x90', '\x8B', '\x89', /* 𐊣 𐊧 𐊷 𐋀 𐊫 𐊸 𐋉 */ '\0', '\xF0', '\x91', '\x84', '\x83', ' ', '\xF0', '\x91', '\x84', '\x85', ' ', '\xF0', '\x91', '\x84', '\x89', ' ', '\xF0', '\x91', '\x84', '\x99', ' ', '\xF0', '\x91', '\x84', '\x97', /* 𑄃 𑄅 𑄉 𑄙 𑄗 */ '\0', '\xF0', '\x91', '\x84', '\x85', ' ', '\xF0', '\x91', '\x84', '\x9B', ' ', '\xF0', '\x91', '\x84', '\x9D', ' ', '\xF0', '\x91', '\x84', '\x97', ' ', '\xF0', '\x91', '\x84', '\x93', /* 𑄅 𑄛 𑄝 𑄗 𑄓 */ '\0', '\xF0', '\x91', '\x84', '\x96', '\xF0', '\x91', '\x84', '\xB3', '\xF0', '\x91', '\x84', '\xA2', ' ', '\xF0', '\x91', '\x84', '\x98', '\xF0', '\x91', '\x84', '\xB3', '\xF0', '\x91', '\x84', '\xA2', ' ', '\xF0', '\x91', '\x84', '\x99', '\xF0', '\x91', '\x84', '\xB3', '\xF0', '\x91', '\x84', '\xA2', ' ', '\xF0', '\x91', '\x84', '\xA4', '\xF0', '\x91', '\x84', '\xB3', '\xF0', '\x91', '\x84', '\xA2', ' ', '\xF0', '\x91', '\x84', '\xA5', '\xF0', '\x91', '\x84', '\xB3', '\xF0', '\x91', '\x84', '\xA2', /* 𑄖𑄳𑄢 𑄘𑄳𑄢 𑄙𑄳𑄢 𑄤𑄳𑄢 𑄥𑄳𑄢 */ '\0', '\xE1', '\x8F', '\x86', ' ', '\xE1', '\x8E', '\xBB', ' ', '\xE1', '\x8E', '\xAC', ' ', '\xE1', '\x8F', '\x83', ' ', '\xE1', '\x8E', '\xA4', ' ', '\xE1', '\x8F', '\xA3', ' ', '\xE1', '\x8E', '\xA6', ' ', '\xE1', '\x8F', '\x95', /* Ꮖ Ꮋ Ꭼ Ꮓ Ꭴ Ꮳ Ꭶ Ꮥ */ '\0', '\xEA', '\xAE', '\x92', ' ', '\xEA', '\xAE', '\xA4', ' ', '\xEA', '\xAE', '\xB6', ' ', '\xEA', '\xAD', '\xB4', ' ', '\xEA', '\xAD', '\xBE', ' ', '\xEA', '\xAE', '\x97', ' ', '\xEA', '\xAE', '\x9D', ' ', '\xEA', '\xAE', '\xBF', /* ꮒ ꮤ ꮶ ꭴ ꭾ ꮗ ꮝ ꮿ */ '\0', '\xEA', '\xAE', '\x96', ' ', '\xEA', '\xAD', '\xBC', ' ', '\xEA', '\xAE', '\x93', ' ', '\xEA', '\xAE', '\xA0', ' ', '\xEA', '\xAE', '\xB3', ' ', '\xEA', '\xAD', '\xB6', ' ', '\xEA', '\xAE', '\xA5', ' ', '\xEA', '\xAE', '\xBB', /* ꮖ ꭼ ꮓ ꮠ ꮳ ꭶ ꮥ ꮻ */ '\0', '\xE1', '\x8F', '\xB8', ' ', '\xEA', '\xAE', '\x90', ' ', '\xEA', '\xAD', '\xB9', ' ', '\xEA', '\xAD', '\xBB', /* ᏸ ꮐ ꭹ ꭻ */ '\0', '\xE2', '\xB2', '\x8C', ' ', '\xE2', '\xB2', '\x8E', ' ', '\xE2', '\xB2', '\xA0', ' ', '\xE2', '\xB3', '\x9E', ' ', '\xE2', '\xB2', '\x9E', ' ', '\xE2', '\xB2', '\x90', ' ', '\xE2', '\xB2', '\xA4', ' ', '\xE2', '\xB3', '\x8A', /* Ⲍ Ⲏ Ⲡ Ⳟ Ⲟ Ⲑ Ⲥ Ⳋ */ '\0', '\xE2', '\xB3', '\x90', ' ', '\xE2', '\xB3', '\x98', ' ', '\xE2', '\xB3', '\x9E', ' ', '\xE2', '\xB2', '\x8E', ' ', '\xE2', '\xB2', '\x9E', ' ', '\xE2', '\xB2', '\x90', ' ', '\xE2', '\xB3', '\x9C', ' ', '\xE2', '\xB2', '\xB0', /* Ⳑ Ⳙ Ⳟ Ⲏ Ⲟ Ⲑ Ⳝ Ⲱ */ '\0', '\xE2', '\xB2', '\x8D', ' ', '\xE2', '\xB2', '\x8F', ' ', '\xE2', '\xB2', '\xA1', ' ', '\xE2', '\xB3', '\x9F', ' ', '\xE2', '\xB2', '\x9F', ' ', '\xE2', '\xB2', '\x91', ' ', '\xE2', '\xB2', '\xA5', ' ', '\xE2', '\xB3', '\x8B', /* ⲍ ⲏ ⲡ ⳟ ⲟ ⲑ ⲥ ⳋ */ '\0', '\xE2', '\xB3', '\x91', ' ', '\xE2', '\xB3', '\x99', ' ', '\xE2', '\xB3', '\x9F', ' ', '\xE2', '\xB2', '\x8F', ' ', '\xE2', '\xB2', '\x9F', ' ', '\xE2', '\xB2', '\x91', ' ', '\xE2', '\xB3', '\x9D', ' ', '\xE2', '\xB3', '\x92', /* ⳑ ⳙ ⳟ ⲏ ⲟ ⲑ ⳝ Ⳓ */ '\0', '\xF0', '\x90', '\xA0', '\x8D', ' ', '\xF0', '\x90', '\xA0', '\x99', ' ', '\xF0', '\x90', '\xA0', '\xB3', ' ', '\xF0', '\x90', '\xA0', '\xB1', ' ', '\xF0', '\x90', '\xA0', '\x85', ' ', '\xF0', '\x90', '\xA0', '\x93', ' ', '\xF0', '\x90', '\xA0', '\xA3', ' ', '\xF0', '\x90', '\xA0', '\xA6', /* 𐠍 𐠙 𐠳 𐠱 𐠅 𐠓 𐠣 𐠦 */ '\0', '\xF0', '\x90', '\xA0', '\x83', ' ', '\xF0', '\x90', '\xA0', '\x8A', ' ', '\xF0', '\x90', '\xA0', '\x9B', ' ', '\xF0', '\x90', '\xA0', '\xA3', ' ', '\xF0', '\x90', '\xA0', '\xB3', ' ', '\xF0', '\x90', '\xA0', '\xB5', ' ', '\xF0', '\x90', '\xA0', '\x90', /* 𐠃 𐠊 𐠛 𐠣 𐠳 𐠵 𐠐 */ '\0', '\xF0', '\x90', '\xA0', '\x88', ' ', '\xF0', '\x90', '\xA0', '\x8F', ' ', '\xF0', '\x90', '\xA0', '\x96', /* 𐠈 𐠏 𐠖 */ '\0', '\xD0', '\x91', ' ', '\xD0', '\x92', ' ', '\xD0', '\x95', ' ', '\xD0', '\x9F', ' ', '\xD0', '\x97', ' ', '\xD0', '\x9E', ' ', '\xD0', '\xA1', ' ', '\xD0', '\xAD', /* Б В Е П З О С Э */ '\0', '\xD0', '\x91', ' ', '\xD0', '\x92', ' ', '\xD0', '\x95', ' ', '\xD0', '\xA8', ' ', '\xD0', '\x97', ' ', '\xD0', '\x9E', ' ', '\xD0', '\xA1', ' ', '\xD0', '\xAD', /* Б В Е Ш З О С Э */ '\0', '\xD1', '\x85', ' ', '\xD0', '\xBF', ' ', '\xD0', '\xBD', ' ', '\xD1', '\x88', ' ', '\xD0', '\xB5', ' ', '\xD0', '\xB7', ' ', '\xD0', '\xBE', ' ', '\xD1', '\x81', /* х п н ш е з о с */ '\0', '\xD1', '\x80', ' ', '\xD1', '\x83', ' ', '\xD1', '\x84', /* р у ф */ '\0', '\xF0', '\x90', '\x90', '\x82', ' ', '\xF0', '\x90', '\x90', '\x84', ' ', '\xF0', '\x90', '\x90', '\x8B', ' ', '\xF0', '\x90', '\x90', '\x97', ' ', '\xF0', '\x90', '\x90', '\x91', /* 𐐂 𐐄 𐐋 𐐗 𐐑 */ '\0', '\xF0', '\x90', '\x90', '\x80', ' ', '\xF0', '\x90', '\x90', '\x82', ' ', '\xF0', '\x90', '\x90', '\x84', ' ', '\xF0', '\x90', '\x90', '\x97', ' ', '\xF0', '\x90', '\x90', '\x9B', /* 𐐀 𐐂 𐐄 𐐗 𐐛 */ '\0', '\xF0', '\x90', '\x90', '\xAA', ' ', '\xF0', '\x90', '\x90', '\xAC', ' ', '\xF0', '\x90', '\x90', '\xB3', ' ', '\xF0', '\x90', '\x90', '\xBF', ' ', '\xF0', '\x90', '\x90', '\xB9', /* 𐐪 𐐬 𐐳 𐐿 𐐹 */ '\0', '\xF0', '\x90', '\x90', '\xA8', ' ', '\xF0', '\x90', '\x90', '\xAA', ' ', '\xF0', '\x90', '\x90', '\xAC', ' ', '\xF0', '\x90', '\x90', '\xBF', ' ', '\xF0', '\x90', '\x91', '\x83', /* 𐐨 𐐪 𐐬 𐐿 𐑃 */ '\0', '\xE0', '\xA4', '\x95', ' ', '\xE0', '\xA4', '\xA8', ' ', '\xE0', '\xA4', '\xAE', ' ', '\xE0', '\xA4', '\x89', ' ', '\xE0', '\xA4', '\x9B', ' ', '\xE0', '\xA4', '\x9F', ' ', '\xE0', '\xA4', '\xA0', ' ', '\xE0', '\xA4', '\xA1', /* क न म उ छ ट ठ ड */ '\0', '\xE0', '\xA4', '\x88', ' ', '\xE0', '\xA4', '\x90', ' ', '\xE0', '\xA4', '\x93', ' ', '\xE0', '\xA4', '\x94', ' ', '\xE0', '\xA4', '\xBF', ' ', '\xE0', '\xA5', '\x80', ' ', '\xE0', '\xA5', '\x8B', ' ', '\xE0', '\xA5', '\x8C', /* ई ऐ ओ औ ि ी ो ौ */ '\0', '\xE0', '\xA4', '\x95', ' ', '\xE0', '\xA4', '\xAE', ' ', '\xE0', '\xA4', '\x85', ' ', '\xE0', '\xA4', '\x86', ' ', '\xE0', '\xA4', '\xA5', ' ', '\xE0', '\xA4', '\xA7', ' ', '\xE0', '\xA4', '\xAD', ' ', '\xE0', '\xA4', '\xB6', /* क म अ आ थ ध भ श */ '\0', '\xE0', '\xA5', '\x81', ' ', '\xE0', '\xA5', '\x83', /* ु ृ */ '\0', '\xE1', '\x88', '\x80', ' ', '\xE1', '\x88', '\x83', ' ', '\xE1', '\x8B', '\x98', ' ', '\xE1', '\x8D', '\x90', ' ', '\xE1', '\x88', '\x9B', ' ', '\xE1', '\x89', '\xA0', ' ', '\xE1', '\x8B', '\x8B', ' ', '\xE1', '\x8B', '\x90', /* ሀ ሃ ዘ ፐ ማ በ ዋ ዐ */ '\0', '\xE1', '\x88', '\x88', ' ', '\xE1', '\x88', '\x90', ' ', '\xE1', '\x89', '\xA0', ' ', '\xE1', '\x8B', '\x98', ' ', '\xE1', '\x88', '\x80', ' ', '\xE1', '\x88', '\xAA', ' ', '\xE1', '\x8B', '\x90', ' ', '\xE1', '\x8C', '\xA8', /* ለ ሐ በ ዘ ሀ ሪ ዐ ጨ */ '\0', '\xE1', '\x83', '\x92', ' ', '\xE1', '\x83', '\x93', ' ', '\xE1', '\x83', '\x94', ' ', '\xE1', '\x83', '\x95', ' ', '\xE1', '\x83', '\x97', ' ', '\xE1', '\x83', '\x98', ' ', '\xE1', '\x83', '\x9D', ' ', '\xE1', '\x83', '\xA6', /* გ დ ე ვ თ ი ო ღ */ '\0', '\xE1', '\x83', '\x90', ' ', '\xE1', '\x83', '\x96', ' ', '\xE1', '\x83', '\x9B', ' ', '\xE1', '\x83', '\xA1', ' ', '\xE1', '\x83', '\xA8', ' ', '\xE1', '\x83', '\xAB', ' ', '\xE1', '\x83', '\xAE', ' ', '\xE1', '\x83', '\x9E', /* ა ზ მ ს შ ძ ხ პ */ '\0', '\xE1', '\x83', '\xA1', ' ', '\xE1', '\x83', '\xAE', ' ', '\xE1', '\x83', '\xA5', ' ', '\xE1', '\x83', '\x96', ' ', '\xE1', '\x83', '\x9B', ' ', '\xE1', '\x83', '\xA8', ' ', '\xE1', '\x83', '\xA9', ' ', '\xE1', '\x83', '\xAC', /* ს ხ ქ ზ მ შ ჩ წ */ '\0', '\xE1', '\x83', '\x94', ' ', '\xE1', '\x83', '\x95', ' ', '\xE1', '\x83', '\x9F', ' ', '\xE1', '\x83', '\xA2', ' ', '\xE1', '\x83', '\xA3', ' ', '\xE1', '\x83', '\xA4', ' ', '\xE1', '\x83', '\xA5', ' ', '\xE1', '\x83', '\xA7', /* ე ვ ჟ ტ უ ფ ქ ყ */ '\0', '\xE1', '\x82', '\xB1', ' ', '\xE1', '\x82', '\xA7', ' ', '\xE1', '\x82', '\xB9', ' ', '\xE1', '\x82', '\xBC', ' ', '\xE1', '\x82', '\xA4', ' ', '\xE1', '\x82', '\xA5', ' ', '\xE1', '\x82', '\xB3', ' ', '\xE1', '\x82', '\xBA', /* Ⴑ Ⴇ Ⴙ Ⴜ Ⴄ Ⴅ Ⴓ Ⴚ */ '\0', '\xE1', '\x82', '\xA4', ' ', '\xE1', '\x82', '\xA5', ' ', '\xE1', '\x82', '\xA7', ' ', '\xE1', '\x82', '\xA8', ' ', '\xE1', '\x82', '\xA6', ' ', '\xE1', '\x82', '\xB1', ' ', '\xE1', '\x82', '\xAA', ' ', '\xE1', '\x82', '\xAB', /* Ⴄ Ⴅ Ⴇ Ⴈ Ⴆ Ⴑ Ⴊ Ⴋ */ '\0', '\xE2', '\xB4', '\x81', ' ', '\xE2', '\xB4', '\x97', ' ', '\xE2', '\xB4', '\x82', ' ', '\xE2', '\xB4', '\x84', ' ', '\xE2', '\xB4', '\x85', ' ', '\xE2', '\xB4', '\x87', ' ', '\xE2', '\xB4', '\x94', ' ', '\xE2', '\xB4', '\x96', /* ⴁ ⴗ ⴂ ⴄ ⴅ ⴇ ⴔ ⴖ */ '\0', '\xE2', '\xB4', '\x88', ' ', '\xE2', '\xB4', '\x8C', ' ', '\xE2', '\xB4', '\x96', ' ', '\xE2', '\xB4', '\x8E', ' ', '\xE2', '\xB4', '\x83', ' ', '\xE2', '\xB4', '\x86', ' ', '\xE2', '\xB4', '\x8B', ' ', '\xE2', '\xB4', '\xA2', /* ⴈ ⴌ ⴖ ⴎ ⴃ ⴆ ⴋ ⴢ */ '\0', '\xE2', '\xB4', '\x90', ' ', '\xE2', '\xB4', '\x91', ' ', '\xE2', '\xB4', '\x93', ' ', '\xE2', '\xB4', '\x95', ' ', '\xE2', '\xB4', '\x99', ' ', '\xE2', '\xB4', '\x9B', ' ', '\xE2', '\xB4', '\xA1', ' ', '\xE2', '\xB4', '\xA3', /* ⴐ ⴑ ⴓ ⴕ ⴙ ⴛ ⴡ ⴣ */ '\0', '\xE2', '\xB4', '\x84', ' ', '\xE2', '\xB4', '\x85', ' ', '\xE2', '\xB4', '\x94', ' ', '\xE2', '\xB4', '\x95', ' ', '\xE2', '\xB4', '\x81', ' ', '\xE2', '\xB4', '\x82', ' ', '\xE2', '\xB4', '\x98', ' ', '\xE2', '\xB4', '\x9D', /* ⴄ ⴅ ⴔ ⴕ ⴁ ⴂ ⴘ ⴝ */ '\0', '\xE1', '\xB2', '\x9C', ' ', '\xE1', '\xB2', '\x9F', ' ', '\xE1', '\xB2', '\xB3', ' ', '\xE1', '\xB2', '\xB8', ' ', '\xE1', '\xB2', '\x92', ' ', '\xE1', '\xB2', '\x94', ' ', '\xE1', '\xB2', '\x9D', ' ', '\xE1', '\xB2', '\xB4', /* Ნ Ჟ Ჳ Ჸ Გ Ე Ო Ჴ */ '\0', '\xE1', '\xB2', '\x98', ' ', '\xE1', '\xB2', '\xB2', ' ', '\xE1', '\xB2', '\x9D', ' ', '\xE1', '\xB2', '\xA9', ' ', '\xE1', '\xB2', '\x9B', ' ', '\xE1', '\xB2', '\xA8', ' ', '\xE1', '\xB2', '\xAF', ' ', '\xE1', '\xB2', '\xBD', /* Ი Ჲ Ო Ჩ Მ Შ Ჯ Ჽ */ '\0', '\xE2', '\xB0', '\x85', ' ', '\xE2', '\xB0', '\x94', ' ', '\xE2', '\xB0', '\xAA', ' ', '\xE2', '\xB0', '\x84', ' ', '\xE2', '\xB0', '\x82', ' ', '\xE2', '\xB0', '\x8A', ' ', '\xE2', '\xB0', '\xAB', ' ', '\xE2', '\xB0', '\x8B', /* Ⰵ Ⱄ Ⱚ Ⰴ Ⰲ Ⰺ Ⱛ Ⰻ */ '\0', '\xE2', '\xB0', '\x85', ' ', '\xE2', '\xB0', '\x84', ' ', '\xE2', '\xB0', '\x82', ' ', '\xE2', '\xB0', '\xAA', ' ', '\xE2', '\xB0', '\x9E', ' ', '\xE2', '\xB0', '\xA1', ' ', '\xE2', '\xB0', '\x8A', ' ', '\xE2', '\xB0', '\x94', /* Ⰵ Ⰴ Ⰲ Ⱚ Ⱎ Ⱑ Ⰺ Ⱄ */ '\0', '\xE2', '\xB0', '\xB5', ' ', '\xE2', '\xB1', '\x84', ' ', '\xE2', '\xB1', '\x9A', ' ', '\xE2', '\xB0', '\xB4', ' ', '\xE2', '\xB0', '\xB2', ' ', '\xE2', '\xB0', '\xBA', ' ', '\xE2', '\xB1', '\x9B', ' ', '\xE2', '\xB0', '\xBB', /* ⰵ ⱄ ⱚ ⰴ ⰲ ⰺ ⱛ ⰻ */ '\0', '\xE2', '\xB0', '\xB5', ' ', '\xE2', '\xB0', '\xB4', ' ', '\xE2', '\xB0', '\xB2', ' ', '\xE2', '\xB1', '\x9A', ' ', '\xE2', '\xB1', '\x8E', ' ', '\xE2', '\xB1', '\x91', ' ', '\xE2', '\xB0', '\xBA', ' ', '\xE2', '\xB1', '\x84', /* ⰵ ⰴ ⰲ ⱚ ⱎ ⱑ ⰺ ⱄ */ '\0', '\xF0', '\x90', '\x8C', '\xB2', ' ', '\xF0', '\x90', '\x8C', '\xB6', ' ', '\xF0', '\x90', '\x8D', '\x80', ' ', '\xF0', '\x90', '\x8D', '\x84', ' ', '\xF0', '\x90', '\x8C', '\xB4', ' ', '\xF0', '\x90', '\x8D', '\x83', ' ', '\xF0', '\x90', '\x8D', '\x88', ' ', '\xF0', '\x90', '\x8C', '\xBE', /* 𐌲 𐌶 𐍀 𐍄 𐌴 𐍃 𐍈 𐌾 */ '\0', '\xF0', '\x90', '\x8C', '\xB6', ' ', '\xF0', '\x90', '\x8C', '\xB4', ' ', '\xF0', '\x90', '\x8D', '\x83', ' ', '\xF0', '\x90', '\x8D', '\x88', /* 𐌶 𐌴 𐍃 𐍈 */ '\0', '\xCE', '\x93', ' ', '\xCE', '\x92', ' ', '\xCE', '\x95', ' ', '\xCE', '\x96', ' ', '\xCE', '\x98', ' ', '\xCE', '\x9F', ' ', '\xCE', '\xA9', /* Γ Β Ε Ζ Θ Ο Ω */ '\0', '\xCE', '\x92', ' ', '\xCE', '\x94', ' ', '\xCE', '\x96', ' ', '\xCE', '\x9E', ' ', '\xCE', '\x98', ' ', '\xCE', '\x9F', /* Β Δ Ζ Ξ Θ Ο */ '\0', '\xCE', '\xB2', ' ', '\xCE', '\xB8', ' ', '\xCE', '\xB4', ' ', '\xCE', '\xB6', ' ', '\xCE', '\xBB', ' ', '\xCE', '\xBE', /* β θ δ ζ λ ξ */ '\0', '\xCE', '\xB1', ' ', '\xCE', '\xB5', ' ', '\xCE', '\xB9', ' ', '\xCE', '\xBF', ' ', '\xCF', '\x80', ' ', '\xCF', '\x83', ' ', '\xCF', '\x84', ' ', '\xCF', '\x89', /* α ε ι ο π σ τ ω */ '\0', '\xCE', '\xB2', ' ', '\xCE', '\xB3', ' ', '\xCE', '\xB7', ' ', '\xCE', '\xBC', ' ', '\xCF', '\x81', ' ', '\xCF', '\x86', ' ', '\xCF', '\x87', ' ', '\xCF', '\x88', /* β γ η μ ρ φ χ ψ */ '\0', '\xE0', '\xAA', '\xA4', ' ', '\xE0', '\xAA', '\xA8', ' ', '\xE0', '\xAA', '\x8B', ' ', '\xE0', '\xAA', '\x8C', ' ', '\xE0', '\xAA', '\x9B', ' ', '\xE0', '\xAA', '\x9F', ' ', '\xE0', '\xAA', '\xB0', ' ', '\xE0', '\xAB', '\xA6', /* ત ન ઋ ઌ છ ટ ર ૦ */ '\0', '\xE0', '\xAA', '\x96', ' ', '\xE0', '\xAA', '\x97', ' ', '\xE0', '\xAA', '\x98', ' ', '\xE0', '\xAA', '\x9E', ' ', '\xE0', '\xAA', '\x87', ' ', '\xE0', '\xAA', '\x88', ' ', '\xE0', '\xAA', '\xA0', ' ', '\xE0', '\xAA', '\x9C', /* ખ ગ ઘ ઞ ઇ ઈ ઠ જ */ '\0', '\xE0', '\xAA', '\x88', ' ', '\xE0', '\xAA', '\x8A', ' ', '\xE0', '\xAA', '\xBF', ' ', '\xE0', '\xAB', '\x80', ' ', '\xE0', '\xAA', '\xB2', '\xE0', '\xAB', '\x80', ' ', '\xE0', '\xAA', '\xB6', '\xE0', '\xAB', '\x8D', '\xE0', '\xAA', '\x9A', '\xE0', '\xAA', '\xBF', ' ', '\xE0', '\xAA', '\x9C', '\xE0', '\xAA', '\xBF', ' ', '\xE0', '\xAA', '\xB8', '\xE0', '\xAB', '\x80', /* ઈ ઊ િ ી લી શ્ચિ જિ સી */ '\0', '\xE0', '\xAB', '\x81', ' ', '\xE0', '\xAB', '\x83', ' ', '\xE0', '\xAB', '\x84', ' ', '\xE0', '\xAA', '\x96', '\xE0', '\xAB', '\x81', ' ', '\xE0', '\xAA', '\x9B', '\xE0', '\xAB', '\x83', ' ', '\xE0', '\xAA', '\x9B', '\xE0', '\xAB', '\x84', /* ુ ૃ ૄ ખુ છૃ છૄ */ '\0', '\xE0', '\xAB', '\xA6', ' ', '\xE0', '\xAB', '\xA7', ' ', '\xE0', '\xAB', '\xA8', ' ', '\xE0', '\xAB', '\xA9', ' ', '\xE0', '\xAB', '\xAD', /* ૦ ૧ ૨ ૩ ૭ */ '\0', '\xE0', '\xA8', '\x95', ' ', '\xE0', '\xA8', '\x97', ' ', '\xE0', '\xA8', '\x99', ' ', '\xE0', '\xA8', '\x9A', ' ', '\xE0', '\xA8', '\x9C', ' ', '\xE0', '\xA8', '\xA4', ' ', '\xE0', '\xA8', '\xA7', ' ', '\xE0', '\xA8', '\xB8', /* ਕ ਗ ਙ ਚ ਜ ਤ ਧ ਸ */ '\0', '\xE0', '\xA8', '\x95', ' ', '\xE0', '\xA8', '\x97', ' ', '\xE0', '\xA8', '\x99', ' ', '\xE0', '\xA8', '\x9A', ' ', '\xE0', '\xA8', '\x9C', ' ', '\xE0', '\xA8', '\xA4', ' ', '\xE0', '\xA8', '\xA7', ' ', '\xE0', '\xA8', '\xB8', /* ਕ ਗ ਙ ਚ ਜ ਤ ਧ ਸ */ '\0', '\xE0', '\xA8', '\x87', ' ', '\xE0', '\xA8', '\x88', ' ', '\xE0', '\xA8', '\x89', ' ', '\xE0', '\xA8', '\x8F', ' ', '\xE0', '\xA8', '\x93', ' ', '\xE0', '\xA9', '\xB3', ' ', '\xE0', '\xA8', '\xBF', ' ', '\xE0', '\xA9', '\x80', /* ਇ ਈ ਉ ਏ ਓ ੳ ਿ ੀ */ '\0', '\xE0', '\xA8', '\x85', ' ', '\xE0', '\xA8', '\x8F', ' ', '\xE0', '\xA8', '\x93', ' ', '\xE0', '\xA8', '\x97', ' ', '\xE0', '\xA8', '\x9C', ' ', '\xE0', '\xA8', '\xA0', ' ', '\xE0', '\xA8', '\xB0', ' ', '\xE0', '\xA8', '\xB8', /* ਅ ਏ ਓ ਗ ਜ ਠ ਰ ਸ */ '\0', '\xE0', '\xA9', '\xA6', ' ', '\xE0', '\xA9', '\xA7', ' ', '\xE0', '\xA9', '\xA8', ' ', '\xE0', '\xA9', '\xA9', ' ', '\xE0', '\xA9', '\xAD', /* ੦ ੧ ੨ ੩ ੭ */ '\0', '\xD7', '\x91', ' ', '\xD7', '\x93', ' ', '\xD7', '\x94', ' ', '\xD7', '\x97', ' ', '\xD7', '\x9A', ' ', '\xD7', '\x9B', ' ', '\xD7', '\x9D', ' ', '\xD7', '\xA1', /* ב ד ה ח ך כ ם ס */ '\0', '\xD7', '\x91', ' ', '\xD7', '\x98', ' ', '\xD7', '\x9B', ' ', '\xD7', '\x9D', ' ', '\xD7', '\xA1', ' ', '\xD7', '\xA6', /* ב ט כ ם ס צ */ '\0', '\xD7', '\xA7', ' ', '\xD7', '\x9A', ' ', '\xD7', '\x9F', ' ', '\xD7', '\xA3', ' ', '\xD7', '\xA5', /* ק ך ן ף ץ */ '\0', '\xE0', '\xB2', '\x87', ' ', '\xE0', '\xB2', '\x8A', ' ', '\xE0', '\xB2', '\x90', ' ', '\xE0', '\xB2', '\xA3', ' ', '\xE0', '\xB2', '\xB8', '\xE0', '\xB2', '\xBE', ' ', '\xE0', '\xB2', '\xA8', '\xE0', '\xB2', '\xBE', ' ', '\xE0', '\xB2', '\xA6', '\xE0', '\xB2', '\xBE', ' ', '\xE0', '\xB2', '\xB0', '\xE0', '\xB2', '\xBE', /* ಇ ಊ ಐ ಣ ಸಾ ನಾ ದಾ ರಾ */ '\0', '\xE0', '\xB2', '\x85', ' ', '\xE0', '\xB2', '\x89', ' ', '\xE0', '\xB2', '\x8E', ' ', '\xE0', '\xB2', '\xB2', ' ', '\xE0', '\xB3', '\xA6', ' ', '\xE0', '\xB3', '\xA8', ' ', '\xE0', '\xB3', '\xAC', ' ', '\xE0', '\xB3', '\xAD', /* ಅ ಉ ಎ ಲ ೦ ೨ ೬ ೭ */ '\0', '\xEA', '\xA4', '\x85', ' ', '\xEA', '\xA4', '\x8F', ' ', '\xEA', '\xA4', '\x81', ' ', '\xEA', '\xA4', '\x8B', ' ', '\xEA', '\xA4', '\x80', ' ', '\xEA', '\xA4', '\x8D', /* ꤅ ꤏ ꤁ ꤋ ꤀ ꤍ */ '\0', '\xEA', '\xA4', '\x88', ' ', '\xEA', '\xA4', '\x98', ' ', '\xEA', '\xA4', '\x80', ' ', '\xEA', '\xA4', '\x8D', ' ', '\xEA', '\xA4', '\xA2', /* ꤈ ꤘ ꤀ ꤍ ꤢ */ '\0', '\xEA', '\xA4', '\x96', ' ', '\xEA', '\xA4', '\xA1', /* ꤖ ꤡ */ '\0', '\xEA', '\xA4', '\x91', ' ', '\xEA', '\xA4', '\x9C', ' ', '\xEA', '\xA4', '\x9E', /* ꤑ ꤜ ꤞ */ '\0', '\xEA', '\xA4', '\x91', '\xEA', '\xA4', '\xAC', ' ', '\xEA', '\xA4', '\x9C', '\xEA', '\xA4', '\xAD', ' ', '\xEA', '\xA4', '\x94', '\xEA', '\xA4', '\xAC', /* ꤑ꤬ ꤜ꤭ ꤔ꤬ */ '\0', '\xE1', '\x9E', '\x81', ' ', '\xE1', '\x9E', '\x91', ' ', '\xE1', '\x9E', '\x93', ' ', '\xE1', '\x9E', '\xA7', ' ', '\xE1', '\x9E', '\xA9', ' ', '\xE1', '\x9E', '\xB6', /* ខ ទ ន ឧ ឩ ា */ '\0', '\xE1', '\x9E', '\x80', '\xE1', '\x9F', '\x92', '\xE1', '\x9E', '\x80', ' ', '\xE1', '\x9E', '\x80', '\xE1', '\x9F', '\x92', '\xE1', '\x9E', '\x81', ' ', '\xE1', '\x9E', '\x80', '\xE1', '\x9F', '\x92', '\xE1', '\x9E', '\x82', ' ', '\xE1', '\x9E', '\x80', '\xE1', '\x9F', '\x92', '\xE1', '\x9E', '\x90', /* ក្ក ក្ខ ក្គ ក្ថ */ '\0', '\xE1', '\x9E', '\x81', ' ', '\xE1', '\x9E', '\x83', ' ', '\xE1', '\x9E', '\x85', ' ', '\xE1', '\x9E', '\x8B', ' ', '\xE1', '\x9E', '\x94', ' ', '\xE1', '\x9E', '\x98', ' ', '\xE1', '\x9E', '\x99', ' ', '\xE1', '\x9E', '\xB2', /* ខ ឃ ច ឋ ប ម យ ឲ */ '\0', '\xE1', '\x9E', '\x8F', '\xE1', '\x9F', '\x92', '\xE1', '\x9E', '\x9A', ' ', '\xE1', '\x9E', '\x9A', '\xE1', '\x9F', '\x80', ' ', '\xE1', '\x9E', '\xB2', '\xE1', '\x9F', '\x92', '\xE1', '\x9E', '\x99', ' ', '\xE1', '\x9E', '\xA2', '\xE1', '\x9E', '\xBF', /* ត្រ រៀ ឲ្យ អឿ */ '\0', '\xE1', '\x9E', '\x93', '\xE1', '\x9F', '\x92', '\xE1', '\x9E', '\x8F', '\xE1', '\x9F', '\x92', '\xE1', '\x9E', '\x9A', '\xE1', '\x9F', '\x83', ' ', '\xE1', '\x9E', '\x84', '\xE1', '\x9F', '\x92', '\xE1', '\x9E', '\x81', '\xE1', '\x9F', '\x92', '\xE1', '\x9E', '\x99', ' ', '\xE1', '\x9E', '\x80', '\xE1', '\x9F', '\x92', '\xE1', '\x9E', '\x94', '\xE1', '\x9F', '\x80', ' ', '\xE1', '\x9E', '\x85', '\xE1', '\x9F', '\x92', '\xE1', '\x9E', '\x9A', '\xE1', '\x9F', '\x80', ' ', '\xE1', '\x9E', '\x93', '\xE1', '\x9F', '\x92', '\xE1', '\x9E', '\x8F', '\xE1', '\x9E', '\xBF', ' ', '\xE1', '\x9E', '\x9B', '\xE1', '\x9F', '\x92', '\xE1', '\x9E', '\x94', '\xE1', '\x9E', '\xBF', /* ន្ត្រៃ ង្ខ្យ ក្បៀ ច្រៀ ន្តឿ ល្បឿ */ '\0', '\xE1', '\xA7', '\xA0', ' ', '\xE1', '\xA7', '\xA1', /* ᧠ ᧡ */ '\0', '\xE1', '\xA7', '\xB6', ' ', '\xE1', '\xA7', '\xB9', /* ᧶ ᧹ */ '\0', '\xE0', '\xBA', '\xB2', ' ', '\xE0', '\xBA', '\x94', ' ', '\xE0', '\xBA', '\xAD', ' ', '\xE0', '\xBA', '\xA1', ' ', '\xE0', '\xBA', '\xA5', ' ', '\xE0', '\xBA', '\xA7', ' ', '\xE0', '\xBA', '\xA3', ' ', '\xE0', '\xBA', '\x87', /* າ ດ ອ ມ ລ ວ ຣ ງ */ '\0', '\xE0', '\xBA', '\xB2', ' ', '\xE0', '\xBA', '\xAD', ' ', '\xE0', '\xBA', '\x9A', ' ', '\xE0', '\xBA', '\x8D', ' ', '\xE0', '\xBA', '\xA3', ' ', '\xE0', '\xBA', '\xAE', ' ', '\xE0', '\xBA', '\xA7', ' ', '\xE0', '\xBA', '\xA2', /* າ ອ ບ ຍ ຣ ຮ ວ ຢ */ '\0', '\xE0', '\xBA', '\x9B', ' ', '\xE0', '\xBA', '\xA2', ' ', '\xE0', '\xBA', '\x9F', ' ', '\xE0', '\xBA', '\x9D', /* ປ ຢ ຟ ຝ */ '\0', '\xE0', '\xBB', '\x82', ' ', '\xE0', '\xBB', '\x84', ' ', '\xE0', '\xBB', '\x83', /* ໂ ໄ ໃ */ '\0', '\xE0', '\xBA', '\x87', ' ', '\xE0', '\xBA', '\x8A', ' ', '\xE0', '\xBA', '\x96', ' ', '\xE0', '\xBA', '\xBD', ' ', '\xE0', '\xBB', '\x86', ' ', '\xE0', '\xBA', '\xAF', /* ງ ຊ ຖ ຽ ໆ ຯ */ '\0', 'T', ' ', 'H', ' ', 'E', ' ', 'Z', ' ', 'O', ' ', 'C', ' ', 'Q', ' ', 'S', /* T H E Z O C Q S */ '\0', 'H', ' ', 'E', ' ', 'Z', ' ', 'L', ' ', 'O', ' ', 'C', ' ', 'U', ' ', 'S', /* H E Z L O C U S */ '\0', 'f', ' ', 'i', ' ', 'j', ' ', 'k', ' ', 'd', ' ', 'b', ' ', 'h', /* f i j k d b h */ '\0', 'u', ' ', 'v', ' ', 'x', ' ', 'z', ' ', 'o', ' ', 'e', ' ', 's', ' ', 'c', /* u v x z o e s c */ '\0', 'n', ' ', 'r', ' ', 'x', ' ', 'z', ' ', 'o', ' ', 'e', ' ', 's', ' ', 'c', /* n r x z o e s c */ '\0', 'p', ' ', 'q', ' ', 'g', ' ', 'j', ' ', 'y', /* p q g j y */ '\0', '\xE2', '\x82', '\x80', ' ', '\xE2', '\x82', '\x83', ' ', '\xE2', '\x82', '\x85', ' ', '\xE2', '\x82', '\x87', ' ', '\xE2', '\x82', '\x88', /* ₀ ₃ ₅ ₇ ₈ */ '\0', '\xE2', '\x82', '\x80', ' ', '\xE2', '\x82', '\x81', ' ', '\xE2', '\x82', '\x82', ' ', '\xE2', '\x82', '\x83', ' ', '\xE2', '\x82', '\x88', /* ₀ ₁ ₂ ₃ ₈ */ '\0', '\xE1', '\xB5', '\xA2', ' ', '\xE2', '\xB1', '\xBC', ' ', '\xE2', '\x82', '\x95', ' ', '\xE2', '\x82', '\x96', ' ', '\xE2', '\x82', '\x97', /* ᵢ ⱼ ₕ ₖ ₗ */ '\0', '\xE2', '\x82', '\x90', ' ', '\xE2', '\x82', '\x91', ' ', '\xE2', '\x82', '\x92', ' ', '\xE2', '\x82', '\x93', ' ', '\xE2', '\x82', '\x99', ' ', '\xE2', '\x82', '\x9B', ' ', '\xE1', '\xB5', '\xA5', ' ', '\xE1', '\xB5', '\xA4', ' ', '\xE1', '\xB5', '\xA3', /* ₐ ₑ ₒ ₓ ₙ ₛ ᵥ ᵤ ᵣ */ '\0', '\xE1', '\xB5', '\xA6', ' ', '\xE1', '\xB5', '\xA7', ' ', '\xE1', '\xB5', '\xA8', ' ', '\xE1', '\xB5', '\xA9', ' ', '\xE2', '\x82', '\x9A', /* ᵦ ᵧ ᵨ ᵩ ₚ */ '\0', '\xE2', '\x81', '\xB0', ' ', '\xC2', '\xB3', ' ', '\xE2', '\x81', '\xB5', ' ', '\xE2', '\x81', '\xB7', ' ', '\xE1', '\xB5', '\x80', ' ', '\xE1', '\xB4', '\xB4', ' ', '\xE1', '\xB4', '\xB1', ' ', '\xE1', '\xB4', '\xBC', /* ⁰ ³ ⁵ ⁷ ᵀ ᴴ ᴱ ᴼ */ '\0', '\xE2', '\x81', '\xB0', ' ', '\xC2', '\xB9', ' ', '\xC2', '\xB2', ' ', '\xC2', '\xB3', ' ', '\xE1', '\xB4', '\xB1', ' ', '\xE1', '\xB4', '\xB8', ' ', '\xE1', '\xB4', '\xBC', ' ', '\xE1', '\xB5', '\x81', /* ⁰ ¹ ² ³ ᴱ ᴸ ᴼ ᵁ */ '\0', '\xE1', '\xB5', '\x87', ' ', '\xE1', '\xB5', '\x88', ' ', '\xE1', '\xB5', '\x8F', ' ', '\xCA', '\xB0', ' ', '\xCA', '\xB2', ' ', '\xE1', '\xB6', '\xA0', ' ', '\xE2', '\x81', '\xB1', /* ᵇ ᵈ ᵏ ʰ ʲ ᶠ ⁱ */ '\0', '\xE1', '\xB5', '\x89', ' ', '\xE1', '\xB5', '\x92', ' ', '\xCA', '\xB3', ' ', '\xCB', '\xA2', ' ', '\xCB', '\xA3', ' ', '\xE1', '\xB6', '\x9C', ' ', '\xE1', '\xB6', '\xBB', /* ᵉ ᵒ ʳ ˢ ˣ ᶜ ᶻ */ '\0', '\xE1', '\xB5', '\x96', ' ', '\xCA', '\xB8', ' ', '\xE1', '\xB5', '\x8D', /* ᵖ ʸ ᵍ */ '\0', '\xEA', '\x93', '\xA1', ' ', '\xEA', '\x93', '\xA7', ' ', '\xEA', '\x93', '\xB1', ' ', '\xEA', '\x93', '\xB6', ' ', '\xEA', '\x93', '\xA9', ' ', '\xEA', '\x93', '\x9A', ' ', '\xEA', '\x93', '\xB5', ' ', '\xEA', '\x93', '\xB3', /* ꓡ ꓧ ꓱ ꓶ ꓩ ꓚ ꓵ ꓳ */ '\0', '\xEA', '\x93', '\x95', ' ', '\xEA', '\x93', '\x9C', ' ', '\xEA', '\x93', '\x9E', ' ', '\xEA', '\x93', '\xA1', ' ', '\xEA', '\x93', '\x9B', ' ', '\xEA', '\x93', '\xA2', ' ', '\xEA', '\x93', '\xB3', ' ', '\xEA', '\x93', '\xB4', /* ꓕ ꓜ ꓞ ꓡ ꓛ ꓢ ꓳ ꓴ */ '\0', '\xE0', '\xB4', '\x92', ' ', '\xE0', '\xB4', '\x9F', ' ', '\xE0', '\xB4', '\xA0', ' ', '\xE0', '\xB4', '\xB1', ' ', '\xE0', '\xB4', '\x9A', ' ', '\xE0', '\xB4', '\xAA', ' ', '\xE0', '\xB4', '\x9A', '\xE0', '\xB5', '\x8D', '\xE0', '\xB4', '\x9A', ' ', '\xE0', '\xB4', '\xAA', '\xE0', '\xB5', '\x8D', '\xE0', '\xB4', '\xAA', /* ഒ ട ഠ റ ച പ ച്ച പ്പ */ '\0', '\xE0', '\xB4', '\x9F', ' ', '\xE0', '\xB4', '\xA0', ' ', '\xE0', '\xB4', '\xA7', ' ', '\xE0', '\xB4', '\xB6', ' ', '\xE0', '\xB4', '\x98', ' ', '\xE0', '\xB4', '\x9A', ' ', '\xE0', '\xB4', '\xA5', ' ', '\xE0', '\xB4', '\xB2', /* ട ഠ ധ ശ ഘ ച ഥ ല */ '\0', '\xF0', '\x96', '\xB9', '\x80', ' ', '\xF0', '\x96', '\xB9', '\x81', ' ', '\xF0', '\x96', '\xB9', '\x82', ' ', '\xF0', '\x96', '\xB9', '\x83', ' ', '\xF0', '\x96', '\xB9', '\x8F', ' ', '\xF0', '\x96', '\xB9', '\x9A', ' ', '\xF0', '\x96', '\xB9', '\x9F', /* 𖹀 𖹁 𖹂 𖹃 𖹏 𖹚 𖹟 */ '\0', '\xF0', '\x96', '\xB9', '\x80', ' ', '\xF0', '\x96', '\xB9', '\x81', ' ', '\xF0', '\x96', '\xB9', '\x82', ' ', '\xF0', '\x96', '\xB9', '\x83', ' ', '\xF0', '\x96', '\xB9', '\x8F', ' ', '\xF0', '\x96', '\xB9', '\x9A', ' ', '\xF0', '\x96', '\xB9', '\x92', ' ', '\xF0', '\x96', '\xB9', '\x93', /* 𖹀 𖹁 𖹂 𖹃 𖹏 𖹚 𖹒 𖹓 */ '\0', '\xF0', '\x96', '\xB9', '\xA4', ' ', '\xF0', '\x96', '\xB9', '\xAC', ' ', '\xF0', '\x96', '\xB9', '\xA7', ' ', '\xF0', '\x96', '\xB9', '\xB4', ' ', '\xF0', '\x96', '\xB9', '\xB6', ' ', '\xF0', '\x96', '\xB9', '\xBE', /* 𖹤 𖹬 𖹧 𖹴 𖹶 𖹾 */ '\0', '\xF0', '\x96', '\xB9', '\xA0', ' ', '\xF0', '\x96', '\xB9', '\xA1', ' ', '\xF0', '\x96', '\xB9', '\xA2', ' ', '\xF0', '\x96', '\xB9', '\xB9', ' ', '\xF0', '\x96', '\xB9', '\xB3', ' ', '\xF0', '\x96', '\xB9', '\xAE', /* 𖹠 𖹡 𖹢 𖹹 𖹳 𖹮 */ '\0', '\xF0', '\x96', '\xB9', '\xA0', ' ', '\xF0', '\x96', '\xB9', '\xA1', ' ', '\xF0', '\x96', '\xB9', '\xA2', ' ', '\xF0', '\x96', '\xB9', '\xB3', ' ', '\xF0', '\x96', '\xB9', '\xAD', ' ', '\xF0', '\x96', '\xB9', '\xBD', /* 𖹠 𖹡 𖹢 𖹳 𖹭 𖹽 */ '\0', '\xF0', '\x96', '\xB9', '\xA5', ' ', '\xF0', '\x96', '\xB9', '\xA8', ' ', '\xF0', '\x96', '\xB9', '\xA9', /* 𖹥 𖹨 𖹩 */ '\0', '\xF0', '\x96', '\xBA', '\x80', ' ', '\xF0', '\x96', '\xBA', '\x85', ' ', '\xF0', '\x96', '\xBA', '\x88', ' ', '\xF0', '\x96', '\xBA', '\x84', ' ', '\xF0', '\x96', '\xBA', '\x8D', /* 𖺀 𖺅 𖺈 𖺄 𖺍 */ '\0', '\xE1', '\xA0', '\xB3', ' ', '\xE1', '\xA0', '\xB4', ' ', '\xE1', '\xA0', '\xB6', ' ', '\xE1', '\xA0', '\xBD', ' ', '\xE1', '\xA1', '\x82', ' ', '\xE1', '\xA1', '\x8A', ' ', '\xE2', '\x80', '\x8D', '\xE1', '\xA1', '\xA1', '\xE2', '\x80', '\x8D', ' ', '\xE2', '\x80', '\x8D', '\xE1', '\xA1', '\xB3', '\xE2', '\x80', '\x8D', /* ᠳ ᠴ ᠶ ᠽ ᡂ ᡊ ‍ᡡ‍ ‍ᡳ‍ */ '\0', '\xE1', '\xA1', '\x83', /* ᡃ */ '\0', '\xE1', '\x80', '\x81', ' ', '\xE1', '\x80', '\x82', ' ', '\xE1', '\x80', '\x84', ' ', '\xE1', '\x80', '\x92', ' ', '\xE1', '\x80', '\x9D', ' ', '\xE1', '\x81', '\xA5', ' ', '\xE1', '\x81', '\x8A', ' ', '\xE1', '\x81', '\x8B', /* ခ ဂ င ဒ ဝ ၥ ၊ ။ */ '\0', '\xE1', '\x80', '\x84', ' ', '\xE1', '\x80', '\x8E', ' ', '\xE1', '\x80', '\x92', ' ', '\xE1', '\x80', '\x95', ' ', '\xE1', '\x80', '\x97', ' ', '\xE1', '\x80', '\x9D', ' ', '\xE1', '\x81', '\x8A', ' ', '\xE1', '\x81', '\x8B', /* င ဎ ဒ ပ ဗ ဝ ၊ ။ */ '\0', '\xE1', '\x80', '\xA9', ' ', '\xE1', '\x80', '\xBC', ' ', '\xE1', '\x81', '\x8D', ' ', '\xE1', '\x81', '\x8F', ' ', '\xE1', '\x81', '\x86', ' ', '\xE1', '\x80', '\xAB', ' ', '\xE1', '\x80', '\xAD', /* ဩ ြ ၍ ၏ ၆ ါ ိ */ '\0', '\xE1', '\x80', '\x89', ' ', '\xE1', '\x80', '\x8A', ' ', '\xE1', '\x80', '\xA5', ' ', '\xE1', '\x80', '\xA9', ' ', '\xE1', '\x80', '\xA8', ' ', '\xE1', '\x81', '\x82', ' ', '\xE1', '\x81', '\x85', ' ', '\xE1', '\x81', '\x89', /* ဉ ည ဥ ဩ ဨ ၂ ၅ ၉ */ '\0', '\xDF', '\x90', ' ', '\xDF', '\x89', ' ', '\xDF', '\x92', ' ', '\xDF', '\x9F', ' ', '\xDF', '\x96', ' ', '\xDF', '\x9C', ' ', '\xDF', '\xA0', ' ', '\xDF', '\xA5', /* ߐ ߉ ߒ ߟ ߖ ߜ ߠ ߥ */ '\0', '\xDF', '\x80', ' ', '\xDF', '\x98', ' ', '\xDF', '\xA1', ' ', '\xDF', '\xA0', ' ', '\xDF', '\xA5', /* ߀ ߘ ߡ ߠ ߥ */ '\0', '\xDF', '\x8F', ' ', '\xDF', '\x9B', ' ', '\xDF', '\x8B', /* ߏ ߛ ߋ */ '\0', '\xDF', '\x8E', ' ', '\xDF', '\x8F', ' ', '\xDF', '\x9B', ' ', '\xDF', '\x8B', /* ߎ ߏ ߛ ߋ */ '\0', '\xE1', '\xB1', '\x9B', ' ', '\xE1', '\xB1', '\x9C', ' ', '\xE1', '\xB1', '\x9D', ' ', '\xE1', '\xB1', '\xA1', ' ', '\xE1', '\xB1', '\xA2', ' ', '\xE1', '\xB1', '\xA5', /* ᱛ ᱜ ᱝ ᱡ ᱢ ᱥ */ '\0', '\xF0', '\x90', '\xB0', '\x97', ' ', '\xF0', '\x90', '\xB0', '\x98', ' ', '\xF0', '\x90', '\xB0', '\xA7', /* 𐰗 𐰘 𐰧 */ '\0', '\xF0', '\x90', '\xB0', '\x89', ' ', '\xF0', '\x90', '\xB0', '\x97', ' ', '\xF0', '\x90', '\xB0', '\xA6', ' ', '\xF0', '\x90', '\xB0', '\xA7', /* 𐰉 𐰗 𐰦 𐰧 */ '\0', '\xF0', '\x90', '\x92', '\xBE', ' ', '\xF0', '\x90', '\x93', '\x8D', ' ', '\xF0', '\x90', '\x93', '\x92', ' ', '\xF0', '\x90', '\x93', '\x93', ' ', '\xF0', '\x90', '\x92', '\xBB', ' ', '\xF0', '\x90', '\x93', '\x82', ' ', '\xF0', '\x90', '\x92', '\xB5', ' ', '\xF0', '\x90', '\x93', '\x86', /* 𐒾 𐓍 𐓒 𐓓 𐒻 𐓂 𐒵 𐓆 */ '\0', '\xF0', '\x90', '\x92', '\xB0', ' ', '\xF0', '\x90', '\x93', '\x8D', ' ', '\xF0', '\x90', '\x93', '\x82', ' ', '\xF0', '\x90', '\x92', '\xBF', ' ', '\xF0', '\x90', '\x93', '\x8E', ' ', '\xF0', '\x90', '\x92', '\xB9', /* 𐒰 𐓍 𐓂 𐒿 𐓎 𐒹 */ '\0', '\xF0', '\x90', '\x92', '\xBC', ' ', '\xF0', '\x90', '\x92', '\xBD', ' ', '\xF0', '\x90', '\x92', '\xBE', /* 𐒼 𐒽 𐒾 */ '\0', '\xF0', '\x90', '\x93', '\xB5', ' ', '\xF0', '\x90', '\x93', '\xB6', ' ', '\xF0', '\x90', '\x93', '\xBA', ' ', '\xF0', '\x90', '\x93', '\xBB', ' ', '\xF0', '\x90', '\x93', '\x9D', ' ', '\xF0', '\x90', '\x93', '\xA3', ' ', '\xF0', '\x90', '\x93', '\xAA', ' ', '\xF0', '\x90', '\x93', '\xAE', /* 𐓵 𐓶 𐓺 𐓻 𐓝 𐓣 𐓪 𐓮 */ '\0', '\xF0', '\x90', '\x93', '\x98', ' ', '\xF0', '\x90', '\x93', '\x9A', ' ', '\xF0', '\x90', '\x93', '\xA3', ' ', '\xF0', '\x90', '\x93', '\xB5', ' ', '\xF0', '\x90', '\x93', '\xA1', ' ', '\xF0', '\x90', '\x93', '\xA7', ' ', '\xF0', '\x90', '\x93', '\xAA', ' ', '\xF0', '\x90', '\x93', '\xB6', /* 𐓘 𐓚 𐓣 𐓵 𐓡 𐓧 𐓪 𐓶 */ '\0', '\xF0', '\x90', '\x93', '\xA4', ' ', '\xF0', '\x90', '\x93', '\xA6', ' ', '\xF0', '\x90', '\x93', '\xB8', ' ', '\xF0', '\x90', '\x93', '\xB9', ' ', '\xF0', '\x90', '\x93', '\x9B', /* 𐓤 𐓦 𐓸 𐓹 𐓛 */ '\0', '\xF0', '\x90', '\x93', '\xA4', ' ', '\xF0', '\x90', '\x93', '\xA5', ' ', '\xF0', '\x90', '\x93', '\xA6', /* 𐓤 𐓥 𐓦 */ '\0', '\xF0', '\x90', '\x92', '\x86', ' ', '\xF0', '\x90', '\x92', '\x89', ' ', '\xF0', '\x90', '\x92', '\x90', ' ', '\xF0', '\x90', '\x92', '\x92', ' ', '\xF0', '\x90', '\x92', '\x98', ' ', '\xF0', '\x90', '\x92', '\x9B', ' ', '\xF0', '\x90', '\x92', '\xA0', ' ', '\xF0', '\x90', '\x92', '\xA3', /* 𐒆 𐒉 𐒐 𐒒 𐒘 𐒛 𐒠 𐒣 */ '\0', '\xF0', '\x90', '\x92', '\x80', ' ', '\xF0', '\x90', '\x92', '\x82', ' ', '\xF0', '\x90', '\x92', '\x86', ' ', '\xF0', '\x90', '\x92', '\x88', ' ', '\xF0', '\x90', '\x92', '\x8A', ' ', '\xF0', '\x90', '\x92', '\x92', ' ', '\xF0', '\x90', '\x92', '\xA0', ' ', '\xF0', '\x90', '\x92', '\xA9', /* 𐒀 𐒂 𐒆 𐒈 𐒊 𐒒 𐒠 𐒩 */ '\0', '\xF0', '\x90', '\xB4', '\x83', ' ', '\xF0', '\x90', '\xB4', '\x80', ' ', '\xF0', '\x90', '\xB4', '\x86', ' ', '\xF0', '\x90', '\xB4', '\x96', ' ', '\xF0', '\x90', '\xB4', '\x95', /* 𐴃 𐴀 𐴆 𐴖 𐴕 */ '\0', '\xF0', '\x90', '\xB4', '\x94', ' ', '\xF0', '\x90', '\xB4', '\x96', ' ', '\xF0', '\x90', '\xB4', '\x95', ' ', '\xF0', '\x90', '\xB4', '\x91', ' ', '\xF0', '\x90', '\xB4', '\x90', /* 𐴔 𐴖 𐴕 𐴑 𐴐 */ '\0', '\xD9', '\x80', /* ـ */ '\0', '\xEA', '\xA2', '\x9C', ' ', '\xEA', '\xA2', '\x9E', ' ', '\xEA', '\xA2', '\xB3', ' ', '\xEA', '\xA2', '\x82', ' ', '\xEA', '\xA2', '\x96', ' ', '\xEA', '\xA2', '\x92', ' ', '\xEA', '\xA2', '\x9D', ' ', '\xEA', '\xA2', '\x9B', /* ꢜ ꢞ ꢳ ꢂ ꢖ ꢒ ꢝ ꢛ */ '\0', '\xEA', '\xA2', '\x82', ' ', '\xEA', '\xA2', '\xA8', ' ', '\xEA', '\xA2', '\xBA', ' ', '\xEA', '\xA2', '\xA4', ' ', '\xEA', '\xA2', '\x8E', /* ꢂ ꢨ ꢺ ꢤ ꢎ */ '\0', '\xF0', '\x90', '\x91', '\x95', ' ', '\xF0', '\x90', '\x91', '\x99', /* 𐑕 𐑙 */ '\0', '\xF0', '\x90', '\x91', '\x94', ' ', '\xF0', '\x90', '\x91', '\x96', ' ', '\xF0', '\x90', '\x91', '\x97', ' ', '\xF0', '\x90', '\x91', '\xB9', ' ', '\xF0', '\x90', '\x91', '\xBB', /* 𐑔 𐑖 𐑗 𐑹 𐑻 */ '\0', '\xF0', '\x90', '\x91', '\x9F', ' ', '\xF0', '\x90', '\x91', '\xA3', /* 𐑟 𐑣 */ '\0', '\xF0', '\x90', '\x91', '\xB1', ' ', '\xF0', '\x90', '\x91', '\xB2', ' ', '\xF0', '\x90', '\x91', '\xB3', ' ', '\xF0', '\x90', '\x91', '\xB4', ' ', '\xF0', '\x90', '\x91', '\xB8', ' ', '\xF0', '\x90', '\x91', '\xBA', ' ', '\xF0', '\x90', '\x91', '\xBC', /* 𐑱 𐑲 𐑳 𐑴 𐑸 𐑺 𐑼 */ '\0', '\xF0', '\x90', '\x91', '\xB4', ' ', '\xF0', '\x90', '\x91', '\xBB', ' ', '\xF0', '\x90', '\x91', '\xB9', /* 𐑴 𐑻 𐑹 */ '\0', '\xE0', '\xB6', '\x89', ' ', '\xE0', '\xB6', '\x9A', ' ', '\xE0', '\xB6', '\x9D', ' ', '\xE0', '\xB6', '\xB3', ' ', '\xE0', '\xB6', '\xB4', ' ', '\xE0', '\xB6', '\xBA', ' ', '\xE0', '\xB6', '\xBD', ' ', '\xE0', '\xB7', '\x86', /* ඉ ක ඝ ඳ ප ය ල ෆ */ '\0', '\xE0', '\xB6', '\x91', ' ', '\xE0', '\xB6', '\x94', ' ', '\xE0', '\xB6', '\x9D', ' ', '\xE0', '\xB6', '\xA2', ' ', '\xE0', '\xB6', '\xA7', ' ', '\xE0', '\xB6', '\xAE', ' ', '\xE0', '\xB6', '\xB0', ' ', '\xE0', '\xB6', '\xBB', /* එ ඔ ඝ ජ ට ථ ධ ර */ '\0', '\xE0', '\xB6', '\xAF', ' ', '\xE0', '\xB6', '\xB3', ' ', '\xE0', '\xB6', '\x8B', ' ', '\xE0', '\xB6', '\xBD', ' ', '\xE0', '\xB6', '\xAD', '\xE0', '\xB7', '\x96', ' ', '\xE0', '\xB6', '\xAD', '\xE0', '\xB7', '\x94', ' ', '\xE0', '\xB6', '\xB6', '\xE0', '\xB7', '\x94', ' ', '\xE0', '\xB6', '\xAF', '\xE0', '\xB7', '\x94', /* ද ඳ උ ල තූ තු බු දු */ '\0', '\xE1', '\xAE', '\x8B', ' ', '\xE1', '\xAE', '\x9E', ' ', '\xE1', '\xAE', '\xAE', ' ', '\xE1', '\xAE', '\xBD', ' ', '\xE1', '\xAE', '\xB0', ' ', '\xE1', '\xAE', '\x88', /* ᮋ ᮞ ᮮ ᮽ ᮰ ᮈ */ '\0', '\xE1', '\xAE', '\x84', ' ', '\xE1', '\xAE', '\x94', ' ', '\xE1', '\xAE', '\x95', ' ', '\xE1', '\xAE', '\x97', ' ', '\xE1', '\xAE', '\xB0', ' ', '\xE1', '\xAE', '\x86', ' ', '\xE1', '\xAE', '\x88', ' ', '\xE1', '\xAE', '\x89', /* ᮄ ᮔ ᮕ ᮗ ᮰ ᮆ ᮈ ᮉ */ '\0', '\xE1', '\xAE', '\xBC', ' ', '\xE1', '\xB3', '\x84', /* ᮼ ᳄ */ '\0', '\xEA', '\xAA', '\x86', ' ', '\xEA', '\xAA', '\x94', ' ', '\xEA', '\xAA', '\x92', ' ', '\xEA', '\xAA', '\x96', ' ', '\xEA', '\xAA', '\xAB', /* ꪆ ꪔ ꪒ ꪖ ꪫ */ '\0', '\xEA', '\xAA', '\x89', ' ', '\xEA', '\xAA', '\xAB', ' ', '\xEA', '\xAA', '\xAE', /* ꪉ ꪫ ꪮ */ '\0', '\xE0', '\xAE', '\x89', ' ', '\xE0', '\xAE', '\x92', ' ', '\xE0', '\xAE', '\x93', ' ', '\xE0', '\xAE', '\xB1', ' ', '\xE0', '\xAE', '\x88', ' ', '\xE0', '\xAE', '\x95', ' ', '\xE0', '\xAE', '\x99', ' ', '\xE0', '\xAE', '\x9A', /* உ ஒ ஓ ற ஈ க ங ச */ '\0', '\xE0', '\xAE', '\x95', ' ', '\xE0', '\xAE', '\x9A', ' ', '\xE0', '\xAE', '\xB2', ' ', '\xE0', '\xAE', '\xB6', ' ', '\xE0', '\xAE', '\x89', ' ', '\xE0', '\xAE', '\x99', ' ', '\xE0', '\xAE', '\x9F', ' ', '\xE0', '\xAE', '\xAA', /* க ச ல ஶ உ ங ட ப */ '\0', '\xE0', '\xB0', '\x87', ' ', '\xE0', '\xB0', '\x8C', ' ', '\xE0', '\xB0', '\x99', ' ', '\xE0', '\xB0', '\x9E', ' ', '\xE0', '\xB0', '\xA3', ' ', '\xE0', '\xB0', '\xB1', ' ', '\xE0', '\xB1', '\xAF', /* ఇ ఌ ఙ ఞ ణ ఱ ౯ */ '\0', '\xE0', '\xB0', '\x85', ' ', '\xE0', '\xB0', '\x95', ' ', '\xE0', '\xB0', '\x9A', ' ', '\xE0', '\xB0', '\xB0', ' ', '\xE0', '\xB0', '\xBD', ' ', '\xE0', '\xB1', '\xA8', ' ', '\xE0', '\xB1', '\xAC', /* అ క చ ర ఽ ౨ ౬ */ '\0', '\xE0', '\xB8', '\x9A', ' ', '\xE0', '\xB9', '\x80', ' ', '\xE0', '\xB9', '\x81', ' ', '\xE0', '\xB8', '\xAD', ' ', '\xE0', '\xB8', '\x81', ' ', '\xE0', '\xB8', '\xB2', /* บ เ แ อ ก า */ '\0', '\xE0', '\xB8', '\x9A', ' ', '\xE0', '\xB8', '\x9B', ' ', '\xE0', '\xB8', '\xA9', ' ', '\xE0', '\xB8', '\xAF', ' ', '\xE0', '\xB8', '\xAD', ' ', '\xE0', '\xB8', '\xA2', ' ', '\xE0', '\xB8', '\xAE', /* บ ป ษ ฯ อ ย ฮ */ '\0', '\xE0', '\xB8', '\x9B', ' ', '\xE0', '\xB8', '\x9D', ' ', '\xE0', '\xB8', '\x9F', /* ป ฝ ฟ */ '\0', '\xE0', '\xB9', '\x82', ' ', '\xE0', '\xB9', '\x83', ' ', '\xE0', '\xB9', '\x84', /* โ ใ ไ */ '\0', '\xE0', '\xB8', '\x8E', ' ', '\xE0', '\xB8', '\x8F', ' ', '\xE0', '\xB8', '\xA4', ' ', '\xE0', '\xB8', '\xA6', /* ฎ ฏ ฤ ฦ */ '\0', '\xE0', '\xB8', '\x8D', ' ', '\xE0', '\xB8', '\x90', /* ญ ฐ */ '\0', '\xE0', '\xB9', '\x90', ' ', '\xE0', '\xB9', '\x91', ' ', '\xE0', '\xB9', '\x93', /* ๐ ๑ ๓ */ '\0', '\xE2', '\xB5', '\x94', ' ', '\xE2', '\xB5', '\x99', ' ', '\xE2', '\xB5', '\x9B', ' ', '\xE2', '\xB5', '\x9E', ' ', '\xE2', '\xB4', '\xB5', ' ', '\xE2', '\xB4', '\xBC', ' ', '\xE2', '\xB4', '\xB9', ' ', '\xE2', '\xB5', '\x8E', /* ⵔ ⵙ ⵛ ⵞ ⴵ ⴼ ⴹ ⵎ */ '\0', '\xEA', '\x97', '\x8D', ' ', '\xEA', '\x98', '\x96', ' ', '\xEA', '\x98', '\x99', ' ', '\xEA', '\x98', '\x9C', ' ', '\xEA', '\x96', '\x9C', ' ', '\xEA', '\x96', '\x9D', ' ', '\xEA', '\x94', '\x85', ' ', '\xEA', '\x95', '\xA2', /* ꗍ ꘖ ꘙ ꘜ ꖜ ꖝ ꔅ ꕢ */ '\0', '\xEA', '\x97', '\x8D', ' ', '\xEA', '\x98', '\x96', ' ', '\xEA', '\x98', '\x99', ' ', '\xEA', '\x97', '\x9E', ' ', '\xEA', '\x94', '\x85', ' ', '\xEA', '\x95', '\xA2', ' ', '\xEA', '\x96', '\x9C', ' ', '\xEA', '\x94', '\x86', /* ꗍ ꘖ ꘙ ꗞ ꔅ ꕢ ꖜ ꔆ */ #ifdef AF_CONFIG_OPTION_CJK '\0', '\xE4', '\xBB', '\x96', ' ', '\xE4', '\xBB', '\xAC', ' ', '\xE4', '\xBD', '\xA0', ' ', '\xE4', '\xBE', '\x86', ' ', '\xE5', '\x80', '\x91', ' ', '\xE5', '\x88', '\xB0', ' ', '\xE5', '\x92', '\x8C', ' ', '\xE5', '\x9C', '\xB0', /* 他 们 你 來 們 到 和 地 */ ' ', '\xE5', '\xAF', '\xB9', ' ', '\xE5', '\xB0', '\x8D', ' ', '\xE5', '\xB0', '\xB1', ' ', '\xE5', '\xB8', '\xAD', ' ', '\xE6', '\x88', '\x91', ' ', '\xE6', '\x97', '\xB6', ' ', '\xE6', '\x99', '\x82', ' ', '\xE6', '\x9C', '\x83', /* 对 對 就 席 我 时 時 會 */ ' ', '\xE6', '\x9D', '\xA5', ' ', '\xE7', '\x82', '\xBA', ' ', '\xE8', '\x83', '\xBD', ' ', '\xE8', '\x88', '\xB0', ' ', '\xE8', '\xAA', '\xAA', ' ', '\xE8', '\xAF', '\xB4', ' ', '\xE8', '\xBF', '\x99', ' ', '\xE9', '\x80', '\x99', /* 来 為 能 舰 說 说 这 這 */ ' ', '\xE9', '\xBD', '\x8A', ' ', '|', /* 齊 | */ ' ', '\xE5', '\x86', '\x9B', ' ', '\xE5', '\x90', '\x8C', ' ', '\xE5', '\xB7', '\xB2', ' ', '\xE6', '\x84', '\xBF', ' ', '\xE6', '\x97', '\xA2', ' ', '\xE6', '\x98', '\x9F', ' ', '\xE6', '\x98', '\xAF', ' ', '\xE6', '\x99', '\xAF', /* 军 同 已 愿 既 星 是 景 */ ' ', '\xE6', '\xB0', '\x91', ' ', '\xE7', '\x85', '\xA7', ' ', '\xE7', '\x8E', '\xB0', ' ', '\xE7', '\x8F', '\xBE', ' ', '\xE7', '\x90', '\x86', ' ', '\xE7', '\x94', '\xA8', ' ', '\xE7', '\xBD', '\xAE', ' ', '\xE8', '\xA6', '\x81', /* 民 照 现 現 理 用 置 要 */ ' ', '\xE8', '\xBB', '\x8D', ' ', '\xE9', '\x82', '\xA3', ' ', '\xE9', '\x85', '\x8D', ' ', '\xE9', '\x87', '\x8C', ' ', '\xE9', '\x96', '\x8B', ' ', '\xE9', '\x9B', '\xB7', ' ', '\xE9', '\x9C', '\xB2', ' ', '\xE9', '\x9D', '\xA2', /* 軍 那 配 里 開 雷 露 面 */ ' ', '\xE9', '\xA1', '\xBE', /* 顾 */ '\0', '\xE4', '\xB8', '\xAA', ' ', '\xE4', '\xB8', '\xBA', ' ', '\xE4', '\xBA', '\xBA', ' ', '\xE4', '\xBB', '\x96', ' ', '\xE4', '\xBB', '\xA5', ' ', '\xE4', '\xBB', '\xAC', ' ', '\xE4', '\xBD', '\xA0', ' ', '\xE4', '\xBE', '\x86', /* 个 为 人 他 以 们 你 來 */ ' ', '\xE5', '\x80', '\x8B', ' ', '\xE5', '\x80', '\x91', ' ', '\xE5', '\x88', '\xB0', ' ', '\xE5', '\x92', '\x8C', ' ', '\xE5', '\xA4', '\xA7', ' ', '\xE5', '\xAF', '\xB9', ' ', '\xE5', '\xB0', '\x8D', ' ', '\xE5', '\xB0', '\xB1', /* 個 們 到 和 大 对 對 就 */ ' ', '\xE6', '\x88', '\x91', ' ', '\xE6', '\x97', '\xB6', ' ', '\xE6', '\x99', '\x82', ' ', '\xE6', '\x9C', '\x89', ' ', '\xE6', '\x9D', '\xA5', ' ', '\xE7', '\x82', '\xBA', ' ', '\xE8', '\xA6', '\x81', ' ', '\xE8', '\xAA', '\xAA', /* 我 时 時 有 来 為 要 說 */ ' ', '\xE8', '\xAF', '\xB4', ' ', '|', /* 说 | */ ' ', '\xE4', '\xB8', '\xBB', ' ', '\xE4', '\xBA', '\x9B', ' ', '\xE5', '\x9B', '\xA0', ' ', '\xE5', '\xAE', '\x83', ' ', '\xE6', '\x83', '\xB3', ' ', '\xE6', '\x84', '\x8F', ' ', '\xE7', '\x90', '\x86', ' ', '\xE7', '\x94', '\x9F', /* 主 些 因 它 想 意 理 生 */ ' ', '\xE7', '\x95', '\xB6', ' ', '\xE7', '\x9C', '\x8B', ' ', '\xE7', '\x9D', '\x80', ' ', '\xE7', '\xBD', '\xAE', ' ', '\xE8', '\x80', '\x85', ' ', '\xE8', '\x87', '\xAA', ' ', '\xE8', '\x91', '\x97', ' ', '\xE8', '\xA3', '\xA1', /* 當 看 着 置 者 自 著 裡 */ ' ', '\xE8', '\xBF', '\x87', ' ', '\xE8', '\xBF', '\x98', ' ', '\xE8', '\xBF', '\x9B', ' ', '\xE9', '\x80', '\xB2', ' ', '\xE9', '\x81', '\x8E', ' ', '\xE9', '\x81', '\x93', ' ', '\xE9', '\x82', '\x84', ' ', '\xE9', '\x87', '\x8C', /* 过 还 进 進 過 道 還 里 */ ' ', '\xE9', '\x9D', '\xA2', /* 面 */ #ifdef AF_CONFIG_OPTION_CJK_BLUE_HANI_VERT '\0', ' ', '\xE4', '\xBA', '\x9B', ' ', '\xE4', '\xBB', '\xAC', ' ', '\xE4', '\xBD', '\xA0', ' ', '\xE4', '\xBE', '\x86', ' ', '\xE5', '\x80', '\x91', ' ', '\xE5', '\x88', '\xB0', ' ', '\xE5', '\x92', '\x8C', ' ', '\xE5', '\x9C', '\xB0', /* 些 们 你 來 們 到 和 地 */ ' ', '\xE5', '\xA5', '\xB9', ' ', '\xE5', '\xB0', '\x86', ' ', '\xE5', '\xB0', '\x87', ' ', '\xE5', '\xB0', '\xB1', ' ', '\xE5', '\xB9', '\xB4', ' ', '\xE5', '\xBE', '\x97', ' ', '\xE6', '\x83', '\x85', ' ', '\xE6', '\x9C', '\x80', /* 她 将 將 就 年 得 情 最 */ ' ', '\xE6', '\xA0', '\xB7', ' ', '\xE6', '\xA8', '\xA3', ' ', '\xE7', '\x90', '\x86', ' ', '\xE8', '\x83', '\xBD', ' ', '\xE8', '\xAA', '\xAA', ' ', '\xE8', '\xAF', '\xB4', ' ', '\xE8', '\xBF', '\x99', ' ', '\xE9', '\x80', '\x99', /* 样 樣 理 能 說 说 这 這 */ ' ', '\xE9', '\x80', '\x9A', ' ', '|', /* 通 | */ ' ', '\xE5', '\x8D', '\xB3', ' ', '\xE5', '\x90', '\x97', ' ', '\xE5', '\x90', '\xA7', ' ', '\xE5', '\x90', '\xAC', ' ', '\xE5', '\x91', '\xA2', ' ', '\xE5', '\x93', '\x81', ' ', '\xE5', '\x93', '\x8D', ' ', '\xE5', '\x97', '\x8E', /* 即 吗 吧 听 呢 品 响 嗎 */ ' ', '\xE5', '\xB8', '\x88', ' ', '\xE5', '\xB8', '\xAB', ' ', '\xE6', '\x94', '\xB6', ' ', '\xE6', '\x96', '\xAD', ' ', '\xE6', '\x96', '\xB7', ' ', '\xE6', '\x98', '\x8E', ' ', '\xE7', '\x9C', '\xBC', ' ', '\xE9', '\x96', '\x93', /* 师 師 收 断 斷 明 眼 間 */ ' ', '\xE9', '\x97', '\xB4', ' ', '\xE9', '\x99', '\x85', ' ', '\xE9', '\x99', '\x88', ' ', '\xE9', '\x99', '\x90', ' ', '\xE9', '\x99', '\xA4', ' ', '\xE9', '\x99', '\xB3', ' ', '\xE9', '\x9A', '\x8F', ' ', '\xE9', '\x9A', '\x9B', /* 间 际 陈 限 除 陳 随 際 */ ' ', '\xE9', '\x9A', '\xA8', /* 隨 */ '\0', '\xE4', '\xBA', '\x8B', ' ', '\xE5', '\x89', '\x8D', ' ', '\xE5', '\xAD', '\xB8', ' ', '\xE5', '\xB0', '\x86', ' ', '\xE5', '\xB0', '\x87', ' ', '\xE6', '\x83', '\x85', ' ', '\xE6', '\x83', '\xB3', ' ', '\xE6', '\x88', '\x96', /* 事 前 學 将 將 情 想 或 */ ' ', '\xE6', '\x94', '\xBF', ' ', '\xE6', '\x96', '\xAF', ' ', '\xE6', '\x96', '\xB0', ' ', '\xE6', '\xA0', '\xB7', ' ', '\xE6', '\xA8', '\xA3', ' ', '\xE6', '\xB0', '\x91', ' ', '\xE6', '\xB2', '\x92', ' ', '\xE6', '\xB2', '\xA1', /* 政 斯 新 样 樣 民 沒 没 */ ' ', '\xE7', '\x84', '\xB6', ' ', '\xE7', '\x89', '\xB9', ' ', '\xE7', '\x8E', '\xB0', ' ', '\xE7', '\x8F', '\xBE', ' ', '\xE7', '\x90', '\x83', ' ', '\xE7', '\xAC', '\xAC', ' ', '\xE7', '\xB6', '\x93', ' ', '\xE8', '\xB0', '\x81', /* 然 特 现 現 球 第 經 谁 */ ' ', '\xE8', '\xB5', '\xB7', ' ', '|', /* 起 | */ ' ', '\xE4', '\xBE', '\x8B', ' ', '\xE5', '\x88', '\xA5', ' ', '\xE5', '\x88', '\xAB', ' ', '\xE5', '\x88', '\xB6', ' ', '\xE5', '\x8A', '\xA8', ' ', '\xE5', '\x8B', '\x95', ' ', '\xE5', '\x90', '\x97', ' ', '\xE5', '\x97', '\x8E', /* 例 別 别 制 动 動 吗 嗎 */ ' ', '\xE5', '\xA2', '\x9E', ' ', '\xE6', '\x8C', '\x87', ' ', '\xE6', '\x98', '\x8E', ' ', '\xE6', '\x9C', '\x9D', ' ', '\xE6', '\x9C', '\x9F', ' ', '\xE6', '\x9E', '\x84', ' ', '\xE7', '\x89', '\xA9', ' ', '\xE7', '\xA1', '\xAE', /* 增 指 明 朝 期 构 物 确 */ ' ', '\xE7', '\xA7', '\x8D', ' ', '\xE8', '\xAA', '\xBF', ' ', '\xE8', '\xB0', '\x83', ' ', '\xE8', '\xB2', '\xBB', ' ', '\xE8', '\xB4', '\xB9', ' ', '\xE9', '\x82', '\xA3', ' ', '\xE9', '\x83', '\xBD', ' ', '\xE9', '\x96', '\x93', /* 种 調 调 費 费 那 都 間 */ ' ', '\xE9', '\x97', '\xB4', /* 间 */ #endif /* AF_CONFIG_OPTION_CJK_BLUE_HANI_VERT */ #endif /* AF_CONFIG_OPTION_CJK */ '\0', }; /* stringsets are specific to styles */ FT_LOCAL_ARRAY_DEF( AF_Blue_StringRec ) af_blue_stringsets[] = { /* */ { AF_BLUE_STRING_ADLAM_CAPITAL_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_ADLAM_CAPITAL_BOTTOM, 0 }, { AF_BLUE_STRING_ADLAM_SMALL_TOP, AF_BLUE_PROPERTY_LATIN_TOP | AF_BLUE_PROPERTY_LATIN_X_HEIGHT }, { AF_BLUE_STRING_ADLAM_SMALL_BOTTOM, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_ARABIC_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_ARABIC_BOTTOM, 0 }, { AF_BLUE_STRING_ARABIC_JOIN, AF_BLUE_PROPERTY_LATIN_NEUTRAL }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_ARMENIAN_CAPITAL_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_ARMENIAN_CAPITAL_BOTTOM, 0 }, { AF_BLUE_STRING_ARMENIAN_SMALL_ASCENDER, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_ARMENIAN_SMALL_TOP, AF_BLUE_PROPERTY_LATIN_TOP | AF_BLUE_PROPERTY_LATIN_X_HEIGHT }, { AF_BLUE_STRING_ARMENIAN_SMALL_BOTTOM, 0 }, { AF_BLUE_STRING_ARMENIAN_SMALL_DESCENDER, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_AVESTAN_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_AVESTAN_BOTTOM, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_BAMUM_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_BAMUM_BOTTOM, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_BENGALI_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_BENGALI_HEAD, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_BENGALI_BASE, AF_BLUE_PROPERTY_LATIN_TOP | AF_BLUE_PROPERTY_LATIN_NEUTRAL | AF_BLUE_PROPERTY_LATIN_X_HEIGHT }, { AF_BLUE_STRING_BENGALI_BASE, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_BUHID_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_BUHID_LARGE, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_BUHID_SMALL, AF_BLUE_PROPERTY_LATIN_TOP | AF_BLUE_PROPERTY_LATIN_X_HEIGHT }, { AF_BLUE_STRING_BUHID_BOTTOM, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_CHAKMA_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_CHAKMA_BOTTOM, 0 }, { AF_BLUE_STRING_CHAKMA_DESCENDER, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_CANADIAN_SYLLABICS_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_CANADIAN_SYLLABICS_BOTTOM, 0 }, { AF_BLUE_STRING_CANADIAN_SYLLABICS_SMALL_TOP, AF_BLUE_PROPERTY_LATIN_TOP | AF_BLUE_PROPERTY_LATIN_X_HEIGHT }, { AF_BLUE_STRING_CANADIAN_SYLLABICS_SMALL_BOTTOM, 0 }, { AF_BLUE_STRING_CANADIAN_SYLLABICS_SUPS_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_CANADIAN_SYLLABICS_SUPS_BOTTOM, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_CARIAN_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_CARIAN_BOTTOM, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_CHEROKEE_CAPITAL, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_CHEROKEE_CAPITAL, 0 }, { AF_BLUE_STRING_CHEROKEE_SMALL_ASCENDER, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_CHEROKEE_SMALL, AF_BLUE_PROPERTY_LATIN_TOP | AF_BLUE_PROPERTY_LATIN_X_HEIGHT }, { AF_BLUE_STRING_CHEROKEE_SMALL, 0 }, { AF_BLUE_STRING_CHEROKEE_SMALL_DESCENDER, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_COPTIC_CAPITAL_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_COPTIC_CAPITAL_BOTTOM, 0 }, { AF_BLUE_STRING_COPTIC_SMALL_TOP, AF_BLUE_PROPERTY_LATIN_TOP | AF_BLUE_PROPERTY_LATIN_X_HEIGHT }, { AF_BLUE_STRING_COPTIC_SMALL_BOTTOM, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_CYPRIOT_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_CYPRIOT_BOTTOM, 0 }, { AF_BLUE_STRING_CYPRIOT_SMALL, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_CYPRIOT_SMALL, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_CYRILLIC_CAPITAL_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_CYRILLIC_CAPITAL_BOTTOM, 0 }, { AF_BLUE_STRING_CYRILLIC_SMALL, AF_BLUE_PROPERTY_LATIN_TOP | AF_BLUE_PROPERTY_LATIN_X_HEIGHT }, { AF_BLUE_STRING_CYRILLIC_SMALL, 0 }, { AF_BLUE_STRING_CYRILLIC_SMALL_DESCENDER, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_DEVANAGARI_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_DEVANAGARI_HEAD, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_DEVANAGARI_BASE, AF_BLUE_PROPERTY_LATIN_TOP | AF_BLUE_PROPERTY_LATIN_NEUTRAL | AF_BLUE_PROPERTY_LATIN_X_HEIGHT }, { AF_BLUE_STRING_DEVANAGARI_BASE, 0 }, { AF_BLUE_STRING_DEVANAGARI_BOTTOM, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_DESERET_CAPITAL_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_DESERET_CAPITAL_BOTTOM, 0 }, { AF_BLUE_STRING_DESERET_SMALL_TOP, AF_BLUE_PROPERTY_LATIN_TOP | AF_BLUE_PROPERTY_LATIN_X_HEIGHT }, { AF_BLUE_STRING_DESERET_SMALL_BOTTOM, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_ETHIOPIC_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_ETHIOPIC_BOTTOM, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_GEORGIAN_MKHEDRULI_TOP, AF_BLUE_PROPERTY_LATIN_TOP | AF_BLUE_PROPERTY_LATIN_X_HEIGHT }, { AF_BLUE_STRING_GEORGIAN_MKHEDRULI_BOTTOM, 0 }, { AF_BLUE_STRING_GEORGIAN_MKHEDRULI_ASCENDER, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_GEORGIAN_MKHEDRULI_DESCENDER, 0 }, { AF_BLUE_STRING_GEORGIAN_MTAVRULI_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_GEORGIAN_MTAVRULI_BOTTOM, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_GEORGIAN_ASOMTAVRULI_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_GEORGIAN_ASOMTAVRULI_BOTTOM, 0 }, { AF_BLUE_STRING_GEORGIAN_NUSKHURI_TOP, AF_BLUE_PROPERTY_LATIN_TOP | AF_BLUE_PROPERTY_LATIN_X_HEIGHT }, { AF_BLUE_STRING_GEORGIAN_NUSKHURI_BOTTOM, 0 }, { AF_BLUE_STRING_GEORGIAN_NUSKHURI_ASCENDER, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_GEORGIAN_NUSKHURI_DESCENDER, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_GLAGOLITIC_CAPITAL_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_GLAGOLITIC_CAPITAL_BOTTOM, 0 }, { AF_BLUE_STRING_GLAGOLITIC_SMALL_TOP, AF_BLUE_PROPERTY_LATIN_TOP | AF_BLUE_PROPERTY_LATIN_X_HEIGHT }, { AF_BLUE_STRING_GLAGOLITIC_SMALL_BOTTOM, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_GOTHIC_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_GOTHIC_BOTTOM, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_GREEK_CAPITAL_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_GREEK_CAPITAL_BOTTOM, 0 }, { AF_BLUE_STRING_GREEK_SMALL_BETA_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_GREEK_SMALL, AF_BLUE_PROPERTY_LATIN_TOP | AF_BLUE_PROPERTY_LATIN_X_HEIGHT }, { AF_BLUE_STRING_GREEK_SMALL, 0 }, { AF_BLUE_STRING_GREEK_SMALL_DESCENDER, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_GUJARATI_TOP, AF_BLUE_PROPERTY_LATIN_TOP | AF_BLUE_PROPERTY_LATIN_X_HEIGHT }, { AF_BLUE_STRING_GUJARATI_BOTTOM, 0 }, { AF_BLUE_STRING_GUJARATI_ASCENDER, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_GUJARATI_DESCENDER, 0 }, { AF_BLUE_STRING_GUJARATI_DIGIT_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_GURMUKHI_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_GURMUKHI_HEAD, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_GURMUKHI_BASE, AF_BLUE_PROPERTY_LATIN_TOP | AF_BLUE_PROPERTY_LATIN_NEUTRAL | AF_BLUE_PROPERTY_LATIN_X_HEIGHT }, { AF_BLUE_STRING_GURMUKHI_BOTTOM, 0 }, { AF_BLUE_STRING_GURMUKHI_DIGIT_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_HEBREW_TOP, AF_BLUE_PROPERTY_LATIN_TOP | AF_BLUE_PROPERTY_LATIN_LONG }, { AF_BLUE_STRING_HEBREW_BOTTOM, 0 }, { AF_BLUE_STRING_HEBREW_DESCENDER, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_KANNADA_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_KANNADA_BOTTOM, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_KAYAH_LI_TOP, AF_BLUE_PROPERTY_LATIN_TOP | AF_BLUE_PROPERTY_LATIN_X_HEIGHT }, { AF_BLUE_STRING_KAYAH_LI_BOTTOM, 0 }, { AF_BLUE_STRING_KAYAH_LI_ASCENDER, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_KAYAH_LI_DESCENDER, 0 }, { AF_BLUE_STRING_KAYAH_LI_LARGE_DESCENDER, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_KHMER_TOP, AF_BLUE_PROPERTY_LATIN_TOP | AF_BLUE_PROPERTY_LATIN_X_HEIGHT }, { AF_BLUE_STRING_KHMER_SUBSCRIPT_TOP, AF_BLUE_PROPERTY_LATIN_SUB_TOP }, { AF_BLUE_STRING_KHMER_BOTTOM, 0 }, { AF_BLUE_STRING_KHMER_DESCENDER, 0 }, { AF_BLUE_STRING_KHMER_LARGE_DESCENDER, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_KHMER_SYMBOLS_WAXING_TOP, AF_BLUE_PROPERTY_LATIN_TOP | AF_BLUE_PROPERTY_LATIN_X_HEIGHT }, { AF_BLUE_STRING_KHMER_SYMBOLS_WANING_BOTTOM, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_LAO_TOP, AF_BLUE_PROPERTY_LATIN_TOP | AF_BLUE_PROPERTY_LATIN_X_HEIGHT }, { AF_BLUE_STRING_LAO_BOTTOM, 0 }, { AF_BLUE_STRING_LAO_ASCENDER, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_LAO_LARGE_ASCENDER, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_LAO_DESCENDER, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_LATIN_CAPITAL_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_LATIN_CAPITAL_BOTTOM, 0 }, { AF_BLUE_STRING_LATIN_SMALL_F_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_LATIN_SMALL_TOP, AF_BLUE_PROPERTY_LATIN_TOP | AF_BLUE_PROPERTY_LATIN_X_HEIGHT }, { AF_BLUE_STRING_LATIN_SMALL_BOTTOM, 0 }, { AF_BLUE_STRING_LATIN_SMALL_DESCENDER, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_LATIN_SUBS_CAPITAL_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_LATIN_SUBS_CAPITAL_BOTTOM, 0 }, { AF_BLUE_STRING_LATIN_SUBS_SMALL_F_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_LATIN_SUBS_SMALL, AF_BLUE_PROPERTY_LATIN_TOP | AF_BLUE_PROPERTY_LATIN_X_HEIGHT }, { AF_BLUE_STRING_LATIN_SUBS_SMALL, 0 }, { AF_BLUE_STRING_LATIN_SUBS_SMALL_DESCENDER, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_LATIN_SUPS_CAPITAL_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_LATIN_SUPS_CAPITAL_BOTTOM, 0 }, { AF_BLUE_STRING_LATIN_SUPS_SMALL_F_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_LATIN_SUPS_SMALL, AF_BLUE_PROPERTY_LATIN_TOP | AF_BLUE_PROPERTY_LATIN_X_HEIGHT }, { AF_BLUE_STRING_LATIN_SUPS_SMALL, 0 }, { AF_BLUE_STRING_LATIN_SUPS_SMALL_DESCENDER, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_LISU_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_LISU_BOTTOM, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_MALAYALAM_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_MALAYALAM_BOTTOM, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_MEDEFAIDRIN_CAPITAL_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_MEDEFAIDRIN_CAPITAL_BOTTOM, 0 }, { AF_BLUE_STRING_MEDEFAIDRIN_SMALL_F_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_MEDEFAIDRIN_SMALL_TOP, AF_BLUE_PROPERTY_LATIN_TOP | AF_BLUE_PROPERTY_LATIN_X_HEIGHT }, { AF_BLUE_STRING_MEDEFAIDRIN_SMALL_BOTTOM, 0 }, { AF_BLUE_STRING_MEDEFAIDRIN_SMALL_DESCENDER, 0 }, { AF_BLUE_STRING_MEDEFAIDRIN_DIGIT_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_MONGOLIAN_TOP_BASE, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_MONGOLIAN_BOTTOM_BASE, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_MYANMAR_TOP, AF_BLUE_PROPERTY_LATIN_TOP | AF_BLUE_PROPERTY_LATIN_X_HEIGHT }, { AF_BLUE_STRING_MYANMAR_BOTTOM, 0 }, { AF_BLUE_STRING_MYANMAR_ASCENDER, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_MYANMAR_DESCENDER, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_NKO_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_NKO_BOTTOM, 0 }, { AF_BLUE_STRING_NKO_SMALL_TOP, AF_BLUE_PROPERTY_LATIN_TOP | AF_BLUE_PROPERTY_LATIN_X_HEIGHT }, { AF_BLUE_STRING_NKO_SMALL_BOTTOM, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_OL_CHIKI, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_OL_CHIKI, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_OLD_TURKIC_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_OLD_TURKIC_BOTTOM, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_OSAGE_CAPITAL_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_OSAGE_CAPITAL_BOTTOM, 0 }, { AF_BLUE_STRING_OSAGE_CAPITAL_DESCENDER, 0 }, { AF_BLUE_STRING_OSAGE_SMALL_TOP, AF_BLUE_PROPERTY_LATIN_TOP | AF_BLUE_PROPERTY_LATIN_X_HEIGHT }, { AF_BLUE_STRING_OSAGE_SMALL_BOTTOM, 0 }, { AF_BLUE_STRING_OSAGE_SMALL_ASCENDER, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_OSAGE_SMALL_DESCENDER, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_OSMANYA_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_OSMANYA_BOTTOM, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_ROHINGYA_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_ROHINGYA_BOTTOM, 0 }, { AF_BLUE_STRING_ROHINGYA_JOIN, AF_BLUE_PROPERTY_LATIN_NEUTRAL }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_SAURASHTRA_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_SAURASHTRA_BOTTOM, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_SHAVIAN_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_SHAVIAN_BOTTOM, 0 }, { AF_BLUE_STRING_SHAVIAN_DESCENDER, 0 }, { AF_BLUE_STRING_SHAVIAN_SMALL_TOP, AF_BLUE_PROPERTY_LATIN_TOP | AF_BLUE_PROPERTY_LATIN_X_HEIGHT }, { AF_BLUE_STRING_SHAVIAN_SMALL_BOTTOM, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_SINHALA_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_SINHALA_BOTTOM, 0 }, { AF_BLUE_STRING_SINHALA_DESCENDER, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_SUNDANESE_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_SUNDANESE_BOTTOM, 0 }, { AF_BLUE_STRING_SUNDANESE_DESCENDER, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_TAMIL_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_TAMIL_BOTTOM, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_TAI_VIET_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_TAI_VIET_BOTTOM, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_TELUGU_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_TELUGU_BOTTOM, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_THAI_TOP, AF_BLUE_PROPERTY_LATIN_TOP | AF_BLUE_PROPERTY_LATIN_X_HEIGHT }, { AF_BLUE_STRING_THAI_BOTTOM, 0 }, { AF_BLUE_STRING_THAI_ASCENDER, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_THAI_LARGE_ASCENDER, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_THAI_DESCENDER, 0 }, { AF_BLUE_STRING_THAI_LARGE_DESCENDER, 0 }, { AF_BLUE_STRING_THAI_DIGIT_TOP, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_TIFINAGH, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_TIFINAGH, 0 }, { AF_BLUE_STRING_MAX, 0 }, { AF_BLUE_STRING_VAI_TOP, AF_BLUE_PROPERTY_LATIN_TOP }, { AF_BLUE_STRING_VAI_BOTTOM, 0 }, { AF_BLUE_STRING_MAX, 0 }, #ifdef AF_CONFIG_OPTION_CJK { AF_BLUE_STRING_CJK_TOP, AF_BLUE_PROPERTY_CJK_TOP }, { AF_BLUE_STRING_CJK_BOTTOM, 0 }, #ifdef AF_CONFIG_OPTION_CJK_BLUE_HANI_VERT { AF_BLUE_STRING_CJK_LEFT, AF_BLUE_PROPERTY_CJK_HORIZ }, { AF_BLUE_STRING_CJK_RIGHT, AF_BLUE_PROPERTY_CJK_HORIZ | AF_BLUE_PROPERTY_CJK_RIGHT }, #endif /* AF_CONFIG_OPTION_CJK_BLUE_HANI_VERT */ { AF_BLUE_STRING_MAX, 0 }, #endif /* AF_CONFIG_OPTION_CJK */ }; /* END */
52,745
1,609
package com.mossle.api.user; public interface ApplicationAliasConverter { String convertAlias(String type, String ip); }
38
2,542
<filename>src/prod/src/data/interop/ReliableCollectionRuntimeImpl/RCREventSource.cpp // ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" using namespace Data::Interop; using namespace Common; Common::Global<RCREventSource> RCREventSource::Events = Common::make_global<RCREventSource>();
128
393
#ifndef __FILTERREGISTER__ #define __FILTERREGISTER__ class FilterRegister { protected: int _refCount; bool _registered; static FilterRegister* _instance; void _Register(); void _UnRegister(); public: FilterRegister(); virtual ~FilterRegister(); void AddRef(); void SubRef(); static FilterRegister* Instance(); }; #endif
111
774
<reponame>qzlvyh/Androidcookbook<filename>SimpleJumper.android/src/com/androidcookbook/simplejumper/MainActivity.java<gh_stars>100-1000 package com.androidcookbook.simplejumper; import org.flixel.FlxAndroidApplication; import android.content.pm.ActivityInfo; import android.os.Bundle; import android.view.WindowManager; public class MainActivity extends FlxAndroidApplication { public MainActivity() { super(new FlixelGame()); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // ORIENTATION // setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } }
314
2,816
#ifndef R_APPEND_H #define R_APPEND_H #include <stdbool.h> #include <stdlib.h> #include "decimal.h" typedef void *append_info; append_info *append_info_get(void *info_list, int table_id); void append_row_start(append_info info); void append_row_end(append_info info); void append_varchar(append_info info, const char *value); void append_key(append_info info, int64_t value); void append_date(append_info info, int64_t value); void append_integer(append_info info, int32_t value); void append_decimal(append_info info, decimal_t *val); void append_boolean(append_info info, int32_t val); #endif
221
507
<reponame>saki-osive/spring-native<filename>spring-native-configuration/src/test/java/org/springframework/validated/ValidatedComponentProcessorTest.java package org.springframework.validated; import org.junit.Before; import org.junit.Test; import org.springframework.ValidatedComponentProcessor; import org.springframework.nativex.type.TypeSystem; import org.springframework.nativex.util.NativeTestContext; import org.springframework.validated.components.ComponentWithValidatedInterface; import org.springframework.validated.components.ComponentWithValidatedInterfaceAndExtraInterface; import org.springframework.validated.components.ComponentWithValidatedInterfaceOverProxyClass; import org.springframework.validated.components.ComponentWithValidatedInterfaceOverProxyInterface; import org.springframework.validated.components.ComponentWithValidatedInterfaceWithDefault; import org.springframework.validated.components.ComponentWithValidatedInterfaceWithoutMethod; import org.springframework.validated.components.ValidatedComponent; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; public class ValidatedComponentProcessorTest { private NativeTestContext nativeContext = new NativeTestContext(); private TypeSystem typeSystem = nativeContext.getTypeSystem(); private ValidatedComponentProcessor processor; @Before public void setUp() { processor = new ValidatedComponentProcessor(); } @Test public void shouldDescribeProxiesForComponentWithValidatedInterface() { checkProxies(ComponentWithValidatedInterface.class, "org.springframework.validated.components.ValidatedInterface", Arrays.asList( "org.springframework.validated.components.ValidatedInterface", "org.springframework.aop.SpringProxy", "org.springframework.aop.framework.Advised", "org.springframework.core.DecoratingProxy"), null); } @Test public void shouldDescribeProxiesForComponentWithValidatedInterfaceAndExtraInterface() { checkProxies(ComponentWithValidatedInterfaceAndExtraInterface.class, "org.springframework.validated.components.ValidatedInterface", Arrays.asList( "org.springframework.validated.components.ValidatedInterface", "org.springframework.validated.components.VoidInterface", "org.springframework.aop.SpringProxy", "org.springframework.aop.framework.Advised", "org.springframework.core.DecoratingProxy"), null); } @Test public void shouldDescribeProxiesForComponentWithValidatedInterfaceOverSuperClass() { checkProxies(ComponentWithValidatedInterfaceOverProxyClass.class, "org.springframework.validated.components.ValidatedInterface", Arrays.asList( "org.springframework.validated.components.ValidatedInterface", "org.springframework.aop.SpringProxy", "org.springframework.aop.framework.Advised", "org.springframework.core.DecoratingProxy"), null); } @Test public void shouldDescribeProxiesForComponentWithValidatedInterfaceOverSuperInterface() { checkProxies(ComponentWithValidatedInterfaceOverProxyInterface.class, "org.springframework.validated.components.ProxyInterface", Arrays.asList( "org.springframework.validated.components.ProxyInterface", "org.springframework.aop.SpringProxy", "org.springframework.aop.framework.Advised", "org.springframework.core.DecoratingProxy"), null); } @Test public void shouldDescribeProxiesForComponentWithValidatedInterfaceWithoutMethod() { checkProxies(ComponentWithValidatedInterfaceWithoutMethod.class, null, null, "org.springframework.validated.components.ComponentWithValidatedInterfaceWithoutMethod"); } @Test public void shouldDescribeProxiesForComponentWithValidatedInterfaceWithDefault() { checkProxies(ComponentWithValidatedInterfaceWithDefault.class, "org.springframework.validated.components.ValidatedInterfaceWithDefault", Arrays.asList( "org.springframework.validated.components.ValidatedInterfaceWithDefault", "org.springframework.aop.SpringProxy", "org.springframework.aop.framework.Advised", "org.springframework.core.DecoratingProxy"), null); } @Test public void shouldDescribeProxiesForValidatedComponent() { checkProxies(ValidatedComponent.class, null, null, "org.springframework.validated.components.ValidatedComponent"); } private void checkProxies(Class component, String key, List<String> jdkProxies, String aotProxy) { String componentType = typeSystem.resolve(component).getDottedName(); // handled assertThat(processor.handle(nativeContext, componentType, Collections.emptyList())).isTrue(); // processed processor.process(nativeContext, componentType, Collections.emptyList()); // and has correct proxies if (key != null) { assertThat(nativeContext.getProxyEntries()).isNotEmpty(); assertThat(nativeContext.getProxyEntries().get(key).get(0)) .isEqualTo(jdkProxies); } else { assertThat(nativeContext.getProxyEntries()).isEmpty(); } if (aotProxy == null) { assertThat(nativeContext.getClassProxyEntries()).isEmpty(); } else { assertThat(nativeContext.getClassProxyEntries().keySet()).isEqualTo(new HashSet<>(Arrays.asList( aotProxy))); } } }
2,536
2,816
//===----------------------------------------------------------------------===// // DuckDB // // duckdb/common/compressed_file_system.hpp // // //===----------------------------------------------------------------------===// #pragma once #include "duckdb/common/common.hpp" #include "duckdb/common/file_system.hpp" namespace duckdb { class CompressedFile; struct StreamData { // various buffers & pointers bool write = false; unique_ptr<data_t[]> in_buff; unique_ptr<data_t[]> out_buff; data_ptr_t out_buff_start = nullptr; data_ptr_t out_buff_end = nullptr; data_ptr_t in_buff_start = nullptr; data_ptr_t in_buff_end = nullptr; idx_t in_buf_size = 0; idx_t out_buf_size = 0; }; struct StreamWrapper { DUCKDB_API virtual ~StreamWrapper(); DUCKDB_API virtual void Initialize(CompressedFile &file, bool write) = 0; DUCKDB_API virtual bool Read(StreamData &stream_data) = 0; DUCKDB_API virtual void Write(CompressedFile &file, StreamData &stream_data, data_ptr_t buffer, int64_t nr_bytes) = 0; DUCKDB_API virtual void Close() = 0; }; class CompressedFileSystem : public FileSystem { public: DUCKDB_API int64_t Read(FileHandle &handle, void *buffer, int64_t nr_bytes) override; DUCKDB_API int64_t Write(FileHandle &handle, void *buffer, int64_t nr_bytes) override; DUCKDB_API void Reset(FileHandle &handle) override; DUCKDB_API int64_t GetFileSize(FileHandle &handle) override; DUCKDB_API bool OnDiskFile(FileHandle &handle) override; DUCKDB_API bool CanSeek() override; DUCKDB_API virtual unique_ptr<StreamWrapper> CreateStream() = 0; DUCKDB_API virtual idx_t InBufferSize() = 0; DUCKDB_API virtual idx_t OutBufferSize() = 0; }; class CompressedFile : public FileHandle { public: DUCKDB_API CompressedFile(CompressedFileSystem &fs, unique_ptr<FileHandle> child_handle_p, const string &path); DUCKDB_API virtual ~CompressedFile() override; CompressedFileSystem &compressed_fs; unique_ptr<FileHandle> child_handle; //! Whether the file is opened for reading or for writing bool write = false; StreamData stream_data; public: DUCKDB_API void Initialize(bool write); DUCKDB_API int64_t ReadData(void *buffer, int64_t nr_bytes); DUCKDB_API int64_t WriteData(data_ptr_t buffer, int64_t nr_bytes); DUCKDB_API void Close() override; private: unique_ptr<StreamWrapper> stream_wrapper; }; } // namespace duckdb
864
305
<reponame>medismailben/llvm-project // RUN: %clang -target x86_64-apple-darwin -arch arm64_32 -miphoneos-version-min=8.0 %s -### 2>&1 | FileCheck %s // CHECK: "-cc1"{{.*}} "-triple" "aarch64_32-apple-ios8.0.0" // CHECK: ld{{.*}} "-arch" "arm64_32"
117
794
<gh_stars>100-1000 // // CACustomAnimation.h // CrossApp // // Created by 栗元峰 on 15/4/29. // Copyright (c) 2015年 http://www.9miao.com All rights reserved. // #ifndef __CrossApp__CACustomAnimation__ #define __CrossApp__CACustomAnimation__ #include "basics/CAScheduler.h" NS_CC_BEGIN class CC_DLL CACustomAnimation { public: struct CC_DLL Model { float dt{0.0f}; float now{0.0f}; float total{0.0f}; bool end{false}; }; typedef std::function<void(const CACustomAnimation::Model&)> Callback; // defaule: interval = 1/60.f, delay = 0.0f; static void schedule(const CACustomAnimation::Callback& callback, const std::string& animationID, float totalTime); static void schedule(const CACustomAnimation::Callback& callback, const std::string& animationID, float totalTime, float interval); static void schedule(const CACustomAnimation::Callback& callback, const std::string& animationID, float totalTime, float interval, float delay); static void unschedule(const std::string& animationID); static bool isSchedule(const std::string& animationID); }; NS_CC_END #endif /* defined(__CrossApp__CACustomAnimation__) */
472
2,268
/* 7zMethodID.h */ #ifndef __7Z_METHOD_ID_H #define __7Z_METHOD_ID_H #include "7zTypes.h" #define kMethodIDSize 15 typedef struct _CMethodID { Byte ID[kMethodIDSize]; Byte IDSize; } CMethodID; int AreMethodsEqual(CMethodID *a1, CMethodID *a2); #endif
118
841
package org.jboss.resteasy.test.client.proxy.resource.GenericEntities; import java.util.HashMap; import static org.jboss.resteasy.test.client.proxy.resource.GenericEntities.GenericEntityExtendingBaseEntityResource.FIRST_NAME; import static org.jboss.resteasy.test.client.proxy.resource.GenericEntities.GenericEntityExtendingBaseEntityResource.LAST_NAME; public class MultipleGenericEntitiesResource implements MultipleGenericEntities<String, EntityExtendingBaseEntity> { @Override public HashMap<String, EntityExtendingBaseEntity> findHashMap() { HashMap<String, EntityExtendingBaseEntity> res = new HashMap<>(); res.put(FIRST_NAME, new EntityExtendingBaseEntity(FIRST_NAME, LAST_NAME)); return res; } }
235
61,676
from django.conf.urls.i18n import i18n_patterns from django.urls import include, path, re_path from django.utils.translation import gettext_lazy as _ from django.views.generic import TemplateView view = TemplateView.as_view(template_name='dummy.html') urlpatterns = [ path('not-prefixed/', view, name='not-prefixed'), path('not-prefixed-include/', include('i18n.patterns.urls.included')), re_path(_(r'^translated/$'), view, name='no-prefix-translated'), re_path(_(r'^translated/(?P<slug>[\w-]+)/$'), view, name='no-prefix-translated-slug'), ] urlpatterns += i18n_patterns( path('prefixed/', view, name='prefixed'), path('prefixed.xml', view, name='prefixed_xml'), re_path( _(r'^with-arguments/(?P<argument>[\w-]+)/(?:(?P<optional>[\w-]+).html)?$'), view, name='with-arguments', ), re_path(_(r'^users/$'), view, name='users'), re_path(_(r'^account/'), include('i18n.patterns.urls.namespace', namespace='account')), )
402
2,460
<gh_stars>1000+ /* * Copyright (c) 2016-2021 <NAME> <<EMAIL>> * * 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 net.devh.boot.grpc.server.interceptor; import static java.util.Objects.requireNonNull; import java.util.ArrayList; import java.util.List; import org.springframework.context.ApplicationContext; import org.springframework.core.annotation.AnnotationAwareOrderComparator; import com.google.common.collect.ImmutableList; import io.grpc.BindableService; import io.grpc.ServerInterceptor; import io.grpc.ServerInterceptors; /** * The global server interceptor registry keeps references to all {@link ServerInterceptor}s that should be registered * to all server channels. The interceptors will be applied in the same order they as specified by the * {@link #sortInterceptors(List)} method. * * <p> * <b>Note:</b> Custom interceptors will be appended to the global interceptors and applied using * {@link ServerInterceptors#interceptForward(BindableService, ServerInterceptor...)}. * </p> * * @author Michael (<EMAIL>) */ public class GlobalServerInterceptorRegistry { private final ApplicationContext applicationContext; private ImmutableList<ServerInterceptor> sortedServerInterceptors; /** * Creates a new GlobalServerInterceptorRegistry. * * @param applicationContext The application context to fetch the {@link GlobalServerInterceptorConfigurer} beans * from. */ public GlobalServerInterceptorRegistry(final ApplicationContext applicationContext) { this.applicationContext = requireNonNull(applicationContext, "applicationContext"); } /** * Gets the immutable list of global server interceptors. * * @return The list of globally registered server interceptors. */ public ImmutableList<ServerInterceptor> getServerInterceptors() { if (this.sortedServerInterceptors == null) { this.sortedServerInterceptors = ImmutableList.copyOf(initServerInterceptors()); } return this.sortedServerInterceptors; } /** * Initializes the list of server interceptors. * * @return The list of global server interceptors. */ protected List<ServerInterceptor> initServerInterceptors() { final List<ServerInterceptor> interceptors = new ArrayList<>(); for (final GlobalServerInterceptorConfigurer configurer : this.applicationContext .getBeansOfType(GlobalServerInterceptorConfigurer.class).values()) { configurer.configureServerInterceptors(interceptors); } sortInterceptors(interceptors); return interceptors; } /** * Sorts the given list of interceptors. Use this method if you want to sort custom interceptors. The default * implementation will sort them by using then {@link AnnotationAwareOrderComparator}. * * @param interceptors The interceptors to sort. */ public void sortInterceptors(final List<? extends ServerInterceptor> interceptors) { interceptors.sort(AnnotationAwareOrderComparator.INSTANCE); } }
1,243
5,169
{ "name": "MultiSelectSegmentedControl", "platforms": { "ios": "7.0" }, "version": "1.0", "authors": { "<NAME>": "<EMAIL>" }, "license": "MIT", "homepage": "https://github.com/yonat/MultiSelectSegmentedControl.git", "summary": "Subclass of UISegmentedControl that supports multiple segment selection.", "source": { "git": "https://github.com/yonat/MultiSelectSegmentedControl.git", "tag": 1.0 }, "source_files": "MultiSelectSegmentedControl.{h,m}", "requires_arc": true }
193
4,772
<reponame>fjacobs/spring-data-examples package example.repo; import example.model.Customer1522; import java.util.List; import org.springframework.data.repository.CrudRepository; public interface Customer1522Repository extends CrudRepository<Customer1522, Long> { List<Customer1522> findByLastName(String lastName); }
103
571
# Copyright 2015 Ufora 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. """ Unit tests for PersistentCacheIndex """ import time import unittest import threading import ufora.distributed.SharedState.ComputedGraph.SharedStateSynchronizer \ as SharedStateSynchronizer from ufora.distributed.SharedState.tests.SharedStateTestHarness import SharedStateTestHarness import ufora.BackendGateway.ComputedGraph.ComputedGraph as ComputedGraph import ufora.BackendGateway.ComputedGraph.ComputedGraphTestHarness as ComputedGraphTestHarness import ufora.native.Cumulus as CumulusNative import ufora.native.Hash as HashNative import ufora.native.TCMalloc as TCMallocNative HashSet = HashNative.ImmutableTreeSetOfHash sha1 = HashNative.Hash.sha1 import ufora.native.CallbackScheduler as CallbackScheduler callbackScheduler = CallbackScheduler.singletonForTesting() class TestPersistentCacheIndex(unittest.TestCase): def setUp(self): self.sharedState = SharedStateTestHarness(inMemory=True) self.synchronizer = SharedStateSynchronizer.SharedStateSynchronizer() self.synchronizer.attachView(self.sharedState.newView()) self.synchronizer.__enter__() def tearDown(self): self.synchronizer.__exit__(None, None, None) def waitForSync(self, predicate, *synchronizers): if not synchronizers: synchronizers = [self.synchronizer] ComputedGraph.assertHasGraph() passes = 0 while passes < 100: for s in synchronizers: s.update() if predicate(): break time.sleep(.1) passes += 1 self.assertTrue(predicate()) @ComputedGraphTestHarness.UnderHarness def test_persistentCacheUnderLoad(self): cppView1 = CumulusNative.PersistentCacheIndex( self.sharedState.newView(), callbackScheduler ) t0 = time.time() #add 100k pages, which is enough for about 5 TB of data for index in range(100000): if index % 1000 == 0 and index > 0: print index, (time.time() - t0) / (index / 1000.0), " seconds per 1000" cppView1.addPage(sha1("page" + str(index)), HashSet(), 1, sha1("")) print "took ", time.time() - t0, " to add 100k." t1 = time.time() bytes0 = TCMallocNative.getBytesUsed() cppView2 = CumulusNative.PersistentCacheIndex( self.sharedState.newView(), callbackScheduler ) while cppView2.totalBytesInCache() < 100000: time.sleep(.1) print cppView2.totalBytesInCache() print "took ", time.time() - t1, " to load 100k. Total RAM is ", (TCMallocNative.getBytesUsed() - bytes0) / 1024 / 1024.0, " MB per view"\ @ComputedGraphTestHarness.UnderHarness def test_circularPageReferencesAreInvalid(self): self.circularPageReferenceTest(True) @ComputedGraphTestHarness.UnderHarness def test_noncircularPageReferencesAreValid(self): self.circularPageReferenceTest(False) def circularPageReferenceTest(self, shouldBeInvalid): cppView1 = CumulusNative.PersistentCacheIndex( self.sharedState.newView(), callbackScheduler ) computationId = CumulusNative.ComputationId.Root( sha1("computation") ) checkpointRequest = CumulusNative.CheckpointRequest(0.0, True, computationId) cppView1.addBigvec(sha1("bigvec1"), HashSet() + sha1("page1"), 2, sha1("")) cppView1.addPage(sha1("page1"), (HashSet() + sha1("bigvec1")) if shouldBeInvalid else HashSet(), 1, sha1("")) cppView1.addCheckpointFile(checkpointRequest, sha1("file"), HashSet() + sha1("bigvec1"), 2, sha1("")) cppView1.addCheckpoint(checkpointRequest, HashSet() + sha1("file"), 2, sha1(""), True, 1.0, HashSet()) self.assertTrue( len(cppView1.computeInvalidObjects()) == (4 if shouldBeInvalid else 0), "%s != %s" % (len(cppView1.computeInvalidObjects()), (4 if shouldBeInvalid else 0)) ) @ComputedGraphTestHarness.UnderHarness def test_orphanedPageIsCollected(self): cppView1 = CumulusNative.PersistentCacheIndex( self.sharedState.newView(), callbackScheduler ) cppView1.addPage(sha1("page1"), HashSet(), 1, sha1("")) self.assertTrue(len(cppView1.computeInvalidObjects()) == 1) @ComputedGraphTestHarness.UnderHarness def test_basicPersistentCache(self): cppView1 = CumulusNative.PersistentCacheIndex( self.sharedState.newView(), callbackScheduler ) cppView2 = CumulusNative.PersistentCacheIndex( self.sharedState.newView(), callbackScheduler ) cppView1.addPage(sha1("page1"), HashSet(), 1, sha1("")) cppView1.addBigvec(sha1("bigvec1"), HashSet() + sha1("page1"), 2, sha1("")) cppView1.addPage(sha1("page2"), HashSet() + sha1("bigvec1"), 3, sha1("")) cppView1.addBigvec(sha1("bigvec2"), HashSet() + sha1("page2"), 4, sha1("")) self.assertEqual(cppView1.totalBytesInCache(), 10) def seesEverything(): if not cppView2.pageExists(sha1("page1")): return False if not cppView2.pageExists(sha1("page2")): return False if not cppView2.bigvecExists(sha1("bigvec1")): return False if not cppView2.bigvecExists(sha1("bigvec2")): return False return True self.waitForSync(seesEverything) for view in [cppView1, cppView2]: self.assertEqual(view.pageBytecount(sha1("page1")), 1) self.assertEqual(view.bigvecBytecount(sha1("bigvec1")), 2) self.assertEqual(view.pageBytecount(sha1("page2")), 3) self.assertEqual(view.bigvecBytecount(sha1("bigvec2")), 4) self.assertEqual(view.totalBytesInCache(), 10) @ComputedGraphTestHarness.UnderHarness def test_writing_while_disconnected(self): currentView = [self.sharedState.newView()] cppView1 = CumulusNative.PersistentCacheIndex( currentView[0], callbackScheduler ) def writeInLoop(): for ix in range(100): time.sleep(0.01) cppView1.addPage(sha1("page" + str(ix)),HashSet(), ix, sha1("")) thread1 = threading.Thread(target=writeInLoop) thread1.start() def disconnectAndReconnectInLoop(): ix = 0 while thread1.isAlive(): ix += 1 time.sleep(0.004) currentView[0].disconnect() currentView[0] = self.sharedState.newView() cppView1.resetView(currentView[0]) thread2 = threading.Thread(target=disconnectAndReconnectInLoop) thread2.start() thread1.join() thread2.join() self.assertTrue(cppView1.timesViewReconnected() > 10) cppView2 = CumulusNative.PersistentCacheIndex( self.sharedState.newView(), callbackScheduler ) time.sleep(2.0) count1 = 0 count2 = 0 for ix in range(100): if cppView1.pageExists(sha1("page" + str(ix))): count1 += 1 if cppView2.pageExists(sha1("page" + str(ix))): count2 += 1 self.assertTrue(count1 == 100 and count2 == 100, (count1, count2))
3,661
372
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.cloudasset.v1beta1.model; /** * Used in `policy_type` to specify how `list_policy` behaves at this resource. `ListPolicy` can * define specific values and subtrees of Cloud Resource Manager resource hierarchy * (`Organizations`, `Folders`, `Projects`) that are allowed or denied by setting the * `allowed_values` and `denied_values` fields. This is achieved by using the `under:` and optional * `is:` prefixes. The `under:` prefix is used to denote resource subtree values. The `is:` prefix * is used to denote specific values, and is required only if the value contains a ":". Values * prefixed with "is:" are treated the same as values with no prefix. Ancestry subtrees must be in * one of the following formats: - "projects/", e.g. "projects/tokyo-rain-123" - "folders/", e.g. * "folders/1234" - "organizations/", e.g. "organizations/1234" The `supports_under` field of the * associated `Constraint` defines whether ancestry prefixes can be used. You can set * `allowed_values` and `denied_values` in the same `Policy` if `all_values` is * `ALL_VALUES_UNSPECIFIED`. `ALLOW` or `DENY` are used to allow or deny all values. If `all_values` * is set to either `ALLOW` or `DENY`, `allowed_values` and `denied_values` must be unset. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Cloud Asset API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class GoogleCloudOrgpolicyV1ListPolicy extends com.google.api.client.json.GenericJson { /** * The policy all_values state. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String allValues; /** * List of values allowed at this resource. Can only be set if `all_values` is set to * `ALL_VALUES_UNSPECIFIED`. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> allowedValues; /** * List of values denied at this resource. Can only be set if `all_values` is set to * `ALL_VALUES_UNSPECIFIED`. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> deniedValues; /** * Determines the inheritance behavior for this `Policy`. By default, a `ListPolicy` set at a * resource supersedes any `Policy` set anywhere up the resource hierarchy. However, if * `inherit_from_parent` is set to `true`, then the values from the effective `Policy` of the * parent resource are inherited, meaning the values set in this `Policy` are added to the values * inherited up the hierarchy. Setting `Policy` hierarchies that inherit both allowed values and * denied values isn't recommended in most circumstances to keep the configuration simple and * understandable. However, it is possible to set a `Policy` with `allowed_values` set that * inherits a `Policy` with `denied_values` set. In this case, the values that are allowed must be * in `allowed_values` and not present in `denied_values`. For example, suppose you have a * `Constraint` `constraints/serviceuser.services`, which has a `constraint_type` of * `list_constraint`, and with `constraint_default` set to `ALLOW`. Suppose that at the * Organization level, a `Policy` is applied that restricts the allowed API activations to {`E1`, * `E2`}. Then, if a `Policy` is applied to a project below the Organization that has * `inherit_from_parent` set to `false` and field all_values set to DENY, then an attempt to * activate any API will be denied. The following examples demonstrate different possible * layerings for `projects/bar` parented by `organizations/foo`: Example 1 (no inherited values): * `organizations/foo` has a `Policy` with values: {allowed_values: "E1" allowed_values:"E2"} * `projects/bar` has `inherit_from_parent` `false` and values: {allowed_values: "E3" * allowed_values: "E4"} The accepted values at `organizations/foo` are `E1`, `E2`. The accepted * values at `projects/bar` are `E3`, and `E4`. Example 2 (inherited values): `organizations/foo` * has a `Policy` with values: {allowed_values: "E1" allowed_values:"E2"} `projects/bar` has a * `Policy` with values: {value: "E3" value: "E4" inherit_from_parent: true} The accepted values * at `organizations/foo` are `E1`, `E2`. The accepted values at `projects/bar` are `E1`, `E2`, * `E3`, and `E4`. Example 3 (inheriting both allowed and denied values): `organizations/foo` has * a `Policy` with values: {allowed_values: "E1" allowed_values: "E2"} `projects/bar` has a * `Policy` with: {denied_values: "E1"} The accepted values at `organizations/foo` are `E1`, `E2`. * The value accepted at `projects/bar` is `E2`. Example 4 (RestoreDefault): `organizations/foo` * has a `Policy` with values: {allowed_values: "E1" allowed_values:"E2"} `projects/bar` has a * `Policy` with values: {RestoreDefault: {}} The accepted values at `organizations/foo` are `E1`, * `E2`. The accepted values at `projects/bar` are either all or none depending on the value of * `constraint_default` (if `ALLOW`, all; if `DENY`, none). Example 5 (no policy inherits parent * policy): `organizations/foo` has no `Policy` set. `projects/bar` has no `Policy` set. The * accepted values at both levels are either all or none depending on the value of * `constraint_default` (if `ALLOW`, all; if `DENY`, none). Example 6 (ListConstraint allowing * all): `organizations/foo` has a `Policy` with values: {allowed_values: "E1" allowed_values: * "E2"} `projects/bar` has a `Policy` with: {all: ALLOW} The accepted values at * `organizations/foo` are `E1`, E2`. Any value is accepted at `projects/bar`. Example 7 * (ListConstraint allowing none): `organizations/foo` has a `Policy` with values: * {allowed_values: "E1" allowed_values: "E2"} `projects/bar` has a `Policy` with: {all: DENY} The * accepted values at `organizations/foo` are `E1`, E2`. No value is accepted at `projects/bar`. * Example 10 (allowed and denied subtrees of Resource Manager hierarchy): Given the following * resource hierarchy O1->{F1, F2}; F1->{P1}; F2->{P2, P3}, `organizations/foo` has a `Policy` * with values: {allowed_values: "under:organizations/O1"} `projects/bar` has a `Policy` with: * {allowed_values: "under:projects/P3"} {denied_values: "under:folders/F2"} The accepted values * at `organizations/foo` are `organizations/O1`, `folders/F1`, `folders/F2`, `projects/P1`, * `projects/P2`, `projects/P3`. The accepted values at `projects/bar` are `organizations/O1`, * `folders/F1`, `projects/P1`. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean inheritFromParent; /** * Optional. The Google Cloud Console will try to default to a configuration that matches the * value specified in this `Policy`. If `suggested_value` is not set, it will inherit the value * specified higher in the hierarchy, unless `inherit_from_parent` is `false`. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String suggestedValue; /** * The policy all_values state. * @return value or {@code null} for none */ public java.lang.String getAllValues() { return allValues; } /** * The policy all_values state. * @param allValues allValues or {@code null} for none */ public GoogleCloudOrgpolicyV1ListPolicy setAllValues(java.lang.String allValues) { this.allValues = allValues; return this; } /** * List of values allowed at this resource. Can only be set if `all_values` is set to * `ALL_VALUES_UNSPECIFIED`. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getAllowedValues() { return allowedValues; } /** * List of values allowed at this resource. Can only be set if `all_values` is set to * `ALL_VALUES_UNSPECIFIED`. * @param allowedValues allowedValues or {@code null} for none */ public GoogleCloudOrgpolicyV1ListPolicy setAllowedValues(java.util.List<java.lang.String> allowedValues) { this.allowedValues = allowedValues; return this; } /** * List of values denied at this resource. Can only be set if `all_values` is set to * `ALL_VALUES_UNSPECIFIED`. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getDeniedValues() { return deniedValues; } /** * List of values denied at this resource. Can only be set if `all_values` is set to * `ALL_VALUES_UNSPECIFIED`. * @param deniedValues deniedValues or {@code null} for none */ public GoogleCloudOrgpolicyV1ListPolicy setDeniedValues(java.util.List<java.lang.String> deniedValues) { this.deniedValues = deniedValues; return this; } /** * Determines the inheritance behavior for this `Policy`. By default, a `ListPolicy` set at a * resource supersedes any `Policy` set anywhere up the resource hierarchy. However, if * `inherit_from_parent` is set to `true`, then the values from the effective `Policy` of the * parent resource are inherited, meaning the values set in this `Policy` are added to the values * inherited up the hierarchy. Setting `Policy` hierarchies that inherit both allowed values and * denied values isn't recommended in most circumstances to keep the configuration simple and * understandable. However, it is possible to set a `Policy` with `allowed_values` set that * inherits a `Policy` with `denied_values` set. In this case, the values that are allowed must be * in `allowed_values` and not present in `denied_values`. For example, suppose you have a * `Constraint` `constraints/serviceuser.services`, which has a `constraint_type` of * `list_constraint`, and with `constraint_default` set to `ALLOW`. Suppose that at the * Organization level, a `Policy` is applied that restricts the allowed API activations to {`E1`, * `E2`}. Then, if a `Policy` is applied to a project below the Organization that has * `inherit_from_parent` set to `false` and field all_values set to DENY, then an attempt to * activate any API will be denied. The following examples demonstrate different possible * layerings for `projects/bar` parented by `organizations/foo`: Example 1 (no inherited values): * `organizations/foo` has a `Policy` with values: {allowed_values: "E1" allowed_values:"E2"} * `projects/bar` has `inherit_from_parent` `false` and values: {allowed_values: "E3" * allowed_values: "E4"} The accepted values at `organizations/foo` are `E1`, `E2`. The accepted * values at `projects/bar` are `E3`, and `E4`. Example 2 (inherited values): `organizations/foo` * has a `Policy` with values: {allowed_values: "E1" allowed_values:"E2"} `projects/bar` has a * `Policy` with values: {value: "E3" value: "E4" inherit_from_parent: true} The accepted values * at `organizations/foo` are `E1`, `E2`. The accepted values at `projects/bar` are `E1`, `E2`, * `E3`, and `E4`. Example 3 (inheriting both allowed and denied values): `organizations/foo` has * a `Policy` with values: {allowed_values: "E1" allowed_values: "E2"} `projects/bar` has a * `Policy` with: {denied_values: "E1"} The accepted values at `organizations/foo` are `E1`, `E2`. * The value accepted at `projects/bar` is `E2`. Example 4 (RestoreDefault): `organizations/foo` * has a `Policy` with values: {allowed_values: "E1" allowed_values:"E2"} `projects/bar` has a * `Policy` with values: {RestoreDefault: {}} The accepted values at `organizations/foo` are `E1`, * `E2`. The accepted values at `projects/bar` are either all or none depending on the value of * `constraint_default` (if `ALLOW`, all; if `DENY`, none). Example 5 (no policy inherits parent * policy): `organizations/foo` has no `Policy` set. `projects/bar` has no `Policy` set. The * accepted values at both levels are either all or none depending on the value of * `constraint_default` (if `ALLOW`, all; if `DENY`, none). Example 6 (ListConstraint allowing * all): `organizations/foo` has a `Policy` with values: {allowed_values: "E1" allowed_values: * "E2"} `projects/bar` has a `Policy` with: {all: ALLOW} The accepted values at * `organizations/foo` are `E1`, E2`. Any value is accepted at `projects/bar`. Example 7 * (ListConstraint allowing none): `organizations/foo` has a `Policy` with values: * {allowed_values: "E1" allowed_values: "E2"} `projects/bar` has a `Policy` with: {all: DENY} The * accepted values at `organizations/foo` are `E1`, E2`. No value is accepted at `projects/bar`. * Example 10 (allowed and denied subtrees of Resource Manager hierarchy): Given the following * resource hierarchy O1->{F1, F2}; F1->{P1}; F2->{P2, P3}, `organizations/foo` has a `Policy` * with values: {allowed_values: "under:organizations/O1"} `projects/bar` has a `Policy` with: * {allowed_values: "under:projects/P3"} {denied_values: "under:folders/F2"} The accepted values * at `organizations/foo` are `organizations/O1`, `folders/F1`, `folders/F2`, `projects/P1`, * `projects/P2`, `projects/P3`. The accepted values at `projects/bar` are `organizations/O1`, * `folders/F1`, `projects/P1`. * @return value or {@code null} for none */ public java.lang.Boolean getInheritFromParent() { return inheritFromParent; } /** * Determines the inheritance behavior for this `Policy`. By default, a `ListPolicy` set at a * resource supersedes any `Policy` set anywhere up the resource hierarchy. However, if * `inherit_from_parent` is set to `true`, then the values from the effective `Policy` of the * parent resource are inherited, meaning the values set in this `Policy` are added to the values * inherited up the hierarchy. Setting `Policy` hierarchies that inherit both allowed values and * denied values isn't recommended in most circumstances to keep the configuration simple and * understandable. However, it is possible to set a `Policy` with `allowed_values` set that * inherits a `Policy` with `denied_values` set. In this case, the values that are allowed must be * in `allowed_values` and not present in `denied_values`. For example, suppose you have a * `Constraint` `constraints/serviceuser.services`, which has a `constraint_type` of * `list_constraint`, and with `constraint_default` set to `ALLOW`. Suppose that at the * Organization level, a `Policy` is applied that restricts the allowed API activations to {`E1`, * `E2`}. Then, if a `Policy` is applied to a project below the Organization that has * `inherit_from_parent` set to `false` and field all_values set to DENY, then an attempt to * activate any API will be denied. The following examples demonstrate different possible * layerings for `projects/bar` parented by `organizations/foo`: Example 1 (no inherited values): * `organizations/foo` has a `Policy` with values: {allowed_values: "E1" allowed_values:"E2"} * `projects/bar` has `inherit_from_parent` `false` and values: {allowed_values: "E3" * allowed_values: "E4"} The accepted values at `organizations/foo` are `E1`, `E2`. The accepted * values at `projects/bar` are `E3`, and `E4`. Example 2 (inherited values): `organizations/foo` * has a `Policy` with values: {allowed_values: "E1" allowed_values:"E2"} `projects/bar` has a * `Policy` with values: {value: "E3" value: "E4" inherit_from_parent: true} The accepted values * at `organizations/foo` are `E1`, `E2`. The accepted values at `projects/bar` are `E1`, `E2`, * `E3`, and `E4`. Example 3 (inheriting both allowed and denied values): `organizations/foo` has * a `Policy` with values: {allowed_values: "E1" allowed_values: "E2"} `projects/bar` has a * `Policy` with: {denied_values: "E1"} The accepted values at `organizations/foo` are `E1`, `E2`. * The value accepted at `projects/bar` is `E2`. Example 4 (RestoreDefault): `organizations/foo` * has a `Policy` with values: {allowed_values: "E1" allowed_values:"E2"} `projects/bar` has a * `Policy` with values: {RestoreDefault: {}} The accepted values at `organizations/foo` are `E1`, * `E2`. The accepted values at `projects/bar` are either all or none depending on the value of * `constraint_default` (if `ALLOW`, all; if `DENY`, none). Example 5 (no policy inherits parent * policy): `organizations/foo` has no `Policy` set. `projects/bar` has no `Policy` set. The * accepted values at both levels are either all or none depending on the value of * `constraint_default` (if `ALLOW`, all; if `DENY`, none). Example 6 (ListConstraint allowing * all): `organizations/foo` has a `Policy` with values: {allowed_values: "E1" allowed_values: * "E2"} `projects/bar` has a `Policy` with: {all: ALLOW} The accepted values at * `organizations/foo` are `E1`, E2`. Any value is accepted at `projects/bar`. Example 7 * (ListConstraint allowing none): `organizations/foo` has a `Policy` with values: * {allowed_values: "E1" allowed_values: "E2"} `projects/bar` has a `Policy` with: {all: DENY} The * accepted values at `organizations/foo` are `E1`, E2`. No value is accepted at `projects/bar`. * Example 10 (allowed and denied subtrees of Resource Manager hierarchy): Given the following * resource hierarchy O1->{F1, F2}; F1->{P1}; F2->{P2, P3}, `organizations/foo` has a `Policy` * with values: {allowed_values: "under:organizations/O1"} `projects/bar` has a `Policy` with: * {allowed_values: "under:projects/P3"} {denied_values: "under:folders/F2"} The accepted values * at `organizations/foo` are `organizations/O1`, `folders/F1`, `folders/F2`, `projects/P1`, * `projects/P2`, `projects/P3`. The accepted values at `projects/bar` are `organizations/O1`, * `folders/F1`, `projects/P1`. * @param inheritFromParent inheritFromParent or {@code null} for none */ public GoogleCloudOrgpolicyV1ListPolicy setInheritFromParent(java.lang.Boolean inheritFromParent) { this.inheritFromParent = inheritFromParent; return this; } /** * Optional. The Google Cloud Console will try to default to a configuration that matches the * value specified in this `Policy`. If `suggested_value` is not set, it will inherit the value * specified higher in the hierarchy, unless `inherit_from_parent` is `false`. * @return value or {@code null} for none */ public java.lang.String getSuggestedValue() { return suggestedValue; } /** * Optional. The Google Cloud Console will try to default to a configuration that matches the * value specified in this `Policy`. If `suggested_value` is not set, it will inherit the value * specified higher in the hierarchy, unless `inherit_from_parent` is `false`. * @param suggestedValue suggestedValue or {@code null} for none */ public GoogleCloudOrgpolicyV1ListPolicy setSuggestedValue(java.lang.String suggestedValue) { this.suggestedValue = suggestedValue; return this; } @Override public GoogleCloudOrgpolicyV1ListPolicy set(String fieldName, Object value) { return (GoogleCloudOrgpolicyV1ListPolicy) super.set(fieldName, value); } @Override public GoogleCloudOrgpolicyV1ListPolicy clone() { return (GoogleCloudOrgpolicyV1ListPolicy) super.clone(); } }
6,424
9,717
<gh_stars>1000+ { "url": "https://github.com/joakker/tree-sitter-json5", "rev": "5dd5cdc418d9659682556b6adca2dd9ace0ac6d2", "date": "2021-08-24T18:08:31-04:00", "path": "/nix/store/0qhffwc84sp97d8im4lfrd06jsyvmzc4-tree-sitter-json5", "sha256": "1la7bq5vi21gy0kf4zpwh0c0jfyv1bb62a3v7158hnxdyd5ijz07", "fetchLFS": false, "fetchSubmodules": false, "deepClone": false, "leaveDotGit": false }
217
325
package com.box.l10n.mojito.service.branch.notification.phabricator; import com.box.l10n.mojito.service.branch.BranchUrlBuilder; import com.google.common.collect.ImmutableMap; import com.ibm.icu.text.MessageFormat; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.util.List; import java.util.stream.Collectors; import static org.slf4j.LoggerFactory.getLogger; @Component public class BranchNotificationMessageBuilderPhabricator { /** * logger */ static Logger logger = getLogger(BranchNotificationMessageBuilderPhabricator.class); @Autowired BranchUrlBuilder branchUrlBuilder; @Value("${l10n.branchNotification.phabricator.notification.message.new.format:{message}{link}\n\n{strings}}") String getNewNotificationMsgFormat; @Value("${l10n.branchNotification.phabricator.notification.message.updated.format:{message}{link}\n\n{strings}}") String getUpdatedNotificationMsgFormat; @Value("${l10n.branchNotification.phabricator.notification.message.new:We received your strings! " + "Please **add screenshots** as soon as possible and **wait for translations** before releasing. }") String newNotificationMsg; @Value("${l10n.branchNotification.phabricator.notification.message.updated:Your branch was updated with new strings! " + "Please **add screenshots** as soon as possible and **wait for translations** before releasing. }") String updatedNotificationMsg; @Value("${l10n.branchNotification.phabricator.notification.message.noMoreStrings:The branch was updated and there are no more strings to translate.}") String noMoreStringsMsg; @Value("${l10n.branchNotification.phabricator.notification.message.translationsReady:Translations are ready!!}") String translationsReadyMsg; @Value("${l10n.branchNotification.phabricator.notification.message.screenshotsMissing:Please provide screenshots to help localization team}") String screenshotsMissingMsg; public String getNewMessage(String branchName, List<String> sourceStrings) { MessageFormat messageFormat = new MessageFormat(getNewNotificationMsgFormat); ImmutableMap<String, Object> messageParamMap = ImmutableMap.<String, Object>builder() .put("message", newNotificationMsg) .put("link", getLinkGoToMojito(branchName)) .put("strings", getFormattedSourceStrings(sourceStrings)) .build(); return messageFormat.format(messageParamMap); } public String getUpdatedMessage(String branchName, List<String> sourceStrings) { String msg = null; MessageFormat messageFormat = new MessageFormat(getUpdatedNotificationMsgFormat); ImmutableMap<String, Object> messageParamMap; if (sourceStrings.isEmpty()) { messageParamMap = ImmutableMap.<String, Object>builder().put("message", noMoreStringsMsg).build(); } else { messageParamMap = ImmutableMap.<String, Object>builder() .put("message", updatedNotificationMsg) .put("link", getLinkGoToMojito(branchName)) .put("strings", getFormattedSourceStrings(sourceStrings)) .build(); } return messageFormat.format(messageParamMap); } public String getNoMoreStringsMessage() { return noMoreStringsMsg; } public String getTranslatedMessage() { return translationsReadyMsg; } public String getScreenshotMissingMessage() { return screenshotsMissingMsg; } String getFormattedSourceStrings(List<String> sourceStrings) { return "**Strings:**\n" + sourceStrings.stream().map(t -> " - " + t).collect(Collectors.joining("\n")); } String getLinkGoToMojito(String branchName) { return "[→ Go to Mojito](" + branchUrlBuilder.getBranchDashboardUrl(branchName) + ")"; } }
1,442