max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
18,396
<filename>trunk/3rdparty/ffmpeg-4-fit/libavcodec/aarch64/h264pred_init.c /* * Copyright (c) 2009 <NAME> <<EMAIL>> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <stdint.h> #include "libavutil/attributes.h" #include "libavutil/aarch64/cpu.h" #include "libavcodec/avcodec.h" #include "libavcodec/h264pred.h" void ff_pred16x16_vert_neon(uint8_t *src, ptrdiff_t stride); void ff_pred16x16_hor_neon(uint8_t *src, ptrdiff_t stride); void ff_pred16x16_plane_neon(uint8_t *src, ptrdiff_t stride); void ff_pred16x16_dc_neon(uint8_t *src, ptrdiff_t stride); void ff_pred16x16_128_dc_neon(uint8_t *src, ptrdiff_t stride); void ff_pred16x16_left_dc_neon(uint8_t *src, ptrdiff_t stride); void ff_pred16x16_top_dc_neon(uint8_t *src, ptrdiff_t stride); void ff_pred8x8_vert_neon(uint8_t *src, ptrdiff_t stride); void ff_pred8x8_hor_neon(uint8_t *src, ptrdiff_t stride); void ff_pred8x8_plane_neon(uint8_t *src, ptrdiff_t stride); void ff_pred8x8_dc_neon(uint8_t *src, ptrdiff_t stride); void ff_pred8x8_128_dc_neon(uint8_t *src, ptrdiff_t stride); void ff_pred8x8_left_dc_neon(uint8_t *src, ptrdiff_t stride); void ff_pred8x8_top_dc_neon(uint8_t *src, ptrdiff_t stride); void ff_pred8x8_l0t_dc_neon(uint8_t *src, ptrdiff_t stride); void ff_pred8x8_0lt_dc_neon(uint8_t *src, ptrdiff_t stride); void ff_pred8x8_l00_dc_neon(uint8_t *src, ptrdiff_t stride); void ff_pred8x8_0l0_dc_neon(uint8_t *src, ptrdiff_t stride); static av_cold void h264_pred_init_neon(H264PredContext *h, int codec_id, const int bit_depth, const int chroma_format_idc) { const int high_depth = bit_depth > 8; if (high_depth) return; if (chroma_format_idc <= 1) { h->pred8x8[VERT_PRED8x8 ] = ff_pred8x8_vert_neon; h->pred8x8[HOR_PRED8x8 ] = ff_pred8x8_hor_neon; if (codec_id != AV_CODEC_ID_VP7 && codec_id != AV_CODEC_ID_VP8) h->pred8x8[PLANE_PRED8x8] = ff_pred8x8_plane_neon; h->pred8x8[DC_128_PRED8x8 ] = ff_pred8x8_128_dc_neon; if (codec_id != AV_CODEC_ID_RV40 && codec_id != AV_CODEC_ID_VP7 && codec_id != AV_CODEC_ID_VP8) { h->pred8x8[DC_PRED8x8 ] = ff_pred8x8_dc_neon; h->pred8x8[LEFT_DC_PRED8x8] = ff_pred8x8_left_dc_neon; h->pred8x8[TOP_DC_PRED8x8 ] = ff_pred8x8_top_dc_neon; h->pred8x8[ALZHEIMER_DC_L0T_PRED8x8] = ff_pred8x8_l0t_dc_neon; h->pred8x8[ALZHEIMER_DC_0LT_PRED8x8] = ff_pred8x8_0lt_dc_neon; h->pred8x8[ALZHEIMER_DC_L00_PRED8x8] = ff_pred8x8_l00_dc_neon; h->pred8x8[ALZHEIMER_DC_0L0_PRED8x8] = ff_pred8x8_0l0_dc_neon; } } h->pred16x16[DC_PRED8x8 ] = ff_pred16x16_dc_neon; h->pred16x16[VERT_PRED8x8 ] = ff_pred16x16_vert_neon; h->pred16x16[HOR_PRED8x8 ] = ff_pred16x16_hor_neon; h->pred16x16[LEFT_DC_PRED8x8] = ff_pred16x16_left_dc_neon; h->pred16x16[TOP_DC_PRED8x8 ] = ff_pred16x16_top_dc_neon; h->pred16x16[DC_128_PRED8x8 ] = ff_pred16x16_128_dc_neon; if (codec_id != AV_CODEC_ID_SVQ3 && codec_id != AV_CODEC_ID_RV40 && codec_id != AV_CODEC_ID_VP7 && codec_id != AV_CODEC_ID_VP8) h->pred16x16[PLANE_PRED8x8 ] = ff_pred16x16_plane_neon; } av_cold void ff_h264_pred_init_aarch64(H264PredContext *h, int codec_id, int bit_depth, const int chroma_format_idc) { int cpu_flags = av_get_cpu_flags(); if (have_neon(cpu_flags)) h264_pred_init_neon(h, codec_id, bit_depth, chroma_format_idc); }
2,137
1,556
<reponame>mkomon/micropython-lib<filename>python-stdlib/shutil/shutil.py # Reimplement, because CPython3.3 impl is rather bloated import os def rmtree(top): for path, dirs, files in os.walk(top, False): for f in files: os.unlink(path + "/" + f) os.rmdir(path) def copyfileobj(src, dest, length=512): if hasattr(src, "readinto"): buf = bytearray(length) while True: sz = src.readinto(buf) if not sz: break if sz == length: dest.write(buf) else: b = memoryview(buf)[:sz] dest.write(b) else: while True: buf = src.read(length) if not buf: break dest.write(buf)
435
474
<filename>packages/dfarm/package.json { "name": "dfarm", "version": "1.0.0", "description": "Decentralized Internet connector for Farmbot", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "dependencies": { "farmbot-web-frontend": "*", "decentralized-internet": "*", "keywords": [ "Decentralized", "Blockchain", "Farmbot", "Environmental", "Environment", "Green", "Weather", "IOT" ] }, "author": "<NAME>, The Lonero Foundation", "license": "MIT" }
225
679
<gh_stars>100-1000 /************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svtools.hxx" #include <svtools/statusbarcontroller.hxx> #include <com/sun/star/beans/PropertyValue.hpp> #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/frame/XDispatchProvider.hpp> #include <com/sun/star/lang/DisposedException.hpp> #include <com/sun/star/frame/XLayoutManager.hpp> #include <vos/mutex.hxx> #include <vcl/svapp.hxx> #include <vcl/window.hxx> #include <vcl/status.hxx> #include <svtools/imgdef.hxx> #include <svtools/miscopt.hxx> #include <toolkit/helper/vclunohelper.hxx> using namespace ::cppu; using namespace ::com::sun::star::awt; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::util; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::frame; using namespace ::com::sun::star::frame; namespace svt { StatusbarController::StatusbarController( const Reference< XMultiServiceFactory >& rServiceManager, const Reference< XFrame >& xFrame, const ::rtl::OUString& aCommandURL, unsigned short nID ) : OWeakObject() , m_bInitialized( sal_False ) , m_bDisposed( sal_False ) , m_nID( nID ) , m_xFrame( xFrame ) , m_xServiceManager( rServiceManager ) , m_aCommandURL( aCommandURL ) , m_aListenerContainer( m_aMutex ) { } StatusbarController::StatusbarController() : OWeakObject() , m_bInitialized( sal_False ) , m_bDisposed( sal_False ) , m_nID( 0 ) , m_aListenerContainer( m_aMutex ) { } StatusbarController::~StatusbarController() { } Reference< XFrame > StatusbarController::getFrameInterface() const { vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() ); return m_xFrame; } Reference< XMultiServiceFactory > StatusbarController::getServiceManager() const { vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() ); return m_xServiceManager; } Reference< XLayoutManager > StatusbarController::getLayoutManager() const { vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() ); Reference< XLayoutManager > xLayoutManager; Reference< XPropertySet > xPropSet( m_xFrame, UNO_QUERY ); if ( xPropSet.is() ) { try { Any a; a = xPropSet->getPropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "LayoutManager" ))); a >>= xLayoutManager; } catch ( Exception& ) { } } return xLayoutManager; } Reference< XURLTransformer > StatusbarController::getURLTransformer() const { vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() ); if ( !m_xURLTransformer.is() && m_xServiceManager.is() ) { m_xURLTransformer = Reference< XURLTransformer >( m_xServiceManager->createInstance( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.util.URLTransformer" ))), UNO_QUERY ); } return m_xURLTransformer; } // XInterface Any SAL_CALL StatusbarController::queryInterface( const Type& rType ) throw ( RuntimeException ) { Any a = ::cppu::queryInterface( rType , static_cast< XStatusbarController* >( this ), static_cast< XStatusListener* >( this ), static_cast< XEventListener* >( this ), static_cast< XInitialization* >( this ), static_cast< XComponent* >( this ), static_cast< XUpdatable* >( this )); if ( a.hasValue() ) return a; return OWeakObject::queryInterface( rType ); } void SAL_CALL StatusbarController::acquire() throw () { OWeakObject::acquire(); } void SAL_CALL StatusbarController::release() throw () { OWeakObject::release(); } void SAL_CALL StatusbarController::initialize( const Sequence< Any >& aArguments ) throw ( Exception, RuntimeException ) { bool bInitialized( true ); { vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() ); if ( m_bDisposed ) throw DisposedException(); bInitialized = m_bInitialized; } if ( !bInitialized ) { vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() ); m_bInitialized = sal_True; PropertyValue aPropValue; for ( int i = 0; i < aArguments.getLength(); i++ ) { if ( aArguments[i] >>= aPropValue ) { if ( aPropValue.Name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "Frame" ))) aPropValue.Value >>= m_xFrame; else if ( aPropValue.Name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "CommandURL" ))) aPropValue.Value >>= m_aCommandURL; else if ( aPropValue.Name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "ServiceManager" ))) aPropValue.Value >>= m_xServiceManager; else if ( aPropValue.Name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "ParentWindow" ))) aPropValue.Value >>= m_xParentWindow; else if ( aPropValue.Name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "Identifier" ))) aPropValue.Value >>= m_nID; else if ( aPropValue.Name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "StatusbarItem" ))) aPropValue.Value >>= m_xStatusbarItem; } } if ( m_aCommandURL.getLength() ) m_aListenerMap.insert( URLToDispatchMap::value_type( m_aCommandURL, Reference< XDispatch >() )); } } void SAL_CALL StatusbarController::update() throw ( RuntimeException ) { { vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() ); if ( m_bDisposed ) throw DisposedException(); } // Bind all registered listeners to their dispatch objects bindListener(); } // XComponent void SAL_CALL StatusbarController::dispose() throw (::com::sun::star::uno::RuntimeException) { Reference< XComponent > xThis( static_cast< OWeakObject* >(this), UNO_QUERY ); { vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() ); if ( m_bDisposed ) throw DisposedException(); } com::sun::star::lang::EventObject aEvent( xThis ); m_aListenerContainer.disposeAndClear( aEvent ); vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() ); Reference< XStatusListener > xStatusListener( static_cast< OWeakObject* >( this ), UNO_QUERY ); Reference< XURLTransformer > xURLTransformer = getURLTransformer(); URLToDispatchMap::iterator pIter = m_aListenerMap.begin(); com::sun::star::util::URL aTargetURL; while ( pIter != m_aListenerMap.end() ) { try { Reference< XDispatch > xDispatch( pIter->second ); aTargetURL.Complete = pIter->first; xURLTransformer->parseStrict( aTargetURL ); if ( xDispatch.is() && xStatusListener.is() ) xDispatch->removeStatusListener( xStatusListener, aTargetURL ); } catch ( Exception& ) { } ++pIter; } // clear hash map m_aListenerMap.clear(); // release references m_xURLTransformer.clear(); m_xServiceManager.clear(); m_xFrame.clear(); m_xParentWindow.clear(); m_xStatusbarItem.clear(); m_bDisposed = sal_True; } void SAL_CALL StatusbarController::addEventListener( const Reference< XEventListener >& xListener ) throw ( RuntimeException ) { m_aListenerContainer.addInterface( ::getCppuType( ( const Reference< XEventListener >* ) NULL ), xListener ); } void SAL_CALL StatusbarController::removeEventListener( const Reference< XEventListener >& aListener ) throw ( RuntimeException ) { m_aListenerContainer.removeInterface( ::getCppuType( ( const Reference< XEventListener >* ) NULL ), aListener ); } // XEventListener void SAL_CALL StatusbarController::disposing( const EventObject& Source ) throw ( RuntimeException ) { vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() ); if ( m_bDisposed ) return; Reference< XFrame > xFrame( Source.Source, UNO_QUERY ); if ( xFrame.is() ) { if ( xFrame == m_xFrame ) m_xFrame.clear(); return; } Reference< XDispatch > xDispatch( Source.Source, UNO_QUERY ); if ( !xDispatch.is() ) return; URLToDispatchMap::iterator pIter = m_aListenerMap.begin(); while ( pIter != m_aListenerMap.end() ) { // Compare references and release dispatch references if they are equal. if ( xDispatch == pIter->second ) pIter->second.clear(); pIter++; } } // XStatusListener void SAL_CALL StatusbarController::statusChanged( const FeatureStateEvent& Event ) throw ( RuntimeException ) { vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() ); if ( m_bDisposed ) return; Window* pWindow = VCLUnoHelper::GetWindow( m_xParentWindow ); if ( pWindow && pWindow->GetType() == WINDOW_STATUSBAR && m_nID != 0 ) { rtl::OUString aStrValue; StatusBar* pStatusBar = (StatusBar *)pWindow; if ( Event.State >>= aStrValue ) pStatusBar->SetItemText( m_nID, aStrValue ); else if ( !Event.State.hasValue() ) pStatusBar->SetItemText( m_nID, String() ); } } // XStatusbarController ::sal_Bool SAL_CALL StatusbarController::mouseButtonDown( const ::com::sun::star::awt::MouseEvent& ) throw (::com::sun::star::uno::RuntimeException) { return sal_False; } ::sal_Bool SAL_CALL StatusbarController::mouseMove( const ::com::sun::star::awt::MouseEvent& ) throw (::com::sun::star::uno::RuntimeException) { return sal_False; } ::sal_Bool SAL_CALL StatusbarController::mouseButtonUp( const ::com::sun::star::awt::MouseEvent& ) throw (::com::sun::star::uno::RuntimeException) { return sal_False; } void SAL_CALL StatusbarController::command( const ::com::sun::star::awt::Point&, ::sal_Int32, ::sal_Bool, const ::com::sun::star::uno::Any& ) throw (::com::sun::star::uno::RuntimeException) { } void SAL_CALL StatusbarController::paint( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XGraphics >&, const ::com::sun::star::awt::Rectangle&, ::sal_Int32 ) throw (::com::sun::star::uno::RuntimeException) { } void SAL_CALL StatusbarController::click( const ::com::sun::star::awt::Point& ) throw (::com::sun::star::uno::RuntimeException) { } void SAL_CALL StatusbarController::doubleClick( const ::com::sun::star::awt::Point& ) throw (::com::sun::star::uno::RuntimeException) { vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() ); if ( m_bDisposed ) return; Sequence< PropertyValue > aArgs; execute( aArgs ); } void StatusbarController::addStatusListener( const rtl::OUString& aCommandURL ) { Reference< XDispatch > xDispatch; Reference< XStatusListener > xStatusListener; com::sun::star::util::URL aTargetURL; { vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() ); URLToDispatchMap::iterator pIter = m_aListenerMap.find( aCommandURL ); // Already in the list of status listener. Do nothing. if ( pIter != m_aListenerMap.end() ) return; // Check if we are already initialized. Implementation starts adding itself as status listener when // intialize is called. if ( !m_bInitialized ) { // Put into the hash_map of status listener. Will be activated when initialized is called m_aListenerMap.insert( URLToDispatchMap::value_type( aCommandURL, Reference< XDispatch >() )); return; } else { // Add status listener directly as intialize has already been called. Reference< XDispatchProvider > xDispatchProvider( m_xFrame, UNO_QUERY ); if ( m_xServiceManager.is() && xDispatchProvider.is() ) { Reference< XURLTransformer > xURLTransformer = getURLTransformer(); aTargetURL.Complete = aCommandURL; xURLTransformer->parseStrict( aTargetURL ); xDispatch = xDispatchProvider->queryDispatch( aTargetURL, ::rtl::OUString(), 0 ); xStatusListener = Reference< XStatusListener >( static_cast< OWeakObject* >( this ), UNO_QUERY ); URLToDispatchMap::iterator aIter = m_aListenerMap.find( aCommandURL ); if ( aIter != m_aListenerMap.end() ) { Reference< XDispatch > xOldDispatch( aIter->second ); aIter->second = xDispatch; try { if ( xOldDispatch.is() ) xOldDispatch->removeStatusListener( xStatusListener, aTargetURL ); } catch ( Exception& ) { } } else m_aListenerMap.insert( URLToDispatchMap::value_type( aCommandURL, xDispatch )); } } } // Call without locked mutex as we are called back from dispatch implementation try { if ( xDispatch.is() ) xDispatch->addStatusListener( xStatusListener, aTargetURL ); } catch ( Exception& ) { } } void StatusbarController::removeStatusListener( const rtl::OUString& aCommandURL ) { vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() ); URLToDispatchMap::iterator pIter = m_aListenerMap.find( aCommandURL ); if ( pIter != m_aListenerMap.end() ) { Reference< XDispatch > xDispatch( pIter->second ); Reference< XStatusListener > xStatusListener( static_cast< OWeakObject* >( this ), UNO_QUERY ); m_aListenerMap.erase( pIter ); try { Reference< XURLTransformer > xURLTransformer = getURLTransformer(); com::sun::star::util::URL aTargetURL; aTargetURL.Complete = aCommandURL; xURLTransformer->parseStrict( aTargetURL ); if ( xDispatch.is() && xStatusListener.is() ) xDispatch->removeStatusListener( xStatusListener, aTargetURL ); } catch ( Exception& ) { } } } void StatusbarController::bindListener() { std::vector< Listener > aDispatchVector; Reference< XStatusListener > xStatusListener; { vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() ); if ( !m_bInitialized ) return; // Collect all registered command URL's and store them temporary Reference< XDispatchProvider > xDispatchProvider( m_xFrame, UNO_QUERY ); if ( m_xServiceManager.is() && xDispatchProvider.is() ) { xStatusListener = Reference< XStatusListener >( static_cast< OWeakObject* >( this ), UNO_QUERY ); URLToDispatchMap::iterator pIter = m_aListenerMap.begin(); while ( pIter != m_aListenerMap.end() ) { Reference< XURLTransformer > xURLTransformer = getURLTransformer(); com::sun::star::util::URL aTargetURL; aTargetURL.Complete = pIter->first; xURLTransformer->parseStrict( aTargetURL ); Reference< XDispatch > xDispatch( pIter->second ); if ( xDispatch.is() ) { // We already have a dispatch object => we have to requery. // Release old dispatch object and remove it as listener try { xDispatch->removeStatusListener( xStatusListener, aTargetURL ); } catch ( Exception& ) { } } pIter->second.clear(); xDispatch.clear(); // Query for dispatch object. Old dispatch will be released with this, too. try { xDispatch = xDispatchProvider->queryDispatch( aTargetURL, ::rtl::OUString(), 0 ); } catch ( Exception& ) { } pIter->second = xDispatch; Listener aListener( aTargetURL, xDispatch ); aDispatchVector.push_back( aListener ); ++pIter; } } } // Call without locked mutex as we are called back from dispatch implementation if ( !xStatusListener.is() ) return; for ( sal_uInt32 i = 0; i < aDispatchVector.size(); i++ ) { try { Listener& rListener = aDispatchVector[i]; if ( rListener.xDispatch.is() ) rListener.xDispatch->addStatusListener( xStatusListener, rListener.aURL ); else if ( rListener.aURL.Complete == m_aCommandURL ) { // Send status changed for the main URL, if we cannot get a valid dispatch object. // UI disables the button. Catch exception as we release our mutex, it is possible // that someone else already disposed this instance! FeatureStateEvent aFeatureStateEvent; aFeatureStateEvent.IsEnabled = sal_False; aFeatureStateEvent.FeatureURL = rListener.aURL; aFeatureStateEvent.State = Any(); xStatusListener->statusChanged( aFeatureStateEvent ); } } catch ( ... ){} } } void StatusbarController::unbindListener() { vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() ); if ( !m_bInitialized ) return; Reference< XStatusListener > xStatusListener( static_cast< OWeakObject* >( this ), UNO_QUERY ); URLToDispatchMap::iterator pIter = m_aListenerMap.begin(); while ( pIter != m_aListenerMap.end() ) { Reference< XURLTransformer > xURLTransformer = getURLTransformer(); com::sun::star::util::URL aTargetURL; aTargetURL.Complete = pIter->first; xURLTransformer->parseStrict( aTargetURL ); Reference< XDispatch > xDispatch( pIter->second ); if ( xDispatch.is() ) { // We already have a dispatch object => we have to requery. // Release old dispatch object and remove it as listener try { xDispatch->removeStatusListener( xStatusListener, aTargetURL ); } catch ( Exception& ) { } } pIter->second.clear(); ++pIter; } } sal_Bool StatusbarController::isBound() const { vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() ); if ( !m_bInitialized ) return sal_False; URLToDispatchMap::const_iterator pIter = m_aListenerMap.find( m_aCommandURL ); if ( pIter != m_aListenerMap.end() ) return ( pIter->second.is() ); return sal_False; } void StatusbarController::updateStatus() { bindListener(); } void StatusbarController::updateStatus( const rtl::OUString aCommandURL ) { Reference< XDispatch > xDispatch; Reference< XStatusListener > xStatusListener; com::sun::star::util::URL aTargetURL; { vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() ); if ( !m_bInitialized ) return; // Try to find a dispatch object for the requested command URL Reference< XDispatchProvider > xDispatchProvider( m_xFrame, UNO_QUERY ); xStatusListener = Reference< XStatusListener >( static_cast< OWeakObject* >( this ), UNO_QUERY ); if ( m_xServiceManager.is() && xDispatchProvider.is() ) { Reference< XURLTransformer > xURLTransformer = getURLTransformer(); aTargetURL.Complete = aCommandURL; xURLTransformer->parseStrict( aTargetURL ); xDispatch = xDispatchProvider->queryDispatch( aTargetURL, rtl::OUString(), 0 ); } } if ( xDispatch.is() && xStatusListener.is() ) { // Catch exception as we release our mutex, it is possible that someone else // has already disposed this instance! // Add/remove status listener to get a update status information from the // requested command. try { xDispatch->addStatusListener( xStatusListener, aTargetURL ); xDispatch->removeStatusListener( xStatusListener, aTargetURL ); } catch ( Exception& ) { } } } ::Rectangle StatusbarController::getControlRect() const { ::Rectangle aRect; { vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() ); if ( m_bDisposed ) throw DisposedException(); if ( m_xParentWindow.is() ) { StatusBar* pStatusBar = dynamic_cast< StatusBar* >( VCLUnoHelper::GetWindow( m_xParentWindow )); if ( pStatusBar && pStatusBar->GetType() == WINDOW_STATUSBAR ) aRect = pStatusBar->GetItemRect( m_nID ); } } return aRect; } void StatusbarController::execute( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aArgs ) { Reference< XDispatch > xDispatch; Reference< XURLTransformer > xURLTransformer; rtl::OUString aCommandURL; { vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() ); if ( m_bDisposed ) throw DisposedException(); if ( m_bInitialized && m_xFrame.is() && m_xServiceManager.is() && m_aCommandURL.getLength() ) { xURLTransformer = getURLTransformer(); aCommandURL = m_aCommandURL; URLToDispatchMap::iterator pIter = m_aListenerMap.find( m_aCommandURL ); if ( pIter != m_aListenerMap.end() ) xDispatch = pIter->second; } } if ( xDispatch.is() && xURLTransformer.is() ) { try { com::sun::star::util::URL aTargetURL; aTargetURL.Complete = aCommandURL; xURLTransformer->parseStrict( aTargetURL ); xDispatch->dispatch( aTargetURL, aArgs ); } catch ( DisposedException& ) { } } } void StatusbarController::execute( const rtl::OUString& aCommandURL, const Sequence< ::com::sun::star::beans::PropertyValue >& aArgs ) { Reference< XDispatch > xDispatch; com::sun::star::util::URL aTargetURL; { vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() ); if ( m_bDisposed ) throw DisposedException(); if ( m_bInitialized && m_xFrame.is() && m_xServiceManager.is() && m_aCommandURL.getLength() ) { Reference< XURLTransformer > xURLTransformer( getURLTransformer() ); aTargetURL.Complete = aCommandURL; xURLTransformer->parseStrict( aTargetURL ); URLToDispatchMap::iterator pIter = m_aListenerMap.find( aCommandURL ); if ( pIter != m_aListenerMap.end() ) xDispatch = pIter->second; else { Reference< ::com::sun::star::frame::XDispatchProvider > xDispatchProvider( m_xFrame->getController(), UNO_QUERY ); if ( xDispatchProvider.is() ) xDispatch = xDispatchProvider->queryDispatch( aTargetURL, ::rtl::OUString(), 0 ); } } } if ( xDispatch.is() ) { try { xDispatch->dispatch( aTargetURL, aArgs ); } catch ( DisposedException& ) { } } } } // svt
10,599
2,959
<reponame>renanmontebelo/aws-sam-cli from unittest import TestCase from unittest.mock import MagicMock from samcli.commands._utils.custom_options.option_nargs import OptionNargs class MockRArgs: def __init__(self, rargs): self.rargs = rargs class TestOptionNargs(TestCase): def setUp(self): self.name = "test" self.opt = "--use" self.prefixes = ["--", "-"] self.arg = "first" self.rargs_list = ["second", "third", "--nextopt"] self.expected_args = tuple([self.arg] + self.rargs_list[:-1]) self.option_nargs = OptionNargs(param_decls=(self.name, self.opt)) def test_option(self): parser = MagicMock() ctx = MagicMock() self.option_nargs.add_to_parser(parser=parser, ctx=ctx) # Get option parser parser._long_opt.get.assert_called_with(self.opt) self.assertEqual(self.option_nargs._nargs_parser, parser._long_opt.get()) # set prefixes self.option_nargs._nargs_parser.prefixes = self.prefixes # create new state with remaining args state = MockRArgs(self.rargs_list) # call process with the monkey patched `parser_process` within `add_to_process` parser._long_opt.get().process(self.arg, state) # finally call parser.process with ("first", "second", "third") self.option_nargs._previous_parser_process.assert_called_with(self.expected_args, state)
600
353
<reponame>muyiluop/nutzmore<gh_stars>100-1000 package org.nutz.plugins.event; import org.nutz.ioc.Ioc; import org.nutz.log.Log; import org.nutz.log.Logs; /** * @author <EMAIL> * @varsion 2017-5-16 */ public class TestBean { private Log log = Logs.get(); private Ioc ioc; public void init() { log.debug(ioc); } }
143
2,151
<filename>services/content/view_delegate.h // Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef SERVICES_CONTENT_VIEW_DELEGATE_H_ #define SERVICES_CONTENT_VIEW_DELEGATE_H_ class GURL; namespace content { // A virtual interface which must be implemented as a backing for ViewImpl // instances. // // This is the primary interface by which the Content Service delegates ViewImpl // behavior out to WebContentsImpl in src/content. As such it is a transitional // API which will be removed as soon as WebContentsImpl itself can be fully // migrated into Content Service. // // Each instance of this interface is constructed by the ContentServiceDelegate // implementation and owned by a ViewImpl. class ViewDelegate { public: virtual ~ViewDelegate() {} // Navigates the content object to a new URL. virtual void Navigate(const GURL& url) = 0; }; } // namespace content #endif // SERVICES_CONTENT_VIEW_DELEGATE_H_
288
679
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef _SFX_PROGRESS_HXX #define _SFX_PROGRESS_HXX #include "sal/config.h" #include "sfx2/dllapi.h" #include "sal/types.h" #include <tools/solar.h> #include <tools/link.hxx> class String; class SfxObjectShell; class SfxStatusBarManager; class INetHint; class SvDispatch; struct SfxProgress_Impl; struct PlugInLoadStatus; struct SvProgressArg; //======================================================================= class SFX2_DLLPUBLIC SfxProgress { SfxProgress_Impl* pImp; sal_uIntPtr nVal; sal_Bool bSuspended; public: SfxProgress( SfxObjectShell* pObjSh, const String& rText, sal_uIntPtr nRange, sal_Bool bAllDocs = sal_False, sal_Bool bWait = sal_True ); virtual ~SfxProgress(); virtual void SetText( const String& rText ); sal_Bool SetStateText( sal_uIntPtr nVal, const String &rVal, sal_uIntPtr nNewRange = 0 ); virtual sal_Bool SetState( sal_uIntPtr nVal, sal_uIntPtr nNewRange = 0 ); sal_uIntPtr GetState() const { return nVal; } void Resume(); void Suspend(); sal_Bool IsSuspended() const { return bSuspended; } void Lock(); void UnLock(); void Reschedule(); void Stop(); void SetWaitMode( sal_Bool bWait ); sal_Bool GetWaitMode() const; static SfxProgress* GetActiveProgress( SfxObjectShell *pDocSh = 0 ); static void EnterLock(); static void LeaveLock(); //#if 0 // _SOLAR__PRIVATE DECL_DLLPRIVATE_STATIC_LINK( SfxProgress, SetStateHdl, PlugInLoadStatus* ); DECL_DLLPRIVATE_STATIC_LINK( SfxProgress, DefaultBindingProgress, SvProgressArg* ); SAL_DLLPRIVATE FASTBOOL StatusBarManagerGone_Impl(SfxStatusBarManager*pStb); SAL_DLLPRIVATE const String& GetStateText_Impl() const; //#endif }; #endif
948
631
package com.eowise.recyclerview.stickyheaders.samples.listeners; /** * Created by Robby on 1/27/2015. */ public interface OnEditListener { public void onEdit(int position); }
62
4,879
<reponame>ivan-konov/mopub-ios-sdk-carthage<filename>MoPubSDK/Internal/VAST/MPVideoEvent.h // // MPVideoEvent.h // // Copyright 2018-2020 Twitter, Inc. // Licensed under the MoPub SDK License Agreement // http://www.mopub.com/legal/sdk-license-agreement/ // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN /** To learn more about these events, please see VAST documentation: https://www.iab.com/wp-content/uploads/2015/06/VASTv3_0.pdf Note: for `MPVideoEventCloseLinear`("closeLinear"): the user clicked the close button on the creative. The name of this event distinguishes it from the existing “close” event described in the 2008 IAB Digital Video In-Stream Ad Metrics Definitions, which defines the “close” metric as applying to non-linear ads only. The "closeLinear" event extends the “close” event for use in Linear creative. Since we don't know whether none, either, or both "close" or "closeLinear" are returned by the creative, we should look for both trackers when the user closes the video. */ typedef NSString * MPVideoEvent; // keep this list sorted alphabetically extern MPVideoEvent const MPVideoEventClick; extern MPVideoEvent const MPVideoEventClose; // see note above about `MPVideoEventCloseLinear` extern MPVideoEvent const MPVideoEventCloseLinear; // see note above about `MPVideoEventClose` extern MPVideoEvent const MPVideoEventCollapse; extern MPVideoEvent const MPVideoEventCompanionAdClick; // MoPub-specific tracking event extern MPVideoEvent const MPVideoEventCompanionAdView; // MoPub-specific tracking event extern MPVideoEvent const MPVideoEventComplete; extern MPVideoEvent const MPVideoEventCreativeView; extern MPVideoEvent const MPVideoEventError; extern MPVideoEvent const MPVideoEventExitFullScreen; extern MPVideoEvent const MPVideoEventExpand; extern MPVideoEvent const MPVideoEventFirstQuartile; extern MPVideoEvent const MPVideoEventFullScreen; extern MPVideoEvent const MPVideoEventImpression; extern MPVideoEvent const MPVideoEventIndustryIconClick; // MoPub-specific tracking event extern MPVideoEvent const MPVideoEventIndustryIconView; // MoPub-specific tracking event extern MPVideoEvent const MPVideoEventMidpoint; extern MPVideoEvent const MPVideoEventMute; extern MPVideoEvent const MPVideoEventPause; extern MPVideoEvent const MPVideoEventProgress; extern MPVideoEvent const MPVideoEventResume; extern MPVideoEvent const MPVideoEventSkip; extern MPVideoEvent const MPVideoEventStart; extern MPVideoEvent const MPVideoEventThirdQuartile; extern MPVideoEvent const MPVideoEventUnmute; /** Provides class-level support for `MPVideoEvent` processing. */ @interface MPVideoEvents : NSObject /** All available and supported `MPVideoEvent` types. */ @property (nonatomic, class, strong, readonly) NSSet<MPVideoEvent> *supported; /** Queries if the inputted event string is a valid supported `MPVideoEvent` type. @param event Video event candidate string. @return `true` if valid; `false` otherwise. */ + (BOOL)isSupportedEvent:(NSString *)event; @end NS_ASSUME_NONNULL_END
876
1,374
<gh_stars>1000+ package def.dom; public class HTMLTextAreaElement extends HTMLElement { /** * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. */ public Boolean autofocus; /** * Sets or retrieves the width of the object. */ public double cols; /** * Sets or retrieves the initial contents of the object. */ public String defaultValue; public Boolean disabled; /** * Retrieves a reference to the form that the object is embedded in. */ public HTMLFormElement form; /** * Sets or retrieves the maximum number of characters that the user can enter in a text control. */ public double maxLength; /** * Sets or retrieves the name of the object. */ public String name; /** * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. */ public String placeholder; /** * Sets or retrieves the value indicated whether the content of the object is read-only. */ public Boolean readOnly; /** * When present, marks an element that can't be submitted without a value. */ public Boolean required; /** * Sets or retrieves the number of horizontal rows contained in the object. */ public double rows; /** * Gets or sets the end position or offset of a text selection. */ public double selectionEnd; /** * Gets or sets the starting position or offset of a text selection. */ public double selectionStart; /** * Sets or retrieves the value indicating whether the control is selected. */ public Object status; /** * Retrieves the type of control. */ public String type; /** * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. */ public String validationMessage; /** * Returns a ValidityState object that represents the validity states of an element. */ public ValidityState validity; /** * Retrieves or sets the text in the entry field of the textArea element. */ public String value; /** * Returns whether an element will successfully validate based on forms validation rules and constraints. */ public Boolean willValidate; /** * Sets or retrieves how to handle wordwrapping in the object. */ public String wrap; /** * Returns whether a form will validate when it is submitted, without having to submit it. */ native public Boolean checkValidity(); /** * Creates a TextRange object for the element. */ native public TextRange createTextRange(); /** * Highlights the input area of a form element. */ native public void select(); /** * Sets a custom error message that is displayed when a form is submitted. * @param error Sets a custom error message that is displayed when a form is submitted. */ native public void setCustomValidity(String error); /** * Sets the start and end positions of a selection in a text field. * @param start The offset into the text field for the start of the selection. * @param end The offset into the text field for the end of the selection. */ native public void setSelectionRange(double start, double end); public static HTMLTextAreaElement prototype; public HTMLTextAreaElement(){} }
1,314
665
<filename>types/map_fwd.h #pragma once #include "mldb/compiler/stdlib.h" namespace std { #ifdef MLDB_STDLIB_GCC template<class K, class V, class L, class A> class map; #elif MLDB_STDLIB_LLVM inline namespace __1 { template<class K, class V, class L, class A> class map; } #else # error "Tell us how to forward declare set for your standard library" #endif } // namespace std
147
1,338
/* * Copyright 2016 Haiku, Inc. All rights reserved. * Distributed under the terms of the MIT License. * * Authors: * <NAME>, <EMAIL> */ #ifndef COLORWHICH_LIST_VIEW_H #define COLORWHICH_LIST_VIEW_H #include <ListView.h> class ColorWhichListView : public BListView { public: ColorWhichListView(const char* name, list_view_type type = B_SINGLE_SELECTION_LIST, uint32 flags = B_WILL_DRAW | B_FRAME_EVENTS | B_NAVIGABLE); virtual ~ColorWhichListView(); virtual bool InitiateDrag(BPoint where, int32 index, bool wasSelected); virtual void MessageReceived(BMessage* message); }; #endif // COLORWHICH_LIST_VIEW_H
295
454
package io.vertx.up.log; import io.vertx.core.json.JsonObject; import io.vertx.up.eon.Plugins; import io.vertx.up.exception.heart.ErrorMissingException; import io.vertx.up.fn.Fn; import io.vertx.up.uca.yaml.Node; import java.text.MessageFormat; /** * */ public final class Errors { private static final String ZERO_ERROR = "[ERR{0}] ({1}) Zero Error: {2}."; private static final String WEB_ERROR = "[ERR{0}] ({1}) Web Error: {2}."; public static String normalize(final Class<?> clazz, final int code, final Object... args) { return normalize(clazz, code, ZERO_ERROR, args); } public static String normalizeWeb(final Class<?> clazz, final int code, final Object... args) { return normalize(clazz, code, WEB_ERROR, args); } private static String normalize(final Class<?> clazz, final int code, final String tpl, final Object... args) { return Fn.getJvm(() -> { final String key = ("E" + Math.abs(code)).intern(); final Node<JsonObject> node = Node.infix(Plugins.ERROR); final JsonObject data = node.read(); if (null != data && data.containsKey(key)) { // 1. Read pattern final String pattern = data.getString(key); // 2. Build message final String error = MessageFormat.format(pattern, args); // 3. Format return MessageFormat.format( tpl, String.valueOf(code), clazz.getSimpleName(), error ); } else { throw new ErrorMissingException(code, clazz.getName()); } }, clazz); } public static String method(final Class<?> clazzPos, final String methodPos) { final StackTraceElement[] methods = Thread.currentThread().getStackTrace(); String methodName = null; int position = 0; for (int idx = 0; idx < methods.length; idx++) { final String clazz = methods[idx].getClassName(); final String method = methods[idx].getMethodName(); if (clazz.equals(clazzPos.getName()) && method.equals(methodPos)) { position = idx + 1; } } if (position < methods.length - 1) { methodName = methods[position].getMethodName(); } return methodName; } }
1,363
376
<reponame>cjsmeele/Kvasir #pragma once #include <Register/Utility.hpp> namespace Kvasir { // peripheral BTIOSELCF namespace BtioselcfBtselcdef{ ///< register BTSELCDEF using Addr = Register::Address<0x40025700,0xffff00ff,0x00000000,unsigned>; /// bitfield SELEF_ constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,12),Register::ReadWriteAccess,unsigned> selef{}; /// bitfield SELCD_ constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,8),Register::ReadWriteAccess,unsigned> selcd{}; } }
235
6,052
<reponame>danielavellar15/ckeditor5 { "Bold": "Toolbar button tooltip for the Bold feature.", "Italic": "Toolbar button tooltip for the Italic feature.", "Underline": "Toolbar button tooltip for the Underline feature.", "Code": "Toolbar button tooltip for the Code feature.", "Strikethrough": "Toolbar button tooltip for the Strikethrough feature.", "Subscript": "Toolbar button tooltip for the Subscript feature.", "Superscript": "Toolbar button tooltip for the Superscript feature." }
143
2,151
<gh_stars>1000+ // Copyright 2017 PDFium 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 "fxbarcode/oned/BC_OnedUPCAWriter.h" #include "testing/gtest/include/gtest/gtest.h" namespace { TEST(OnedUPCAWriterTest, Encode) { CBC_OnedUPCAWriter writer; int32_t width; int32_t height; // TODO(hnakashima): CBC_OnedUPCAWriter is unique in that it needs to be // Init()'d. Get rid of this call. writer.Init(); // UPCA barcodes encode 12-digit numbers into 95 modules in a unidimensional // disposition. uint8_t* encoded = writer.Encode("", BCFORMAT_UPC_A, width, height); EXPECT_EQ(nullptr, encoded); FX_Free(encoded); encoded = writer.Encode("123", BCFORMAT_UPC_A, width, height); EXPECT_EQ(nullptr, encoded); FX_Free(encoded); encoded = writer.Encode("12345678901", BCFORMAT_UPC_A, width, height); EXPECT_EQ(nullptr, encoded); FX_Free(encoded); encoded = writer.Encode("1234567890123", BCFORMAT_UPC_A, width, height); EXPECT_EQ(nullptr, encoded); FX_Free(encoded); encoded = writer.Encode("123456789012", BCFORMAT_UPC_A, width, height); const char* expected = "# #" // Start " ## #" // 1 L " # ##" // 2 L " #### #" // 3 L " # ##" // 4 L " ## #" // 5 L " # ####" // 6 L " # # " // Middle "# # " // 7 R "# # " // 8 R "### # " // 9 R "### # " // 0 R "## ## " // 1 R "## ## " // 2 R "# #"; // End EXPECT_NE(nullptr, encoded); EXPECT_EQ(1, height); EXPECT_EQ(static_cast<int32_t>(strlen(expected)), width); for (size_t i = 0; i < strlen(expected); i++) { EXPECT_EQ(expected[i] != ' ', !!encoded[i]) << i; } FX_Free(encoded); encoded = writer.Encode("777666555440", BCFORMAT_UPC_A, width, height); expected = "# #" // Start " ### ##" // 7 L " ### ##" // 7 L " ### ##" // 7 L " # ####" // 6 L " # ####" // 6 L " # ####" // 6 L " # # " // Middle "# ### " // 5 R "# ### " // 5 R "# ### " // 5 R "# ### " // 4 R "# ### " // 4 R "### # " // 0 R "# #"; // End EXPECT_NE(nullptr, encoded); EXPECT_EQ(1, height); EXPECT_EQ(static_cast<int32_t>(strlen(expected)), width); for (size_t i = 0; i < strlen(expected); i++) { EXPECT_EQ(expected[i] != ' ', !!encoded[i]) << i; } FX_Free(encoded); } TEST(OnedUPCAWriterTest, Checksum) { CBC_OnedUPCAWriter writer; EXPECT_EQ(0, writer.CalcChecksum("")); EXPECT_EQ(6, writer.CalcChecksum("123")); EXPECT_EQ(2, writer.CalcChecksum("12345678901")); EXPECT_EQ(0, writer.CalcChecksum("77766655544")); } } // namespace
1,270
328
package com.poiji.bind.mapping; /** * @author Matthew 2018/09/01 */ final class WorkBookSheet { private String name; private String sheetId; private String state = "visible"; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSheetId() { return sheetId; } public void setSheetId(String sheetId) { this.sheetId = sheetId; } public String getState() { return state; } public void setState(String state) { this.state = state; } }
248
335
<reponame>Safal08/Hacktoberfest-1 { "word": "Earth", "definitions": [ "Connect (an electrical device) with the ground.", "Drive (a fox) to its underground lair.", "(of a fox) run to its underground lair.", "Cover the root and lower stem of a plant with heaped-up earth." ], "parts-of-speech": "Verb" }
141
2,542
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" using namespace std; using namespace Common; using namespace ServiceModel; StringLiteral const TraceComponent("ComposeDeploymentUpgradeDescription"); ComposeDeploymentUpgradeDescription::ComposeDeploymentUpgradeDescription( std::wstring &&deploymentName, std::wstring &&applicationName, std::vector<Common::ByteBuffer> &&composeFiles, std::vector<Common::ByteBuffer> &&sfSettingsFiles, std::wstring &&repositoryUserName, std::wstring &&repositoryPassword, bool isPasswordEncrypted, ServiceModel::UpgradeType::Enum upgradeType, ServiceModel::RollingUpgradeMode::Enum upgradeMode, bool forceRestart, ServiceModel::RollingUpgradeMonitoringPolicy &&monitoringPolicy, bool isHealthPolicyValid, ServiceModel::ApplicationHealthPolicy &&healthPolicy, Common::TimeSpan const &replicaSetCheckTimeout) : deploymentName_(move(deploymentName)) , applicationName_(move(applicationName)) , composeFiles_(move(composeFiles)) , sfSettingsFiles_(move(sfSettingsFiles)) , repositoryUserName_(move(repositoryUserName)) , repositoryPassword_(move(repositoryPassword)) , isPasswordEncrypted_(isPasswordEncrypted) , upgradeType_(upgradeType) , rollingUpgradeMode_(upgradeMode) , forceRestart_(forceRestart) , monitoringPolicy_(move(monitoringPolicy)) , healthPolicy_(move(healthPolicy)) , isHealthPolicyValid_(isHealthPolicyValid) , replicaSetCheckTimeout_(replicaSetCheckTimeout) {} ErrorCode ComposeDeploymentUpgradeDescription::FromPublicApi(FABRIC_COMPOSE_DEPLOYMENT_UPGRADE_DESCRIPTION const &publicDesc) { auto error = StringUtility::LpcwstrToWstring2(publicDesc.DeploymentName, false, deploymentName_); if (!error.IsSuccess()) { return error; } error = StringUtility::LpcwstrToWstring2(publicDesc.ContainerRegistryUserName, true, repositoryUserName_); if (!error.IsSuccess()) { return error; } error = StringUtility::LpcwstrToWstring2(publicDesc.ContainerRegistryPassword, true, repositoryPassword_); if (!error.IsSuccess()) { return error; } isPasswordEncrypted_ = !!publicDesc.IsPasswordEncrypted; composeFiles_.reserve(publicDesc.ComposeFilePaths.Count); for (unsigned int i = 0; i < publicDesc.ComposeFilePaths.Count; ++i) { wstring filePath; error = StringUtility::LpcwstrToWstring2(publicDesc.ComposeFilePaths.Items[i], false, filePath); if (!error.IsSuccess()) { Trace.WriteInfo( TraceComponent, "Failed to parse compose file path, Error: {0}", error); return error; } ByteBuffer fileContents; error = GetFileContents(filePath, fileContents); if (!error.IsSuccess()) { Trace.WriteInfo( TraceComponent, "Failed to read from Compose file '{0}', Error: {1}", filePath, error); return error; } composeFiles_.push_back(move(fileContents)); } sfSettingsFiles_.reserve(publicDesc.ServiceFabricSettingsFilePaths.Count); for (unsigned int i = 0; i < publicDesc.ServiceFabricSettingsFilePaths.Count; ++i) { wstring filePath; error = StringUtility::LpcwstrToWstring2(publicDesc.ServiceFabricSettingsFilePaths.Items[i], false, filePath); if (!error.IsSuccess()) { Trace.WriteInfo( TraceComponent, "Failed to parse settings file path, Error: {0}", error); return error; } ByteBuffer fileContents; error = GetFileContents(filePath, fileContents); if (!error.IsSuccess()) { Trace.WriteInfo( TraceComponent, "Failed to read from SF Settings file '{0}', Error: {1}", filePath, error); return error; } sfSettingsFiles_.push_back(move(fileContents)); } // TODO : Make this common code between all upgrade input parsing. upgradeType_ = UpgradeType::Rolling; auto policyDescription = reinterpret_cast<FABRIC_ROLLING_UPGRADE_POLICY_DESCRIPTION *>(publicDesc.UpgradePolicyDescription); switch (policyDescription->RollingUpgradeMode) { case FABRIC_ROLLING_UPGRADE_MODE_UNMONITORED_AUTO: rollingUpgradeMode_ = RollingUpgradeMode::UnmonitoredAuto; break; case FABRIC_ROLLING_UPGRADE_MODE_UNMONITORED_MANUAL: rollingUpgradeMode_ = RollingUpgradeMode::UnmonitoredManual; break; case FABRIC_ROLLING_UPGRADE_MODE_MONITORED: rollingUpgradeMode_ = RollingUpgradeMode::Monitored; if (policyDescription->Reserved != NULL) { auto policyDescriptionEx = reinterpret_cast<FABRIC_ROLLING_UPGRADE_POLICY_DESCRIPTION_EX1*>(policyDescription->Reserved); if (policyDescriptionEx != NULL) { if (policyDescriptionEx->MonitoringPolicy != NULL) { error = monitoringPolicy_.FromPublicApi(*(policyDescriptionEx->MonitoringPolicy)); if (!error.IsSuccess()) { return error; } } if (policyDescriptionEx->HealthPolicy != NULL) { auto healthPolicy = reinterpret_cast<FABRIC_APPLICATION_HEALTH_POLICY*>(policyDescriptionEx->HealthPolicy); error = healthPolicy_.FromPublicApi(*healthPolicy); if (!error.IsSuccess()) { return error; } isHealthPolicyValid_ = true; } } } break; default: return ErrorCodeValue::InvalidArgument; } forceRestart_ = (policyDescription->ForceRestart == TRUE) ? true : false; replicaSetCheckTimeout_ = TimeSpan::FromSeconds(policyDescription->UpgradeReplicaSetCheckTimeoutInSeconds); return ErrorCodeValue::Success; } ErrorCode ComposeDeploymentUpgradeDescription::Validate() { if ((rollingUpgradeMode_ != RollingUpgradeMode::Monitored) && (rollingUpgradeMode_ != RollingUpgradeMode::UnmonitoredAuto) && (rollingUpgradeMode_ != RollingUpgradeMode::UnmonitoredManual)) { return ErrorCodeValue::InvalidArgument; } return ErrorCodeValue::Success; } ErrorCode ComposeDeploymentUpgradeDescription::GetFileContents(wstring const &filePath, __out ByteBuffer &fileContents) { File composeFile; auto error = composeFile.TryOpen( filePath, FileMode::Open, FileAccess::Read, FileShare::Read, FileAttributes::SequentialScan); if (!error.IsSuccess()) { return error; } size_t fileSize = composeFile.size(); DWORD bytesRead; int size = static_cast<int>(fileSize); ByteBuffer temp(size); error = composeFile.TryRead2(temp.data(), size, bytesRead); if (!error.IsSuccess()) { return error; } fileContents = move(temp); return error; }
2,969
416
// // WKInterfaceSKScene.h // WatchKit // // Copyright © 2016 Apple Inc. All rights reserved. // #import <Foundation/Foundation.h> #import <WatchKit/WKDefines.h> #import <WatchKit/WKInterfaceObject.h> NS_ASSUME_NONNULL_BEGIN @class SKScene, SKTransition, SKTexture, SKNode; WK_AVAILABLE_WATCHOS_ONLY(3.0) @interface WKInterfaceSKScene : WKInterfaceObject /** Pause the entire interface */ @property (nonatomic, getter = isPaused) BOOL paused; /* Defines the desired rate for interface to render it's content. Actual rate maybe be limited by hardware or other software. */ @property (nonatomic) NSInteger preferredFramesPerSecond NS_AVAILABLE(10_12, 10_0); /** Present an SKScene in the interface, replacing the current scene. @param scene the scene to present. */ - (void)presentScene:(nullable SKScene *)scene; /** Present an SKScene in the interface, replacing the current scene. If there is currently a scene being presented in the interface, the transition is used to swap between them. @param scene the scene to present. @param transition the transition to use when presenting the scene. */ - (void)presentScene:(SKScene *)scene transition:(SKTransition *)transition; /** The currently presented scene, otherwise nil. If in a transition, the 'incoming' scene is returned. */ @property (nonatomic, readonly, nullable) SKScene *scene; /** Create an SKTexture containing a snapshot of how it would have been rendered in this interface. The texture is tightly cropped to the size of the node. @param node the node subtree to render to the texture. */ - (nullable SKTexture *)textureFromNode:(SKNode *)node; /** Create an SKTexture containing a snapshot of how it would have been rendered in this interface. The texture is cropped to the specified rectangle @param node the node subtree to render to the texture. @param crop the rectangle to crop to */ - (nullable SKTexture *)textureFromNode:(SKNode *)node crop:(CGRect)crop; @end NS_ASSUME_NONNULL_END
567
569
# -*- coding: utf-8 -*- """ Text generator using n-gram language model code from https://towardsdatascience.com/understanding-word-n-grams-and-n-gram-probability-in-natural-language-processing-9d9eef0fa058 """ import random from pythainlp.corpus.tnc import unigram_word_freqs as tnc_word_freqs_unigram from pythainlp.corpus.tnc import bigram_word_freqs as tnc_word_freqs_bigram from pythainlp.corpus.tnc import trigram_word_freqs as tnc_word_freqs_trigram from pythainlp.corpus.ttc import unigram_word_freqs as ttc_word_freqs_unigram from pythainlp.corpus.oscar import ( unigram_word_freqs as oscar_word_freqs_unigram ) from typing import List, Union class Unigram: """ Text generator using Unigram :param str name: corpus name * *tnc* - Thai National Corpus (default) * *ttc* - Thai Textbook Corpus (TTC) * *oscar* - OSCAR Corpus """ def __init__(self, name: str = "tnc"): if name == "tnc": self.counts = tnc_word_freqs_unigram() elif name == "ttc": self.counts = ttc_word_freqs_unigram() elif name == "oscar": self.counts = oscar_word_freqs_unigram() self.word = list(self.counts.keys()) self.n = 0 for i in self.word: self.n += self.counts[i] self.prob = { i: self.counts[i] / self.n for i in self.word } self._word_prob = {} def gen_sentence( self, start_seq: str = None, N: int = 3, prob: float = 0.001, output_str: bool = True, duplicate: bool = False ) -> Union[List[str], str]: """ :param str start_seq: word for begin word. :param int N: number of word. :param bool output_str: output is str :param bool duplicate: duplicate word in sent :return: list words or str words :rtype: List[str], str :Example: :: from pythainlp.generate import Unigram gen = Unigram() gen.gen_sentence("แมว") # ouput: 'แมวเวลานะนั้น' """ if start_seq is None: start_seq = random.choice(self.word) rand_text = start_seq.lower() self._word_prob = { i: self.counts[i] / self.n for i in self.word if self.counts[i] / self.n >= prob } return self._next_word( rand_text, N, output_str, prob=prob, duplicate=duplicate ) def _next_word( self, text: str, N: int, output_str: str, prob: float, duplicate: bool = False ): self.words = [] self.words.append(text) self._word_list = list(self._word_prob.keys()) if N > len(self._word_list): N = len(self._word_list) for i in range(N): self._word = random.choice(self._word_list) if duplicate is False: while self._word in self.words: self._word = random.choice(self._word_list) self.words.append(self._word) if output_str: return "".join(self.words) return self.words class Bigram: """ Text generator using Bigram :param str name: corpus name * *tnc* - Thai National Corpus (default) """ def __init__(self, name: str = "tnc"): if name == "tnc": self.uni = tnc_word_freqs_unigram() self.bi = tnc_word_freqs_bigram() self.uni_keys = list(self.uni.keys()) self.bi_keys = list(self.bi.keys()) self.words = [i[-1] for i in self.bi_keys] def prob(self, t1: str, t2: str) -> float: """ probability word :param int t1: text 1 :param int t2: text 2 :return: probability value :rtype: float """ try: v = self.bi[(t1, t2)] / self.uni[t1] except ZeroDivisionError: v = 0.0 return v def gen_sentence( self, start_seq: str = None, N: int = 4, prob: float = 0.001, output_str: bool = True, duplicate: bool = False ) -> Union[List[str], str]: """ :param str start_seq: word for begin word. :param int N: number of word. :param bool output_str: output is str :param bool duplicate: duplicate word in sent :return: list words or str words :rtype: List[str], str :Example: :: from pythainlp.generate import Bigram gen = Bigram() gen.gen_sentence("แมว") # ouput: 'แมวไม่ได้รับเชื้อมัน' """ if start_seq is None: start_seq = random.choice(self.words) self.late_word = start_seq self.list_word = [] self.list_word.append(start_seq) for i in range(N): if duplicate: self._temp = [ j for j in self.bi_keys if j[0] == self.late_word ] else: self._temp = [ j for j in self.bi_keys if j[0] == self.late_word and j[1] not in self.list_word ] self._probs = [ self.prob( self.late_word, next_word[-1] ) for next_word in self._temp ] self._p2 = [j for j in self._probs if j >= prob] if len(self._p2) == 0: break self.items = self._temp[self._probs.index(random.choice(self._p2))] self.late_word = self.items[-1] self.list_word.append(self.late_word) if output_str: return ''.join(self.list_word) return self.list_word class Trigram: """ Text generator using Trigram :param str name: corpus name * *tnc* - Thai National Corpus (default) """ def __init__(self, name: str = "tnc"): if name == "tnc": self.uni = tnc_word_freqs_unigram() self.bi = tnc_word_freqs_bigram() self.ti = tnc_word_freqs_trigram() self.uni_keys = list(self.uni.keys()) self.bi_keys = list(self.bi.keys()) self.ti_keys = list(self.ti.keys()) self.words = [i[-1] for i in self.bi_keys] def prob(self, t1: str, t2: str, t3: str) -> float: """ probability word :param int t1: text 1 :param int t2: text 2 :param int t3: text 3 :return: probability value :rtype: float """ try: v = self.ti[(t1, t2, t3)] / self.bi[(t1, t2)] except ZeroDivisionError: v = 0.0 return v def gen_sentence( self, start_seq: str = None, N: int = 4, prob: float = 0.001, output_str: bool = True, duplicate: bool = False ) -> Union[List[str], str]: """ :param str start_seq: word for begin word. :param int N: number of word. :param bool output_str: output is str :param bool duplicate: duplicate word in sent :return: list words or str words :rtype: List[str], str :Example: :: from pythainlp.generate import Trigram gen = Trigram() gen.gen_sentence() # ouput: 'ยังทำตัวเป็นเซิร์ฟเวอร์คือ' """ if start_seq is None: start_seq = random.choice(self.bi_keys) self.late_word = start_seq self.list_word = [] self.list_word.append(start_seq) for i in range(N): if duplicate: self._temp = [ j for j in self.ti_keys if j[:2] == self.late_word ] else: self._temp = [ j for j in self.ti_keys if j[:2] == self.late_word and j[1:] not in self.list_word ] self._probs = [ self.prob(word[0], word[1], word[2]) for word in self._temp ] self._p2 = [j for j in self._probs if j >= prob] if len(self._p2) == 0: break self.items = self._temp[self._probs.index(random.choice(self._p2))] self.late_word = self.items[1:] self.list_word.append(self.late_word) self.listdata = [] for i in self.list_word: for j in i: if j not in self.listdata: self.listdata.append(j) if output_str: return ''.join(self.listdata) return self.listdata
4,628
1,080
<filename>neutron/objects/port/extensions/port_security.py # 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. from neutron.db.port_security import models from neutron.objects import base from neutron.objects.extensions import port_security as base_ps @base.NeutronObjectRegistry.register class PortSecurity(base_ps._PortSecurity): # Version 1.0: Initial version VERSION = "1.0" fields_need_translation = {'id': 'port_id'} db_model = models.PortSecurityBinding
306
1,540
package test.enable; import org.testng.annotations.Test; @Test public class Issue420SecondSample extends Issue420BaseTestCase { @Test public void verifySomethingSecondSample() {} }
53
2,993
<filename>wifi-users.py from __future__ import print_function import subprocess import re import sys import argparse import os from collections import defaultdict import netifaces from netaddr import EUI, mac_unix_expanded from wireless import Wireless from tqdm import tqdm NO_SSID = 'No SSID is currently available. Connect to the network first.' NO_WIRELESS = 'Error getting wireless interface.' NO_GATEWAY_MAC = 'Error getting gateway MAC address.' def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def run_process(cmd, err=False): err_pipe = subprocess.STDOUT if err else open(os.devnull, 'w') p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=err_pipe) while True: retcode = p.poll() line = p.stdout.readline() yield line if retcode is not None: break def main(args): parser = argparse.ArgumentParser( description='Find active users on the current wireless network.') parser.add_argument('-p', '--packets', default=1000, type=int, help='How many packets to capture.') parser.add_argument('-i', '--interface', default=None, type=str, help='Which wireless interface to use.') parser.add_argument('-s', '--ssid', default=None, type=str, help='Which SSID to use.') parser.add_argument('-r', '--results', default=None, type=int, help='How many results to show.') args = parser.parse_args() try: if args.interface: iface = args.interface else: wireless = Wireless() ifaces = wireless.interfaces() eprint('Available interfaces: {}'.format(', '.join(ifaces))) iface = ifaces[-1] eprint('Interface: {}'.format(iface)) if args.ssid: ssid = args.ssid else: wireless = Wireless() ssid = wireless.current() if ssid is None: eprint(NO_SSID) return eprint('SSID: {}'.format(ssid)) except: eprint(NO_WIRELESS) raise mac_re_str = '([\dA-F]{2}:){5}[\dA-F]{2}' mac_re = re.compile(mac_re_str, re.I) network_macs = set() try: gws = netifaces.gateways()[netifaces.AF_INET] gw_ifaces = ', '.join([gw[1] for gw in gws]) eprint('Available gateways: {}'.format(gw_ifaces)) gw_ip = next(gw[0] for gw in gws if gw[1] == iface) eprint('Gateway IP: {}'.format(gw_ip)) gw_arp = subprocess.check_output(['arp', '-n', str(gw_ip)]) gw_arp = gw_arp.decode('utf-8') gw_mac = EUI(mac_re.search(gw_arp).group(0)) gw_mac.dialect = mac_unix_expanded network_macs.add(gw_mac) eprint('Gateway MAC: {}'.format(gw_mac)) except StopIteration: eprint('No gateway for {}'.format(iface)) except KeyError: eprint('No gateways available: {}'.format(netifaces.gateways())) except: eprint(NO_GATEWAY_MAC) bssid_re = re.compile(' BSSID:(\S+) ') tcpdump_mac_re = re.compile('(SA|DA|BSSID):(' + mac_re_str + ')', re.I) length_re = re.compile(' length (\d+)') client_macs = set() data_totals = defaultdict(int) cmd = 'tcpdump -i {} -Ile -c {} -s 0'.format(iface, args.packets).split() try: bar_format = '{n_fmt}/{total_fmt} {bar} {remaining}' progress = tqdm(run_process(cmd), total=args.packets, bar_format=bar_format) for line in progress: line = line.decode('utf-8') # find BSSID for SSID if ssid in line: bssid_matches = bssid_re.search(line) if bssid_matches: bssid = bssid_matches.group(1) if 'Broadcast' not in bssid: network_macs.add(EUI(bssid)) # count data packets length_match = length_re.search(line) if length_match: length = int(length_match.group(1)) mac_matches = tcpdump_mac_re.findall(line) if mac_matches: macs = set([EUI(match[1]) for match in mac_matches]) leftover = macs - network_macs if len(leftover) < len(macs): for mac in leftover: data_totals[mac] += length client_macs.add(mac) if progress.n < progress.total: eprint('Sniffing finished early.') except subprocess.CalledProcessError: eprint('Error collecting packets.') raise except KeyboardInterrupt: pass totals_sorted = sorted(data_totals.items(), key=lambda x: x[1], reverse=True) eprint('Total of {} user(s)'.format(len(totals_sorted))) for mac, total in reversed(totals_sorted[:args.results]): mac.dialect = mac_unix_expanded if total > 0: print('{}\t{} bytes'.format(mac, total)) if __name__ == '__main__': from sys import argv try: main(argv) except KeyboardInterrupt: pass sys.exit()
2,799
3,670
<reponame>jakee417/probability-1 # Copyright 2020 The TensorFlow Probability Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Computes log-ratios of Jacobian determinants numerically stably.""" import inspect import tensorflow.compat.v2 as tf from tensorflow_probability.python.bijectors import bijector as bijector_lib from tensorflow_probability.python.internal import prefer_static as ps __all__ = [ 'forward_log_det_jacobian_ratio', 'inverse_log_det_jacobian_ratio', 'RegisterFLDJRatio', 'RegisterILDJRatio', ] _fldj_ratio_registry = {} _ildj_ratio_registry = {} def _reduce_ldj_ratio(unreduced_ldj_ratio, p, q, input_shape, min_event_ndims, event_ndims): """Reduces an LDJ ratio computed with event_ndims=min_event_ndims.""" # pylint: disable=protected-access have_parameter_batch_shape = ( p._parameter_batch_shape is not None and q._parameter_batch_shape is not None) if have_parameter_batch_shape: parameter_batch_shape = ps.broadcast_shape(p._parameter_batch_shape, q._parameter_batch_shape) else: parameter_batch_shape = None reduce_shape, assertions = bijector_lib.ldj_reduction_shape( input_shape, event_ndims=event_ndims, min_event_ndims=min_event_ndims, parameter_batch_shape=parameter_batch_shape, allow_event_shape_broadcasting=not (p._parts_interact or q._parts_interact), validate_args=p.validate_args or q.validate_args) sum_fn = getattr(p, '_sum_fn', getattr(q, '_sum_fn', tf.reduce_sum)) with tf.control_dependencies(assertions): return bijector_lib.reduce_jacobian_det_over_shape( unreduced_ldj_ratio, reduce_shape=reduce_shape, sum_fn=sum_fn) def _default_fldj_ratio_fn(p, x, q, y, event_ndims, p_kwargs, q_kwargs): min_event_ndims = p.forward_min_event_ndims unreduced_fldj_ratio = ( p.forward_log_det_jacobian(x, event_ndims=min_event_ndims, **p_kwargs) - q.forward_log_det_jacobian(y, event_ndims=min_event_ndims, **q_kwargs)) return _reduce_ldj_ratio(unreduced_fldj_ratio, p, q, ps.shape(x), min_event_ndims, event_ndims) def _default_ildj_ratio_fn(p, x, q, y, event_ndims, p_kwargs, q_kwargs): min_event_ndims = p.inverse_min_event_ndims unreduced_fldj_ratio = ( p.inverse_log_det_jacobian(x, event_ndims=min_event_ndims, **p_kwargs) - q.inverse_log_det_jacobian(y, event_ndims=min_event_ndims, **q_kwargs)) return _reduce_ldj_ratio(unreduced_fldj_ratio, p, q, ps.shape(x), min_event_ndims, event_ndims) def _get_ldj_ratio_fn(cls, registry): ldj_ratio_fn = None for ref_cls in inspect.getmro(cls): if ref_cls in registry: ldj_ratio_fn = registry[ref_cls] break return ldj_ratio_fn def forward_log_det_jacobian_ratio( p, x, q, y, event_ndims, p_kwargs=None, q_kwargs=None, ): """Computes `p.fldj(x, ndims) - q.fdlj(y, ndims)`, numerically stably. `p_kwargs` and `q_kwargs` are passed to the registered `fldj_ratio_fn`. The fallback implementation passes them to the `forward_log_det_jacobian` methods of `p` and `q`. Args: p: A bijector instance. x: A tensor from the preimage of `p.forward`. q: A bijector instance of the same type as `p`, with matching shape. y: A tensor from the preimage of `q.forward`. event_ndims: The number of right-hand dimensions comprising the event shapes of `x` and `y`. p_kwargs: Keyword args to pass to `p`. q_kwargs: Keyword args to pass to `q`. Returns: fldj_ratio: `log ((abs o det o jac p)(x) / (abs o det o jac q)(y))`, i.e. in TFP code, `p.forward_log_det_jacobian(x, event_ndims) - q.forward_log_det_jacobian(y, event_ndims)`. In some cases this will be computed with better than naive numerical precision, e.g. by moving differences inside of a sum reduction. """ assert type(p) == type(q) # pylint: disable=unidiomatic-typecheck if p_kwargs is None: p_kwargs = {} if q_kwargs is None: q_kwargs = {} fldj_ratio_fn = _get_ldj_ratio_fn(type(p), registry=_fldj_ratio_registry) ildj_ratio_fn = _get_ldj_ratio_fn(type(p), registry=_ildj_ratio_registry) def inverse_fldj_ratio_fn(p, x, q, y, event_ndims, p_kwargs, q_kwargs): # p.fldj(x) - q.fldj(y) = q.ildj(q(y)) - p.ildj(p(x)) return ildj_ratio_fn(q, q.forward(y), p, p.forward(x), q.forward_event_ndims(event_ndims), q_kwargs, p_kwargs) if fldj_ratio_fn is None: if ildj_ratio_fn is None: fldj_ratio_fn = _default_fldj_ratio_fn else: fldj_ratio_fn = inverse_fldj_ratio_fn return fldj_ratio_fn(p, x, q, y, event_ndims, p_kwargs, q_kwargs) def inverse_log_det_jacobian_ratio( p, x, q, y, event_ndims, p_kwargs=None, q_kwargs=None, ): """Computes `p.ildj(x, ndims) - q.idlj(y, ndims)`, numerically stably. `p_kwargs` and `q_kwargs` are passed to the registered `ildj_ratio_fn`. The fallback implementation passes them to the `inverse_log_det_jacobian` methods of `p` and `q`. Args: p: A bijector instance. x: A tensor from the image of `p.forward`. q: A bijector instance of the same type as `p`, with matching shape. y: A tensor from the image of `q.forward`. event_ndims: The number of right-hand dimensions comprising the event shapes of `x` and `y`. p_kwargs: Keyword args to pass to `p`. q_kwargs: Keyword args to pass to `q`. Returns: ildj_ratio: `log ((abs o det o jac p^-1)(x) / (abs o det o jac q^-1)(y))`, i.e. in TFP code, `p.inverse_log_det_jacobian(x, event_ndims) - q.inverse_log_det_jacobian(y, event_ndims)`. In some cases this will be computed with better than naive numerical precision, e.g. by moving differences inside of a sum reduction. """ assert type(p) == type(q) # pylint: disable=unidiomatic-typecheck if p_kwargs is None: p_kwargs = {} if q_kwargs is None: q_kwargs = {} ildj_ratio_fn = _get_ldj_ratio_fn(type(p), registry=_ildj_ratio_registry) fldj_ratio_fn = _get_ldj_ratio_fn(type(p), registry=_fldj_ratio_registry) def inverse_ildj_ratio_fn(p, x, q, y, event_ndims, p_kwargs, q_kwargs): # p.ildj(x) - q.ildj(y) = q.fldj(q^-1(y)) - p.fldj(p^-1(x)) return fldj_ratio_fn(q, q.inverse(y), p, p.inverse(x), q.inverse_event_ndims(event_ndims), q_kwargs, p_kwargs) if ildj_ratio_fn is None: if fldj_ratio_fn is None: ildj_ratio_fn = _default_ildj_ratio_fn else: ildj_ratio_fn = inverse_ildj_ratio_fn return ildj_ratio_fn(p, x, q, y, event_ndims, p_kwargs, q_kwargs) class RegisterFLDJRatio(object): def __init__(self, bijector_class): self.cls = bijector_class def __call__(self, fn): assert self.cls not in _fldj_ratio_registry _fldj_ratio_registry[self.cls] = fn return fn class RegisterILDJRatio(object): def __init__(self, bijector_class): self.cls = bijector_class def __call__(self, fn): assert self.cls not in _ildj_ratio_registry _ildj_ratio_registry[self.cls] = fn return fn
3,426
994
<reponame>cnm06/Competitive-Programming from collections import deque def valid(v, a, b): if a >= 0 and a < 8 and b >= 0 and b < 8: if v[a][b] == 0: return True return False return False def getPoint(n): return divmod(n, 8); def answer(a, b): a = getPoint(a) b = getPoint(b) v = [] for i in range(0, 8): t = [] for j in range(0, 8): t.append(0) v.append(t) q = deque() q.append(a) ans = 0 t = 0 while len(q) > 0: s = len(q) for i in range(0, s): r = q.popleft() #print r v[r[0]][r[1]] = 1 if r[0] == b[0] and r[1] == b[1]: return ans x = r[0] y = r[1] if valid(v, x+2, y+1): q.append([x+2, y+1]) if valid(v, x-2, y+1): q.append([x-2, y+1]) if valid(v, x+2, y-1): q.append([x+2, y-1]) if valid(v, x-2, y-1): q.append([x-2, y-1]) if valid(v, x+1, y+2): q.append([x+1, y+2]) if valid(v, x-1, y+2): q.append([x-1, y+2]) if valid(v, x+1, y-2): q.append([x+1, y-2]) if valid(v, x-1, y-2): q.append([x-1, y-2]) ans = ans + 1 print answer(19, 36) print answer(0, 1) print answer(0, 63) print answer(0, 8)
633
841
<reponame>brunolmfg/resteasy package org.jboss.resteasy.test.asynch.resource; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import jakarta.ws.rs.ext.Provider; import org.jboss.resteasy.spi.ContextInjector; @Provider public class AsyncInjectionContextInjector implements ContextInjector<CompletionStage<AsyncInjectionContext>, AsyncInjectionContext> { @Override public CompletionStage<AsyncInjectionContext> resolve( Class<? extends CompletionStage<AsyncInjectionContext>> rawType, Type genericType, Annotation[] annotations) { boolean async = false; boolean error = false; for (Annotation annotation : annotations) { if(annotation.annotationType() == AsyncInjectionContextAsyncSpecifier.class) { async = true; break; } if(annotation.annotationType() == AsyncInjectionContextErrorSpecifier.class) { error = true; break; } } if(async) { CompletableFuture<AsyncInjectionContext> ret = new CompletableFuture<>(); boolean finalError = error; new Thread(() -> { try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } if(finalError) ret.completeExceptionally(new AsyncInjectionException("Async exception")); else ret.complete(new AsyncInjectionContext()); }).start(); return ret; } if(error) { CompletableFuture<AsyncInjectionContext> ret = new CompletableFuture<>(); ret.completeExceptionally(new AsyncInjectionException("Async exception")); return ret; } return CompletableFuture.completedFuture(new AsyncInjectionContext()); } }
854
6,132
from . import SimLibrary from .. import SIM_PROCEDURES as P from ...calling_conventions import SimCCStdcall, SimCCMicrosoftAMD64 from ...sim_type import SimTypeFunction, SimTypeLong, SimTypeLongLong lib = SimLibrary() lib.set_library_names('kernel32.dll') lib.add_all_from_dict(P['win32']) lib.set_default_cc('X86', SimCCStdcall) lib.set_default_cc('AMD64', SimCCMicrosoftAMD64) lib.add_alias('EncodePointer', 'DecodePointer') lib.add_alias('GlobalAlloc', 'LocalAlloc') lib.add('lstrcatA', P['libc']['strcat']) lib.add('lstrcmpA', P['libc']['strcmp']) lib.add('lstrcpyA', P['libc']['strcpy']) lib.add('lstrcpynA', P['libc']['strncpy']) lib.add('lstrlenA', P['libc']['strlen']) lib.add('lstrcmpW', P['libc']['wcscmp']) lib.add('lstrcmpiW', P['libc']['wcscasecmp']) prototypes = { "AcquireSRWLockExclusive": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "AcquireSRWLockShared": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "ActivateActCtx": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "AddAtomA": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "AddAtomW": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "AddConsoleAliasA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "AddConsoleAliasW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "AddIntegrityLabelToBoundaryDescriptor": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "AddLocalAlternateComputerNameA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "AddLocalAlternateComputerNameW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "AddRefActCtx": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "AddSIDToBoundaryDescriptor": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "AddSecureMemoryCacheCallback": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "AddVectoredContinueHandler": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "AddVectoredExceptionHandler": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "AdjustCalendarDate": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "AllocConsole": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "AllocateUserPhysicalPages": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "AllocateUserPhysicalPagesNuma": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "ApplicationRecoveryFinished": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "ApplicationRecoveryInProgress": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "AreFileApisANSI": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "AssignProcessToJobObject": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "AttachConsole": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "BackupRead": SimTypeFunction((SimTypeLong(),)*7, SimTypeLong()), "BackupSeek": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "BackupWrite": SimTypeFunction((SimTypeLong(),)*7, SimTypeLong()), "BaseCheckAppcompatCache": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "BaseCheckAppcompatCacheEx": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "BaseCheckRunApp": SimTypeFunction((SimTypeLong(),)*13, SimTypeLong()), "BaseCleanupAppcompatCacheSupport": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "BaseDllReadWriteIniFile": SimTypeFunction((SimTypeLong(),)*8, SimTypeLong()), "BaseDumpAppcompatCache": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "BaseFlushAppcompatCache": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "BaseFormatObjectAttributes": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "BaseFormatTimeOut": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "BaseGenerateAppCompatData": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "BaseGetNamedObjectDirectory": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "BaseInitAppcompatCacheSupport": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "BaseIsAppcompatInfrastructureDisabled": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "BaseQueryModuleData": SimTypeFunction((SimTypeLong(),)*7, SimTypeLong()), "BaseSetLastNTError": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "BaseThreadInitThunk": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "BaseUpdateAppcompatCache": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "BaseVerifyUnicodeString": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "Basep8BitStringToDynamicUnicodeString": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "BasepAllocateActivationContextActivationBlock": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "BasepAnsiStringToDynamicUnicodeString": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "BasepCheckAppCompat": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "BasepCheckBadapp": SimTypeFunction((SimTypeLong(),)*15, SimTypeLong()), "BasepCheckWinSaferRestrictions": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "BasepFreeActivationContextActivationBlock": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "BasepFreeAppCompatData": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "BasepMapModuleHandle": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "Beep": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "BeginUpdateResourceA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "BeginUpdateResourceW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "BindIoCompletionCallback": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "BuildCommDCBA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "BuildCommDCBAndTimeoutsA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "BuildCommDCBAndTimeoutsW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "BuildCommDCBW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "CallNamedPipeA": SimTypeFunction((SimTypeLong(),)*7, SimTypeLong()), "CallNamedPipeW": SimTypeFunction((SimTypeLong(),)*7, SimTypeLong()), "CallbackMayRunLong": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "CancelDeviceWakeupRequest": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "CancelIo": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "CancelIoEx": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "CancelSynchronousIo": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "CancelThreadpoolIo": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "CancelTimerQueueTimer": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "CancelWaitableTimer": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "ChangeTimerQueueTimer": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "CheckElevation": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "CheckElevationEnabled": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "CheckForReadOnlyResource": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "CheckNameLegalDOS8Dot3A": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "CheckNameLegalDOS8Dot3W": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "CheckRemoteDebuggerPresent": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "ClearCommBreak": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "ClearCommError": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "CloseConsoleHandle": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "CloseHandle": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "ClosePrivateNamespace": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "CloseProfileUserMapping": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "CloseThreadpool": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "CloseThreadpoolCleanupGroup": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "CloseThreadpoolCleanupGroupMembers": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "CloseThreadpoolIo": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "CloseThreadpoolTimer": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "CloseThreadpoolWait": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "CloseThreadpoolWork": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "CmdBatNotification": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "CommConfigDialogA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "CommConfigDialogW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "CompareCalendarDates": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "CompareFileTime": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "CompareStringA": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "CompareStringEx": SimTypeFunction((SimTypeLong(),)*9, SimTypeLong()), "CompareStringOrdinal": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "CompareStringW": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "ConnectNamedPipe": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "ConsoleMenuControl": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "ContinueDebugEvent": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "ConvertCalDateTimeToSystemTime": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "ConvertDefaultLocale": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "ConvertFiberToThread": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "ConvertNLSDayOfWeekToWin32DayOfWeek": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "ConvertSystemTimeToCalDateTime": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "ConvertThreadToFiber": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "ConvertThreadToFiberEx": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "CopyContext": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "CopyFileA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "CopyFileExA": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "CopyFileExW": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "CopyFileTransactedA": SimTypeFunction((SimTypeLong(),)*7, SimTypeLong()), "CopyFileTransactedW": SimTypeFunction((SimTypeLong(),)*7, SimTypeLong()), "CopyFileW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "CopyLZFile": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "CreateActCtxA": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "CreateActCtxW": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "CreateBoundaryDescriptorA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "CreateBoundaryDescriptorW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "CreateConsoleScreenBuffer": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "CreateDirectoryA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "CreateDirectoryExA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "CreateDirectoryExW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "CreateDirectoryTransactedA": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "CreateDirectoryTransactedW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "CreateDirectoryW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "CreateEventA": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "CreateEventExA": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "CreateEventExW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "CreateEventW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "CreateFiber": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "CreateFiberEx": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "CreateFileA": SimTypeFunction((SimTypeLong(),)*7, SimTypeLong()), "CreateFileMappingA": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "CreateFileMappingNumaA": SimTypeFunction((SimTypeLong(),)*7, SimTypeLong()), "CreateFileMappingNumaW": SimTypeFunction((SimTypeLong(),)*7, SimTypeLong()), "CreateFileMappingW": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "CreateFileTransactedA": SimTypeFunction((SimTypeLong(),)*10, SimTypeLong()), "CreateFileTransactedW": SimTypeFunction((SimTypeLong(),)*10, SimTypeLong()), "CreateFileW": SimTypeFunction((SimTypeLong(),)*7, SimTypeLong()), "CreateHardLinkA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "CreateHardLinkTransactedA": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "CreateHardLinkTransactedW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "CreateHardLinkW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "CreateIoCompletionPort": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "CreateJobObjectA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "CreateJobObjectW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "CreateJobSet": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "CreateMailslotA": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "CreateMailslotW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "CreateMemoryResourceNotification": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "CreateMutexA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "CreateMutexExA": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "CreateMutexExW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "CreateMutexW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "CreateNamedPipeA": SimTypeFunction((SimTypeLong(),)*8, SimTypeLong()), "CreateNamedPipeW": SimTypeFunction((SimTypeLong(),)*8, SimTypeLong()), "CreatePipe": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "CreatePrivateNamespaceA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "CreatePrivateNamespaceW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "CreateProcessA": SimTypeFunction((SimTypeLong(),)*10, SimTypeLong()), "CreateProcessAsUserW": SimTypeFunction((SimTypeLong(),)*11, SimTypeLong()), "CreateProcessInternalA": SimTypeFunction((SimTypeLong(),)*12, SimTypeLong()), "CreateProcessInternalW": SimTypeFunction((SimTypeLong(),)*12, SimTypeLong()), "CreateProcessW": SimTypeFunction((SimTypeLong(),)*10, SimTypeLong()), "CreateRemoteThread": SimTypeFunction((SimTypeLong(),)*7, SimTypeLong()), "CreateRemoteThreadEx": SimTypeFunction((SimTypeLong(),)*8, SimTypeLong()), "CreateSemaphoreA": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "CreateSemaphoreExA": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "CreateSemaphoreExW": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "CreateSemaphoreW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "CreateSocketHandle": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "CreateSymbolicLinkA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "CreateSymbolicLinkTransactedA": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "CreateSymbolicLinkTransactedW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "CreateSymbolicLinkW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "CreateTapePartition": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "CreateThread": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "CreateThreadpool": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "CreateThreadpoolCleanupGroup": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "CreateThreadpoolIo": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "CreateThreadpoolTimer": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "CreateThreadpoolWait": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "CreateThreadpoolWork": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "CreateTimerQueue": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "CreateTimerQueueTimer": SimTypeFunction((SimTypeLong(),)*7, SimTypeLong()), "CreateToolhelp32Snapshot": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "CreateWaitableTimerA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "CreateWaitableTimerExA": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "CreateWaitableTimerExW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "CreateWaitableTimerW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "CtrlRoutine": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "DeactivateActCtx": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "DebugActiveProcess": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "DebugActiveProcessStop": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "DebugBreak": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "DebugBreakProcess": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "DebugSetProcessKillOnExit": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "DecodePointer": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "DecodeSystemPointer": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "DefineDosDeviceA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "DefineDosDeviceW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "DelayLoadFailureHook": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "DeleteAtom": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "DeleteBoundaryDescriptor": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "DeleteCriticalSection": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "DeleteFiber": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "DeleteFileA": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "DeleteFileTransactedA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "DeleteFileTransactedW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "DeleteFileW": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "DeleteProcThreadAttributeList": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "DeleteTimerQueue": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "DeleteTimerQueueEx": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "DeleteTimerQueueTimer": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "DeleteVolumeMountPointA": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "DeleteVolumeMountPointW": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "DeviceIoControl": SimTypeFunction((SimTypeLong(),)*8, SimTypeLong()), "DisableThreadLibraryCalls": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "DisableThreadProfiling": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "DisassociateCurrentThreadFromCallback": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "DisconnectNamedPipe": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "DnsHostnameToComputerNameA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "DnsHostnameToComputerNameW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "DosDateTimeToFileTime": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "DosPathToSessionPathA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "DosPathToSessionPathW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "DuplicateConsoleHandle": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "DuplicateHandle": SimTypeFunction((SimTypeLong(),)*7, SimTypeLong()), "EnableThreadProfiling": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "EncodePointer": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "EncodeSystemPointer": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "EndUpdateResourceA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "EndUpdateResourceW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "EnterCriticalSection": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "EnumCalendarInfoA": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "EnumCalendarInfoExA": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "EnumCalendarInfoExEx": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "EnumCalendarInfoExW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "EnumCalendarInfoW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "EnumDateFormatsA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "EnumDateFormatsExA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "EnumDateFormatsExEx": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "EnumDateFormatsExW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "EnumDateFormatsW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "EnumLanguageGroupLocalesA": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "EnumLanguageGroupLocalesW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "EnumResourceLanguagesA": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "EnumResourceLanguagesExA": SimTypeFunction((SimTypeLong(),)*7, SimTypeLong()), "EnumResourceLanguagesExW": SimTypeFunction((SimTypeLong(),)*7, SimTypeLong()), "EnumResourceLanguagesW": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "EnumResourceNamesA": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "EnumResourceNamesExA": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "EnumResourceNamesExW": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "EnumResourceNamesW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "EnumResourceTypesA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "EnumResourceTypesExA": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "EnumResourceTypesExW": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "EnumResourceTypesW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "EnumSystemCodePagesA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "EnumSystemCodePagesW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "EnumSystemFirmwareTables": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "EnumSystemGeoID": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "EnumSystemLanguageGroupsA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "EnumSystemLanguageGroupsW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "EnumSystemLocalesA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "EnumSystemLocalesEx": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "EnumSystemLocalesW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "EnumTimeFormatsA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "EnumTimeFormatsEx": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "EnumTimeFormatsW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "EnumUILanguagesA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "EnumUILanguagesW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "EnumerateLocalComputerNamesA": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "EnumerateLocalComputerNamesW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "EraseTape": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "EscapeCommFunction": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "ExitProcess": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "ExitThread": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "ExitVDM": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "ExpandEnvironmentStringsA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "ExpandEnvironmentStringsW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "ExpungeConsoleCommandHistoryA": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "ExpungeConsoleCommandHistoryW": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "FatalAppExitA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "FatalAppExitW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "FatalExit": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "FileTimeToDosDateTime": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "FileTimeToLocalFileTime": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "FileTimeToSystemTime": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "FillConsoleOutputAttribute": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "FillConsoleOutputCharacterA": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "FillConsoleOutputCharacterW": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "FindActCtxSectionGuid": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "FindActCtxSectionStringA": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "FindActCtxSectionStringW": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "FindAtomA": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "FindAtomW": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "FindClose": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "FindCloseChangeNotification": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "FindFirstChangeNotificationA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "FindFirstChangeNotificationW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "FindFirstFileA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "FindFirstFileExA": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "FindFirstFileExW": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "FindFirstFileNameTransactedW": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "FindFirstFileNameW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "FindFirstFileTransactedA": SimTypeFunction((SimTypeLong(),)*7, SimTypeLong()), "FindFirstFileTransactedW": SimTypeFunction((SimTypeLong(),)*7, SimTypeLong()), "FindFirstFileW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "FindFirstStreamTransactedW": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "FindFirstStreamW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "FindFirstVolumeA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "FindFirstVolumeMountPointA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "FindFirstVolumeMountPointW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "FindFirstVolumeW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "FindNLSString": SimTypeFunction((SimTypeLong(),)*7, SimTypeLong()), "FindNLSStringEx": SimTypeFunction((SimTypeLong(),)*10, SimTypeLong()), "FindNextChangeNotification": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "FindNextFileA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "FindNextFileNameW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "FindNextFileW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "FindNextStreamW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "FindNextVolumeA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "FindNextVolumeMountPointA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "FindNextVolumeMountPointW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "FindNextVolumeW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "FindResourceA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "FindResourceExA": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "FindResourceExW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "FindResourceW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "FindStringOrdinal": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "FindVolumeClose": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "FindVolumeMountPointClose": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "FlsAlloc": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "FlsFree": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "FlsGetValue": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "FlsSetValue": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "FlushConsoleInputBuffer": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "FlushFileBuffers": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "FlushInstructionCache": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "FlushProcessWriteBuffers": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "FlushViewOfFile": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "FoldStringA": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "FoldStringW": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "FormatMessageA": SimTypeFunction((SimTypeLong(),)*7, SimTypeLong()), "FormatMessageW": SimTypeFunction((SimTypeLong(),)*7, SimTypeLong()), "FreeConsole": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "FreeEnvironmentStringsA": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "FreeEnvironmentStringsW": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "FreeLibrary": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "FreeLibraryAndExitThread": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "FreeLibraryWhenCallbackReturns": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "FreeResource": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "FreeUserPhysicalPages": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GenerateConsoleCtrlEvent": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetACP": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "GetActiveProcessorCount": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetActiveProcessorGroupCount": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "GetApplicationRecoveryCallback": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "GetApplicationRestartSettings": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "GetAtomNameA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetAtomNameW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetBinaryType": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetBinaryTypeA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetBinaryTypeW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetCPInfo": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetCPInfoExA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetCPInfoExW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetCalendarDateFormat": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "GetCalendarDateFormatEx": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "GetCalendarDaysInMonth": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "GetCalendarDifferenceInDays": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetCalendarInfoA": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "GetCalendarInfoEx": SimTypeFunction((SimTypeLong(),)*7, SimTypeLong()), "GetCalendarInfoW": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "GetCalendarMonthsInYear": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetCalendarSupportedDateRange": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetCalendarWeekNumber": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "GetComPlusPackageInstallStatus": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "GetCommConfig": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetCommMask": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetCommModemStatus": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetCommProperties": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetCommState": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetCommTimeouts": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetCommandLineA": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "GetCommandLineW": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "GetCompressedFileSizeA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetCompressedFileSizeTransactedA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetCompressedFileSizeTransactedW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetCompressedFileSizeW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetComputerNameA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetComputerNameExA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetComputerNameExW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetComputerNameW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetConsoleAliasA": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "GetConsoleAliasExesA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetConsoleAliasExesLengthA": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "GetConsoleAliasExesLengthW": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "GetConsoleAliasExesW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetConsoleAliasW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "GetConsoleAliasesA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetConsoleAliasesLengthA": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetConsoleAliasesLengthW": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetConsoleAliasesW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetConsoleCP": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "GetConsoleCharType": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetConsoleCommandHistoryA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetConsoleCommandHistoryLengthA": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetConsoleCommandHistoryLengthW": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetConsoleCommandHistoryW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetConsoleCursorInfo": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetConsoleCursorMode": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetConsoleDisplayMode": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetConsoleFontInfo": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "GetConsoleFontSize": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetConsoleHardwareState": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetConsoleHistoryInfo": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetConsoleInputExeNameA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetConsoleInputExeNameW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetConsoleInputWaitHandle": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "GetConsoleKeyboardLayoutNameA": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetConsoleKeyboardLayoutNameW": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetConsoleMode": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetConsoleNlsMode": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetConsoleOriginalTitleA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetConsoleOriginalTitleW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetConsoleOutputCP": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "GetConsoleProcessList": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetConsoleScreenBufferInfo": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetConsoleScreenBufferInfoEx": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetConsoleSelectionInfo": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetConsoleTitleA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetConsoleTitleW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetConsoleWindow": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "GetCurrencyFormatA": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "GetCurrencyFormatEx": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "GetCurrencyFormatW": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "GetCurrentActCtx": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetCurrentConsoleFont": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetCurrentConsoleFontEx": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetCurrentDirectoryA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetCurrentDirectoryW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetCurrentProcess": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "GetCurrentProcessId": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "GetCurrentProcessorNumber": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "GetCurrentProcessorNumberEx": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetCurrentThread": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "GetCurrentThreadId": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "GetDateFormatA": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "GetDateFormatEx": SimTypeFunction((SimTypeLong(),)*7, SimTypeLong()), "GetDateFormatW": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "GetDefaultCommConfigA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetDefaultCommConfigW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetDevicePowerState": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetDiskFreeSpaceA": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "GetDiskFreeSpaceExA": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "GetDiskFreeSpaceExW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "GetDiskFreeSpaceW": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "GetDllDirectoryA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetDllDirectoryW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetDriveTypeA": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetDriveTypeW": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetDurationFormat": SimTypeFunction((SimTypeLong(),)*8, SimTypeLong()), "GetDurationFormatEx": SimTypeFunction((SimTypeLong(),)*8, SimTypeLong()), "GetDynamicTimeZoneInformation": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetEnabledXStateFeatures": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "GetEnvironmentStrings": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "GetEnvironmentStringsA": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "GetEnvironmentStringsW": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "GetEnvironmentVariableA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetEnvironmentVariableW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetEraNameCountedString": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "GetErrorMode": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "GetExitCodeProcess": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetExitCodeThread": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetExpandedNameA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetExpandedNameW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetFileAttributesA": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetFileAttributesExA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetFileAttributesExW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetFileAttributesTransactedA": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "GetFileAttributesTransactedW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "GetFileAttributesW": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetFileBandwidthReservation": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "GetFileInformationByHandle": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetFileInformationByHandleEx": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "GetFileMUIInfo": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "GetFileMUIPath": SimTypeFunction((SimTypeLong(),)*7, SimTypeLong()), "GetFileSize": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetFileSizeEx": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetFileTime": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "GetFileType": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetFinalPathNameByHandleA": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "GetFinalPathNameByHandleW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "GetFirmwareEnvironmentVariableA": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "GetFirmwareEnvironmentVariableW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "GetFullPathNameA": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "GetFullPathNameTransactedA": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "GetFullPathNameTransactedW": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "GetFullPathNameW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "GetGeoInfoA": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "GetGeoInfoW": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "GetHandleContext": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetHandleInformation": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetLargePageMinimum": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "GetLargestConsoleWindowSize": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetLastError": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "GetLocalTime": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetLocaleInfoA": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "GetLocaleInfoEx": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "GetLocaleInfoW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "GetLogicalDriveStringsA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetLogicalDriveStringsW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetLogicalDrives": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "GetLogicalProcessorInformation": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetLogicalProcessorInformationEx": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetLongPathNameA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetLongPathNameTransactedA": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "GetLongPathNameTransactedW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "GetLongPathNameW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetMailslotInfo": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "GetMaximumProcessorCount": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetMaximumProcessorGroupCount": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "GetModuleFileNameA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetModuleFileNameW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetModuleHandleA": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetModuleHandleExA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetModuleHandleExW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetModuleHandleW": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetNLSVersion": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetNLSVersionEx": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetNamedPipeAttribute": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "GetNamedPipeClientComputerNameA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetNamedPipeClientComputerNameW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetNamedPipeClientProcessId": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetNamedPipeClientSessionId": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetNamedPipeHandleStateA": SimTypeFunction((SimTypeLong(),)*7, SimTypeLong()), "GetNamedPipeHandleStateW": SimTypeFunction((SimTypeLong(),)*7, SimTypeLong()), "GetNamedPipeInfo": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "GetNamedPipeServerProcessId": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetNamedPipeServerSessionId": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetNativeSystemInfo": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetNextVDMCommand": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetNumaAvailableMemoryNode": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetNumaAvailableMemoryNodeEx": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetNumaHighestNodeNumber": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetNumaNodeNumberFromHandle": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetNumaNodeProcessorMask": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetNumaNodeProcessorMaskEx": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetNumaProcessorNode": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetNumaProcessorNodeEx": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetNumaProximityNode": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetNumaProximityNodeEx": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetNumberFormatA": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "GetNumberFormatEx": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "GetNumberFormatW": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "GetNumberOfConsoleFonts": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "GetNumberOfConsoleInputEvents": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetNumberOfConsoleMouseButtons": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetOEMCP": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "GetOverlappedResult": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "GetPhysicallyInstalledSystemMemory": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetPriorityClass": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetPrivateProfileIntA": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "GetPrivateProfileIntW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "GetPrivateProfileSectionA": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "GetPrivateProfileSectionNamesA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetPrivateProfileSectionNamesW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetPrivateProfileSectionW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "GetPrivateProfileStringA": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "GetPrivateProfileStringW": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "GetPrivateProfileStructA": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "GetPrivateProfileStructW": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "GetProcAddress": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetProcessAffinityMask": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetProcessDEPPolicy": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetProcessGroupAffinity": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetProcessHandleCount": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetProcessHeap": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "GetProcessHeaps": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetProcessId": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetProcessIdOfThread": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetProcessIoCounters": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetProcessPreferredUILanguages": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "GetProcessPriorityBoost": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetProcessShutdownParameters": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetProcessTimes": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "GetProcessUserModeExceptionPolicy": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetProcessVersion": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetProcessWorkingSetSize": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetProcessWorkingSetSizeEx": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "GetProcessorSystemCycleTime": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetProductInfo": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "GetProfileIntA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetProfileIntW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetProfileSectionA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetProfileSectionW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetProfileStringA": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "GetProfileStringW": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "GetQueuedCompletionStatus": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "GetQueuedCompletionStatusEx": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "GetShortPathNameA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetShortPathNameW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetStartupInfoA": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetStartupInfoW": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetStdHandle": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetStringScripts": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "GetStringTypeA": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "GetStringTypeExA": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "GetStringTypeExW": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "GetStringTypeW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "GetSystemDEPPolicy": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "GetSystemDefaultLCID": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "GetSystemDefaultLangID": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "GetSystemDefaultLocaleName": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetSystemDefaultUILanguage": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "GetSystemDirectoryA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetSystemDirectoryW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetSystemFileCacheSize": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetSystemFirmwareTable": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "GetSystemInfo": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetSystemPowerStatus": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetSystemPreferredUILanguages": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "GetSystemRegistryQuota": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetSystemTime": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetSystemTimeAdjustment": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetSystemTimeAsFileTime": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetSystemTimes": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetSystemWindowsDirectoryA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetSystemWindowsDirectoryW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetSystemWow64DirectoryA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetSystemWow64DirectoryW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetTapeParameters": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "GetTapePosition": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "GetTapeStatus": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetTempFileNameA": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "GetTempFileNameW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "GetTempPathA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetTempPathW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetThreadContext": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetThreadErrorMode": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "GetThreadGroupAffinity": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetThreadIOPendingFlag": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetThreadId": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetThreadIdealProcessorEx": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetThreadLocale": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "GetThreadPreferredUILanguages": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "GetThreadPriority": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetThreadPriorityBoost": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetThreadSelectorEntry": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetThreadTimes": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "GetThreadUILanguage": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "GetTickCount": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "GetTickCount64": SimTypeFunction((SimTypeLong(),)*0, SimTypeLongLong()), "GetTimeFormatA": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "GetTimeFormatEx": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "GetTimeFormatW": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "GetTimeZoneInformation": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetTimeZoneInformationForYear": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetUILanguageInfo": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "GetUserDefaultLCID": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "GetUserDefaultLangID": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "GetUserDefaultLocaleName": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetUserDefaultUILanguage": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "GetUserGeoID": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetUserPreferredUILanguages": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "GetVDMCurrentDirectories": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetVersion": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "GetVersionExA": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetVersionExW": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GetVolumeInformationA": SimTypeFunction((SimTypeLong(),)*8, SimTypeLong()), "GetVolumeInformationByHandleW": SimTypeFunction((SimTypeLong(),)*8, SimTypeLong()), "GetVolumeInformationW": SimTypeFunction((SimTypeLong(),)*8, SimTypeLong()), "GetVolumeNameForVolumeMountPointA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetVolumeNameForVolumeMountPointW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetVolumePathNameA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetVolumePathNameW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GetVolumePathNamesForVolumeNameA": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "GetVolumePathNamesForVolumeNameW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "GetWindowsDirectoryA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetWindowsDirectoryW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GetWriteWatch": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "GetXStateFeaturesMask": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GlobalAddAtomA": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GlobalAddAtomW": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GlobalAlloc": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "GlobalCompact": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GlobalDeleteAtom": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GlobalFindAtomA": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GlobalFindAtomW": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GlobalFix": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GlobalFlags": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GlobalFree": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GlobalGetAtomNameA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GlobalGetAtomNameW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GlobalHandle": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GlobalLock": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GlobalMemoryStatus": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GlobalMemoryStatusEx": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GlobalReAlloc": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "GlobalSize": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GlobalUnWire": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GlobalUnfix": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GlobalUnlock": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "GlobalWire": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "Heap32First": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "Heap32ListFirst": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "Heap32ListNext": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "Heap32Next": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "HeapAlloc": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "HeapCompact": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "HeapCreate": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "HeapDestroy": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "HeapFree": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "HeapLock": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "HeapQueryInformation": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "HeapReAlloc": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "HeapSetInformation": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "HeapSize": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "HeapSummary": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "HeapUnlock": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "HeapValidate": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "HeapWalk": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "IdnToAscii": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "IdnToNameprepUnicode": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "IdnToUnicode": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "InitAtomTable": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "InitOnceBeginInitialize": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "InitOnceComplete": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "InitOnceExecuteOnce": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "InitOnceInitialize": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "InitializeConditionVariable": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "InitializeContext": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "InitializeCriticalSection": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "InitializeCriticalSectionAndSpinCount": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "InitializeCriticalSectionEx": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "InitializeProcThreadAttributeList": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "InitializeSListHead": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "InitializeSRWLock": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "InterlockedCompareExchange": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "InterlockedCompareExchange64": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "InterlockedDecrement": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "InterlockedExchange": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "InterlockedExchangeAdd": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "InterlockedFlushSList": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "InterlockedIncrement": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "InterlockedPopEntrySList": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "InterlockedPushEntrySList": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "InterlockedPushListSList": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "InvalidateConsoleDIBits": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "IsBadCodePtr": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "IsBadHugeReadPtr": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "IsBadHugeWritePtr": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "IsBadReadPtr": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "IsBadStringPtrA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "IsBadStringPtrW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "IsBadWritePtr": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "IsCalendarLeapDay": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "IsCalendarLeapMonth": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "IsCalendarLeapYear": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "IsDBCSLeadByte": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "IsDBCSLeadByteEx": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "IsDebuggerPresent": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "IsNLSDefinedString": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "IsNormalizedString": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "IsProcessInJob": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "IsProcessorFeaturePresent": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "IsSystemResumeAutomatic": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "IsThreadAFiber": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "IsThreadpoolTimerSet": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "IsTimeZoneRedirectionEnabled": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "IsValidCalDateTime": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "IsValidCodePage": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "IsValidLanguageGroup": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "IsValidLocale": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "IsValidLocaleName": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "IsWow64Process": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "K32EmptyWorkingSet": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "K32EnumDeviceDrivers": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "K32EnumPageFilesA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "K32EnumPageFilesW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "K32EnumProcessModules": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "K32EnumProcessModulesEx": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "K32EnumProcesses": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "K32GetDeviceDriverBaseNameA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "K32GetDeviceDriverBaseNameW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "K32GetDeviceDriverFileNameA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "K32GetDeviceDriverFileNameW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "K32GetMappedFileNameA": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "K32GetMappedFileNameW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "K32GetModuleBaseNameA": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "K32GetModuleBaseNameW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "K32GetModuleFileNameExA": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "K32GetModuleFileNameExW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "K32GetModuleInformation": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "K32GetPerformanceInfo": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "K32GetProcessImageFileNameA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "K32GetProcessImageFileNameW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "K32GetProcessMemoryInfo": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "K32GetWsChanges": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "K32GetWsChangesEx": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "K32InitializeProcessForWsWatch": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "K32QueryWorkingSet": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "K32QueryWorkingSetEx": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "LCIDToLocaleName": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "LCMapStringA": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "LCMapStringEx": SimTypeFunction((SimTypeLong(),)*9, SimTypeLong()), "LCMapStringW": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "LZClose": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "LZCloseFile": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "LZCopy": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "LZCreateFileW": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "LZDone": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "LZInit": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "LZOpenFileA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "LZOpenFileW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "LZRead": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "LZSeek": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "LZStart": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "LeaveCriticalSection": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "LeaveCriticalSectionWhenCallbackReturns": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "LoadAppInitDlls": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "LoadLibraryA": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "LoadLibraryExA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "LoadLibraryExW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "LoadLibraryW": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "LoadModule": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "LoadResource": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "LoadStringBaseExW": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "LoadStringBaseW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "LocalAlloc": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "LocalCompact": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "LocalFileTimeToFileTime": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "LocalFlags": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "LocalFree": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "LocalHandle": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "LocalLock": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "LocalReAlloc": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "LocalShrink": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "LocalSize": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "LocalUnlock": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "LocaleNameToLCID": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "LocateXStateFeature": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "LockFile": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "LockFileEx": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "LockResource": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "MapUserPhysicalPages": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "MapUserPhysicalPagesScatter": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "MapViewOfFile": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "MapViewOfFileEx": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "MapViewOfFileExNuma": SimTypeFunction((SimTypeLong(),)*7, SimTypeLong()), "Module32First": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "Module32FirstW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "Module32Next": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "Module32NextW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "MoveFileA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "MoveFileExA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "MoveFileExW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "MoveFileTransactedA": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "MoveFileTransactedW": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "MoveFileW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "MoveFileWithProgressA": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "MoveFileWithProgressW": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "MulDiv": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "MultiByteToWideChar": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "NeedCurrentDirectoryForExePathA": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "NeedCurrentDirectoryForExePathW": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "NlsCheckPolicy": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "NlsEventDataDescCreate": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "NlsGetCacheUpdateCount": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "NlsUpdateLocale": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "NlsUpdateSystemLocale": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "NlsWriteEtwEvent": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "NormalizeString": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "NotifyMountMgr": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "NotifyUILanguageChange": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "OpenConsoleW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "OpenEventA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "OpenEventW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "OpenFile": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "OpenFileById": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "OpenFileMappingA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "OpenFileMappingW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "OpenJobObjectA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "OpenJobObjectW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "OpenMutexA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "OpenMutexW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "OpenPrivateNamespaceA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "OpenPrivateNamespaceW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "OpenProcess": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "OpenProcessToken": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "OpenProfileUserMapping": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "OpenSemaphoreA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "OpenSemaphoreW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "OpenThread": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "OpenThreadToken": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "OpenWaitableTimerA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "OpenWaitableTimerW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "OutputDebugStringA": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "OutputDebugStringW": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "PeekConsoleInputA": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "PeekConsoleInputW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "PeekNamedPipe": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "PostQueuedCompletionStatus": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "PowerClearRequest": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "PowerCreateRequest": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "PowerSetRequest": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "PrepareTape": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "PrivCopyFileExW": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "PrivMoveFileIdentityW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "Process32First": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "Process32FirstW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "Process32Next": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "Process32NextW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "ProcessIdToSessionId": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "PulseEvent": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "PurgeComm": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "QueryActCtxSettingsW": SimTypeFunction((SimTypeLong(),)*7, SimTypeLong()), "QueryActCtxW": SimTypeFunction((SimTypeLong(),)*7, SimTypeLong()), "QueryDepthSList": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "QueryDosDeviceA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "QueryDosDeviceW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "QueryFullProcessImageNameA": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "QueryFullProcessImageNameW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "QueryIdleProcessorCycleTime": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "QueryIdleProcessorCycleTimeEx": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "QueryInformationJobObject": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "QueryMemoryResourceNotification": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "QueryPerformanceCounter": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "QueryPerformanceFrequency": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "QueryProcessAffinityUpdateMode": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "QueryProcessCycleTime": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "QueryThreadCycleTime": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "QueryThreadProfiling": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "QueryThreadpoolStackInformation": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "QueryUnbiasedInterruptTime": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "QueueUserAPC": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "QueueUserWorkItem": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "RaiseException": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "RaiseFailFastException": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "ReOpenFile": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "ReadConsoleA": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "ReadConsoleInputA": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "ReadConsoleInputExA": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "ReadConsoleInputExW": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "ReadConsoleInputW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "ReadConsoleOutputA": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "ReadConsoleOutputAttribute": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "ReadConsoleOutputCharacterA": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "ReadConsoleOutputCharacterW": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "ReadConsoleOutputW": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "ReadConsoleW": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "ReadDirectoryChangesW": SimTypeFunction((SimTypeLong(),)*8, SimTypeLong()), "ReadFile": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "ReadFileEx": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "ReadFileScatter": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "ReadProcessMemory": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "ReadThreadProfilingData": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "RegCloseKey": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "RegCreateKeyExA": SimTypeFunction((SimTypeLong(),)*9, SimTypeLong()), "RegCreateKeyExW": SimTypeFunction((SimTypeLong(),)*9, SimTypeLong()), "RegDeleteKeyExA": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "RegDeleteKeyExW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "RegDeleteTreeA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "RegDeleteTreeW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "RegDeleteValueA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "RegDeleteValueW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "RegDisablePredefinedCacheEx": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "RegEnumKeyExA": SimTypeFunction((SimTypeLong(),)*8, SimTypeLong()), "RegEnumKeyExW": SimTypeFunction((SimTypeLong(),)*8, SimTypeLong()), "RegEnumValueA": SimTypeFunction((SimTypeLong(),)*8, SimTypeLong()), "RegEnumValueW": SimTypeFunction((SimTypeLong(),)*8, SimTypeLong()), "RegFlushKey": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "RegGetKeySecurity": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "RegGetValueA": SimTypeFunction((SimTypeLong(),)*7, SimTypeLong()), "RegGetValueW": SimTypeFunction((SimTypeLong(),)*7, SimTypeLong()), "RegKrnGetGlobalState": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "RegKrnInitialize": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "RegLoadKeyA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "RegLoadKeyW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "RegLoadMUIStringA": SimTypeFunction((SimTypeLong(),)*7, SimTypeLong()), "RegLoadMUIStringW": SimTypeFunction((SimTypeLong(),)*7, SimTypeLong()), "RegNotifyChangeKeyValue": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "RegOpenCurrentUser": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "RegOpenKeyExA": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "RegOpenKeyExW": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "RegOpenUserClassesRoot": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "RegQueryInfoKeyA": SimTypeFunction((SimTypeLong(),)*12, SimTypeLong()), "RegQueryInfoKeyW": SimTypeFunction((SimTypeLong(),)*12, SimTypeLong()), "RegQueryValueExA": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "RegQueryValueExW": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "RegRestoreKeyA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "RegRestoreKeyW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "RegSaveKeyExA": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "RegSaveKeyExW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "RegSetKeySecurity": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "RegSetValueExA": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "RegSetValueExW": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "RegUnLoadKeyA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "RegUnLoadKeyW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "RegisterApplicationRecoveryCallback": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "RegisterApplicationRestart": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "RegisterConsoleIME": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "RegisterConsoleOS2": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "RegisterConsoleVDM": SimTypeFunction((SimTypeLong(),)*9, SimTypeLong()), "RegisterWaitForInputIdle": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "RegisterWaitForSingleObject": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "RegisterWaitForSingleObjectEx": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "RegisterWowBaseHandlers": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "RegisterWowExec": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "ReleaseActCtx": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "ReleaseMutex": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "ReleaseMutexWhenCallbackReturns": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "ReleaseSRWLockExclusive": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "ReleaseSRWLockShared": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "ReleaseSemaphore": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "ReleaseSemaphoreWhenCallbackReturns": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "RemoveDirectoryA": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "RemoveDirectoryTransactedA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "RemoveDirectoryTransactedW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "RemoveDirectoryW": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "RemoveLocalAlternateComputerNameA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "RemoveLocalAlternateComputerNameW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "RemoveSecureMemoryCacheCallback": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "RemoveVectoredContinueHandler": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "RemoveVectoredExceptionHandler": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "ReplaceFile": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "ReplaceFileA": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "ReplaceFileW": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "ReplacePartitionUnit": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "RequestDeviceWakeup": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "RequestWakeupLatency": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "ResetEvent": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "ResetWriteWatch": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "ResolveLocaleName": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "RestoreLastError": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "ResumeThread": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "RtlCaptureContext": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "RtlCaptureStackBackTrace": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "RtlFillMemory": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "RtlMoveMemory": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "RtlUnwind": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "RtlZeroMemory": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "ScrollConsoleScreenBufferA": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "ScrollConsoleScreenBufferW": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "SearchPathA": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "SearchPathW": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "SetCalendarInfoA": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "SetCalendarInfoW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "SetClientTimeZoneInformation": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SetComPlusPackageInstallStatus": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SetCommBreak": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SetCommConfig": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "SetCommMask": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetCommState": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetCommTimeouts": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetComputerNameA": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SetComputerNameExA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetComputerNameExW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetComputerNameW": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SetConsoleActiveScreenBuffer": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SetConsoleCP": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SetConsoleCtrlHandler": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetConsoleCursor": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetConsoleCursorInfo": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetConsoleCursorMode": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "SetConsoleCursorPosition": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetConsoleDisplayMode": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "SetConsoleFont": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetConsoleHardwareState": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "SetConsoleHistoryInfo": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SetConsoleIcon": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SetConsoleInputExeNameA": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SetConsoleInputExeNameW": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SetConsoleKeyShortcuts": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "SetConsoleLocalEUDC": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "SetConsoleMaximumWindowSize": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetConsoleMenuClose": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SetConsoleMode": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetConsoleNlsMode": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetConsoleNumberOfCommandsA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetConsoleNumberOfCommandsW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetConsoleOS2OemFormat": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SetConsoleOutputCP": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SetConsolePalette": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "SetConsoleScreenBufferInfoEx": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetConsoleScreenBufferSize": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetConsoleTextAttribute": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetConsoleTitleA": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SetConsoleTitleW": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SetConsoleWindowInfo": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "SetCriticalSectionSpinCount": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetCurrentConsoleFontEx": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "SetCurrentDirectoryA": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SetCurrentDirectoryW": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SetDefaultCommConfigA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "SetDefaultCommConfigW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "SetDllDirectoryA": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SetDllDirectoryW": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SetDynamicTimeZoneInformation": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SetEndOfFile": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SetEnvironmentStringsA": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SetEnvironmentStringsW": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SetEnvironmentVariableA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetEnvironmentVariableW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetErrorMode": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SetEvent": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SetEventWhenCallbackReturns": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetFileApisToANSI": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "SetFileApisToOEM": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "SetFileAttributesA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetFileAttributesTransactedA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "SetFileAttributesTransactedW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "SetFileAttributesW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetFileBandwidthReservation": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "SetFileCompletionNotificationModes": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetFileInformationByHandle": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "SetFileIoOverlappedRange": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "SetFilePointer": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "SetFilePointerEx": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "SetFileShortNameA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetFileShortNameW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetFileTime": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "SetFileValidData": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "SetFirmwareEnvironmentVariableA": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "SetFirmwareEnvironmentVariableW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "SetHandleContext": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetHandleCount": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SetHandleInformation": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "SetInformationJobObject": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "SetLastConsoleEventActive": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "SetLastError": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SetLocalPrimaryComputerNameA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetLocalPrimaryComputerNameW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetLocalTime": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SetLocaleInfoA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "SetLocaleInfoW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "SetMailslotInfo": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetMessageWaitingIndicator": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetNamedPipeAttribute": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "SetNamedPipeHandleState": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "SetPriorityClass": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetProcessAffinityMask": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetProcessAffinityUpdateMode": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetProcessDEPPolicy": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SetProcessPreferredUILanguages": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "SetProcessPriorityBoost": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetProcessShutdownParameters": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetProcessUserModeExceptionPolicy": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SetProcessWorkingSetSize": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "SetProcessWorkingSetSizeEx": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "SetSearchPathMode": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SetStdHandle": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetStdHandleEx": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "SetSystemFileCacheSize": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "SetSystemPowerState": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetSystemTime": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SetSystemTimeAdjustment": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetTapeParameters": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "SetTapePosition": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "SetTermsrvAppInstallMode": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SetThreadAffinityMask": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetThreadContext": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetThreadErrorMode": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetThreadExecutionState": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SetThreadGroupAffinity": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "SetThreadIdealProcessor": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetThreadIdealProcessorEx": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "SetThreadLocale": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SetThreadPreferredUILanguages": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "SetThreadPriority": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetThreadPriorityBoost": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetThreadStackGuarantee": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SetThreadToken": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetThreadUILanguage": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SetThreadpoolStackInformation": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetThreadpoolThreadMaximum": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetThreadpoolThreadMinimum": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetThreadpoolTimer": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "SetThreadpoolWait": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "SetTimeZoneInformation": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SetTimerQueueTimer": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "SetUnhandledExceptionFilter": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SetUserGeoID": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SetVDMCurrentDirectories": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetVolumeLabelA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetVolumeLabelW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetVolumeMountPointA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetVolumeMountPointW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SetWaitableTimer": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "SetXStateFeaturesMask": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "SetupComm": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "ShowConsoleCursor": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SignalObjectAndWait": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "SizeofResource": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "Sleep": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SleepConditionVariableCS": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "SleepConditionVariableSRW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "SleepEx": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SortCloseHandle": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SortGetHandle": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "StartThreadpoolIo": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SubmitThreadpoolWork": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SuspendThread": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SwitchToFiber": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "SwitchToThread": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "SystemTimeToFileTime": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "SystemTimeToTzSpecificLocalTime": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "TerminateJobObject": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "TerminateProcess": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "TerminateThread": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "TermsrvAppInstallMode": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "Thread32First": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "Thread32Next": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "TlsAlloc": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "TlsFree": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "TlsGetValue": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "TlsSetValue": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "Toolhelp32ReadProcessMemory": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "TransactNamedPipe": SimTypeFunction((SimTypeLong(),)*7, SimTypeLong()), "TransmitCommChar": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "TryAcquireSRWLockExclusive": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "TryAcquireSRWLockShared": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "TryEnterCriticalSection": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "TrySubmitThreadpoolCallback": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "TzSpecificLocalTimeToSystemTime": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "UTRegister": SimTypeFunction((SimTypeLong(),)*7, SimTypeLong()), "UTUnRegister": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "UnhandledExceptionFilter": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "UnlockFile": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "UnlockFileEx": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "UnmapViewOfFile": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "UnregisterApplicationRecoveryCallback": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "UnregisterApplicationRestart": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "UnregisterConsoleIME": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "UnregisterWait": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "UnregisterWaitEx": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "UpdateCalendarDayOfWeek": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "UpdateProcThreadAttribute": SimTypeFunction((SimTypeLong(),)*7, SimTypeLong()), "UpdateResourceA": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "UpdateResourceW": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "VDMConsoleOperation": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "VDMOperationStarted": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "VerLanguageNameA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "VerLanguageNameW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "VerSetConditionMask": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "VerifyConsoleIoHandle": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "VerifyScripts": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "VerifyVersionInfoA": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "VerifyVersionInfoW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "VirtualAlloc": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "VirtualAllocEx": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "VirtualAllocExNuma": SimTypeFunction((SimTypeLong(),)*6, SimTypeLong()), "VirtualFree": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "VirtualFreeEx": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "VirtualLock": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "VirtualProtect": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "VirtualProtectEx": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "VirtualQuery": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "VirtualQueryEx": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "VirtualUnlock": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "WTSGetActiveConsoleSessionId": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "WaitCommEvent": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "WaitForDebugEvent": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "WaitForMultipleObjects": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "WaitForMultipleObjectsEx": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "WaitForSingleObject": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "WaitForSingleObjectEx": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "WaitForThreadpoolIoCallbacks": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "WaitForThreadpoolTimerCallbacks": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "WaitForThreadpoolWaitCallbacks": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "WaitForThreadpoolWorkCallbacks": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "WaitNamedPipeA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "WaitNamedPipeW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "WakeAllConditionVariable": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "WakeConditionVariable": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "WerGetFlags": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "WerRegisterFile": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "WerRegisterMemoryBlock": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "WerRegisterRuntimeExceptionModule": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "WerSetFlags": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "WerUnregisterFile": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "WerUnregisterMemoryBlock": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "WerUnregisterRuntimeExceptionModule": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "WerpCleanupMessageMapping": SimTypeFunction((SimTypeLong(),)*0, SimTypeLong()), "WerpInitiateRemoteRecovery": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "WerpNotifyLoadStringResource": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "WerpNotifyLoadStringResourceEx": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "WerpNotifyUseStringResource": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "WerpStringLookup": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "WideCharToMultiByte": SimTypeFunction((SimTypeLong(),)*8, SimTypeLong()), "WinExec": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "Wow64DisableWow64FsRedirection": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "Wow64EnableWow64FsRedirection": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "Wow64GetThreadContext": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "Wow64GetThreadSelectorEntry": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "Wow64RevertWow64FsRedirection": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "Wow64SetThreadContext": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "Wow64SuspendThread": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "WriteConsoleA": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "WriteConsoleInputA": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "WriteConsoleInputVDMA": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "WriteConsoleInputVDMW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "WriteConsoleInputW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "WriteConsoleOutputA": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "WriteConsoleOutputAttribute": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "WriteConsoleOutputCharacterA": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "WriteConsoleOutputCharacterW": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "WriteConsoleOutputW": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "WriteConsoleW": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "WriteFile": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "WriteFileEx": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "WriteFileGather": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "WritePrivateProfileSectionA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "WritePrivateProfileSectionW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "WritePrivateProfileStringA": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "WritePrivateProfileStringW": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "WritePrivateProfileStructA": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "WritePrivateProfileStructW": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "WriteProcessMemory": SimTypeFunction((SimTypeLong(),)*5, SimTypeLong()), "WriteProfileSectionA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "WriteProfileSectionW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "WriteProfileStringA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "WriteProfileStringW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "WriteTapemark": SimTypeFunction((SimTypeLong(),)*4, SimTypeLong()), "ZombifyActCtx": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "_hread": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "_hwrite": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "_lclose": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "_lcreat": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "_llseek": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "_lopen": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "_lread": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "_lwrite": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "lstrcat": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "lstrcatA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "lstrcatW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "lstrcmp": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "lstrcmpA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "lstrcmpW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "lstrcmpi": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "lstrcmpiA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "lstrcmpiW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "lstrcpy": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "lstrcpyA": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "lstrcpyW": SimTypeFunction((SimTypeLong(),)*2, SimTypeLong()), "lstrcpyn": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "lstrcpynA": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "lstrcpynW": SimTypeFunction((SimTypeLong(),)*3, SimTypeLong()), "lstrlen": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "lstrlenA": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()), "lstrlenW": SimTypeFunction((SimTypeLong(),)*1, SimTypeLong()) } lib.set_prototypes(prototypes)
36,799
336
/** * @file wsl_bypasser.h * @author risinek (<EMAIL>) * @date 2021-04-05 * @copyright Copyright (c) 2021 * * @brief Provides interface for Wi-Fi Stack Libraries bypasser * * This component bypasses blocking mechanism that doesn't allow sending some arbitrary 802.11 frames like deauth etc. */ #ifndef WSL_BYPASSER_H #define WSL_BYPASSER_H #include "esp_wifi_types.h" /** * @brief Sends frame in frame_buffer using esp_wifi_80211_tx but bypasses blocking mechanism * * @param frame_buffer * @param size size of frame buffer */ void wsl_bypasser_send_raw_frame(const uint8_t *frame_buffer, int size); /** * @brief Sends deauthentication frame with forged source AP from given ap_record * * This will send deauthentication frame acting as frame from given AP, and destination will be broadcast * MAC address - \c ff:ff:ff:ff:ff:ff * * @param ap_record AP record with valid AP information */ void wsl_bypasser_send_deauth_frame(const wifi_ap_record_t *ap_record); #endif
326
310
{ "name": "Zwoptex", "description": "A 2D sprite-packing tool.", "url": "https://zwopple.com/zwoptex/" }
48
379
from .meter import AverageMeter, ROCMeter from .optimizer import get_lr_scheduler from .optimizer import get_optimizer
35
332
#!/usr/bin/env python # -*- coding: utf-8 -*- """A basic demonstration of how to traverse the instances of a USD stage.""" # IMPORT THIRD-PARTY LIBRARIES from pxr import Gf, Sdf, Usd def create_basic_instance_stage(): """A USD stage that has instanced Prims on it. Reference: https://graphics.pixar.com/usd/docs/api/_usd__page__scenegraph_instancing.html#Usd_ScenegraphInstancing_Querying Returns: `pxr.Usd.Stage`: The generated, in-memory object. """ stage = Usd.Stage.CreateInMemory() car = stage.CreateClassPrim("/Car") car.CreateAttribute("color", Sdf.ValueTypeNames.Color3f).Set(Gf.Vec3f([0, 0, 0])) body = stage.DefinePrim("/Car/Body") body.CreateAttribute("color", Sdf.ValueTypeNames.Color3f).Set(Gf.Vec3f([0, 0, 0])) stage.DefinePrim("/Car/Door") paths = ("/ParkingLot/Car_1", "/ParkingLot/Car_2", "/ParkingLot/Car_n") for path in paths: prim = stage.DefinePrim(path) prim.SetInstanceable(True) prim.GetReferences().AddReference(assetPath="", primPath=car.GetPath()) return stage def traverse_instanced_children(prim): """Get every Prim child beneath `prim`, even if `prim` is instanced. Important: If `prim` is instanced, any child that this function yields will be an instance proxy. Args: prim (`pxr.Usd.Prim`): Some Prim to check for children. Yields: `pxr.Usd.Prim`: The children of `prim`. """ for child in prim.GetFilteredChildren(Usd.TraverseInstanceProxies()): yield child for subchild in traverse_instanced_children(child): yield subchild def main(): """Run the main execution of the current script.""" stage = create_basic_instance_stage() all_uninstanced_prims = list(stage.TraverseAll()) all_prims_including_instanced_child_prims = sorted( traverse_instanced_children(stage.GetPseudoRoot()) ) print( 'The instanced Prims list found "{number}" more Prims than TraverseAll.'.format( number=len(all_prims_including_instanced_child_prims) - len(all_uninstanced_prims) ) ) for prim in all_prims_including_instanced_child_prims: print(prim) if __name__ == "__main__": main()
924
53,007
import os from pathlib import Path import pytest from fastapi.testclient import TestClient @pytest.fixture(scope="module") def client(): static_dir: Path = Path(os.getcwd()) / "static" print(static_dir) static_dir.mkdir(exist_ok=True) from docs_src.extending_openapi.tutorial002 import app with TestClient(app) as client: yield client static_dir.rmdir() def test_swagger_ui_html(client: TestClient): response = client.get("/docs") assert response.status_code == 200, response.text assert "/static/swagger-ui-bundle.js" in response.text assert "/static/swagger-ui.css" in response.text def test_swagger_ui_oauth2_redirect_html(client: TestClient): response = client.get("/docs/oauth2-redirect") assert response.status_code == 200, response.text assert "window.opener.swaggerUIRedirectOauth2" in response.text def test_redoc_html(client: TestClient): response = client.get("/redoc") assert response.status_code == 200, response.text assert "/static/redoc.standalone.js" in response.text def test_api(client: TestClient): response = client.get("/users/john") assert response.status_code == 200, response.text assert response.json()["message"] == "Hello john"
442
423
import torch from torch import Tensor import torch._decomp from typing import Tuple, List, Optional aten = torch.ops.aten decomposition_table = torch._decomp.decomposition_table register_decomposition = torch._decomp.register_decomposition get_decompositions = torch._decomp.get_decompositions # Decompositions have been ported to torch._decomp inside of PyTorch core. The only decompositions here are temporary or hacks. Please submit your contributions to PyTorch core! def maybe_register_decomposition(op): def decorator(f): try: return register_decomposition(op)(f) except Exception: return f return decorator # Functions where we need a special decomposition for jvp but there's another version that # should be used more generally (ex. for jvp we need to recompute the mean and variance for # the backwards of a normalization function. Without jvp, it should used the saved value) decomposition_table_for_jvp = {} def register_decomposition_for_jvp(fn): return register_decomposition(fn, registry=decomposition_table_for_jvp) @maybe_register_decomposition(aten.trace.default) def trace(self: Tensor) -> Tensor: return torch.sum(torch.diag(self)) @maybe_register_decomposition(aten.log_sigmoid_forward.default) def log_sigmoid_forward(self: Tensor) -> Tuple[Tensor, Tensor]: min = torch.minimum(self.new_zeros(()), self) z = torch.exp(-torch.abs(self)) if self.is_cuda: buffer = self.new_zeros((0,)) else: buffer = z return min - torch.log1p(z), buffer @register_decomposition_for_jvp(aten.native_layer_norm_backward) def native_layer_norm_backward( grad_out: Tensor, input: Tensor, normalized_shape: List[int], mean: Tensor, rstd: Tensor, weight: Optional[Tensor], bias: Optional[Tensor], output_mask: List[bool], ) -> Tuple[Optional[Tensor], Optional[Tensor], Optional[Tensor]]: input_shape = input.shape input_ndim = input.dim() axis = input_ndim - len(normalized_shape) inner_dims = input_shape[axis:] outer_dims = input_shape[:axis] inner_dim_indices = list(range(axis, input_ndim)) outer_dim_indices = list(range(0, axis)) N = 1 for i in inner_dims: N *= i M = 1 for i in outer_dims: M *= i if M <= 0 or N <= 0: return ( input.new_zeros(input_shape), input.new_zeros(input_shape[axis:]), input.new_zeros(input_shape[axis:]), ) # this is exactly the same as the other decomposition except for here. We recompute the mean and variance # so that they track gradients through input mean_ = torch.mean(input, dim=inner_dim_indices, keepdim=True) var = torch.var(input, dim=inner_dim_indices, unbiased=False, keepdim=True) eps = torch.pow(1 / rstd, 2) - var # this makes me so sad inside eps = eps.detach() rstd_ = 1 / torch.sqrt(var + eps) x_hat = (input - mean_) * rstd_ if weight is not None: grad_x_hat = grad_out * weight else: grad_x_hat = grad_out a = grad_x_hat * N b = torch.sum(grad_x_hat, inner_dim_indices, True) c1 = torch.mul(grad_x_hat, x_hat) c2 = torch.sum(c1, inner_dim_indices, True) c3 = torch.mul(x_hat, c2) inner = a - b - c3 if output_mask[0]: d_input: Optional[Tensor] = (rstd_ / N) * inner else: d_input = torch.zeros_like(input) # should be None but doesn't work with vjp if output_mask[1] and weight is not None: if len(outer_dim_indices) > 0: d_weight: Optional[Tensor] = torch.sum( grad_out * x_hat, outer_dim_indices, False ) else: d_weight = grad_out * x_hat elif weight is not None: d_weight = torch.zeros_like(weight) # should be None but doesn't work with vjp else: d_weight = torch.zeros(()) # should be None but doesn't work with vjp if output_mask[2] and bias is not None: if len(outer_dim_indices) > 0: d_bias: Optional[Tensor] = torch.sum(grad_out, outer_dim_indices, False) else: d_bias = grad_out elif bias is not None: d_bias = torch.zeros_like(bias) # should be None but doesn't work with vjp else: d_bias = torch.zeros(()) # should be None but doesn't work with vjp return (d_input, d_weight, d_bias)
1,813
460
#include "../../../src/xmlpatterns/data/qatomicmathematician_p.h"
26
2,406
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <gtest/gtest.h> #include <gmock/gmock.h> #include <gmock/gmock-spec-builders.h> #include <file_utils.h> #include <memory> #include <common_test_utils/test_assertions.hpp> #include <details/ie_so_pointer.hpp> #include <cpp_interfaces/interface/ie_iplugin_internal.hpp> using namespace InferenceEngine; using namespace InferenceEngine::details; using namespace ::testing; using ::testing::InSequence; namespace InferenceEngine { namespace details { struct UnknownPlugin : std::enable_shared_from_this<UnknownPlugin> {}; template<> class SOCreatorTrait<InferenceEngine::details::UnknownPlugin> { public: static constexpr auto name = "CreateUnknownPlugin"; }; } // namespace details } // namespace InferenceEngine class SoPointerTests : public ::testing::Test {}; TEST_F(SoPointerTests, UnknownPlugin) { ASSERT_THROW(SOPointer<InferenceEngine::details::UnknownPlugin>{std::string{"UnknownPlugin"}}, Exception); } TEST_F(SoPointerTests, UnknownPluginExceptionStr) { try { SOPointer<InferenceEngine::details::UnknownPlugin>(std::string{"UnknownPlugin"}); } catch (Exception &e) { ASSERT_STR_CONTAINS(e.what(), "Cannot load library 'UnknownPlugin':"); ASSERT_STR_DOES_NOT_CONTAIN(e.what(), "path:"); ASSERT_STR_DOES_NOT_CONTAIN(e.what(), "from CWD:"); } }
508
344
#include "disassembler.h" #include "base/commandlineflags.h" #include "gtest/gtest.h" #define FLAGS_test_tmpdir std::string(testing::UnitTest::GetInstance()->original_working_dir()) #define FLAGS_test_srcdir std::string(testing::UnitTest::GetInstance()->original_working_dir()) namespace { class DisassemblerTest : public testing::Test { }; class TestDisassembler : public devtools_crosstool_autofdo::Disassembler { public: std::map<uint64, uint64> call_target_map_; std::map<uint64, uint64> cjmp_target_map_; std::map<uint64, uint64> djmp_target_map_; std::map<uint64, std::vector<uint64> > idjmp_targets_map_; std::vector<uint64> terminators_; std::set<uint64> GetAddrs() { return addr_set_; } protected: void HandleConditionalJump(uint64 addr, uint64 fall_through, uint64 target) override { cjmp_target_map_[addr] = target; } void HandleUnconditionalJump(uint64 addr, uint64 target) override { djmp_target_map_[addr] = target; } void HandleDirectCall(uint64 addr, uint64 target) override { call_target_map_[addr] = target; } void HandleIndirectJump(uint64 addr, std::vector<uint64> targets) override { idjmp_targets_map_[addr] = targets; } void HandleTerminator(uint64 addr) override { terminators_.push_back(addr); } }; TEST_F(DisassemblerTest, DisassembleTest) { TestDisassembler d; CHECK(d.Init(FLAGS_test_srcdir + "/testdata/test.binary")); EXPECT_TRUE(d.DisassembleRange(0x400b80, 0x400eac)); EXPECT_EQ(d.call_target_map_[0x400cdd], 0x404930); EXPECT_EQ(d.cjmp_target_map_[0x400ccd], 0x400da0); EXPECT_EQ(d.djmp_target_map_[0x400d0c], 0x400d2f); EXPECT_TRUE(d.call_target_map_.find(0x400ed0) == d.call_target_map_.end()); EXPECT_EQ(d.terminators_[0], 0x400d81); std::set<uint64> addr = d.GetAddrs(); EXPECT_EQ(addr.size(), 187); EXPECT_TRUE(addr.find(0x400ccd) != addr.end()); } TEST_F(DisassemblerTest, JumpTableTest) { TestDisassembler d; CHECK(d.Init(FLAGS_test_srcdir + "/testdata/" + "jump_table_test.binary")); EXPECT_TRUE(d.DisassembleRange(0x40055d, 0x400628)); EXPECT_EQ(d.idjmp_targets_map_[0x40057d].size(), 19); EXPECT_EQ(d.idjmp_targets_map_[0x4005db].size(), 19); EXPECT_EQ(d.terminators_[0], 0x400627); std::set<uint64> addr = d.GetAddrs(); EXPECT_EQ(addr.size(), 56); EXPECT_TRUE(addr.find(0x400598) == addr.end()); } } // namespace
1,086
14,668
<reponame>zealoussnow/chromium // Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef MEDIA_CAST_COMMON_MOD_UTIL_H_ #define MEDIA_CAST_COMMON_MOD_UTIL_H_ #include "base/check.h" namespace media { namespace cast { // MAP is a map<uint??, ...> where the unsigned integer is // assumed to wrap around, but only a small range is used at a time. // Return the oldest entry in the map. template<class MAP> typename MAP::iterator ModMapOldest(MAP* map) { typename MAP::iterator ret = map->begin(); if (ret != map->end()) { typename MAP::key_type lower_quarter = 0; lower_quarter--; lower_quarter >>= 1; if (ret->first < lower_quarter) { typename MAP::iterator tmp = map->upper_bound(lower_quarter * 3); if (tmp != map->end()) ret = tmp; } } return ret; } // MAP is a map<uint??, ...> where the unsigned integer is // assumed to wrap around, but only a small range is used at a time. // Returns the previous entry in the map. template<class MAP> typename MAP::iterator ModMapPrevious(MAP* map, typename MAP::iterator i) { DCHECK(!map->empty()); typename MAP::iterator ret = i; if (i == map->begin()) { ret = map->end(); } ret--; if (i == ret) return map->end(); if ((i->first - ret->first) > ((typename MAP::key_type(0) - 1)) >> 1) return map->end(); return ret; } } // namespace cast } // namespace media #endif // MEDIA_CAST_COMMON_MOD_UTIL_H_
549
3,200
/** * Copyright 2021 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "frontend/parallel/ops_info/virtual_output_info.h" #include <memory> #include <utility> #include <vector> #include "frontend/parallel/device_manager.h" #include "frontend/parallel/device_matrix.h" #include "frontend/parallel/step_parallel.h" #include "frontend/parallel/context.h" #include "utils/log_adapter.h" namespace mindspore { namespace parallel { Status VirtualOutputInfo::CheckStrategy(const StrategyPtr &strategy) { if (CheckStrategyValue(strategy, inputs_shape_) != SUCCESS) { MS_LOG(ERROR) << name_ << ": Invalid strategy."; return FAILED; } Strategys stra = strategy->GetInputDim(); if (stra.size() != 1) { MS_LOG(ERROR) << name_ << ": Strategys size must be 1."; return FAILED; } Dimensions strategy_first = stra.at(0); for (auto dim = strategy_first.begin() + 1; dim != strategy_first.end(); ++dim) { if (*dim != 1) { MS_LOG(ERROR) << name_ << ": All dimension except the first dimension of the strategy must be 1."; return FAILED; } } if (!strategy_first.empty()) { shard_num_ = strategy_first[0]; } return SUCCESS; } Status VirtualOutputInfo::GenerateStrategies(int64_t stage_id) { StrategyPtr sp; Strategys strategy; bool full_batch = ParallelContext::GetInstance()->full_batch(); size_t total_dev_num; if (full_batch) { total_dev_num = 1; } else { total_dev_num = LongToSize(stage_device_size_); } if (total_dev_num == 0) { MS_LOG(ERROR) << name_ << ": The total devices num is 0"; return FAILED; } for (auto &shape : inputs_shape_) { Shape temp; if (!shape.empty()) { if (LongToSize(shape[0]) % total_dev_num == 0) { (void)temp.emplace_back(SizeToLong(total_dev_num)); } else { (void)temp.emplace_back(1); } (void)temp.insert(temp.end(), shape.size() - 1, 1); } strategy.push_back(temp); } sp = std::make_shared<Strategy>(stage_id, strategy); if (SetCostUnderStrategy(sp) == SUCCESS) { MS_LOG(INFO) << name_ << ": Successfully dataset strategy."; PrintStrategy(sp); } else { MS_LOG(ERROR) << name_ << ": Generating dataset strategy failed."; return FAILED; } return SUCCESS; } } // namespace parallel } // namespace mindspore
1,023
365
<reponame>raksa/blender<gh_stars>100-1000 /* * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** \file * \ingroup spoutliner */ #include "DNA_ID.h" #include "BLI_listbase.h" #include "BLI_listbase_wrapper.hh" #include "BLI_utildefines.h" #include "BKE_main.h" #include "../outliner_intern.h" #include "tree_display.hh" namespace blender::ed::outliner { /* Convenience/readability. */ template<typename T> using List = ListBaseWrapper<T>; TreeDisplayIDOrphans::TreeDisplayIDOrphans(SpaceOutliner &space_outliner) : AbstractTreeDisplay(space_outliner) { } ListBase TreeDisplayIDOrphans::buildTree(const TreeSourceData &source_data) { ListBase tree = {nullptr}; ListBase *lbarray[MAX_LIBARRAY]; short filter_id_type = (space_outliner_.filter & SO_FILTER_ID_TYPE) ? space_outliner_.filter_id_type : 0; int tot; if (filter_id_type) { lbarray[0] = which_libbase(source_data.bmain, filter_id_type); tot = 1; } else { tot = set_listbasepointers(source_data.bmain, lbarray); } for (int a = 0; a < tot; a++) { if (BLI_listbase_is_empty(lbarray[a])) { continue; } if (!datablock_has_orphans(*lbarray[a])) { continue; } /* Header for this type of data-block. */ TreeElement *te = nullptr; if (!filter_id_type) { ID *id = (ID *)lbarray[a]->first; te = outliner_add_element(&space_outliner_, &tree, lbarray[a], nullptr, TSE_ID_BASE, 0); te->directdata = lbarray[a]; te->name = outliner_idcode_to_plural(GS(id->name)); } /* Add the orphaned data-blocks - these will not be added with any subtrees attached. */ for (ID *id : List<ID>(lbarray[a])) { if (ID_REAL_USERS(id) <= 0) { outliner_add_element(&space_outliner_, (te) ? &te->subtree : &tree, id, te, 0, 0); } } } return tree; } bool TreeDisplayIDOrphans::datablock_has_orphans(ListBase &lb) const { for (ID *id : List<ID>(lb)) { if (ID_REAL_USERS(id) <= 0) { return true; } } return false; } } // namespace blender::ed::outliner
1,092
835
<filename>client/verta/verta/_swagger/_public/uac/model/UacRole.py<gh_stars>100-1000 # THIS FILE IS AUTO-GENERATED. DO NOT EDIT from verta._swagger.base_type import BaseType class UacRole(BaseType): def __init__(self, id=None, name=None, scope=None, resource_action_groups=None): required = { "id": False, "name": False, "scope": False, "resource_action_groups": False, } self.id = id self.name = name self.scope = scope self.resource_action_groups = resource_action_groups for k, v in required.items(): if self[k] is None and v: raise ValueError('attribute {} is required'.format(k)) @staticmethod def from_json(d): from .UacRoleScope import UacRoleScope from .UacResourceActionGroup import UacResourceActionGroup tmp = d.get('id', None) if tmp is not None: d['id'] = tmp tmp = d.get('name', None) if tmp is not None: d['name'] = tmp tmp = d.get('scope', None) if tmp is not None: d['scope'] = UacRoleScope.from_json(tmp) tmp = d.get('resource_action_groups', None) if tmp is not None: d['resource_action_groups'] = [UacResourceActionGroup.from_json(tmp) for tmp in tmp] return UacRole(**d)
504
14,668
<filename>components/global_media_controls/media_item_manager_impl_unittest.cc // 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 "components/global_media_controls/media_item_manager_impl.h" #include <memory> #include <utility> #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/test/metrics/histogram_tester.h" #include "components/global_media_controls/public/test/mock_media_dialog_delegate.h" #include "components/global_media_controls/public/test/mock_media_item_manager_observer.h" #include "components/global_media_controls/public/test/mock_media_item_producer.h" #include "components/media_message_center/media_notification_util.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using testing::_; using testing::AtLeast; using testing::NiceMock; namespace global_media_controls { class MediaItemManagerImplTest : public testing::Test { public: MediaItemManagerImplTest() = default; ~MediaItemManagerImplTest() override = default; void SetUp() override { item_manager_ = std::make_unique<MediaItemManagerImpl>(); item_manager_->AddObserver(&observer_); } void TearDown() override { item_manager_.reset(); } protected: void ExpectHistogramCountRecorded(int count, int size) { histogram_tester_.ExpectBucketCount( media_message_center::kCountHistogramName, count, size); } test::MockMediaItemManagerObserver& observer() { return observer_; } MediaItemManagerImpl* item_manager() { return item_manager_.get(); } private: NiceMock<test::MockMediaItemManagerObserver> observer_; std::unique_ptr<MediaItemManagerImpl> item_manager_; base::HistogramTester histogram_tester_; }; TEST_F(MediaItemManagerImplTest, ShowsItemsFromAllProducers) { // Before there are any active items, the item manager should not say there // are active items. test::MockMediaItemProducer producer1; test::MockMediaItemProducer producer2; item_manager()->AddItemProducer(&producer1); item_manager()->AddItemProducer(&producer2); EXPECT_FALSE(item_manager()->HasActiveItems()); // Once there are active items, the item manager should say so. producer1.AddItem("foo", true, false, false); producer1.AddItem("foo2", true, false, false); producer2.AddItem("bar", true, false, false); EXPECT_TRUE(item_manager()->HasActiveItems()); // It should inform observers of this change. EXPECT_CALL(observer(), OnItemListChanged()); item_manager()->OnItemsChanged(); testing::Mock::VerifyAndClearExpectations(&observer()); // When a dialog is opened, it should receive all the items. NiceMock<test::MockMediaDialogDelegate> dialog_delegate; EXPECT_CALL(dialog_delegate, ShowMediaItem("foo", _)); EXPECT_CALL(dialog_delegate, ShowMediaItem("foo2", _)); ; EXPECT_CALL(dialog_delegate, ShowMediaItem("bar", _)); EXPECT_CALL(observer(), OnMediaDialogOpened()); EXPECT_CALL(producer1, OnDialogDisplayed()); EXPECT_CALL(producer2, OnDialogDisplayed()); item_manager()->SetDialogDelegate(&dialog_delegate); // Ensure that we properly recorded the number of active sessions shown. ExpectHistogramCountRecorded(3, 1); EXPECT_CALL(observer(), OnMediaDialogClosed()); item_manager()->SetDialogDelegate(nullptr); } TEST_F(MediaItemManagerImplTest, NewMediaSessionWhileDialogOpen) { // First, start playing active media. test::MockMediaItemProducer producer; item_manager()->AddItemProducer(&producer); producer.AddItem("foo", true, false, false); EXPECT_TRUE(item_manager()->HasActiveItems()); // Then, open a dialog. NiceMock<test::MockMediaDialogDelegate> dialog_delegate; EXPECT_CALL(dialog_delegate, ShowMediaItem("foo", _)); item_manager()->SetDialogDelegate(&dialog_delegate); ExpectHistogramCountRecorded(1, 1); testing::Mock::VerifyAndClearExpectations(&dialog_delegate); // Then, have a new item start while the dialog is opened. This // should update the dialog. EXPECT_CALL(dialog_delegate, ShowMediaItem("bar", _)); producer.AddItem("bar", true, false, false); item_manager()->ShowItem("bar"); testing::Mock::VerifyAndClearExpectations(&dialog_delegate); // If we close this dialog and open a new one, the new one should receive both // media sessions immediately. item_manager()->SetDialogDelegate(nullptr); NiceMock<test::MockMediaDialogDelegate> new_dialog; EXPECT_CALL(new_dialog, ShowMediaItem("foo", _)); EXPECT_CALL(new_dialog, ShowMediaItem("bar", _)); item_manager()->SetDialogDelegate(&new_dialog); ExpectHistogramCountRecorded(1, 1); ExpectHistogramCountRecorded(2, 1); item_manager()->SetDialogDelegate(nullptr); } TEST_F(MediaItemManagerImplTest, CanOpenDialogForSpecificItem) { // Set up multiple producers with multiple items. test::MockMediaItemProducer producer1; test::MockMediaItemProducer producer2; item_manager()->AddItemProducer(&producer1); item_manager()->AddItemProducer(&producer2); producer1.AddItem("foo", true, false, false); producer1.AddItem("foo2", true, false, false); producer2.AddItem("bar", true, false, false); producer2.AddItem("bar2", true, false, false); // If we open a dialog for a specific item, it should only receive that item. NiceMock<test::MockMediaDialogDelegate> dialog_delegate; EXPECT_CALL(dialog_delegate, ShowMediaItem("foo", _)).Times(0); EXPECT_CALL(dialog_delegate, ShowMediaItem("foo2", _)); ; EXPECT_CALL(dialog_delegate, ShowMediaItem("bar", _)).Times(0); EXPECT_CALL(dialog_delegate, ShowMediaItem("bar2", _)).Times(0); // The producers shouldn't be informed of dialog opens for a specific item, // but the observer still should be. EXPECT_CALL(producer1, OnDialogDisplayed()).Times(0); EXPECT_CALL(producer2, OnDialogDisplayed()).Times(0); EXPECT_CALL(observer(), OnMediaDialogOpened()); item_manager()->SetDialogDelegateForId(&dialog_delegate, "foo2"); // We should not have recorded any histograms for item count. ExpectHistogramCountRecorded(1, 0); // If a new item becomes active while the dialog is opened for a specific // item, that new item should not show up in the dialog. EXPECT_CALL(dialog_delegate, ShowMediaItem("foo3", _)).Times(0); producer1.AddItem("foo3", true, false, false); item_manager()->ShowItem("foo3"); item_manager()->SetDialogDelegate(nullptr); } } // namespace global_media_controls
2,121
485
/* MIT License Copyright (c) 2015 <NAME> 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 za.co.riggaroo.materialhelptutorial.tutorial; import java.util.List; import za.co.riggaroo.materialhelptutorial.MaterialTutorialFragment; import za.co.riggaroo.materialhelptutorial.TutorialItem; /** * @author rebeccafranks * @since 15/11/09. */ public interface MaterialTutorialContract { interface View { void showNextTutorial(); void showEndTutorial(); void setBackgroundColor(int color); void showDoneButton(); void showSkipButton(); void setViewPagerFragments(List<MaterialTutorialFragment> materialTutorialFragments); } interface UserActionsListener { void loadViewPagerFragments(List<TutorialItem> tutorialItems); void doneOrSkipClick(); void nextClick(); void onPageSelected(int pageNo); void transformPage(android.view.View page, float position); int getNumberOfTutorials(); } }
612
1,253
<reponame>JanStoltman/DaggerMock package it.cosenonjaviste.daggermock.subcomponentbuilder; import dagger.Subcomponent; @Subcomponent(modules = MySubModule.class) public interface MySubComponent { MainService mainService(); @Subcomponent.Builder interface Builder { Builder mySubModule(MySubModule module); MySubComponent build(); } }
127
3,428
<filename>lib/node_modules/@stdlib/datasets/spam-assassin/data/easy-ham-1/02240.fe7a1b134c52afd2b9a666ee65e789cb.json<gh_stars>1000+ {"id":"02240","group":"easy-ham-1","checksum":{"type":"MD5","value":"fe7a1b134c52afd2b9a666ee65e789cb"},"text":"From <EMAIL> Thu Oct 3 12:25:21 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: y<EMAIL>int.org\nReceived: from localhost (jalapeno [127.0.0.1])\n\tby jmason.org (Postfix) with ESMTP id D6B7A16F18\n\tfor <jm@localhost>; Thu, 3 Oct 2002 12:24:33 +0100 (IST)\nReceived: from jalapeno [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor jm@localhost (single-drop); Thu, 03 Oct 2002 12:24:33 +0100 (IST)\nReceived: from dogma.slashnull.org (localhost [127.0.0.1]) by\n dogma.slashnull.org (8.11.6/8.11.6) with ESMTP id g9382MK20045 for\n <<EMAIL>>; Thu, 3 Oct 2002 09:02:22 +0100\nMessage-Id: <<EMAIL>>\nTo: y<EMAIL>.org\nFrom: guardian <<EMAIL>>\nSubject: Education debate\nDate: Thu, 03 Oct 2002 08:02:21 -0000\nContent-Type: text/plain; encoding=utf-8\n\nURL: http://www.newsisfree.com/click/215,11,215/\nDate: 2002-10-01T12:41:57+01:00\n\n*Live online:* The Observer's *<NAME>* and experts *<NAME>* and *\n<NAME>* will be here on Thursday at 3pm to discuss the government's \nrecord. Post your questions now.\n\n\n"}
546
14,668
<reponame>zealoussnow/chromium # Copyright (c) 2012 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. '''In GRIT, we used to compile a lot of regular expressions at parse time. Since many of them never get used, we use lazy_re to compile them on demand the first time they are used, thus speeding up startup time in some cases. ''' from __future__ import print_function import re class LazyRegexObject(object): '''This object creates a RegexObject with the arguments passed in its constructor, the first time any attribute except the several on the class itself is accessed. This accomplishes lazy compilation of the regular expression while maintaining a nearly-identical interface. ''' def __init__(self, *args, **kwargs): self._stash_args = args self._stash_kwargs = kwargs self._lazy_re = None def _LazyInit(self): if not self._lazy_re: self._lazy_re = re.compile(*self._stash_args, **self._stash_kwargs) def __getattribute__(self, name): if name in ('_LazyInit', '_lazy_re', '_stash_args', '_stash_kwargs'): return object.__getattribute__(self, name) else: self._LazyInit() return getattr(self._lazy_re, name) def compile(*args, **kwargs): '''Creates a LazyRegexObject that, when invoked on, will compile a re.RegexObject (via re.compile) with the same arguments passed to this function, and delegate almost all of its methods to it. ''' return LazyRegexObject(*args, **kwargs)
510
348
<filename>docs/data/leg-t1/022/02202190.json {"nom":"Pleslin-Trigavou","circ":"2ème circonscription","dpt":"Côtes-d'Armor","inscrits":2812,"abs":1293,"votants":1519,"blancs":27,"nuls":12,"exp":1480,"res":[{"nuance":"REM","nom":"M. <NAME>","voix":512},{"nuance":"FI","nom":"<NAME>","voix":237},{"nuance":"FN","nom":"Mme <NAME>","voix":205},{"nuance":"SOC","nom":"Mme <NAME>","voix":192},{"nuance":"LR","nom":"<NAME>","voix":156},{"nuance":"ECO","nom":"Mme <NAME>","voix":48},{"nuance":"DVD","nom":"<NAME>","voix":44},{"nuance":"EXG","nom":"Mme <NAME>","voix":21},{"nuance":"ECO","nom":"M. <NAME>","voix":20},{"nuance":"REG","nom":"<NAME>","voix":13},{"nuance":"DVD","nom":"<NAME>","voix":11},{"nuance":"REG","nom":"<NAME>","voix":10},{"nuance":"DIV","nom":"M. <NAME>","voix":7},{"nuance":"DVG","nom":"<NAME>","voix":4}]}
333
363
<reponame>LaudateCorpus1/ik<gh_stars>100-1000 #include "ik/solver_ONE_BONE.h" #include "ik/ik.h" #include "ik/chain.h" #include "ik/vec3_static.h" #include <stddef.h> #include <assert.h> /* ------------------------------------------------------------------------- */ uintptr_t ik_solver_ONE_BONE_type_size(void) { return sizeof(struct ik_solver_t); } /* ------------------------------------------------------------------------- */ int ik_solver_ONE_BONE_construct(struct ik_solver_t* solver) { return 0; } /* ------------------------------------------------------------------------- */ void ik_solver_ONE_BONE_destruct(struct ik_solver_t* solver) { } /* ------------------------------------------------------------------------- */ int ik_solver_ONE_BONE_rebuild(struct ik_solver_t* solver) { /* * We need to assert that there really are only chains of length 1 and no * sub chains. */ SOLVER_FOR_EACH_CHAIN(solver, chain) if (chain_length(chain) != 2) /* 2 nodes = 1 bone */ { IKAPI.log.message("ERROR: Your tree has chains that are longer than 1 bone. Are you sure you selected the correct solver algorithm?"); return -1; } if (chain_length(chain) > 0) { IKAPI.log.message("ERROR: Your tree has child chains. This solver does not support arbitrary trees. You will need to switch to another algorithm (e.g. FABRIK)"); return -1; } SOLVER_END_EACH return 0; } /* ------------------------------------------------------------------------- */ int ik_solver_ONE_BONE_solve(struct ik_solver_t* solver) { SOLVER_FOR_EACH_CHAIN(solver, chain) struct ik_node_t* node_tip; struct ik_node_t* node_base; assert(chain_length(chain) > 1); node_tip = chain_get_node(chain, 0); node_base = chain_get_node(chain, 1); assert(node_tip->effector != NULL); node_tip->position = node_tip->effector->target_position; ik_vec3_static_sub_vec3(node_tip->position.f, node_base->position.f); ik_vec3_static_normalize(node_tip->position.f); ik_vec3_static_mul_scalar(node_tip->position.f, node_tip->dist_to_parent); ik_vec3_static_add_vec3(node_tip->position.f, node_base->position.f); SOLVER_END_EACH return 0; }
915
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. package org.chromium.chrome.browser.ntp.cards; import android.content.Context; import android.text.format.DateUtils; import androidx.annotation.VisibleForTesting; import org.chromium.base.ContextUtils; import org.chromium.chrome.browser.preferences.ChromePreferenceKeys; import org.chromium.chrome.browser.preferences.SharedPreferencesManager; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.chrome.browser.signin.SyncConsentActivityLauncherImpl; import org.chromium.chrome.browser.signin.services.IdentityServicesProvider; import org.chromium.chrome.browser.signin.services.ProfileDataCache; import org.chromium.chrome.browser.signin.services.SigninManager; import org.chromium.chrome.browser.signin.services.SigninManager.SignInStateObserver; import org.chromium.chrome.browser.signin.services.SigninPreferencesManager; import org.chromium.chrome.browser.ui.signin.SigninPromoController; import org.chromium.components.signin.AccountManagerFacade; import org.chromium.components.signin.AccountManagerFacadeProvider; import org.chromium.components.signin.AccountsChangeObserver; import org.chromium.components.signin.identitymanager.ConsentLevel; import org.chromium.components.signin.identitymanager.IdentityManager; import org.chromium.components.signin.metrics.SigninAccessPoint; /** * Superclass tracking whether a signin card could be shown. * * Subclasses are notified when relevant signin status changes. */ public abstract class SignInPromo { /** * Period for which promos are suppressed if signin is refused in FRE. */ @VisibleForTesting static final long SUPPRESSION_PERIOD_MS = DateUtils.DAY_IN_MILLIS; private static boolean sDisablePromoForTests; /** * Whether the signin status means that the user has the possibility to sign in. */ private boolean mCanSignIn; /** * Whether personalized suggestions can be shown. If it's not the case, we have no reason to * offer the user to sign in. */ private boolean mCanShowPersonalizedSuggestions; private boolean mIsVisible; private final SigninObserver mSigninObserver; protected final SigninPromoController mSigninPromoController; protected final ProfileDataCache mProfileDataCache; protected SignInPromo(SigninManager signinManager) { Context context = ContextUtils.getApplicationContext(); // TODO(bsazonov): Signin manager should check for native status in isSignInAllowed mCanSignIn = signinManager.isSignInAllowed() && !signinManager.getIdentityManager().hasPrimaryAccount(ConsentLevel.SYNC); updateVisibility(); mProfileDataCache = ProfileDataCache.createWithDefaultImageSizeAndNoBadge(context); mSigninPromoController = new SigninPromoController( SigninAccessPoint.NTP_CONTENT_SUGGESTIONS, SyncConsentActivityLauncherImpl.get()); mSigninObserver = new SigninObserver(signinManager); } /** Clear any dependencies. */ public void destroy() { mSigninObserver.unregister(); } /** * Update whether personalized suggestions can be shown and update visibility for this * {@link SignInPromo} accordingly. * @param canShow Whether personalized suggestions can be shown. */ public void setCanShowPersonalizedSuggestions(boolean canShow) { mCanShowPersonalizedSuggestions = canShow; updateVisibility(); } /** * Suppress signin promos in New Tab Page for {@link SignInPromo#SUPPRESSION_PERIOD_MS}. This * will not affect promos that were created before this call. */ public static void temporarilySuppressPromos() { SigninPreferencesManager.getInstance().setNewTabPageSigninPromoSuppressionPeriodStart( System.currentTimeMillis()); } /** * @return Whether the {@link SignInPromo} should be created. */ public static boolean shouldCreatePromo() { return !sDisablePromoForTests && !SharedPreferencesManager.getInstance().readBoolean( ChromePreferenceKeys.SIGNIN_PROMO_NTP_PROMO_DISMISSED, false) && !getSuppressionStatus(); } private static boolean getSuppressionStatus() { long suppressedFrom = SigninPreferencesManager.getInstance() .getNewTabPageSigninPromoSuppressionPeriodStart(); if (suppressedFrom == 0) return false; long currentTime = System.currentTimeMillis(); long suppressedTo = suppressedFrom + SUPPRESSION_PERIOD_MS; if (suppressedFrom <= currentTime && currentTime < suppressedTo) { return true; } SigninPreferencesManager.getInstance().clearNewTabPageSigninPromoSuppressionPeriodStart(); return false; } public boolean isUserSignedInButNotSyncing() { IdentityManager identityManager = IdentityServicesProvider.get().getIdentityManager( Profile.getLastUsedRegularProfile()); return identityManager.hasPrimaryAccount(ConsentLevel.SIGNIN) && !identityManager.hasPrimaryAccount(ConsentLevel.SYNC); } /** Notify that the content for this {@link SignInPromo} has changed. */ protected abstract void notifyDataChanged(); private void updateVisibility() { final boolean isAccountsCachePopulated = AccountManagerFacadeProvider.getInstance().getAccounts().isFulfilled(); boolean canShowPersonalizedSigninPromo = mCanSignIn && mCanShowPersonalizedSuggestions && isAccountsCachePopulated; boolean canShowPersonalizedSyncPromo = isUserSignedInButNotSyncing() && mCanShowPersonalizedSuggestions && isAccountsCachePopulated; setVisibilityInternal(canShowPersonalizedSigninPromo || canShowPersonalizedSyncPromo); } /** * Updates visibility status. Overridden by subclasses that want to track visibility changes. */ protected void setVisibilityInternal(boolean visibility) { if (!mIsVisible && visibility) mSigninPromoController.increasePromoShowCount(); mIsVisible = visibility; } /** Returns current visibility status of the underlying promo view. */ public boolean isVisible() { return mIsVisible; } public void onDismissPromo() { SharedPreferencesManager.getInstance().writeBoolean( ChromePreferenceKeys.SIGNIN_PROMO_NTP_PROMO_DISMISSED, true); mSigninPromoController.detach(); setVisibilityInternal(false); } @VisibleForTesting public static void setDisablePromoForTests(boolean disable) { sDisablePromoForTests = disable; } @VisibleForTesting public SigninObserver getSigninObserverForTesting() { return mSigninObserver; } /** * Observer to get notifications about various sign-in events. */ @VisibleForTesting public class SigninObserver implements SignInStateObserver, ProfileDataCache.Observer, AccountsChangeObserver { private final SigninManager mSigninManager; private final AccountManagerFacade mAccountManagerFacade; /** Guards {@link #unregister()}, which can be called multiple times. */ private boolean mUnregistered; private SigninObserver(SigninManager signinManager) { mSigninManager = signinManager; mAccountManagerFacade = AccountManagerFacadeProvider.getInstance(); mSigninManager.addSignInStateObserver(this); mProfileDataCache.addObserver(this); mAccountManagerFacade.addObserver(this); } private void unregister() { if (mUnregistered) return; mUnregistered = true; mSigninManager.removeSignInStateObserver(this); mProfileDataCache.removeObserver(this); mAccountManagerFacade.removeObserver(this); } // SignInAllowedObserver implementation. @Override public void onSignInAllowedChanged() { // Listening to onSignInAllowedChanged is important for the FRE. Sign in is not allowed // until it is completed, but the NTP is initialised before the FRE is even shown. By // implementing this we can show the promo if the user did not sign in during the FRE. mCanSignIn = mSigninManager.isSignInAllowed(); updateVisibility(); // Update the promo state between sign-in promo and sync promo if required. notifyDataChanged(); } // SignInStateObserver implementation. @Override public void onSignedIn() { mCanSignIn = false; updateVisibility(); // Update the promo state between sign-in promo and sync promo if required. notifyDataChanged(); } @Override public void onSignedOut() { mCanSignIn = mSigninManager.isSignInAllowed(); updateVisibility(); // Update the promo state between sign-in promo and sync promo if required. notifyDataChanged(); } // AccountsChangeObserver implementation. @Override public void onAccountsChanged() { // We don't change the visibility here to avoid the promo popping up in the feed // unexpectedly. If accounts are ready, the promo will be shown up on the next reload. notifyDataChanged(); } // ProfileDataCache.Observer implementation. @Override public void onProfileDataUpdated(String accountEmail) { notifyDataChanged(); } } }
3,577
1,144
<reponame>rlourette/TI_SDK_u-boot-2019.01 /* SPDX-License-Identifier: GPL-2.0+ */ /* * Copyright (C) 2014 <NAME> <<EMAIL>> */ #ifndef _NIC301_REGISTERS_H_ #define _NIC301_REGISTERS_H_ struct nic301_registers { u32 remap; /* 0x0 */ /* Security Register Group */ u32 _pad_0x4_0x8[1]; u32 l4main; u32 l4sp; u32 l4mp; /* 0x10 */ u32 l4osc1; u32 l4spim; u32 stm; u32 lwhps2fpgaregs; /* 0x20 */ u32 _pad_0x24_0x28[1]; u32 usb1; u32 nanddata; u32 _pad_0x30_0x80[20]; u32 usb0; /* 0x80 */ u32 nandregs; u32 qspidata; u32 fpgamgrdata; u32 hps2fpgaregs; /* 0x90 */ u32 acp; u32 rom; u32 ocram; u32 sdrdata; /* 0xA0 */ u32 _pad_0xa4_0x1fd0[1995]; /* ID Register Group */ u32 periph_id_4; /* 0x1FD0 */ u32 _pad_0x1fd4_0x1fe0[3]; u32 periph_id_0; /* 0x1FE0 */ u32 periph_id_1; u32 periph_id_2; u32 periph_id_3; u32 comp_id_0; /* 0x1FF0 */ u32 comp_id_1; u32 comp_id_2; u32 comp_id_3; u32 _pad_0x2000_0x2008[2]; /* L4 MAIN */ u32 l4main_fn_mod_bm_iss; u32 _pad_0x200c_0x3008[1023]; /* L4 SP */ u32 l4sp_fn_mod_bm_iss; u32 _pad_0x300c_0x4008[1023]; /* L4 MP */ u32 l4mp_fn_mod_bm_iss; u32 _pad_0x400c_0x5008[1023]; /* L4 OSC1 */ u32 l4osc_fn_mod_bm_iss; u32 _pad_0x500c_0x6008[1023]; /* L4 SPIM */ u32 l4spim_fn_mod_bm_iss; u32 _pad_0x600c_0x7008[1023]; /* STM */ u32 stm_fn_mod_bm_iss; u32 _pad_0x700c_0x7108[63]; u32 stm_fn_mod; u32 _pad_0x710c_0x8008[959]; /* LWHPS2FPGA */ u32 lwhps2fpga_fn_mod_bm_iss; u32 _pad_0x800c_0x8108[63]; u32 lwhps2fpga_fn_mod; u32 _pad_0x810c_0xa008[1983]; /* USB1 */ u32 usb1_fn_mod_bm_iss; u32 _pad_0xa00c_0xa044[14]; u32 usb1_ahb_cntl; u32 _pad_0xa048_0xb008[1008]; /* NANDDATA */ u32 nanddata_fn_mod_bm_iss; u32 _pad_0xb00c_0xb108[63]; u32 nanddata_fn_mod; u32 _pad_0xb10c_0x20008[21439]; /* USB0 */ u32 usb0_fn_mod_bm_iss; u32 _pad_0x2000c_0x20044[14]; u32 usb0_ahb_cntl; u32 _pad_0x20048_0x21008[1008]; /* NANDREGS */ u32 nandregs_fn_mod_bm_iss; u32 _pad_0x2100c_0x21108[63]; u32 nandregs_fn_mod; u32 _pad_0x2110c_0x22008[959]; /* QSPIDATA */ u32 qspidata_fn_mod_bm_iss; u32 _pad_0x2200c_0x22044[14]; u32 qspidata_ahb_cntl; u32 _pad_0x22048_0x23008[1008]; /* FPGAMGRDATA */ u32 fpgamgrdata_fn_mod_bm_iss; u32 _pad_0x2300c_0x23040[13]; u32 fpgamgrdata_wr_tidemark; /* 0x23040 */ u32 _pad_0x23044_0x23108[49]; u32 fn_mod; u32 _pad_0x2310c_0x24008[959]; /* HPS2FPGA */ u32 hps2fpga_fn_mod_bm_iss; u32 _pad_0x2400c_0x24040[13]; u32 hps2fpga_wr_tidemark; /* 0x24040 */ u32 _pad_0x24044_0x24108[49]; u32 hps2fpga_fn_mod; u32 _pad_0x2410c_0x25008[959]; /* ACP */ u32 acp_fn_mod_bm_iss; u32 _pad_0x2500c_0x25108[63]; u32 acp_fn_mod; u32 _pad_0x2510c_0x26008[959]; /* Boot ROM */ u32 bootrom_fn_mod_bm_iss; u32 _pad_0x2600c_0x26108[63]; u32 bootrom_fn_mod; u32 _pad_0x2610c_0x27008[959]; /* On-chip RAM */ u32 ocram_fn_mod_bm_iss; u32 _pad_0x2700c_0x27040[13]; u32 ocram_wr_tidemark; /* 0x27040 */ u32 _pad_0x27044_0x27108[49]; u32 ocram_fn_mod; u32 _pad_0x2710c_0x42024[27590]; /* DAP */ u32 dap_fn_mod2; u32 dap_fn_mod_ahb; u32 _pad_0x4202c_0x42100[53]; u32 dap_read_qos; /* 0x42100 */ u32 dap_write_qos; u32 dap_fn_mod; u32 _pad_0x4210c_0x43100[1021]; /* MPU */ u32 mpu_read_qos; /* 0x43100 */ u32 mpu_write_qos; u32 mpu_fn_mod; u32 _pad_0x4310c_0x44028[967]; /* SDMMC */ u32 sdmmc_fn_mod_ahb; u32 _pad_0x4402c_0x44100[53]; u32 sdmmc_read_qos; /* 0x44100 */ u32 sdmmc_write_qos; u32 sdmmc_fn_mod; u32 _pad_0x4410c_0x45100[1021]; /* DMA */ u32 dma_read_qos; /* 0x45100 */ u32 dma_write_qos; u32 dma_fn_mod; u32 _pad_0x4510c_0x46040[973]; /* FPGA2HPS */ u32 fpga2hps_wr_tidemark; /* 0x46040 */ u32 _pad_0x46044_0x46100[47]; u32 fpga2hps_read_qos; /* 0x46100 */ u32 fpga2hps_write_qos; u32 fpga2hps_fn_mod; u32 _pad_0x4610c_0x47100[1021]; /* ETR */ u32 etr_read_qos; /* 0x47100 */ u32 etr_write_qos; u32 etr_fn_mod; u32 _pad_0x4710c_0x48100[1021]; /* EMAC0 */ u32 emac0_read_qos; /* 0x48100 */ u32 emac0_write_qos; u32 emac0_fn_mod; u32 _pad_0x4810c_0x49100[1021]; /* EMAC1 */ u32 emac1_read_qos; /* 0x49100 */ u32 emac1_write_qos; u32 emac1_fn_mod; u32 _pad_0x4910c_0x4a028[967]; /* USB0 */ u32 usb0_fn_mod_ahb; u32 _pad_0x4a02c_0x4a100[53]; u32 usb0_read_qos; /* 0x4A100 */ u32 usb0_write_qos; u32 usb0_fn_mod; u32 _pad_0x4a10c_0x4b100[1021]; /* NAND */ u32 nand_read_qos; /* 0x4B100 */ u32 nand_write_qos; u32 nand_fn_mod; u32 _pad_0x4b10c_0x4c028[967]; /* USB1 */ u32 usb1_fn_mod_ahb; u32 _pad_0x4c02c_0x4c100[53]; u32 usb1_read_qos; /* 0x4C100 */ u32 usb1_write_qos; u32 usb1_fn_mod; }; #endif /* _NIC301_REGISTERS_H_ */
2,966
605
<reponame>yuriykoch/llvm<gh_stars>100-1000 import lldb import binascii import os.path from lldbsuite.test.lldbtest import * from lldbsuite.test.decorators import * from lldbsuite.test.gdbclientutils import * from lldbsuite.test.lldbgdbclient import GDBRemoteTestBase class TestGDBRemoteClient(GDBRemoteTestBase): mydir = TestBase.compute_mydir(__file__) class gPacketResponder(MockGDBServerResponder): registers = [ "name:rax;bitsize:64;offset:0;encoding:uint;format:hex;set:General Purpose Registers;ehframe:0;dwarf:0;", "name:rbx;bitsize:64;offset:8;encoding:uint;format:hex;set:General Purpose Registers;ehframe:3;dwarf:3;", "name:rcx;bitsize:64;offset:16;encoding:uint;format:hex;set:General Purpose Registers;ehframe:2;dwarf:2;generic:arg4;", "name:rdx;bitsize:64;offset:24;encoding:uint;format:hex;set:General Purpose Registers;ehframe:1;dwarf:1;generic:arg3;", "name:rdi;bitsize:64;offset:32;encoding:uint;format:hex;set:General Purpose Registers;ehframe:5;dwarf:5;generic:arg1;", "name:rsi;bitsize:64;offset:40;encoding:uint;format:hex;set:General Purpose Registers;ehframe:4;dwarf:4;generic:arg2;", "name:rbp;bitsize:64;offset:48;encoding:uint;format:hex;set:General Purpose Registers;ehframe:6;dwarf:6;generic:fp;", "name:rsp;bitsize:64;offset:56;encoding:uint;format:hex;set:General Purpose Registers;ehframe:7;dwarf:7;generic:sp;", ] def qRegisterInfo(self, num): try: return self.registers[num] except IndexError: return "E45" def readRegisters(self): return len(self.registers) * 16 * '0' def readRegister(self, register): return "0000000000000000" def test_connect(self): """Test connecting to a remote gdb server""" target = self.createTarget("a.yaml") process = self.connect(target) self.assertPacketLogContains(["qProcessInfo", "qfThreadInfo"]) def test_attach_fail(self): error_msg = "mock-error-msg" class MyResponder(MockGDBServerResponder): # Pretend we don't have any process during the initial queries. def qC(self): return "E42" def qfThreadInfo(self): return "OK" # No threads. # Then, when we are asked to attach, error out. def vAttach(self, pid): return "E42;" + binascii.hexlify(error_msg.encode()).decode() self.server.responder = MyResponder() target = self.dbg.CreateTarget("") process = self.connect(target) lldbutil.expect_state_changes(self, self.dbg.GetListener(), process, [lldb.eStateConnected]) error = lldb.SBError() target.AttachToProcessWithID(lldb.SBListener(), 47, error) self.assertEquals(error_msg, error.GetCString()) def test_launch_fail(self): class MyResponder(MockGDBServerResponder): # Pretend we don't have any process during the initial queries. def qC(self): return "E42" def qfThreadInfo(self): return "OK" # No threads. # Then, when we are asked to attach, error out. def A(self, packet): return "E47" self.server.responder = MyResponder() target = self.createTarget("a.yaml") process = self.connect(target) lldbutil.expect_state_changes(self, self.dbg.GetListener(), process, [lldb.eStateConnected]) error = lldb.SBError() target.Launch(lldb.SBListener(), None, None, None, None, None, None, 0, True, error) self.assertEquals("'A' packet returned an error: 71", error.GetCString()) def test_read_registers_using_g_packets(self): """Test reading registers using 'g' packets (default behavior)""" self.dbg.HandleCommand( "settings set plugin.process.gdb-remote.use-g-packet-for-reading true") self.addTearDownHook(lambda: self.runCmd("settings set plugin.process.gdb-remote.use-g-packet-for-reading false")) self.server.responder = self.gPacketResponder() target = self.createTarget("a.yaml") process = self.connect(target) self.assertEquals(1, self.server.responder.packetLog.count("g")) self.server.responder.packetLog = [] self.read_registers(process) # Reading registers should not cause any 'p' packets to be exchanged. self.assertEquals( 0, len([p for p in self.server.responder.packetLog if p.startswith("p")])) def test_read_registers_using_p_packets(self): """Test reading registers using 'p' packets""" self.dbg.HandleCommand( "settings set plugin.process.gdb-remote.use-g-packet-for-reading false") self.server.responder = self.gPacketResponder() target = self.createTarget("a.yaml") process = self.connect(target) self.read_registers(process) self.assertNotIn("g", self.server.responder.packetLog) self.assertGreater( len([p for p in self.server.responder.packetLog if p.startswith("p")]), 0) def test_write_registers_using_P_packets(self): """Test writing registers using 'P' packets (default behavior)""" self.server.responder = self.gPacketResponder() target = self.createTarget("a.yaml") process = self.connect(target) self.write_registers(process) self.assertEquals(0, len( [p for p in self.server.responder.packetLog if p.startswith("G")])) self.assertGreater( len([p for p in self.server.responder.packetLog if p.startswith("P")]), 0) def test_write_registers_using_G_packets(self): """Test writing registers using 'G' packets""" class MyResponder(self.gPacketResponder): def readRegister(self, register): # empty string means unsupported return "" self.server.responder = MyResponder() target = self.createTarget("a.yaml") process = self.connect(target) self.write_registers(process) self.assertEquals(0, len( [p for p in self.server.responder.packetLog if p.startswith("P")])) self.assertGreater(len( [p for p in self.server.responder.packetLog if p.startswith("G")]), 0) def read_registers(self, process): self.for_each_gpr( process, lambda r: self.assertEquals("0x0000000000000000", r.GetValue())) def write_registers(self, process): self.for_each_gpr( process, lambda r: r.SetValueFromCString("0x0000000000000000")) def for_each_gpr(self, process, operation): registers = process.GetThreadAtIndex(0).GetFrameAtIndex(0).GetRegisters() self.assertGreater(registers.GetSize(), 0) regSet = registers[0] numChildren = regSet.GetNumChildren() self.assertGreater(numChildren, 0) for i in range(numChildren): operation(regSet.GetChildAtIndex(i)) def test_launch_A(self): class MyResponder(MockGDBServerResponder): def __init__(self, *args, **kwargs): self.started = False return super().__init__(*args, **kwargs) def qC(self): if self.started: return "QCp10.10" else: return "E42" def qfThreadInfo(self): if self.started: return "mp10.10" else: return "E42" def qsThreadInfo(self): return "l" def A(self, packet): self.started = True return "OK" def qLaunchSuccess(self): if self.started: return "OK" return "E42" self.server.responder = MyResponder() target = self.createTarget("a.yaml") # NB: apparently GDB packets are using "/" on Windows too exe_path = self.getBuildArtifact("a").replace(os.path.sep, '/') exe_hex = binascii.b2a_hex(exe_path.encode()).decode() process = self.connect(target) lldbutil.expect_state_changes(self, self.dbg.GetListener(), process, [lldb.eStateConnected]) target.Launch(lldb.SBListener(), ["arg1", "arg2", "arg3"], # argv [], # envp None, # stdin_path None, # stdout_path None, # stderr_path None, # working_directory 0, # launch_flags True, # stop_at_entry lldb.SBError()) # error self.assertTrue(process, PROCESS_IS_VALID) self.assertEqual(process.GetProcessID(), 16) self.assertPacketLogContains([ "A%d,0,%s,8,1,61726731,8,2,61726732,8,3,61726733" % ( len(exe_hex), exe_hex), ]) def test_launch_vRun(self): class MyResponder(MockGDBServerResponder): def __init__(self, *args, **kwargs): self.started = False return super().__init__(*args, **kwargs) def qC(self): if self.started: return "QCp10.10" else: return "E42" def qfThreadInfo(self): if self.started: return "mp10.10" else: return "E42" def qsThreadInfo(self): return "l" def vRun(self, packet): self.started = True return "T13" def A(self, packet): return "E28" self.server.responder = MyResponder() target = self.createTarget("a.yaml") # NB: apparently GDB packets are using "/" on Windows too exe_path = self.getBuildArtifact("a").replace(os.path.sep, '/') exe_hex = binascii.b2a_hex(exe_path.encode()).decode() process = self.connect(target) lldbutil.expect_state_changes(self, self.dbg.GetListener(), process, [lldb.eStateConnected]) process = target.Launch(lldb.SBListener(), ["arg1", "arg2", "arg3"], # argv [], # envp None, # stdin_path None, # stdout_path None, # stderr_path None, # working_directory 0, # launch_flags True, # stop_at_entry lldb.SBError()) # error self.assertTrue(process, PROCESS_IS_VALID) self.assertEqual(process.GetProcessID(), 16) self.assertPacketLogContains([ "vRun;%s;61726731;61726732;61726733" % (exe_hex,) ]) def test_launch_QEnvironment(self): class MyResponder(MockGDBServerResponder): def qC(self): return "E42" def qfThreadInfo(self): return "E42" def vRun(self, packet): self.started = True return "E28" self.server.responder = MyResponder() target = self.createTarget("a.yaml") process = self.connect(target) lldbutil.expect_state_changes(self, self.dbg.GetListener(), process, [lldb.eStateConnected]) target.Launch(lldb.SBListener(), [], # argv ["PLAIN=foo", "NEEDSENC=frob$", "NEEDSENC2=fr*ob", "NEEDSENC3=fro}b", "NEEDSENC4=f#rob", "EQUALS=foo=bar", ], # envp None, # stdin_path None, # stdout_path None, # stderr_path None, # working_directory 0, # launch_flags True, # stop_at_entry lldb.SBError()) # error self.assertPacketLogContains([ "QEnvironment:PLAIN=foo", "QEnvironmentHexEncoded:4e45454453454e433d66726f6224", "QEnvironmentHexEncoded:4e45454453454e43323d66722a6f62", "QEnvironmentHexEncoded:4e45454453454e43333d66726f7d62", "QEnvironmentHexEncoded:4e45454453454e43343d6623726f62", "QEnvironment:EQUALS=foo=bar", ]) def test_launch_QEnvironmentHexEncoded_only(self): class MyResponder(MockGDBServerResponder): def qC(self): return "E42" def qfThreadInfo(self): return "E42" def vRun(self, packet): self.started = True return "E28" def QEnvironment(self, packet): return "" self.server.responder = MyResponder() target = self.createTarget("a.yaml") process = self.connect(target) lldbutil.expect_state_changes(self, self.dbg.GetListener(), process, [lldb.eStateConnected]) target.Launch(lldb.SBListener(), [], # argv ["PLAIN=foo", "NEEDSENC=frob$", "NEEDSENC2=fr*ob", "NEEDSENC3=fro}b", "NEEDSENC4=f#rob", "EQUALS=foo=bar", ], # envp None, # stdin_path None, # stdout_path None, # stderr_path None, # working_directory 0, # launch_flags True, # stop_at_entry lldb.SBError()) # error self.assertPacketLogContains([ "QEnvironmentHexEncoded:504c41494e3d666f6f", "QEnvironmentHexEncoded:4e45454453454e433d66726f6224", "QEnvironmentHexEncoded:4e45454453454e43323d66722a6f62", "QEnvironmentHexEncoded:4e45454453454e43333d66726f7d62", "QEnvironmentHexEncoded:4e45454453454e43343d6623726f62", "QEnvironmentHexEncoded:455155414c533d666f6f3d626172", ]) def test_detach_no_multiprocess(self): class MyResponder(MockGDBServerResponder): def __init__(self): super().__init__() self.detached = None def qfThreadInfo(self): return "10200" def D(self, packet): self.detached = packet return "OK" self.server.responder = MyResponder() target = self.dbg.CreateTarget('') process = self.connect(target) process.Detach() self.assertEqual(self.server.responder.detached, "D") def test_detach_pid(self): class MyResponder(MockGDBServerResponder): def __init__(self, test_case): super().__init__() self.test_case = test_case self.detached = None def qSupported(self, client_supported): self.test_case.assertIn("multiprocess+", client_supported) return "multiprocess+;" + super().qSupported(client_supported) def qfThreadInfo(self): return "mp400.10200" def D(self, packet): self.detached = packet return "OK" self.server.responder = MyResponder(self) target = self.dbg.CreateTarget('') process = self.connect(target) process.Detach() self.assertRegex(self.server.responder.detached, r"D;0*400") def test_signal_gdb(self): class MyResponder(MockGDBServerResponder): def qSupported(self, client_supported): return "PacketSize=3fff;QStartNoAckMode+" def haltReason(self): return "S0a" def cont(self): return self.haltReason() self.server.responder = MyResponder() self.runCmd("platform select remote-linux") target = self.createTarget("a.yaml") process = self.connect(target) self.assertEqual(process.threads[0].GetStopReason(), lldb.eStopReasonSignal) self.assertEqual(process.threads[0].GetStopDescription(100), 'signal SIGBUS') def test_signal_lldb_old(self): class MyResponder(MockGDBServerResponder): def qSupported(self, client_supported): return "PacketSize=3fff;QStartNoAckMode+" def qHostInfo(self): return "triple:61726d76372d756e6b6e6f776e2d6c696e75782d676e75;" def QThreadSuffixSupported(self): return "OK" def haltReason(self): return "S0a" def cont(self): return self.haltReason() self.server.responder = MyResponder() self.runCmd("platform select remote-linux") target = self.createTarget("a.yaml") process = self.connect(target) self.assertEqual(process.threads[0].GetStopReason(), lldb.eStopReasonSignal) self.assertEqual(process.threads[0].GetStopDescription(100), 'signal SIGUSR1') def test_signal_lldb(self): class MyResponder(MockGDBServerResponder): def qSupported(self, client_supported): return "PacketSize=3fff;QStartNoAckMode+;native-signals+" def qHostInfo(self): return "triple:61726d76372d756e6b6e6f776e2d6c696e75782d676e75;" def haltReason(self): return "S0a" def cont(self): return self.haltReason() self.server.responder = MyResponder() self.runCmd("platform select remote-linux") target = self.createTarget("a.yaml") process = self.connect(target) self.assertEqual(process.threads[0].GetStopReason(), lldb.eStopReasonSignal) self.assertEqual(process.threads[0].GetStopDescription(100), 'signal SIGUSR1')
9,621
777
// 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 "components/offline_pages/core/offline_page_feature.h" #include <string> #include "base/feature_list.h" namespace offline_pages { const base::Feature kOfflineBookmarksFeature{"OfflineBookmarks", base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kOffliningRecentPagesFeature{ "OfflineRecentPages", base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kOfflinePagesCTFeature{"OfflinePagesCT", base::FEATURE_ENABLED_BY_DEFAULT}; const base::Feature kOfflinePagesSharingFeature{ "OfflinePagesSharing", base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kOfflinePagesSvelteConcurrentLoadingFeature{ "OfflinePagesSvelteConcurrentLoading", base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kBackgroundLoaderForDownloadsFeature{ "BackgroundLoadingForDownloads", base::FEATURE_ENABLED_BY_DEFAULT}; const base::Feature kOfflinePagesAsyncDownloadFeature{ "OfflinePagesAsyncDownload", base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kNewBackgroundLoaderFeature { "BackgroundLoader", base::FEATURE_DISABLED_BY_DEFAULT }; bool IsOfflineBookmarksEnabled() { return base::FeatureList::IsEnabled(kOfflineBookmarksFeature); } bool IsOffliningRecentPagesEnabled() { return base::FeatureList::IsEnabled(kOffliningRecentPagesFeature); } bool IsOfflinePagesSvelteConcurrentLoadingEnabled() { return base::FeatureList::IsEnabled( kOfflinePagesSvelteConcurrentLoadingFeature); } bool IsOfflinePagesCTEnabled() { return base::FeatureList::IsEnabled(kOfflinePagesCTFeature); } bool IsOfflinePagesSharingEnabled() { return base::FeatureList::IsEnabled(kOfflinePagesSharingFeature); } bool IsBackgroundLoaderForDownloadsEnabled() { return base::FeatureList::IsEnabled(kBackgroundLoaderForDownloadsFeature); } bool IsOfflinePagesAsyncDownloadEnabled() { return base::FeatureList::IsEnabled(kOfflinePagesAsyncDownloadFeature); } bool ShouldUseNewBackgroundLoader() { return base::FeatureList::IsEnabled(kNewBackgroundLoaderFeature); } } // namespace offline_pages
737
1,545
<reponame>pkumar-singh/bookkeeper /* * 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.bookkeeper.stream.storage.impl.kv; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.concurrent.CompletableFuture; import org.apache.bookkeeper.common.concurrent.FutureUtils; import org.apache.bookkeeper.statelib.api.mvcc.MVCCAsyncStore; import org.apache.bookkeeper.stream.protocol.RangeId; import org.apache.bookkeeper.stream.storage.api.kv.TableStore; import org.apache.bookkeeper.stream.storage.impl.store.MVCCStoreFactory; import org.junit.Before; import org.junit.Test; /** * Unit test of {@link TableStoreCache}. */ public class TableStoreCacheTest { private static final long SCID = 3456L; private static final RangeId RID = RangeId.of(1234L, 3456L); private MVCCStoreFactory factory; private TableStoreCache storeCache; @Before public void setUp() { this.factory = mock(MVCCStoreFactory.class); this.storeCache = new TableStoreCache(this.factory); } @Test public void testGetTableStoreWithoutOpen() { assertNull(storeCache.getTableStore(RID)); assertTrue(storeCache.getTableStores().isEmpty()); assertTrue(storeCache.getTableStoresOpening().isEmpty()); } @SuppressWarnings("unchecked") @Test public void testOpenTableStoreSuccessWhenStoreIsNotCached() throws Exception { assertNull(storeCache.getTableStore(RID)); assertTrue(storeCache.getTableStores().isEmpty()); assertTrue(storeCache.getTableStoresOpening().isEmpty()); MVCCAsyncStore<byte[], byte[]> mvccStore = mock(MVCCAsyncStore.class); when(factory.openStore(eq(SCID), eq(RID.getStreamId()), eq(RID.getRangeId()), anyInt())) .thenReturn(FutureUtils.value(mvccStore)); TableStore store = FutureUtils.result(storeCache.openTableStore(SCID, RID, 0)); assertEquals(1, storeCache.getTableStores().size()); assertEquals(0, storeCache.getTableStoresOpening().size()); assertTrue(storeCache.getTableStores().containsKey(RID)); assertSame(store, storeCache.getTableStores().get(RID)); } @Test public void testOpenTableStoreFailureWhenStoreIsNotCached() throws Exception { assertNull(storeCache.getTableStore(RID)); assertTrue(storeCache.getTableStores().isEmpty()); assertTrue(storeCache.getTableStoresOpening().isEmpty()); Exception cause = new Exception("Failure"); when(factory.openStore(eq(SCID), eq(RID.getStreamId()), eq(RID.getRangeId()), anyInt())) .thenReturn(FutureUtils.exception(cause)); try { FutureUtils.result(storeCache.openTableStore(SCID, RID, 0)); fail("Should fail to open table if the underlying factory fails to open a local store"); } catch (Exception ee) { assertSame(cause, ee); } assertEquals(0, storeCache.getTableStores().size()); assertEquals(0, storeCache.getTableStoresOpening().size()); } @Test public void testOpenTableStoreWhenStoreIsCached() throws Exception { TableStore store = mock(TableStore.class); storeCache.getTableStores().put(RID, store); assertSame(store, storeCache.getTableStore(RID)); assertSame(store, FutureUtils.result(storeCache.openTableStore(SCID, RID, 0))); } @SuppressWarnings("unchecked") @Test public void testConcurrentOpenTableStore() throws Exception { MVCCAsyncStore<byte[], byte[]> mvccStore1 = mock(MVCCAsyncStore.class); MVCCAsyncStore<byte[], byte[]> mvccStore2 = mock(MVCCAsyncStore.class); CompletableFuture<MVCCAsyncStore<byte[], byte[]>> future1 = FutureUtils.createFuture(); CompletableFuture<MVCCAsyncStore<byte[], byte[]>> future2 = FutureUtils.createFuture(); when(factory.openStore(eq(SCID), eq(RID.getStreamId()), eq(RID.getRangeId()), anyInt())) .thenReturn(future1) .thenReturn(future2); CompletableFuture<TableStore> openFuture1 = storeCache.openTableStore(SCID, RID, 0); assertEquals(0, storeCache.getTableStores().size()); assertEquals(1, storeCache.getTableStoresOpening().size()); CompletableFuture<TableStore> openFuture2 = storeCache.openTableStore(SCID, RID, 0); assertEquals(0, storeCache.getTableStores().size()); assertEquals(1, storeCache.getTableStoresOpening().size()); assertSame(openFuture1, openFuture2); future1.complete(mvccStore1); future1.complete(mvccStore2); TableStore store1 = FutureUtils.result(openFuture1); TableStore store2 = FutureUtils.result(openFuture2); assertSame(store1, store2); assertEquals(0, storeCache.getTableStoresOpening().size()); assertEquals(1, storeCache.getTableStores().size()); assertSame(store1, storeCache.getTableStores().get(RID)); verify(factory, times(1)) .openStore(eq(SCID), eq(RID.getStreamId()), eq(RID.getRangeId()), anyInt()); } }
2,324
2,542
<filename>src/prod/src/inc/clr/pal/pal_capi.h // ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #ifndef __PAL_CAPI_H__ #define __PAL_CAPI_H__ // cert store location. static const UINT CERT_SYSTEM_STORE_UNPROTECTED_FLAG = 0x40000000; static const UINT CERT_SYSTEM_STORE_LOCATION_MASK = 0x00FF0000; static const UINT CERT_SYSTEM_STORE_LOCATION_SHIFT = 16; static const UINT CERT_SYSTEM_STORE_CURRENT_USER_ID = 1; static const UINT CERT_SYSTEM_STORE_LOCAL_MACHINE_ID = 2; static const UINT CERT_SYSTEM_STORE_CURRENT_SERVICE_ID = 4; static const UINT CERT_SYSTEM_STORE_SERVICES_ID = 5; static const UINT CERT_SYSTEM_STORE_USERS_ID = 6; static const UINT CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY_ID = 7; static const UINT CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY_ID = 8; static const UINT CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE_ID = 9; static const UINT CERT_SYSTEM_STORE_CURRENT_USER = ((INT) CERT_SYSTEM_STORE_CURRENT_USER_ID << (INT) CERT_SYSTEM_STORE_LOCATION_SHIFT); static const UINT CERT_SYSTEM_STORE_LOCAL_MACHINE = ((INT) CERT_SYSTEM_STORE_LOCAL_MACHINE_ID << (INT) CERT_SYSTEM_STORE_LOCATION_SHIFT); static const UINT CERT_SYSTEM_STORE_CURRENT_SERVICE = ((INT) CERT_SYSTEM_STORE_CURRENT_SERVICE_ID << (INT) CERT_SYSTEM_STORE_LOCATION_SHIFT); static const UINT CERT_SYSTEM_STORE_SERVICES = ((INT) CERT_SYSTEM_STORE_SERVICES_ID << (INT) CERT_SYSTEM_STORE_LOCATION_SHIFT); static const UINT CERT_SYSTEM_STORE_USERS = ((INT) CERT_SYSTEM_STORE_USERS_ID << (INT) CERT_SYSTEM_STORE_LOCATION_SHIFT); static const UINT CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY = ((INT) CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY_ID << (INT) CERT_SYSTEM_STORE_LOCATION_SHIFT); static const UINT CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY = ((INT) CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY_ID << (INT) CERT_SYSTEM_STORE_LOCATION_SHIFT); static const UINT CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE = ((INT) CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE_ID << (INT) CERT_SYSTEM_STORE_LOCATION_SHIFT); // cert info flags. static const UINT CERT_INFO_VERSION_FLAG = 1; static const UINT CERT_INFO_SERIAL_NUMBER_FLAG = 2; static const UINT CERT_INFO_SIGNATURE_ALGORITHM_FLAG = 3; static const UINT CERT_INFO_ISSUER_FLAG = 4; static const UINT CERT_INFO_NOT_BEFORE_FLAG = 5; static const UINT CERT_INFO_NOT_AFTER_FLAG = 6; static const UINT CERT_INFO_SUBJECT_FLAG = 7; static const UINT CERT_INFO_SUBJECT_PUBLIC_KEY_INFO_FLAG = 8; static const UINT CERT_INFO_ISSUER_UNIQUE_ID_FLAG = 9; static const UINT CERT_INFO_SUBJECT_UNIQUE_ID_FLAG = 10; static const UINT CERT_INFO_EXTENSION_FLAG = 11; // cert compare flags. static const UINT CERT_COMPARE_MASK = 0xFFFF; static const UINT CERT_COMPARE_SHIFT = 16; static const UINT CERT_COMPARE_ANY = 0; static const UINT CERT_COMPARE_SHA1_HASH = 1; static const UINT CERT_COMPARE_NAME = 2; static const UINT CERT_COMPARE_ATTR = 3; static const UINT CERT_COMPARE_MD5_HASH = 4; static const UINT CERT_COMPARE_PROPERTY = 5; static const UINT CERT_COMPARE_PUBLIC_KEY = 6; static const UINT CERT_COMPARE_HASH = CERT_COMPARE_SHA1_HASH; static const UINT CERT_COMPARE_NAME_STR_A = 7; static const UINT CERT_COMPARE_NAME_STR_W = 8; static const UINT CERT_COMPARE_KEY_SPEC = 9; static const UINT CERT_COMPARE_ENHKEY_USAGE = 10; static const UINT CERT_COMPARE_CTL_USAGE = CERT_COMPARE_ENHKEY_USAGE; static const UINT CERT_COMPARE_SUBJECT_CERT = 11; static const UINT CERT_COMPARE_ISSUER_OF = 12; static const UINT CERT_COMPARE_EXISTING = 13; static const UINT CERT_COMPARE_SIGNATURE_HASH = 14; static const UINT CERT_COMPARE_KEY_IDENTIFIER = 15; static const UINT CERT_COMPARE_CERT_ID = 16; static const UINT CERT_COMPARE_CROSS_CERT_DIST_POINTS = 17; static const UINT CERT_COMPARE_PUBKEY_MD5_HASH = 18; // cert find flags. static const UINT CERT_FIND_ANY = ((INT) CERT_COMPARE_ANY << (INT) CERT_COMPARE_SHIFT); static const UINT CERT_FIND_SHA1_HASH = ((INT) CERT_COMPARE_SHA1_HASH << (INT) CERT_COMPARE_SHIFT); static const UINT CERT_FIND_MD5_HASH = ((INT) CERT_COMPARE_MD5_HASH << (INT) CERT_COMPARE_SHIFT); static const UINT CERT_FIND_SIGNATURE_HASH = ((INT) CERT_COMPARE_SIGNATURE_HASH << (INT) CERT_COMPARE_SHIFT); static const UINT CERT_FIND_KEY_IDENTIFIER = ((INT) CERT_COMPARE_KEY_IDENTIFIER << (INT) CERT_COMPARE_SHIFT); static const UINT CERT_FIND_HASH = CERT_FIND_SHA1_HASH; static const UINT CERT_FIND_PROPERTY = ((INT) CERT_COMPARE_PROPERTY << (INT) CERT_COMPARE_SHIFT); static const UINT CERT_FIND_PUBLIC_KEY = ((INT) CERT_COMPARE_PUBLIC_KEY << (INT) CERT_COMPARE_SHIFT); static const UINT CERT_FIND_SUBJECT_NAME = ((INT) CERT_COMPARE_NAME << (INT) CERT_COMPARE_SHIFT | (INT) CERT_INFO_SUBJECT_FLAG); static const UINT CERT_FIND_SUBJECT_ATTR = ((INT) CERT_COMPARE_ATTR << (INT) CERT_COMPARE_SHIFT | (INT) CERT_INFO_SUBJECT_FLAG); static const UINT CERT_FIND_ISSUER_NAME = ((INT) CERT_COMPARE_NAME << (INT) CERT_COMPARE_SHIFT | (INT) CERT_INFO_ISSUER_FLAG); static const UINT CERT_FIND_ISSUER_ATTR = ((INT) CERT_COMPARE_ATTR << (INT) CERT_COMPARE_SHIFT | (INT) CERT_INFO_ISSUER_FLAG); static const UINT CERT_FIND_SUBJECT_STR_A = ((INT) CERT_COMPARE_NAME_STR_A << (INT) CERT_COMPARE_SHIFT | (INT) CERT_INFO_SUBJECT_FLAG); static const UINT CERT_FIND_SUBJECT_STR_W = ((INT) CERT_COMPARE_NAME_STR_W << (INT) CERT_COMPARE_SHIFT | (INT) CERT_INFO_SUBJECT_FLAG); static const UINT CERT_FIND_SUBJECT_STR = CERT_FIND_SUBJECT_STR_W; static const UINT CERT_FIND_ISSUER_STR_A = ((INT) CERT_COMPARE_NAME_STR_A << (INT) CERT_COMPARE_SHIFT | (INT) CERT_INFO_ISSUER_FLAG); static const UINT CERT_FIND_ISSUER_STR_W = ((INT) CERT_COMPARE_NAME_STR_W << (INT) CERT_COMPARE_SHIFT | (INT) CERT_INFO_ISSUER_FLAG); static const UINT CERT_FIND_ISSUER_STR = CERT_FIND_ISSUER_STR_W; static const UINT CERT_FIND_KEY_SPEC = ((INT) CERT_COMPARE_KEY_SPEC << (INT) CERT_COMPARE_SHIFT); static const UINT CERT_FIND_ENHKEY_USAGE = ((INT) CERT_COMPARE_ENHKEY_USAGE << (INT) CERT_COMPARE_SHIFT); static const UINT CERT_FIND_CTL_USAGE = CERT_FIND_ENHKEY_USAGE; static const UINT CERT_FIND_SUBJECT_CERT = ((INT) CERT_COMPARE_SUBJECT_CERT << (INT) CERT_COMPARE_SHIFT); static const UINT CERT_FIND_ISSUER_OF = ((INT) CERT_COMPARE_ISSUER_OF << (INT) CERT_COMPARE_SHIFT); static const UINT CERT_FIND_EXISTING = ((INT) CERT_COMPARE_EXISTING << (INT) CERT_COMPARE_SHIFT); static const UINT CERT_FIND_CERT_ID = ((INT) CERT_COMPARE_CERT_ID << (INT) CERT_COMPARE_SHIFT); static const UINT CERT_FIND_CROSS_CERT_DIST_POINTS = ((INT) CERT_COMPARE_CROSS_CERT_DIST_POINTS << (INT) CERT_COMPARE_SHIFT); static const UINT CERT_FIND_PUBKEY_MD5_HASH = ((INT) CERT_COMPARE_PUBKEY_MD5_HASH << (INT) CERT_COMPARE_SHIFT); typedef struct _CRYPTOAPI_BLOB { DWORD cbData; BYTE *pbData; } CRYPT_INTEGER_BLOB, *PCRYPT_INTEGER_BLOB, CRYPT_UINT_BLOB, *PCRYPT_UINT_BLOB, CRYPT_OBJID_BLOB, *PCRYPT_OBJID_BLOB, CERT_NAME_BLOB, CERT_RDN_VALUE_BLOB, *PCERT_NAME_BLOB, *PCERT_RDN_VALUE_BLOB, CERT_BLOB, *PCERT_BLOB, CRL_BLOB, *PCRL_BLOB, DATA_BLOB, *PDATA_BLOB, CRYPT_DATA_BLOB, *PCRYPT_DATA_BLOB, CRYPT_HASH_BLOB, *PCRYPT_HASH_BLOB, CRYPT_DIGEST_BLOB, *PCRYPT_DIGEST_BLOB, CRYPT_DER_BLOB, PCRYPT_DER_BLOB, CRYPT_ATTR_BLOB, *PCRYPT_ATTR_BLOB; typedef struct _CRYPT_BIT_BLOB { DWORD cbData; BYTE *pbData; DWORD cUnusedBits; } CRYPT_BIT_BLOB, *PCRYPT_BIT_BLOB; typedef struct _CERT_EXTENSION { LPSTR pszObjId; BOOL fCritical; CRYPT_OBJID_BLOB Value; } CERT_EXTENSION, *PCERT_EXTENSION; typedef struct _CRYPT_ALGORITHM_IDENTIFIER { LPSTR pszObjId; CRYPT_OBJID_BLOB Parameters; } CRYPT_ALGORITHM_IDENTIFIER, *PCRYPT_ALGORITHM_IDENTIFIER; typedef struct _CERT_PUBLIC_KEY_INFO { CRYPT_ALGORITHM_IDENTIFIER Algorithm; CRYPT_BIT_BLOB PublicKey; } CERT_PUBLIC_KEY_INFO, *PCERT_PUBLIC_KEY_INFO; typedef struct _CERT_INFO { DWORD dwVersion; CRYPT_INTEGER_BLOB SerialNumber; CRYPT_ALGORITHM_IDENTIFIER SignatureAlgorithm; CERT_NAME_BLOB Issuer; FILETIME NotBefore; FILETIME NotAfter; CERT_NAME_BLOB Subject; CERT_PUBLIC_KEY_INFO SubjectPublicKeyInfo; CRYPT_BIT_BLOB IssuerUniqueId; CRYPT_BIT_BLOB SubjectUniqueId; DWORD cExtension; PCERT_EXTENSION rgExtension; } CERT_INFO, *PCERT_INFO; typedef void * HCERTSTORE; typedef struct _CERT_CONTEXT { DWORD dwCertEncodingType; BYTE *pbCertEncoded; DWORD cbCertEncoded; PCERT_INFO pCertInfo; HCERTSTORE hCertStore; } CERT_CONTEXT, *PCERT_CONTEXT; typedef const CERT_CONTEXT *PCCERT_CONTEXT; #endif // __PAL_CAPI_H__
4,879
1,968
<gh_stars>1000+ ////////////////////////////////////////////////////////////////////////////// // // This file is part of the Corona game engine. // For overview and more information on licensing please refer to README.md // Home page: https://github.com/coronalabs/corona // Contact: <EMAIL> // ////////////////////////////////////////////////////////////////////////////// #ifndef _Rtt_TesselatorStream_H__ #define _Rtt_TesselatorStream_H__ #include "Core/Rtt_Geometry.h" #include "Rtt_RenderingStream.h" // ---------------------------------------------------------------------------- namespace Rtt { class Matrix; class VertexCache; // ---------------------------------------------------------------------------- class TesselatorStream : public RenderingStream { public: typedef RenderingStream Super; // Returns number of elements added // typedef int (*DidSubdivideArc)( ArrayVertex2& vertices, ); private: static const Vertex2 kUnitCircleVertices[]; public: // If non-NULL, srcToDstSpace is used to transform all generated // vertices. It overrides the "origin" parameter for the Submit() // methods (i.e. rounded rectangle, circle, ellipse). If NULL, then // the origin parameter is used to displace (translate) the vertices. TesselatorStream( const Matrix* srcToDstSpace, VertexCache& cache ); // const Matrix* srcToDstSpace, // ArrayVertex2& vertices, // ArrayS32& counts ); protected: void ApplyTransform( const Vertex2& origin ); private: void SubdivideCircleSegment( const Vertex2& p1, const Vertex2& p2, int depth ); void SubdivideCircleArc( const Vertex2& p1, const Vertex2& p2, int depth, bool appendDuplicate ); protected: enum _Constants { kNoScale = 0x1, kAppendDuplicate = 0x2, kAppendArcEndPoints = 0x4 }; void AppendCircle( Real radius, bool circularSegmentOnly ); void AppendCircleArc( Real radius, U32 options ); void AppendRectangle( Real halfW, Real halfH ); protected: const Matrix* fSrcToDstSpace; VertexCache& fCache; private: int fMaxSubdivideDepth; }; // ---------------------------------------------------------------------------- } // namespace Rtt // ---------------------------------------------------------------------------- #endif // _Rtt_TesselatorStream_H__
677
14,668
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.browserservices.ui.controller.trustedwebactivity; import static org.chromium.chrome.browser.dependency_injection.ChromeCommonQualifiers.SAVED_INSTANCE_SUPPLIER; import android.os.Bundle; import org.chromium.base.supplier.Supplier; import org.chromium.chrome.browser.browserservices.intents.BrowserServicesIntentDataProvider; import org.chromium.chrome.browser.customtabs.CustomTabsConnection; import org.chromium.chrome.browser.dependency_injection.ActivityScope; import org.chromium.chrome.browser.lifecycle.ActivityLifecycleDispatcher; import org.chromium.chrome.browser.lifecycle.SaveInstanceStateObserver; import javax.inject.Inject; import javax.inject.Named; /** * Provides the client package name for TWAs - this can come from either the Custom Tabs Connection * or one previously stored in the Activity's save instance state. */ @ActivityScope public class ClientPackageNameProvider implements SaveInstanceStateObserver { /** Key for storing in Activity instance state. */ private static final String KEY_CLIENT_PACKAGE = "twaClientPackageName"; private final String mClientPackageName; @Inject public ClientPackageNameProvider(ActivityLifecycleDispatcher lifecycleDispatcher, BrowserServicesIntentDataProvider intentDataProvider, CustomTabsConnection customTabsConnection, @Named(SAVED_INSTANCE_SUPPLIER) Supplier<Bundle> savedInstanceStateSupplier) { Bundle savedInstanceState = savedInstanceStateSupplier.get(); if (savedInstanceState != null) { mClientPackageName = savedInstanceState.getString(KEY_CLIENT_PACKAGE); } else { mClientPackageName = customTabsConnection.getClientPackageNameForSession( intentDataProvider.getSession()); } assert mClientPackageName != null; lifecycleDispatcher.register(this); } @Override public void onSaveInstanceState(Bundle outState) { // TODO(pshmakov): address this problem in a more general way, http://crbug.com/952221 outState.putString(KEY_CLIENT_PACKAGE, mClientPackageName); } public String get() { return mClientPackageName; } }
793
529
<reponame>PervasiveDigital/netmf-interpreter #include <tinyhal.h> #include <mfupdate_decl.h> static const IUpdatePackage s_UpdatePackages[] = { { "NetMF", NULL, NULL, NULL, NULL, }, }; const IUpdatePackage* g_UpdatePackages = s_UpdatePackages; const INT32 g_UpdatePackageCount = ARRAYSIZE(s_UpdatePackages);
195
575
<filename>extensions/common/manifest.cc<gh_stars>100-1000 // Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "extensions/common/manifest.h" #include <utility> #include "base/check.h" #include "base/logging.h" #include "base/memory/ptr_util.h" #include "base/notreached.h" #include "base/strings/strcat.h" #include "base/strings/utf_string_conversions.h" #include "extensions/common/api/shared_module.h" #include "extensions/common/error_utils.h" #include "extensions/common/features/feature.h" #include "extensions/common/features/feature_provider.h" #include "extensions/common/install_warning.h" #include "extensions/common/manifest_constants.h" #include "extensions/common/manifest_handler_helpers.h" using extensions::mojom::ManifestLocation; namespace extensions { namespace keys = manifest_keys; namespace { // Rank extension locations in a way that allows // Manifest::GetHigherPriorityLocation() to compare locations. // An extension installed from two locations will have the location // with the higher rank, as returned by this function. The actual // integer values may change, and should never be persisted. int GetLocationRank(ManifestLocation location) { const int kInvalidRank = -1; int rank = kInvalidRank; // Will CHECK that rank is not kInvalidRank. switch (location) { // Component extensions can not be overridden by any other type. case ManifestLocation::kComponent: rank = 9; break; case ManifestLocation::kExternalComponent: rank = 8; break; // Policy controlled extensions may not be overridden by any type // that is not part of chrome. case ManifestLocation::kExternalPolicy: rank = 7; break; case ManifestLocation::kExternalPolicyDownload: rank = 6; break; // A developer-loaded extension should override any installed type // that a user can disable. Anything specified on the command-line should // override one loaded via the extensions UI. case ManifestLocation::kCommandLine: rank = 5; break; case ManifestLocation::kUnpacked: rank = 4; break; // The relative priority of various external sources is not important, // but having some order ensures deterministic behavior. case ManifestLocation::kExternalRegistry: rank = 3; break; case ManifestLocation::kExternalPref: rank = 2; break; case ManifestLocation::kExternalPrefDownload: rank = 1; break; // User installed extensions are overridden by any external type. case ManifestLocation::kInternal: rank = 0; break; // kInvalidLocation should never be passed to this function. case ManifestLocation::kInvalidLocation: break; } CHECK(rank != kInvalidRank); return rank; } int GetManifestVersion(const base::DictionaryValue& manifest_value, Manifest::Type type) { // Platform apps were launched after manifest version 2 was the preferred // version, so they default to that. int manifest_version = type == Manifest::TYPE_PLATFORM_APP ? 2 : 1; manifest_value.GetInteger(keys::kManifestVersion, &manifest_version); return manifest_version; } // Helper class to filter available values from a manifest. class AvailableValuesFilter { public: // Filters `manifest.values()` removing any unavailable keys. static base::Value Filter(const Manifest& manifest) { return FilterInternal(manifest, *manifest.value(), ""); } private: // Returns a DictionaryValue corresponding to |input_dict| for the given // |manifest|, with all unavailable keys removed. static base::Value FilterInternal(const Manifest& manifest, const base::Value& input_dict, std::string current_path) { base::Value output_dict(base::Value::Type::DICTIONARY); DCHECK(input_dict.is_dict()); DCHECK(CanAccessFeature(manifest, current_path)); for (const auto& it : input_dict.DictItems()) { std::string child_path = CombineKeys(current_path, it.first); // Unavailable key, skip it. if (!CanAccessFeature(manifest, child_path)) continue; // If |child_path| corresponds to a leaf node, copy it. bool is_leaf_node = !it.second.is_dict(); if (is_leaf_node) { output_dict.SetKey(it.first, it.second.Clone()); continue; } // Child dictionary. Populate it recursively. output_dict.SetKey(it.first, FilterInternal(manifest, it.second, child_path)); } return output_dict; } // Returns true if the manifest feature corresponding to |feature_path| is // available to this manifest. Note: This doesn't check parent feature // availability. This is ok since we check feature availability in a // breadth-first manner below which ensures that we only ever check a child // feature if its parent is available. Note that api features don't follow // similar availability semantics i.e. we can have child api features be // available even if the parent feature is not (e.g., // runtime.sendMessage()). static bool CanAccessFeature(const Manifest& manifest, const std::string& feature_path) { const Feature* feature = FeatureProvider::GetManifestFeatures()->GetFeature(feature_path); // TODO(crbug.com/1171466): We assume that if a feature does not exist, // it is available. This is ok for child features (if its parent is // available) but is probably not correct for top-level features. We // should see if false can be returned for these non-existent top-level // features here. if (!feature) return true; return feature ->IsAvailableToManifest(manifest.hashed_id(), manifest.type(), manifest.location(), manifest.manifest_version()) .is_available(); } static std::string CombineKeys(const std::string& parent, const std::string& child) { if (parent.empty()) return child; return base::StrCat({parent, ".", child}); } }; } // namespace // static ManifestLocation Manifest::GetHigherPriorityLocation(ManifestLocation loc1, ManifestLocation loc2) { if (loc1 == loc2) return loc1; int loc1_rank = GetLocationRank(loc1); int loc2_rank = GetLocationRank(loc2); // If two different locations have the same rank, then we can not // deterministicly choose a location. CHECK(loc1_rank != loc2_rank); // Highest rank has highest priority. return (loc1_rank > loc2_rank ? loc1 : loc2 ); } // static Manifest::Type Manifest::GetTypeFromManifestValue( const base::DictionaryValue& value, bool for_login_screen) { Type type = TYPE_UNKNOWN; if (value.HasKey(keys::kTheme)) { type = TYPE_THEME; } else if (value.HasKey(api::shared_module::ManifestKeys::kExport)) { type = TYPE_SHARED_MODULE; } else if (value.HasKey(keys::kApp)) { if (value.Get(keys::kWebURLs, nullptr) || value.Get(keys::kLaunchWebURL, nullptr)) { type = TYPE_HOSTED_APP; } else if (value.Get(keys::kPlatformAppBackground, nullptr)) { type = TYPE_PLATFORM_APP; } else { type = TYPE_LEGACY_PACKAGED_APP; } } else if (for_login_screen) { type = TYPE_LOGIN_SCREEN_EXTENSION; } else { type = TYPE_EXTENSION; } DCHECK_NE(type, TYPE_UNKNOWN); return type; } // static bool Manifest::ShouldAlwaysLoadExtension(ManifestLocation location, bool is_theme) { if (location == ManifestLocation::kComponent) return true; // Component extensions are always allowed. if (is_theme) return true; // Themes are allowed, even with --disable-extensions. // TODO(devlin): This seems wrong. See https://crbug.com/833540. if (Manifest::IsExternalLocation(location)) return true; return false; } // static std::unique_ptr<Manifest> Manifest::CreateManifestForLoginScreen( ManifestLocation location, std::unique_ptr<base::DictionaryValue> value, ExtensionId extension_id) { CHECK(IsPolicyLocation(location)); // Use base::WrapUnique + new because the constructor is private. return base::WrapUnique( new Manifest(location, std::move(value), std::move(extension_id), true)); } Manifest::Manifest(ManifestLocation location, std::unique_ptr<base::DictionaryValue> value, ExtensionId extension_id) : Manifest(location, std::move(value), std::move(extension_id), false) {} Manifest::Manifest(ManifestLocation location, std::unique_ptr<base::DictionaryValue> value, ExtensionId extension_id, bool for_login_screen) : extension_id_(std::move(extension_id)), hashed_id_(HashedExtensionId(extension_id_)), location_(location), value_(std::move(value)), type_(GetTypeFromManifestValue(*value_, for_login_screen)), manifest_version_(GetManifestVersion(*value_, type_)) { DCHECK(!extension_id_.empty()); available_values_ = base::DictionaryValue::From( base::Value::ToUniquePtrValue(AvailableValuesFilter::Filter(*this))); } Manifest::~Manifest() = default; bool Manifest::ValidateManifest( std::string* error, std::vector<InstallWarning>* warnings) const { *error = ""; // Check every feature to see if its in the manifest. Note that this means // we will ignore keys that are not features; we do this for forward // compatibility. const FeatureProvider* manifest_feature_provider = FeatureProvider::GetManifestFeatures(); for (const auto& map_entry : manifest_feature_provider->GetAllFeatures()) { // Use Get instead of HasKey because the former uses path expansion. if (!value_->Get(map_entry.first, nullptr)) continue; Feature::Availability result = map_entry.second->IsAvailableToManifest( hashed_id_, type_, location_, manifest_version_); if (!result.is_available()) warnings->push_back(InstallWarning(result.message(), map_entry.first)); } // Also generate warnings for keys that are not features. for (base::DictionaryValue::Iterator it(*value_); !it.IsAtEnd(); it.Advance()) { if (!manifest_feature_provider->GetFeature(it.key())) { warnings->push_back(InstallWarning( ErrorUtils::FormatErrorMessage( manifest_errors::kUnrecognizedManifestKey, it.key()), it.key())); } } if (IsUnpackedLocation(location_) && value_->FindPath(manifest_keys::kDifferentialFingerprint)) { warnings->push_back( InstallWarning(manifest_errors::kHasDifferentialFingerprint, manifest_keys::kDifferentialFingerprint)); } return true; } bool Manifest::HasKey(const std::string& key) const { return available_values_->HasKey(key); } bool Manifest::HasPath(const std::string& path) const { const base::Value* ignored = nullptr; return available_values_->Get(path, &ignored); } bool Manifest::Get( const std::string& path, const base::Value** out_value) const { return available_values_->Get(path, out_value); } bool Manifest::GetBoolean( const std::string& path, bool* out_value) const { return available_values_->GetBoolean(path, out_value); } bool Manifest::GetInteger( const std::string& path, int* out_value) const { return available_values_->GetInteger(path, out_value); } bool Manifest::GetString( const std::string& path, std::string* out_value) const { return available_values_->GetString(path, out_value); } bool Manifest::GetString(const std::string& path, std::u16string* out_value) const { return available_values_->GetString(path, out_value); } bool Manifest::GetDictionary( const std::string& path, const base::DictionaryValue** out_value) const { return available_values_->GetDictionary(path, out_value); } bool Manifest::GetDictionary(const std::string& path, const base::Value** out_value) const { return GetPathOfType(path, base::Value::Type::DICTIONARY, out_value); } bool Manifest::GetList( const std::string& path, const base::ListValue** out_value) const { return available_values_->GetList(path, out_value); } bool Manifest::GetList(const std::string& path, const base::Value** out_value) const { return GetPathOfType(path, base::Value::Type::LIST, out_value); } bool Manifest::GetPathOfType(const std::string& path, base::Value::Type type, const base::Value** out_value) const { const std::vector<base::StringPiece> components = manifest_handler_helpers::TokenizeDictionaryPath(path); *out_value = available_values_->FindPathOfType(components, type); return *out_value != nullptr; } bool Manifest::EqualsForTesting(const Manifest& other) const { return value_->Equals(other.value()) && location_ == other.location_ && extension_id_ == other.extension_id_; } } // namespace extensions
4,738
14,668
<gh_stars>1000+ import pytest from webdriver.error import NoSuchAlertException from tests.support.asserts import assert_error, assert_success def get_computed_role(session, element): return session.transport.send( "GET", "session/{session_id}/element/{element_id}/computedrole".format( session_id=session.session_id, element_id=element)) def test_no_browsing_context(session, closed_window): response = get_computed_role(session, "id") assert_error(response, "no such window") def test_no_user_prompt(session): response = get_computed_role(session, "id") assert_error(response, "no such alert") @pytest.mark.parametrize("html,tag,expected", [ ("<li role=menuitem>foo", "li", "menu"), ("<input role=searchbox>", "input", "searchbox"), ("<img role=presentation>", "img", "presentation")]) def test_computed_roles(session, inline, html, tag, expected): session.url = inline(html) element = session.find.css(tag, all=False) result = get_computed_role(session, element.id) assert_success(result, expected)
403
852
<reponame>ckamtsikis/cmssw #include <cstdlib> #include <iostream> #include "DetectorDescription/Core/interface/DDCompactView.h" #include "DetectorDescription/RegressionTest/src/DDCheck.h" #include "DetectorDescription/Parser/interface/DDLParser.h" #include "DetectorDescription/Parser/interface/FIPConfiguration.h" #include "FWCore/PluginManager/interface/PluginManager.h" #include "FWCore/PluginManager/interface/standard.h" #include "FWCore/Utilities/interface/Exception.h" int main(int argc, char* argv[]) { try { edmplugin::PluginManager::configure(edmplugin::standard::config()); std::cout << "Get a hold of aDDLParser." << std::endl; DDCompactView cpv; DDLParser myP(cpv); std::cout << "main:: initialize" << std::endl; std::cout << "======================" << std::endl << std::endl; std::cout << "Defining my Document Provider, using the default one provided" << std::endl; FIPConfiguration cf(cpv); std::cout << "Make sure the provider is ready... you don't need this, it's just necessary for the default one." << std::endl; int errNumcf; errNumcf = cf.readConfig("DetectorDescription/Parser/test/config1.xml"); if (!errNumcf) { std::cout << "about to call DumpFileList of configuration cf" << std::endl; cf.dumpFileList(); } else { std::cout << "error in ReadConfig" << std::endl; return -1; } // Parse the files provided by the DDLDocumentProvider above. std::cout << " parse all the files provided by the DDLDocumentProvider" << std::endl; myP.parse(cf); std::cout << "===================" << std::endl << std::endl; std::cout << " parse just one file THAT WAS ALREADY PARSED (materials.xml). We should get a WARNING message." << std::endl; myP.parseOneFile("DetectorDescription/Parser/test/materials.xml"); std::cout << "===================" << std::endl << std::endl; std::cout << " parse just one file that has not been parsed (specpars.xml). This should just go through." << std::endl; myP.parseOneFile("DetectorDescription/Parser/test/specpars.xml"); std::cout << "===================" << std::endl << std::endl; std::cout << " make a new provider and read some other configuration" << std::endl; FIPConfiguration cf2(cpv); cf2.readConfig("DetectorDescription/Parser/test/config2.xml"); myP.parse(cf2); std::cout << "Done Parsing" << std::endl; std::cout << "===================" << std::endl << std::endl; std::cout << std::endl << std::endl << "main::Start checking!" << std::endl << std::endl; DDCheckMaterials(std::cout); std::cout << "cleared DDCompactView. " << std::endl; return EXIT_SUCCESS; } catch (cms::Exception& e) { std::cout << "main::PROBLEM:" << std::endl << " " << e.what() << std::endl; } }
1,066
11,351
package com.netflix.discovery.shared.transport.jersey2; import static com.netflix.discovery.util.DiscoveryBuildInfo.buildVersion; import java.io.FileInputStream; import java.io.IOException; import java.security.KeyStore; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import org.apache.http.client.params.ClientPNames; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.params.CoreProtocolPNames; import org.glassfish.jersey.apache.connector.ApacheClientProperties; import org.glassfish.jersey.apache.connector.ApacheConnectorProvider; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.client.ClientProperties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.discovery.converters.wrappers.CodecWrappers; import com.netflix.discovery.converters.wrappers.DecoderWrapper; import com.netflix.discovery.converters.wrappers.EncoderWrapper; import com.netflix.discovery.provider.DiscoveryJerseyProvider; import com.netflix.servo.monitor.BasicCounter; import com.netflix.servo.monitor.BasicTimer; import com.netflix.servo.monitor.Counter; import com.netflix.servo.monitor.MonitorConfig; import com.netflix.servo.monitor.Monitors; import com.netflix.servo.monitor.Stopwatch; /** * @author <NAME> */ public class EurekaJersey2ClientImpl implements EurekaJersey2Client { private static final Logger s_logger = LoggerFactory.getLogger(EurekaJersey2ClientImpl.class); private static final int HTTP_CONNECTION_CLEANER_INTERVAL_MS = 30 * 1000; private static final String PROTOCOL = "https"; private static final String PROTOCOL_SCHEME = "SSL"; private static final int HTTPS_PORT = 443; private static final String KEYSTORE_TYPE = "JKS"; private final Client apacheHttpClient; private final ConnectionCleanerTask connectionCleanerTask; ClientConfig jerseyClientConfig; private final ScheduledExecutorService eurekaConnCleaner = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { private final AtomicInteger threadNumber = new AtomicInteger(1); @Override public Thread newThread(Runnable r) { Thread thread = new Thread(r, "Eureka-Jersey2Client-Conn-Cleaner" + threadNumber.incrementAndGet()); thread.setDaemon(true); return thread; } }); public EurekaJersey2ClientImpl( int connectionTimeout, int readTimeout, final int connectionIdleTimeout, ClientConfig clientConfig) { try { jerseyClientConfig = clientConfig; jerseyClientConfig.register(DiscoveryJerseyProvider.class); // Disable json autodiscovery, since json (de)serialization is provided by DiscoveryJerseyProvider jerseyClientConfig.property(ClientProperties.JSON_PROCESSING_FEATURE_DISABLE, Boolean.TRUE); jerseyClientConfig.property(ClientProperties.MOXY_JSON_FEATURE_DISABLE, Boolean.TRUE); jerseyClientConfig.connectorProvider(new ApacheConnectorProvider()); jerseyClientConfig.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout); jerseyClientConfig.property(ClientProperties.READ_TIMEOUT, readTimeout); apacheHttpClient = ClientBuilder.newClient(jerseyClientConfig); connectionCleanerTask = new ConnectionCleanerTask(connectionIdleTimeout); eurekaConnCleaner.scheduleWithFixedDelay( connectionCleanerTask, HTTP_CONNECTION_CLEANER_INTERVAL_MS, HTTP_CONNECTION_CLEANER_INTERVAL_MS, TimeUnit.MILLISECONDS); } catch (Throwable e) { throw new RuntimeException("Cannot create Jersey2 client", e); } } @Override public Client getClient() { return apacheHttpClient; } /** * Clean up resources. */ @Override public void destroyResources() { if (eurekaConnCleaner != null) { // Execute the connection cleaner one final time during shutdown eurekaConnCleaner.execute(connectionCleanerTask); eurekaConnCleaner.shutdown(); } if (apacheHttpClient != null) { apacheHttpClient.close(); } } public static class EurekaJersey2ClientBuilder { private boolean systemSSL; private String clientName; private int maxConnectionsPerHost; private int maxTotalConnections; private String trustStoreFileName; private String trustStorePassword; private String userAgent; private String proxyUserName; private String proxyPassword; private String proxyHost; private String proxyPort; private int connectionTimeout; private int readTimeout; private int connectionIdleTimeout; private EncoderWrapper encoderWrapper; private DecoderWrapper decoderWrapper; public EurekaJersey2ClientBuilder withClientName(String clientName) { this.clientName = clientName; return this; } public EurekaJersey2ClientBuilder withUserAgent(String userAgent) { this.userAgent = userAgent; return this; } public EurekaJersey2ClientBuilder withConnectionTimeout(int connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } public EurekaJersey2ClientBuilder withReadTimeout(int readTimeout) { this.readTimeout = readTimeout; return this; } public EurekaJersey2ClientBuilder withConnectionIdleTimeout(int connectionIdleTimeout) { this.connectionIdleTimeout = connectionIdleTimeout; return this; } public EurekaJersey2ClientBuilder withMaxConnectionsPerHost(int maxConnectionsPerHost) { this.maxConnectionsPerHost = maxConnectionsPerHost; return this; } public EurekaJersey2ClientBuilder withMaxTotalConnections(int maxTotalConnections) { this.maxTotalConnections = maxTotalConnections; return this; } public EurekaJersey2ClientBuilder withProxy(String proxyHost, String proxyPort, String user, String password) { this.proxyHost = proxyHost; this.proxyPort = proxyPort; this.proxyUserName = user; this.proxyPassword = password; return this; } public EurekaJersey2ClientBuilder withSystemSSLConfiguration() { this.systemSSL = true; return this; } public EurekaJersey2ClientBuilder withTrustStoreFile(String trustStoreFileName, String trustStorePassword) { this.trustStoreFileName = trustStoreFileName; this.trustStorePassword = <PASSWORD>StorePassword; return this; } public EurekaJersey2ClientBuilder withEncoder(String encoderName) { return this.withEncoderWrapper(CodecWrappers.getEncoder(encoderName)); } public EurekaJersey2ClientBuilder withEncoderWrapper(EncoderWrapper encoderWrapper) { this.encoderWrapper = encoderWrapper; return this; } public EurekaJersey2ClientBuilder withDecoder(String decoderName, String clientDataAccept) { return this.withDecoderWrapper(CodecWrappers.resolveDecoder(decoderName, clientDataAccept)); } public EurekaJersey2ClientBuilder withDecoderWrapper(DecoderWrapper decoderWrapper) { this.decoderWrapper = decoderWrapper; return this; } public EurekaJersey2Client build() { MyDefaultApacheHttpClient4Config config = new MyDefaultApacheHttpClient4Config(); try { return new EurekaJersey2ClientImpl( connectionTimeout, readTimeout, connectionIdleTimeout, config); } catch (Throwable e) { throw new RuntimeException("Cannot create Jersey client ", e); } } class MyDefaultApacheHttpClient4Config extends ClientConfig { MyDefaultApacheHttpClient4Config() { PoolingHttpClientConnectionManager cm; if (systemSSL) { cm = createSystemSslCM(); } else if (trustStoreFileName != null) { cm = createCustomSslCM(); } else { cm = new PoolingHttpClientConnectionManager(); } if (proxyHost != null) { addProxyConfiguration(); } DiscoveryJerseyProvider discoveryJerseyProvider = new DiscoveryJerseyProvider(encoderWrapper, decoderWrapper); // getSingletons().add(discoveryJerseyProvider); register(discoveryJerseyProvider); // Common properties to all clients cm.setDefaultMaxPerRoute(maxConnectionsPerHost); cm.setMaxTotal(maxTotalConnections); property(ApacheClientProperties.CONNECTION_MANAGER, cm); String fullUserAgentName = (userAgent == null ? clientName : userAgent) + "/v" + buildVersion(); property(CoreProtocolPNames.USER_AGENT, fullUserAgentName); // To pin a client to specific server in case redirect happens, we handle redirects directly // (see DiscoveryClient.makeRemoteCall methods). property(ClientProperties.FOLLOW_REDIRECTS, Boolean.FALSE); property(ClientPNames.HANDLE_REDIRECTS, Boolean.FALSE); } private void addProxyConfiguration() { if (proxyUserName != null && proxyPassword != null) { property(ClientProperties.PROXY_USERNAME, proxyUserName); property(ClientProperties.PROXY_PASSWORD, proxyPassword); } else { // Due to bug in apache client, user name/password must always be set. // Otherwise proxy configuration is ignored. property(ClientProperties.PROXY_USERNAME, "guest"); property(ClientProperties.PROXY_PASSWORD, "<PASSWORD>"); } property(ClientProperties.PROXY_URI, "http://" + proxyHost + ":" + proxyPort); } private PoolingHttpClientConnectionManager createSystemSslCM() { ConnectionSocketFactory socketFactory = SSLConnectionSocketFactory.getSystemSocketFactory(); Registry registry = RegistryBuilder.<ConnectionSocketFactory>create() .register(PROTOCOL, socketFactory) .build(); return new PoolingHttpClientConnectionManager(registry); } private PoolingHttpClientConnectionManager createCustomSslCM() { FileInputStream fin = null; try { SSLContext sslContext = SSLContext.getInstance(PROTOCOL_SCHEME); KeyStore sslKeyStore = KeyStore.getInstance(KEYSTORE_TYPE); fin = new FileInputStream(trustStoreFileName); sslKeyStore.load(fin, trustStorePassword.toCharArray()); TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); factory.init(sslKeyStore); TrustManager[] trustManagers = factory.getTrustManagers(); sslContext.init(null, trustManagers, null); ConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Registry registry = RegistryBuilder.<ConnectionSocketFactory>create() .register(PROTOCOL, socketFactory) .build(); return new PoolingHttpClientConnectionManager(registry); } catch (Exception ex) { throw new IllegalStateException("SSL configuration issue", ex); } finally { if (fin != null) { try { fin.close(); } catch (IOException ignore) { } } } } } } private class ConnectionCleanerTask implements Runnable { private final int connectionIdleTimeout; private final BasicTimer executionTimeStats; private final Counter cleanupFailed; private ConnectionCleanerTask(int connectionIdleTimeout) { this.connectionIdleTimeout = connectionIdleTimeout; MonitorConfig.Builder monitorConfigBuilder = MonitorConfig.builder("Eureka-Connection-Cleaner-Time"); executionTimeStats = new BasicTimer(monitorConfigBuilder.build()); cleanupFailed = new BasicCounter(MonitorConfig.builder("Eureka-Connection-Cleaner-Failure").build()); try { Monitors.registerObject(this); } catch (Exception e) { s_logger.error("Unable to register with servo.", e); } } @Override public void run() { Stopwatch start = executionTimeStats.start(); try { HttpClientConnectionManager cm = (HttpClientConnectionManager) apacheHttpClient .getConfiguration() .getProperty(ApacheClientProperties.CONNECTION_MANAGER); cm.closeIdleConnections(connectionIdleTimeout, TimeUnit.SECONDS); } catch (Throwable e) { s_logger.error("Cannot clean connections", e); cleanupFailed.increment(); } finally { if (null != start) { start.stop(); } } } } }
6,330
578
/* * Tencent is pleased to support the open source community by making BK-JOB蓝鲸智云作业平台 available. * * Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. * * BK-JOB蓝鲸智云作业平台 is licensed under the MIT License. * * License for BK-JOB蓝鲸智云作业平台: * -------------------------------------------------------------------- * 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.tencent.bk.job.execute.dao.impl; import com.tencent.bk.job.execute.constants.VariableValueTypeEnum; import com.tencent.bk.job.execute.dao.StepInstanceVariableDAO; import com.tencent.bk.job.execute.model.HostVariableValuesDTO; import com.tencent.bk.job.execute.model.StepInstanceVariableValuesDTO; import com.tencent.bk.job.execute.model.VariableValueDTO; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.jdbc.Sql; import org.springframework.test.context.jdbc.SqlConfig; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.util.ArrayList; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; @ExtendWith(SpringExtension.class) @SpringBootTest @ActiveProfiles("test") @TestPropertySource(locations = "classpath:test.properties") @SqlConfig(encoding = "utf-8") @Sql({"/init_step_instance_variable_data.sql"}) class StepInstanceVariableDAOImplIntegrationTest { @Autowired private StepInstanceVariableDAO stepInstanceVariableDAO; @Test void testSaveVariableValues() { StepInstanceVariableValuesDTO variableValues = new StepInstanceVariableValuesDTO(); variableValues.setTaskInstanceId(100L); variableValues.setStepInstanceId(200L); variableValues.setExecuteCount(1); variableValues.setType(VariableValueTypeEnum.OUTPUT.getValue()); List<VariableValueDTO> globalParams = new ArrayList<>(); VariableValueDTO value1 = new VariableValueDTO("param11", 1, "value11"); VariableValueDTO value2 = new VariableValueDTO("param12", 1, "value12"); globalParams.add(value1); globalParams.add(value2); variableValues.setGlobalParams(globalParams); List<HostVariableValuesDTO> hostParamValuesList = new ArrayList<>(); HostVariableValuesDTO hostParamValues = new HostVariableValuesDTO(); hostParamValues.setIp("1.1.1.1"); List<VariableValueDTO> namespaceParamValues = new ArrayList<>(); namespaceParamValues.add(new VariableValueDTO("param11", 2, "value11")); namespaceParamValues.add(new VariableValueDTO("param12", 2, "value12")); hostParamValues.setValues(namespaceParamValues); hostParamValuesList.add(hostParamValues); variableValues.setNamespaceParams(hostParamValuesList); stepInstanceVariableDAO.saveVariableValues(variableValues); StepInstanceVariableValuesDTO actual = stepInstanceVariableDAO .getStepVariableValues(200L, 1, VariableValueTypeEnum.OUTPUT); assertThat(actual.getStepInstanceId()).isEqualTo(200L); assertThat(actual.getExecuteCount()).isEqualTo(1); assertThat(actual.getType()).isEqualTo(VariableValueTypeEnum.OUTPUT.getValue()); assertThat(actual.getGlobalParams()).hasSize(2); assertThat(actual.getGlobalParams()).extracting("name").containsOnly("param11", "param12"); assertThat(actual.getGlobalParams()).extracting("value").containsOnly("value11", "value12"); assertThat(actual.getNamespaceParams()).hasSize(1); assertThat(actual.getNamespaceParams().get(0).getIp()).isEqualTo("1.1.1.1"); assertThat(actual.getNamespaceParams().get(0).getValues()).hasSize(2); assertThat(actual.getNamespaceParams().get(0).getValues()).extracting("name") .containsOnly("param11", "param12"); assertThat(actual.getNamespaceParams().get(0).getValues()).extracting("value") .containsOnly("value11", "value12"); } @Test void testListSortedPreStepOutputVariableValues() { List<StepInstanceVariableValuesDTO> stepInstanceVariableValuesList = stepInstanceVariableDAO.listSortedPreStepOutputVariableValues(1L, 3L); assertThat(stepInstanceVariableValuesList).hasSize(3); assertThat(stepInstanceVariableValuesList.get(0).getTaskInstanceId()).isEqualTo(1L); assertThat(stepInstanceVariableValuesList.get(0).getStepInstanceId()).isEqualTo(1L); assertThat(stepInstanceVariableValuesList.get(0).getExecuteCount()).isEqualTo(0); assertThat(stepInstanceVariableValuesList.get(1).getTaskInstanceId()).isEqualTo(1L); assertThat(stepInstanceVariableValuesList.get(1).getStepInstanceId()).isEqualTo(2L); assertThat(stepInstanceVariableValuesList.get(1).getExecuteCount()).isEqualTo(0); assertThat(stepInstanceVariableValuesList.get(2).getTaskInstanceId()).isEqualTo(1L); assertThat(stepInstanceVariableValuesList.get(2).getStepInstanceId()).isEqualTo(2L); assertThat(stepInstanceVariableValuesList.get(2).getExecuteCount()).isEqualTo(1); } }
2,219
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.sheets.v4.model; /** * A single response from an update. * * <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 Google Sheets 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 Response extends com.google.api.client.json.GenericJson { /** * A reply from adding a banded range. * The value may be {@code null}. */ @com.google.api.client.util.Key private AddBandingResponse addBanding; /** * A reply from adding a chart. * The value may be {@code null}. */ @com.google.api.client.util.Key private AddChartResponse addChart; /** * A reply from adding a data source. * The value may be {@code null}. */ @com.google.api.client.util.Key private AddDataSourceResponse addDataSource; /** * A reply from adding a dimension group. * The value may be {@code null}. */ @com.google.api.client.util.Key private AddDimensionGroupResponse addDimensionGroup; /** * A reply from adding a filter view. * The value may be {@code null}. */ @com.google.api.client.util.Key private AddFilterViewResponse addFilterView; /** * A reply from adding a named range. * The value may be {@code null}. */ @com.google.api.client.util.Key private AddNamedRangeResponse addNamedRange; /** * A reply from adding a protected range. * The value may be {@code null}. */ @com.google.api.client.util.Key private AddProtectedRangeResponse addProtectedRange; /** * A reply from adding a sheet. * The value may be {@code null}. */ @com.google.api.client.util.Key private AddSheetResponse addSheet; /** * A reply from adding a slicer. * The value may be {@code null}. */ @com.google.api.client.util.Key private AddSlicerResponse addSlicer; /** * A reply from creating a developer metadata entry. * The value may be {@code null}. */ @com.google.api.client.util.Key private CreateDeveloperMetadataResponse createDeveloperMetadata; /** * A reply from deleting a conditional format rule. * The value may be {@code null}. */ @com.google.api.client.util.Key private DeleteConditionalFormatRuleResponse deleteConditionalFormatRule; /** * A reply from deleting a developer metadata entry. * The value may be {@code null}. */ @com.google.api.client.util.Key private DeleteDeveloperMetadataResponse deleteDeveloperMetadata; /** * A reply from deleting a dimension group. * The value may be {@code null}. */ @com.google.api.client.util.Key private DeleteDimensionGroupResponse deleteDimensionGroup; /** * A reply from removing rows containing duplicate values. * The value may be {@code null}. */ @com.google.api.client.util.Key private DeleteDuplicatesResponse deleteDuplicates; /** * A reply from duplicating a filter view. * The value may be {@code null}. */ @com.google.api.client.util.Key private DuplicateFilterViewResponse duplicateFilterView; /** * A reply from duplicating a sheet. * The value may be {@code null}. */ @com.google.api.client.util.Key private DuplicateSheetResponse duplicateSheet; /** * A reply from doing a find/replace. * The value may be {@code null}. */ @com.google.api.client.util.Key private FindReplaceResponse findReplace; /** * A reply from refreshing data source objects. * The value may be {@code null}. */ @com.google.api.client.util.Key private RefreshDataSourceResponse refreshDataSource; /** * A reply from trimming whitespace. * The value may be {@code null}. */ @com.google.api.client.util.Key private TrimWhitespaceResponse trimWhitespace; /** * A reply from updating a conditional format rule. * The value may be {@code null}. */ @com.google.api.client.util.Key private UpdateConditionalFormatRuleResponse updateConditionalFormatRule; /** * A reply from updating a data source. * The value may be {@code null}. */ @com.google.api.client.util.Key private UpdateDataSourceResponse updateDataSource; /** * A reply from updating a developer metadata entry. * The value may be {@code null}. */ @com.google.api.client.util.Key private UpdateDeveloperMetadataResponse updateDeveloperMetadata; /** * A reply from updating an embedded object's position. * The value may be {@code null}. */ @com.google.api.client.util.Key private UpdateEmbeddedObjectPositionResponse updateEmbeddedObjectPosition; /** * A reply from adding a banded range. * @return value or {@code null} for none */ public AddBandingResponse getAddBanding() { return addBanding; } /** * A reply from adding a banded range. * @param addBanding addBanding or {@code null} for none */ public Response setAddBanding(AddBandingResponse addBanding) { this.addBanding = addBanding; return this; } /** * A reply from adding a chart. * @return value or {@code null} for none */ public AddChartResponse getAddChart() { return addChart; } /** * A reply from adding a chart. * @param addChart addChart or {@code null} for none */ public Response setAddChart(AddChartResponse addChart) { this.addChart = addChart; return this; } /** * A reply from adding a data source. * @return value or {@code null} for none */ public AddDataSourceResponse getAddDataSource() { return addDataSource; } /** * A reply from adding a data source. * @param addDataSource addDataSource or {@code null} for none */ public Response setAddDataSource(AddDataSourceResponse addDataSource) { this.addDataSource = addDataSource; return this; } /** * A reply from adding a dimension group. * @return value or {@code null} for none */ public AddDimensionGroupResponse getAddDimensionGroup() { return addDimensionGroup; } /** * A reply from adding a dimension group. * @param addDimensionGroup addDimensionGroup or {@code null} for none */ public Response setAddDimensionGroup(AddDimensionGroupResponse addDimensionGroup) { this.addDimensionGroup = addDimensionGroup; return this; } /** * A reply from adding a filter view. * @return value or {@code null} for none */ public AddFilterViewResponse getAddFilterView() { return addFilterView; } /** * A reply from adding a filter view. * @param addFilterView addFilterView or {@code null} for none */ public Response setAddFilterView(AddFilterViewResponse addFilterView) { this.addFilterView = addFilterView; return this; } /** * A reply from adding a named range. * @return value or {@code null} for none */ public AddNamedRangeResponse getAddNamedRange() { return addNamedRange; } /** * A reply from adding a named range. * @param addNamedRange addNamedRange or {@code null} for none */ public Response setAddNamedRange(AddNamedRangeResponse addNamedRange) { this.addNamedRange = addNamedRange; return this; } /** * A reply from adding a protected range. * @return value or {@code null} for none */ public AddProtectedRangeResponse getAddProtectedRange() { return addProtectedRange; } /** * A reply from adding a protected range. * @param addProtectedRange addProtectedRange or {@code null} for none */ public Response setAddProtectedRange(AddProtectedRangeResponse addProtectedRange) { this.addProtectedRange = addProtectedRange; return this; } /** * A reply from adding a sheet. * @return value or {@code null} for none */ public AddSheetResponse getAddSheet() { return addSheet; } /** * A reply from adding a sheet. * @param addSheet addSheet or {@code null} for none */ public Response setAddSheet(AddSheetResponse addSheet) { this.addSheet = addSheet; return this; } /** * A reply from adding a slicer. * @return value or {@code null} for none */ public AddSlicerResponse getAddSlicer() { return addSlicer; } /** * A reply from adding a slicer. * @param addSlicer addSlicer or {@code null} for none */ public Response setAddSlicer(AddSlicerResponse addSlicer) { this.addSlicer = addSlicer; return this; } /** * A reply from creating a developer metadata entry. * @return value or {@code null} for none */ public CreateDeveloperMetadataResponse getCreateDeveloperMetadata() { return createDeveloperMetadata; } /** * A reply from creating a developer metadata entry. * @param createDeveloperMetadata createDeveloperMetadata or {@code null} for none */ public Response setCreateDeveloperMetadata(CreateDeveloperMetadataResponse createDeveloperMetadata) { this.createDeveloperMetadata = createDeveloperMetadata; return this; } /** * A reply from deleting a conditional format rule. * @return value or {@code null} for none */ public DeleteConditionalFormatRuleResponse getDeleteConditionalFormatRule() { return deleteConditionalFormatRule; } /** * A reply from deleting a conditional format rule. * @param deleteConditionalFormatRule deleteConditionalFormatRule or {@code null} for none */ public Response setDeleteConditionalFormatRule(DeleteConditionalFormatRuleResponse deleteConditionalFormatRule) { this.deleteConditionalFormatRule = deleteConditionalFormatRule; return this; } /** * A reply from deleting a developer metadata entry. * @return value or {@code null} for none */ public DeleteDeveloperMetadataResponse getDeleteDeveloperMetadata() { return deleteDeveloperMetadata; } /** * A reply from deleting a developer metadata entry. * @param deleteDeveloperMetadata deleteDeveloperMetadata or {@code null} for none */ public Response setDeleteDeveloperMetadata(DeleteDeveloperMetadataResponse deleteDeveloperMetadata) { this.deleteDeveloperMetadata = deleteDeveloperMetadata; return this; } /** * A reply from deleting a dimension group. * @return value or {@code null} for none */ public DeleteDimensionGroupResponse getDeleteDimensionGroup() { return deleteDimensionGroup; } /** * A reply from deleting a dimension group. * @param deleteDimensionGroup deleteDimensionGroup or {@code null} for none */ public Response setDeleteDimensionGroup(DeleteDimensionGroupResponse deleteDimensionGroup) { this.deleteDimensionGroup = deleteDimensionGroup; return this; } /** * A reply from removing rows containing duplicate values. * @return value or {@code null} for none */ public DeleteDuplicatesResponse getDeleteDuplicates() { return deleteDuplicates; } /** * A reply from removing rows containing duplicate values. * @param deleteDuplicates deleteDuplicates or {@code null} for none */ public Response setDeleteDuplicates(DeleteDuplicatesResponse deleteDuplicates) { this.deleteDuplicates = deleteDuplicates; return this; } /** * A reply from duplicating a filter view. * @return value or {@code null} for none */ public DuplicateFilterViewResponse getDuplicateFilterView() { return duplicateFilterView; } /** * A reply from duplicating a filter view. * @param duplicateFilterView duplicateFilterView or {@code null} for none */ public Response setDuplicateFilterView(DuplicateFilterViewResponse duplicateFilterView) { this.duplicateFilterView = duplicateFilterView; return this; } /** * A reply from duplicating a sheet. * @return value or {@code null} for none */ public DuplicateSheetResponse getDuplicateSheet() { return duplicateSheet; } /** * A reply from duplicating a sheet. * @param duplicateSheet duplicateSheet or {@code null} for none */ public Response setDuplicateSheet(DuplicateSheetResponse duplicateSheet) { this.duplicateSheet = duplicateSheet; return this; } /** * A reply from doing a find/replace. * @return value or {@code null} for none */ public FindReplaceResponse getFindReplace() { return findReplace; } /** * A reply from doing a find/replace. * @param findReplace findReplace or {@code null} for none */ public Response setFindReplace(FindReplaceResponse findReplace) { this.findReplace = findReplace; return this; } /** * A reply from refreshing data source objects. * @return value or {@code null} for none */ public RefreshDataSourceResponse getRefreshDataSource() { return refreshDataSource; } /** * A reply from refreshing data source objects. * @param refreshDataSource refreshDataSource or {@code null} for none */ public Response setRefreshDataSource(RefreshDataSourceResponse refreshDataSource) { this.refreshDataSource = refreshDataSource; return this; } /** * A reply from trimming whitespace. * @return value or {@code null} for none */ public TrimWhitespaceResponse getTrimWhitespace() { return trimWhitespace; } /** * A reply from trimming whitespace. * @param trimWhitespace trimWhitespace or {@code null} for none */ public Response setTrimWhitespace(TrimWhitespaceResponse trimWhitespace) { this.trimWhitespace = trimWhitespace; return this; } /** * A reply from updating a conditional format rule. * @return value or {@code null} for none */ public UpdateConditionalFormatRuleResponse getUpdateConditionalFormatRule() { return updateConditionalFormatRule; } /** * A reply from updating a conditional format rule. * @param updateConditionalFormatRule updateConditionalFormatRule or {@code null} for none */ public Response setUpdateConditionalFormatRule(UpdateConditionalFormatRuleResponse updateConditionalFormatRule) { this.updateConditionalFormatRule = updateConditionalFormatRule; return this; } /** * A reply from updating a data source. * @return value or {@code null} for none */ public UpdateDataSourceResponse getUpdateDataSource() { return updateDataSource; } /** * A reply from updating a data source. * @param updateDataSource updateDataSource or {@code null} for none */ public Response setUpdateDataSource(UpdateDataSourceResponse updateDataSource) { this.updateDataSource = updateDataSource; return this; } /** * A reply from updating a developer metadata entry. * @return value or {@code null} for none */ public UpdateDeveloperMetadataResponse getUpdateDeveloperMetadata() { return updateDeveloperMetadata; } /** * A reply from updating a developer metadata entry. * @param updateDeveloperMetadata updateDeveloperMetadata or {@code null} for none */ public Response setUpdateDeveloperMetadata(UpdateDeveloperMetadataResponse updateDeveloperMetadata) { this.updateDeveloperMetadata = updateDeveloperMetadata; return this; } /** * A reply from updating an embedded object's position. * @return value or {@code null} for none */ public UpdateEmbeddedObjectPositionResponse getUpdateEmbeddedObjectPosition() { return updateEmbeddedObjectPosition; } /** * A reply from updating an embedded object's position. * @param updateEmbeddedObjectPosition updateEmbeddedObjectPosition or {@code null} for none */ public Response setUpdateEmbeddedObjectPosition(UpdateEmbeddedObjectPositionResponse updateEmbeddedObjectPosition) { this.updateEmbeddedObjectPosition = updateEmbeddedObjectPosition; return this; } @Override public Response set(String fieldName, Object value) { return (Response) super.set(fieldName, value); } @Override public Response clone() { return (Response) super.clone(); } }
5,200
649
<gh_stars>100-1000 package net.thucydides.core.model.flags; import net.serenitybdd.core.collect.NewMap; import net.thucydides.core.model.TestOutcome; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; public class FlagCounts { private final List<? extends TestOutcome> testOutcomes; private final Map<Flag, Integer> flagMap = new HashMap(); public FlagCounts(List<? extends TestOutcome> testOutcomes) { this.testOutcomes = testOutcomes; } public static FlagCounts in(List<? extends TestOutcome> testOutcomes) { return new FlagCounts(testOutcomes); } public Map<Flag, Integer> asAMap() { for(TestOutcome testOutcome : testOutcomes) { addToMap(testOutcome.getFlags()); } return NewMap.copyOf(flagMap); } private void addToMap(Set<? extends Flag> flags) { for(Flag flag : flags) { if (flagMap.containsKey(flag)) { flagMap.put(flag, flagMap.get(flag) + 1); } else { flagMap.put(flag, 1); } } } }
483
1,031
//{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by maxPlugin.rc // #define IDS_CATEGORY 2 #define IDS_CLASS_NAME 3 #define IDS_PARAMS 4 #define IDS_SPIN 5 #define IDS_LIBDESCRIPTION 6 #define IDD_EXPORT_DIALOG 102 #define IDD_NEWTON_WORLD_PANE 103 #define IDD_NEWTON_BODY_PANE 105 #define IDD_CONVEX_APPROXIMATION_PANE 108 #define IDC_EXPORT_MESH 1001 #define IDC_EXPORT_ANIMATION 1002 #define IDC_EXPORT_SKELETON 1003 #define IDC_EXPORT_MODEL 1004 #define IDC_RIGID_BODY_MASS 1011 #define IDC_RIGID_BODY_MASS_PINNER 1014 #define IDC_RIGID_BODY_COLLISION 1021 #define IDC_PREVIEW_WORLD 1026 #define IDC_STEP_WORLD 1027 #define IDC_GRAVITY_X 1030 #define IDC_MINUMIN_SIMULATION_RATE 1031 #define IDC_GRAVITY_Y 1033 #define IDC_HIDE_GIZMO 1033 #define IDC_GRAVITY_Z 1034 #define IDC_DELETE_RIGIDBODY 1035 #define IDC_MAKE_RIGIDBODY 1036 #define IDC_MAX_CONCAVITY 1036 #define IDC_HIDE_GIZMOS 1037 #define IDC_MAX_SEGMENTS 1037 #define IDC_SHOW_GIZMOS 1038 #define IDC_MAX_CONCAVITY_SPINNER 1038 #define IDC_REMOVE_ALL 1039 #define IDC_MAX_SEGMENTS_SPINNER 1039 #define IDC_SELECT_ALL 1040 #define IDC_SOURCE_MODEL 1041 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 109 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1043 #define _APS_NEXT_SYMED_VALUE 103 #endif #endif
1,114
409
// // rest_controller.cpp // ******************* // // Copyright (c) 2020 <NAME> (sharon at xandium dot io) // // Distributed under the MIT License. (See accompanying file LICENSE) // #include "aegis/rest/rest_controller.hpp" namespace aegis { namespace rest { AEGIS_DECL rest_controller::rest_controller(const std::string & token, asio::io_context * _io_context) : _token(token) , _io_context(_io_context) { } AEGIS_DECL rest_controller::rest_controller(const std::string & token, const std::string & prefix, asio::io_context * _io_context) : _token(token) , _prefix(prefix) , _io_context(_io_context) { } AEGIS_DECL rest_controller::rest_controller(const std::string & token, const std::string & prefix, const std::string & host, asio::io_context * _io_context) : _token(token) , _prefix(prefix) , _host(host) , _io_context(_io_context) { } AEGIS_DECL rest_reply rest_controller::execute(rest::request_params && params) { if (_host.empty() && params.host.empty()) throw aegis::exception("REST host not set"); websocketpp::http::parser::response hresponse; int32_t limit = 0; int32_t remaining = 0; int64_t reset = 0; int32_t retry = 0; std::chrono::system_clock::time_point http_date; bool global = false; auto start_time = std::chrono::steady_clock::now(); try { asio::ip::basic_resolver<asio::ip::tcp>::results_type r; const std::string & tar_host = params.host.empty() ? _host : params.host; //TODO: make cache expire? auto it = _resolver_cache.find(tar_host); if (it == _resolver_cache.end()) { asio::ip::tcp::resolver resolver(*_io_context); r = resolver.resolve(tar_host, params.port); _resolver_cache.emplace(tar_host, r); } else r = it->second; asio::ssl::context ctx(asio::ssl::context::tlsv12); ctx.set_options( asio::ssl::context::default_workarounds | asio::ssl::context::no_sslv2 | asio::ssl::context::no_sslv3); asio::ssl::stream<asio::ip::tcp::socket> socket(*_io_context, ctx); SSL_set_tlsext_host_name(socket.native_handle(), tar_host.data()); asio::connect(socket.lowest_layer(), r); asio::error_code handshake_ec; socket.handshake(asio::ssl::stream_base::client, handshake_ec); asio::streambuf request; std::ostream request_stream(&request); request_stream << get_method(params.method) << " " << _prefix << params.path << params._path_ex << " HTTP/1.0\r\n"; request_stream << "Host: " << tar_host << "\r\n"; request_stream << "Accept: */*\r\n"; request_stream << "Authorization: Bot " << _token << "\r\n"; request_stream << "User-Agent: DiscordBot (https://github.com/zeroxs/aegis.cpp, " << AEGIS_VERSION_LONG << ")\r\n"; if (params.file.has_value()) { auto & file = params.file.value(); std::string boundary{ utility::random_string(20) }; std::stringstream ss; request_stream << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n"; ss << "--" << boundary << "\r\n"; ss << R"(Content-Disposition: form-data; name="file"; filename=")" << utility::escape_quotes(file.name) << "\"\r\n"; request_stream << "Connection: close\r\n"; if (!file.content_type.empty()) { ss << "Content-Type: " << file.content_type << "\r\n\r\n"; } else { ss << "Content-Type: " << utility::guess_mime_type(file.name) << "\r\n\r\n"; } ss.write(file.data.data(), file.data.size()); ss << "\r\n"; ss << "--" << boundary << "--"; request_stream << "Content-Length: " << ss.str().length() << "\r\n\r\n"; request_stream << ss.str(); } else if (!params.body.empty() || params.method == Post || params.method == Put || params.method == Patch) { request_stream << "Content-Length: " << params.body.size() << "\r\n"; request_stream << "Connection: close\r\n"; request_stream << "Content-Type: application/json\r\n\r\n"; request_stream << params.body; } else request_stream << "Connection: close\r\n\r\n"; asio::write(socket, request); asio::streambuf response; asio::read_until(socket, response, "\r\n"); std::stringstream response_content; response_content << &response; asio::error_code error; while (asio::read(socket, response, asio::transfer_at_least(1), error)) response_content << &response; std::istringstream istrm(response_content.str()); hresponse.consume(istrm); auto test = hresponse.get_header("X-RateLimit-Limit"); if (!test.empty()) limit = std::stoul(test); test = hresponse.get_header("X-RateLimit-Remaining"); if (!test.empty()) remaining = std::stoul(test); test = hresponse.get_header("X-RateLimit-Reset"); if (!test.empty()) reset = std::stoul(test); test = hresponse.get_header("Retry-After"); if (!test.empty()) retry = std::stoul(test); http_date = utility::from_http_date(hresponse.get_header("Date")) - _tz_bias; global = !(hresponse.get_header("X-RateLimit-Global").empty()); #if defined(AEGIS_PROFILING) if (rest_end) rest_end(start_time, static_cast<uint16_t>(hresponse.get_status_code())); #endif if (error != asio::error::eof && error != asio::ssl::error::stream_truncated) throw asio::system_error(error); } catch (std::exception& e) { std::cout << "Exception: " << e.what() << "\n"; } return { static_cast<http_code>(hresponse.get_status_code()), global, limit, remaining, reset, retry, hresponse.get_body(), http_date, std::chrono::steady_clock::now() - start_time }; } AEGIS_DECL rest_reply rest_controller::execute2(rest::request_params && params) { if (_host.empty() && params.host.empty()) throw aegis::exception("REST host not set"); websocketpp::http::parser::response hresponse; int32_t limit = 0; int32_t remaining = 0; int64_t reset = 0; int32_t retry = 0; std::chrono::system_clock::time_point http_date; bool global = false; auto start_time = std::chrono::steady_clock::now(); try { asio::ip::basic_resolver<asio::ip::tcp>::results_type r; const std::string & tar_host = params.host.empty() ? _host : params.host; //TODO: make cache expire? auto it = _resolver_cache.find(tar_host); if (it == _resolver_cache.end()) { asio::ip::tcp::resolver resolver(*_io_context); r = resolver.resolve(tar_host, params.port); _resolver_cache.emplace(tar_host, r); } else r = it->second; if (params.port == "443") { asio::ssl::context ctx(asio::ssl::context::tlsv12); ctx.set_options( asio::ssl::context::default_workarounds | asio::ssl::context::no_sslv2 | asio::ssl::context::no_sslv3); asio::ssl::stream<asio::ip::tcp::socket> socket(*_io_context, ctx); SSL_set_tlsext_host_name(socket.native_handle(), tar_host.data()); asio::connect(socket.lowest_layer(), r); asio::error_code handshake_ec; socket.handshake(asio::ssl::stream_base::client, handshake_ec); asio::streambuf request; std::ostream request_stream(&request); request_stream << get_method(params.method) << " " << (!params.path.empty() ? params.path : "/") << " HTTP/1.0\r\n"; request_stream << "Host: " << tar_host << "\r\n"; request_stream << "Accept: */*\r\n"; for (auto & h : params.headers) request_stream << h << "\r\n"; if (!params.body.empty() || params.method == Post || params.method == Put || params.method == Patch) { request_stream << "Connection: close\r\n"; request_stream << "Content-Length: " << params.body.size() << "\r\n"; request_stream << "Content-Type: application/json\r\n\r\n"; request_stream << params.body; } else request_stream << "Connection: close\r\n\r\n"; asio::write(socket, request); asio::streambuf response; asio::read_until(socket, response, "\r\n"); std::stringstream response_content; response_content << &response; asio::error_code error; while (asio::read(socket, response, asio::transfer_at_least(1), error)) response_content << &response; std::istringstream istrm(response_content.str()); hresponse.consume(istrm); http_date = utility::from_http_date(hresponse.get_header("Date")); if (error != asio::error::eof && error != asio::ssl::error::stream_truncated) throw asio::system_error(error); //TODO: return reply headers } else { asio::ip::tcp::socket socket(*_io_context); asio::connect(socket, r); asio::streambuf request; std::ostream request_stream(&request); request_stream << get_method(params.method) << " " << (!params.path.empty() ? params.path : "/") << " HTTP/1.0\r\n"; request_stream << "Host: " << tar_host << "\r\n"; request_stream << "Accept: */*\r\n"; for (auto & h : params.headers) request_stream << h << "\r\n"; if (!params.body.empty() || params.method == Post || params.method == Put || params.method == Patch) { request_stream << "Connection: close\r\n"; request_stream << "Content-Length: " << params.body.size() << "\r\n"; request_stream << "Content-Type: application/json\r\n\r\n"; request_stream << params.body; } else request_stream << "Connection: close\r\n\r\n"; asio::write(socket, request); asio::streambuf response; asio::read_until(socket, response, "\r\n"); std::stringstream response_content; response_content << &response; std::istringstream istrm(response_content.str()); hresponse.consume(istrm); http_date = utility::from_http_date(hresponse.get_header("Date")); //TODO: return reply headers } } catch (std::exception& e) { std::cout << "Exception: " << e.what() << "\n"; } return { static_cast<http_code>(hresponse.get_status_code()), global, limit, remaining, reset, retry, hresponse.get_body(), http_date, std::chrono::steady_clock::now() - start_time }; } } }
5,196
837
package me.saket.dank.data; /** * Things that can be pre-filled in cache. */ public enum CachePreFillThing { COMMENTS, IMAGES, LINK_METADATA }
57
400
<gh_stars>100-1000 package com.github.bkhezry.weather.utils; import android.annotation.SuppressLint; import android.app.Application; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.content.res.Configuration; import android.content.res.Resources; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Build; import android.text.Html; import android.text.Layout; import android.text.Spannable; import android.text.TextUtils; import android.text.style.ClickableSpan; import android.util.DisplayMetrics; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.animation.AnimationUtils; import android.view.animation.Interpolator; import android.widget.TextView; import androidx.annotation.CheckResult; import androidx.annotation.ColorInt; import androidx.annotation.FloatRange; import androidx.annotation.IntRange; import androidx.annotation.NonNull; import androidx.annotation.RequiresPermission; import androidx.appcompat.widget.AppCompatEditText; import androidx.appcompat.widget.AppCompatImageView; import androidx.core.os.ConfigurationCompat; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; import com.bumptech.glide.Glide; import com.github.bkhezry.weather.R; import com.github.bkhezry.weather.listener.OnSetApiKeyEventListener; import com.github.pwittchen.prefser.library.rx2.Prefser; import java.lang.reflect.InvocationTargetException; import java.util.Calendar; import java.util.Locale; import java.util.TimeZone; import static android.Manifest.permission.ACCESS_NETWORK_STATE; public class AppUtil { private static Interpolator fastOutSlowIn; /** * Get timestamp of start of day 00:00:00 * * @param calendar instance of {@link Calendar} * @return timestamp */ public static long getStartOfDayTimestamp(Calendar calendar) { Calendar newCalendar = Calendar.getInstance(TimeZone.getDefault()); newCalendar.setTimeInMillis(calendar.getTimeInMillis()); newCalendar.set(Calendar.HOUR_OF_DAY, 0); newCalendar.set(Calendar.MINUTE, 0); newCalendar.set(Calendar.SECOND, 0); newCalendar.set(Calendar.MILLISECOND, 0); return newCalendar.getTimeInMillis(); } /** * Get timestamp of end of day 23:59:59 * * @param calendar instance of {@link Calendar} * @return timestamp */ public static long getEndOfDayTimestamp(Calendar calendar) { Calendar newCalendar = Calendar.getInstance(TimeZone.getDefault()); newCalendar.setTimeInMillis(calendar.getTimeInMillis()); newCalendar.set(Calendar.HOUR_OF_DAY, 23); newCalendar.set(Calendar.MINUTE, 59); newCalendar.set(Calendar.SECOND, 59); newCalendar.set(Calendar.MILLISECOND, 0); return newCalendar.getTimeInMillis(); } /** * Add days to calendar and return result * * @param cal instance of {@link Calendar} * @param days number of days * @return instance of {@link Calendar} */ public static Calendar addDays(Calendar cal, int days) { Calendar calendar = Calendar.getInstance(TimeZone.getDefault()); calendar.setTimeInMillis(cal.getTimeInMillis()); calendar.add(Calendar.DATE, days); return calendar; } /** * Set icon to imageView according to weather code status * * @param context instance of {@link Context} * @param imageView instance of {@link android.widget.ImageView} * @param weatherCode code of weather status */ public static void setWeatherIcon(Context context, AppCompatImageView imageView, int weatherCode) { if (weatherCode / 100 == 2) { Glide.with(context).load(R.drawable.ic_storm_weather).into(imageView); } else if (weatherCode / 100 == 3) { Glide.with(context).load(R.drawable.ic_rainy_weather).into(imageView); } else if (weatherCode / 100 == 5) { Glide.with(context).load(R.drawable.ic_rainy_weather).into(imageView); } else if (weatherCode / 100 == 6) { Glide.with(context).load(R.drawable.ic_snow_weather).into(imageView); } else if (weatherCode / 100 == 7) { Glide.with(context).load(R.drawable.ic_unknown).into(imageView); } else if (weatherCode == 800) { Glide.with(context).load(R.drawable.ic_clear_day).into(imageView); } else if (weatherCode == 801) { Glide.with(context).load(R.drawable.ic_few_clouds).into(imageView); } else if (weatherCode == 803) { Glide.with(context).load(R.drawable.ic_broken_clouds).into(imageView); } else if (weatherCode / 100 == 8) { Glide.with(context).load(R.drawable.ic_cloudy_weather).into(imageView); } } /** * Show fragment with fragment manager with animation parameter * * @param fragment instance of {@link Fragment} * @param fragmentManager instance of {@link FragmentManager} * @param withAnimation boolean value */ public static void showFragment(Fragment fragment, FragmentManager fragmentManager, boolean withAnimation) { FragmentTransaction transaction = fragmentManager.beginTransaction(); if (withAnimation) { transaction.setCustomAnimations(R.anim.slide_up_anim, R.anim.slide_down_anim); } else { transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); } transaction.add(android.R.id.content, fragment).addToBackStack(null).commit(); } /** * Get time of calendar as 00:00 format * * @param calendar instance of {@link Calendar} * @param context instance of {@link Context} * @return string value */ public static String getTime(Calendar calendar, Context context) { int hour = calendar.get(Calendar.HOUR_OF_DAY); int minute = calendar.get(Calendar.MINUTE); String hourString; if (hour < 10) { hourString = String.format(Locale.getDefault(), context.getString(R.string.zero_label), hour); } else { hourString = String.format(Locale.getDefault(), "%d", hour); } String minuteString; if (minute < 10) { minuteString = String.format(Locale.getDefault(), context.getString(R.string.zero_label), minute); } else { minuteString = String.format(Locale.getDefault(), "%d", minute); } return hourString + ":" + minuteString; } /** * Get animation file according to weather status code * * @param weatherCode int weather status code * @return id of animation json file */ public static int getWeatherAnimation(int weatherCode) { if (weatherCode / 100 == 2) { return R.raw.storm_weather; } else if (weatherCode / 100 == 3) { return R.raw.rainy_weather; } else if (weatherCode / 100 == 5) { return R.raw.rainy_weather; } else if (weatherCode / 100 == 6) { return R.raw.snow_weather; } else if (weatherCode / 100 == 7) { return R.raw.unknown; } else if (weatherCode == 800) { return R.raw.clear_day; } else if (weatherCode == 801) { return R.raw.few_clouds; } else if (weatherCode == 803) { return R.raw.broken_clouds; } else if (weatherCode / 100 == 8) { return R.raw.cloudy_weather; } return R.raw.unknown; } /** * Get weather status string according to weather status code * * @param weatherCode weather status code * @param isRTL boolean value * @return String weather status */ public static String getWeatherStatus(int weatherCode, boolean isRTL) { if (weatherCode / 100 == 2) { if (isRTL) { return Constants.WEATHER_STATUS_PERSIAN[0]; } else { return Constants.WEATHER_STATUS[0]; } } else if (weatherCode / 100 == 3) { if (isRTL) { return Constants.WEATHER_STATUS_PERSIAN[1]; } else { return Constants.WEATHER_STATUS[1]; } } else if (weatherCode / 100 == 5) { if (isRTL) { return Constants.WEATHER_STATUS_PERSIAN[2]; } else { return Constants.WEATHER_STATUS[2]; } } else if (weatherCode / 100 == 6) { if (isRTL) { return Constants.WEATHER_STATUS_PERSIAN[3]; } else { return Constants.WEATHER_STATUS[3]; } } else if (weatherCode / 100 == 7) { if (isRTL) { return Constants.WEATHER_STATUS_PERSIAN[4]; } else { return Constants.WEATHER_STATUS[4]; } } else if (weatherCode == 800) { if (isRTL) { return Constants.WEATHER_STATUS_PERSIAN[5]; } else { return Constants.WEATHER_STATUS[5]; } } else if (weatherCode == 801) { if (isRTL) { return Constants.WEATHER_STATUS_PERSIAN[6]; } else { return Constants.WEATHER_STATUS[6]; } } else if (weatherCode == 803) { if (isRTL) { return Constants.WEATHER_STATUS_PERSIAN[7]; } else { return Constants.WEATHER_STATUS[7]; } } else if (weatherCode / 100 == 8) { if (isRTL) { return Constants.WEATHER_STATUS_PERSIAN[8]; } else { return Constants.WEATHER_STATUS[8]; } } if (isRTL) { return Constants.WEATHER_STATUS_PERSIAN[4]; } else { return Constants.WEATHER_STATUS[4]; } } /** * If thirty minutes is pass from parameter return true otherwise return false * * @param lastStored timestamp * @return boolean value */ public static boolean isTimePass(long lastStored) { return System.currentTimeMillis() - lastStored > Constants.TIME_TO_PASS; } /** * Showing dialog for set api key value * * @param context instance of {@link Context} * @param prefser instance of {@link Prefser} * @param listener instance of {@link OnSetApiKeyEventListener} */ public static void showSetAppIdDialog(Context context, Prefser prefser, OnSetApiKeyEventListener listener) { final Dialog dialog = new Dialog(context); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // before dialog.setContentView(R.layout.dialog_set_appid); dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent); dialog.setCancelable(false); WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); lp.copyFrom(dialog.getWindow().getAttributes()); lp.width = WindowManager.LayoutParams.MATCH_PARENT; lp.height = WindowManager.LayoutParams.WRAP_CONTENT; dialog.getWindow().setAttributes(lp); dialog.findViewById(R.id.open_openweather_button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(Constants.OPEN_WEATHER_MAP_WEBSITE)); context.startActivity(i); } }); dialog.findViewById(R.id.store_button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AppCompatEditText apiKeyEditText = dialog.findViewById(R.id.api_key_edit_text); String apiKey = apiKeyEditText.getText().toString(); if (!apiKey.equals("")) { prefser.put(Constants.API_KEY, apiKey); listener.setApiKey(); dialog.dismiss(); } } }); dialog.show(); } /** * Set text of textView with html format of html parameter * * @param textView instance {@link TextView} * @param html String */ @SuppressLint("ClickableViewAccessibility") public static void setTextWithLinks(TextView textView, CharSequence html) { textView.setText(html); textView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { int action = event.getAction(); if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) { int x = (int) event.getX(); int y = (int) event.getY(); TextView widget = (TextView) v; x -= widget.getTotalPaddingLeft(); y -= widget.getTotalPaddingTop(); x += widget.getScrollX(); y += widget.getScrollY(); Layout layout = widget.getLayout(); int line = layout.getLineForVertical(y); int off = layout.getOffsetForHorizontal(line, x); ClickableSpan[] link = Spannable.Factory.getInstance() .newSpannable(widget.getText()) .getSpans(off, off, ClickableSpan.class); if (link.length != 0) { if (action == MotionEvent.ACTION_UP) { link[0].onClick(widget); } return true; } } return false; } }); } /** * Change string to html format * * @param htmlText String text * @return String text */ public static CharSequence fromHtml(String htmlText) { if (TextUtils.isEmpty(htmlText)) { return null; } CharSequence spanned; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { spanned = Html.fromHtml(htmlText, Html.FROM_HTML_MODE_LEGACY); } else { spanned = Html.fromHtml(htmlText); } return trim(spanned); } /** * Trim string text * * @param charSequence String text * @return String text */ private static CharSequence trim(CharSequence charSequence) { if (TextUtils.isEmpty(charSequence)) { return charSequence; } int end = charSequence.length() - 1; while (Character.isWhitespace(charSequence.charAt(end))) { end--; } return charSequence.subSequence(0, end + 1); } /** * Check version of SDK * * @param version int SDK version * @return boolean value */ static boolean isAtLeastVersion(int version) { return Build.VERSION.SDK_INT >= version; } /** * Check current direction of application. if is RTL return true * * @param context instance of {@link Context} * @return boolean value */ public static boolean isRTL(Context context) { Locale locale = ConfigurationCompat.getLocales(context.getResources().getConfiguration()).get(0); final int directionality = Character.getDirectionality(locale.getDisplayName().charAt(0)); return directionality == Character.DIRECTIONALITY_RIGHT_TO_LEFT || directionality == Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC; } /** * Network status functions. */ @SuppressLint("StaticFieldLeak") private static Application sApplication; private static void init(final Application app) { if (sApplication == null) { if (app == null) { sApplication = getApplicationByReflect(); } else { sApplication = app; } } else { if (app != null && app.getClass() != sApplication.getClass()) { sApplication = app; } } } public static Application getApp() { if (sApplication != null) return sApplication; Application app = getApplicationByReflect(); init(app); return app; } private static Application getApplicationByReflect() { try { @SuppressLint("PrivateApi") Class<?> activityThread = Class.forName("android.app.ActivityThread"); Object thread = activityThread.getMethod("currentActivityThread").invoke(null); Object app = activityThread.getMethod("getApplication").invoke(thread); if (app == null) { throw new NullPointerException("u should init first"); } return (Application) app; } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | ClassNotFoundException e) { e.printStackTrace(); } throw new NullPointerException("u should init first"); } /** * If network connection is connect, return true * * @return boolean value */ @RequiresPermission(ACCESS_NETWORK_STATE) public static boolean isNetworkConnected() { NetworkInfo info = getActiveNetworkInfo(); return info != null && info.isConnected(); } /** * Get activity network info instace * * @return instance of {@link NetworkInfo} */ @RequiresPermission(ACCESS_NETWORK_STATE) private static NetworkInfo getActiveNetworkInfo() { ConnectivityManager cm = (ConnectivityManager) getApp().getSystemService(Context.CONNECTIVITY_SERVICE); if (cm == null) return null; return cm.getActiveNetworkInfo(); } /** * Determine if the navigation bar will be on the bottom of the screen, based on logic in * PhoneWindowManager. */ static boolean isNavBarOnBottom(@NonNull Context context) { final Resources res = context.getResources(); final Configuration cfg = context.getResources().getConfiguration(); final DisplayMetrics dm = res.getDisplayMetrics(); boolean canMove = (dm.widthPixels != dm.heightPixels && cfg.smallestScreenWidthDp < 600); return (!canMove || dm.widthPixels < dm.heightPixels); } static Interpolator getFastOutSlowInInterpolator(Context context) { if (fastOutSlowIn == null) { fastOutSlowIn = AnimationUtils.loadInterpolator(context, android.R.interpolator.fast_out_slow_in); } return fastOutSlowIn; } /** * Set the alpha component of {@code color} to be {@code alpha}. */ static @CheckResult @ColorInt int modifyAlpha(@ColorInt int color, @IntRange(from = 0, to = 255) int alpha) { return (color & 0x00ffffff) | (alpha << 24); } /** * Set the alpha component of {@code color} to be {@code alpha}. */ public static @CheckResult @ColorInt int modifyAlpha(@ColorInt int color, @FloatRange(from = 0f, to = 1f) float alpha) { return modifyAlpha(color, (int) (255f * alpha)); } }
6,639
1,870
<filename>tests/test_runtime/test_config.py # Copyright (c) OpenMMLab. All rights reserved. import glob import os import os.path as osp import mmcv import torch.nn as nn from mmaction.models import build_localizer, build_recognizer def _get_config_path(): """Find the predefined recognizer config path.""" repo_dir = osp.dirname(osp.dirname(osp.dirname(__file__))) config_dpath = osp.join(repo_dir, 'configs') if not osp.exists(config_dpath): raise Exception('Cannot find config path') config_fpaths = list(glob.glob(osp.join(config_dpath, '*.py'))) config_names = [os.path.relpath(p, config_dpath) for p in config_fpaths] print(f'Using {len(config_names)} config files') config_fpaths = [ osp.join(config_dpath, config_fpath) for config_fpath in config_fpaths ] return config_fpaths def test_config_build_recognizer(): """Test that all mmaction models defined in the configs can be initialized.""" repo_dir = osp.dirname(osp.dirname(osp.dirname(__file__))) config_dpath = osp.join(repo_dir, 'configs/recognition') if not osp.exists(config_dpath): raise Exception('Cannot find config path') config_fpaths = list(glob.glob(osp.join(config_dpath, '*.py'))) # test all config file in `configs` directory for config_fpath in config_fpaths: config_mod = mmcv.Config.fromfile(config_fpath) print(f'Building recognizer, config_fpath = {config_fpath!r}') # Remove pretrained keys to allow for testing in an offline environment if 'pretrained' in config_mod.model['backbone']: config_mod.model['backbone']['pretrained'] = None recognizer = build_recognizer(config_mod.model) assert isinstance(recognizer, nn.Module) def _get_config_path_for_localizer(): """Find the predefined localizer config path for localizer.""" repo_dir = osp.dirname(osp.dirname(osp.dirname(__file__))) config_dpath = osp.join(repo_dir, 'configs/localization') if not osp.exists(config_dpath): raise Exception('Cannot find config path') config_fpaths = list(glob.glob(osp.join(config_dpath, '*.py'))) config_names = [os.path.relpath(p, config_dpath) for p in config_fpaths] print(f'Using {len(config_names)} config files') config_fpaths = [ osp.join(config_dpath, config_fpath) for config_fpath in config_fpaths ] return config_fpaths def test_config_build_localizer(): """Test that all mmaction models defined in the configs can be initialized.""" config_fpaths = _get_config_path_for_localizer() # test all config file in `configs/localization` directory for config_fpath in config_fpaths: config_mod = mmcv.Config.fromfile(config_fpath) print(f'Building localizer, config_fpath = {config_fpath!r}') if config_mod.get('model', None): localizer = build_localizer(config_mod.model) assert isinstance(localizer, nn.Module)
1,166
743
package io.adaptivecards.objectmodel; import org.junit.Assert; import org.junit.Test; public class MediaPropertiesTest { static { System.loadLibrary("adaptivecards-native-lib"); } public static Media cast(BaseCardElement baseCardElement) { Media media = null; if (baseCardElement instanceof Media) { media = (Media) baseCardElement; } else if ((media = Media.dynamic_cast(baseCardElement)) == null) { throw new InternalError("Unable to convert BaseCardElement to Media object model."); } return media; } public static Media createMockMedia() { Media media = new Media(); MediaSource mediaSource = new MediaSource(); mediaSource.SetUrl("http://"); mediaSource.SetMimeType("video/mp4"); media.GetSources().add(mediaSource); return media; } @Test public void TestMockMedia() { Assert.assertEquals(s_defaultMedia, createMockMedia().Serialize()); } @Test public void AllPropertiesTest() { final String mediaAltText = "{\"altText\":\"Alternative Text\"," + "\"poster\":\"http://\"," + "\"sources\":[{\"mimeType\":\"video/mp4\",\"url\":\"http://\"}]," + "\"type\":\"Media\"}\n"; Media media = createMockMedia(); media.SetAltText("Alternative Text"); media.SetPoster("http://"); Assert.assertEquals(mediaAltText, media.Serialize()); } @Test public void AllPropertiesWithInheritedTest() throws Exception { final String mediaNoDefaultValues = "{\"altText\":\"Alternative Text\"," + "\"fallback\":{\"type\":\"Image\",\"url\":\"http://\"}," + "\"height\":\"Stretch\"," + "\"id\":\"Sample id\"," + "\"isVisible\":false," + "\"poster\":\"http://\"," + "\"separator\":true," + "\"sources\":[{\"mimeType\":\"video/mp4\",\"url\":\"http://\"}]," + "\"spacing\":\"medium\"," + "\"type\":\"Media\"}\n"; Media media = createMockMedia(); media.SetAltText("Alternative Text"); media.SetFallbackType(FallbackType.Content); media.SetFallbackContent(TestUtil.createMockImage()); media.SetHeight(HeightType.Stretch); media.SetId("Sample id"); media.SetIsVisible(false); media.SetPoster("http://"); media.SetSeparator(true); media.SetSpacing(Spacing.Medium); Assert.assertEquals(mediaNoDefaultValues, media.Serialize()); } @Test public void AltTextTest() throws Exception { { Media media = createMockMedia(); media.SetAltText(""); Assert.assertEquals(s_defaultMedia, media.Serialize()); ParseResult result = AdaptiveCard.DeserializeFromString(TestUtil.encloseElementJsonInCard(s_defaultMedia), "1.0"); Media parsedMedia = MediaPropertiesTest.cast(result.GetAdaptiveCard().GetBody().get(0)); Assert.assertEquals("", parsedMedia.GetAltText()); } { final String mediaAltText = "{\"altText\":\"Alternative Text\",\"sources\":[{\"mimeType\":\"video/mp4\",\"url\":\"http://\"}],\"type\":\"Media\"}\n"; Media media = createMockMedia(); media.SetAltText("Alternative Text"); Assert.assertEquals(mediaAltText, media.Serialize()); ParseResult result = AdaptiveCard.DeserializeFromString(TestUtil.encloseElementJsonInCard(mediaAltText), "1.0"); Media parsedMedia = MediaPropertiesTest.cast(result.GetAdaptiveCard().GetBody().get(0)); Assert.assertEquals("Alternative Text", parsedMedia.GetAltText()); } } @Test public void PosterTest() throws Exception { { Media media = createMockMedia(); media.SetAltText(""); Assert.assertEquals(s_defaultMedia, media.Serialize()); ParseResult result = AdaptiveCard.DeserializeFromString(TestUtil.encloseElementJsonInCard(s_defaultMedia), "1.0"); Media parsedMedia = MediaPropertiesTest.cast(result.GetAdaptiveCard().GetBody().get(0)); Assert.assertEquals("", parsedMedia.GetAltText()); } { final String mediaPoster = "{\"poster\":\"http://\",\"sources\":[{\"mimeType\":\"video/mp4\",\"url\":\"http://\"}],\"type\":\"Media\"}\n"; Media media = createMockMedia(); media.SetPoster("http://"); Assert.assertEquals(mediaPoster, media.Serialize()); ParseResult result = AdaptiveCard.DeserializeFromString(TestUtil.encloseElementJsonInCard(mediaPoster), "1.0"); Media parsedMedia = MediaPropertiesTest.cast(result.GetAdaptiveCard().GetBody().get(0)); Assert.assertEquals("http://", parsedMedia.GetPoster()); } } private static String s_defaultMedia = "{\"sources\":[{\"mimeType\":\"video/mp4\",\"url\":\"http://\"}],\"type\":\"Media\"}\n"; }
2,231
1,367
<reponame>developer-inspur/SwissArmyKnife package com.wanjian.sak.converter; /** * Created by wanjian on 2017/2/20. */ public class Size { private Size() { } public Size(int length, String unit) { } public static Size obtain() { return null; } public float getLength() { return 0; } public Size setLength(float length) { return this; } public String getUnit() { return null; } public Size setUnit(String unit) { return this; } }
229
2,279
<gh_stars>1000+ /* ** ** Copyright 2009, The Android Open Source Project ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ #include <stdio.h> #include <assert.h> #include <jni.h> #include <string.h> #include "dictionary.h" // ---------------------------------------------------------------------------- using namespace nativeime; static jmethodID sGetWordsCallbackMethodId; // // helper function to throw an exception // static void throwException(JNIEnv *env, const char *ex, const char *fmt, int data) { if (jclass cls = env->FindClass(ex)) { char msg[1000]; sprintf(msg, fmt, data); env->ThrowNew(cls, msg); env->DeleteLocalRef(cls); } } static jlong nativeime_ResourceBinaryDictionary_open (JNIEnv *env, jobject object, jobject dictDirectBuffer, jint typedLetterMultiplier, jint fullWordMultiplier) { void *dict = env->GetDirectBufferAddress(dictDirectBuffer); if (dict == NULL) { fprintf(stderr, "DICT: Dictionary buffer is null\n"); return 0; } Dictionary *dictionary = new Dictionary(dict, typedLetterMultiplier, fullWordMultiplier); return jlong(dictionary); } static int nativeime_ResourceBinaryDictionary_getSuggestions( JNIEnv *env, jobject object, jlong dict, jintArray inputArray, jint arraySize, jcharArray outputArray, jintArray frequencyArray, jint maxWordLength, jint maxWords, jint maxAlternatives, jint skipPos, jintArray nextLettersArray, jint nextLettersSize) { Dictionary *dictionary = reinterpret_cast<Dictionary *>(dict); if (dictionary == NULL) return 0; int *frequencies = env->GetIntArrayElements(frequencyArray, NULL); int *inputCodes = env->GetIntArrayElements(inputArray, NULL); jchar *outputChars = env->GetCharArrayElements(outputArray, NULL); int *nextLetters = nextLettersArray != NULL ? env->GetIntArrayElements(nextLettersArray, NULL) : NULL; int count = dictionary->getSuggestions(inputCodes, arraySize, outputChars, frequencies, maxWordLength, maxWords, maxAlternatives, skipPos, nextLetters, nextLettersSize); env->ReleaseIntArrayElements(frequencyArray, frequencies, 0); env->ReleaseIntArrayElements(inputArray, inputCodes, JNI_ABORT); env->ReleaseCharArrayElements(outputArray, outputChars, 0); if (nextLetters) { env->ReleaseIntArrayElements(nextLettersArray, nextLetters, 0); } return count; } static jboolean nativeime_ResourceBinaryDictionary_isValidWord (JNIEnv *env, jobject object, jlong dict, jcharArray wordArray, jint wordLength) { Dictionary *dictionary = reinterpret_cast<Dictionary *>(dict); if (dictionary == NULL) return (jboolean) false; jchar *word = env->GetCharArrayElements(wordArray, NULL); jboolean result = static_cast<jboolean>(dictionary->isValidWord(word, wordLength)); env->ReleaseCharArrayElements(wordArray, word, JNI_ABORT); return result; } static void nativeime_ResourceBinaryDictionary_getWords (JNIEnv *env, jobject object, jlong dict, jobject getWordsCallback) { Dictionary *dictionary = reinterpret_cast<Dictionary *>(dict); if (!dictionary) return; int wordCount = 0, wordsCharsCount = 0; dictionary->countWordsChars(wordCount, wordsCharsCount); unsigned short *words = new unsigned short[wordsCharsCount]; jintArray frequencyArray = env->NewIntArray(wordCount); int *frequencies = env->GetIntArrayElements(frequencyArray, NULL); dictionary->getWords(words, frequencies); env->ReleaseIntArrayElements(frequencyArray, frequencies, 0); jobjectArray javaLandChars = env->NewObjectArray(wordCount, env->FindClass("[C"), NULL); unsigned short *pos = words; for (int i = 0; i < wordCount; ++i) { size_t count = 0; while (pos[count] != 0x00) ++count; jcharArray jchr = env->NewCharArray((jsize) count); jchar *chr = env->GetCharArrayElements(jchr, NULL); memcpy(chr, pos, count * sizeof(unsigned short)); env->ReleaseCharArrayElements(jchr, chr, 0); env->SetObjectArrayElement(javaLandChars, i, jchr); pos += count + 1; env->DeleteLocalRef(jchr); } delete[] words; env->CallVoidMethod(getWordsCallback, sGetWordsCallbackMethodId, javaLandChars, frequencyArray); } static void nativeime_ResourceBinaryDictionary_close (JNIEnv *env, jobject object, jlong dict) { Dictionary *dictionary = reinterpret_cast<Dictionary *>(dict); delete dictionary; } // ---------------------------------------------------------------------------- static JNINativeMethod gMethods[] = { {"openNative", "(Ljava/nio/ByteBuffer;II)J", (void *) nativeime_ResourceBinaryDictionary_open}, {"closeNative", "(J)V", (void *) nativeime_ResourceBinaryDictionary_close}, {"getSuggestionsNative", "(J[II[C[IIIII[II)I", (void *) nativeime_ResourceBinaryDictionary_getSuggestions}, {"isValidWordNative", "(J[CI)Z", (void *) nativeime_ResourceBinaryDictionary_isValidWord}, {"getWordsNative", "(JLcom/anysoftkeyboard/dictionaries/GetWordsCallback;)V", (void *) nativeime_ResourceBinaryDictionary_getWords} }; static int registerNativeMethods(JNIEnv *env, const char *className, JNINativeMethod *gMethods, int numMethods) { jclass clazz; clazz = env->FindClass(className); if (clazz == NULL) { fprintf(stderr, "Native registration unable to find class '%s'\n", className); return JNI_FALSE; } if (env->RegisterNatives(clazz, gMethods, numMethods) < 0) { fprintf(stderr, "RegisterNatives failed for '%s'\n", className); return JNI_FALSE; } return JNI_TRUE; } static int registerNatives(JNIEnv *env) { const char *const kClassPathName = "com/anysoftkeyboard/dictionaries/jni/ResourceBinaryDictionary"; return registerNativeMethods(env, kClassPathName, gMethods, sizeof(gMethods) / sizeof(gMethods[0])); } /* * Returns the JNI version on success, -1 on failure. */ jint JNI_OnLoad(JavaVM *vm, void *reserved) { JNIEnv *env = NULL; if (vm->GetEnv((void **) &env, JNI_VERSION_1_6) != JNI_OK) { fprintf(stderr, "ERROR: GetEnv failed\n"); return -1; } assert(env != NULL); if (!registerNatives(env)) { fprintf(stderr, "ERROR: BinaryDictionary native registration failed\n"); return -1; } jclass getWordsCallbackClass = env->FindClass( "com/anysoftkeyboard/dictionaries/GetWordsCallback"); //void (char[][] words, int[] frequencies); sGetWordsCallbackMethodId = env->GetMethodID(getWordsCallbackClass, "onGetWordsFinished", "([[C[I)V"); /* success -- return valid version number */ return JNI_VERSION_1_6; }
3,064
412
<filename>odps/tests/test_serializers.py #!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 1999-2017 Alibaba Group Holding Ltd. # # 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. from datetime import datetime import time from odps.tests.core import TestBase, to_str from odps.compat import unittest from odps.serializers import * from odps import utils expected_xml_template = '''<?xml version="1.0" encoding="utf-8"?> <Example type="ex"> <Name>example 1</Name> <Created>%s</Created> <Lessons> <Lesson>less1</Lesson> <Lesson>less2</Lesson> </Lessons> <Teacher> <Name>t1</Name> </Teacher> <Student name="s1">s1_content</Student> <Professors> <Professor> <Name>p1</Name> </Professor> <Professor> <Name>p2</Name> </Professor> </Professors> <Config> <Property> <Name>test</Name> <Value>true</Value> </Property> </Config> <json>{"label": "json", "tags": [{"tag": "t1"}, {"tag": "t2"}], "nest": {"name": "n"}, "nests": {"nest": [{"name": "n1"}, {"name": "n2"}]}}</json> <Disabled>false</Disabled> <Enabled>true</Enabled> </Example> ''' LIST_OBJ_TMPL = '''<?xml version="1.0" ?> <objs> <marker>%s</marker> <obj>%s</obj> </objs> ''' LIST_OBJ_LAST_TMPL = '''<?xml version="1.0" ?> <objs> <obj>%s</obj> </objs> ''' class Example(XMLSerializableModel): __slots__ = 'name', 'type', 'date', 'lessons', 'teacher', 'student',\ 'professors', 'properties', 'jsn', 'bool_false', 'bool_true' _root = 'Example' class Teacher(XMLSerializableModel): name = XMLNodeField('Name') tag = XMLTagField('.') def __eq__(self, other): return isinstance(other, Example.Teacher) and \ self.name == other.name class Student(XMLSerializableModel): name = XMLNodeAttributeField(attr='name') content = XMLNodeField('.') def __eq__(self, other): return isinstance(other, Example.Student) and \ self.name == other.name and \ self.content == other.content class Json(JSONSerializableModel): __slots__ = 'label', 'tags', 'nest', 'nests' class Nest(JSONSerializableModel): name = JSONNodeField('name') def __eq__(self, other): return isinstance(other, Example.Json.Nest) and \ self.name == other.name label = JSONNodeField('label') tags = JSONNodesField('tags', 'tag') nest = JSONNodeReferenceField(Nest, 'nest') nests = JSONNodesReferencesField(Nest, 'nests', 'nest') name = XMLNodeField('Name') type = XMLNodeAttributeField('.', attr='type') date = XMLNodeField('Created', type='rfc822l') bool_true = XMLNodeField('Enabled', type='bool') bool_false = XMLNodeField('Disabled', type='bool') lessons = XMLNodesField('Lessons', 'Lesson') teacher = XMLNodeReferenceField(Teacher, 'Teacher') student = XMLNodeReferenceField(Student, 'Student') professors = XMLNodesReferencesField(Teacher, 'Professors', 'Professor') properties = XMLNodePropertiesField('Config', 'Property', key_tag='Name', value_tag='Value') jsn = XMLNodeReferenceField(Json, 'json') class Test(TestBase): def testSerializers(self): teacher = Example.Teacher(name='t1') student = Example.Student(name='s1', content='s1_content') professors = [Example.Teacher(name='p1'), Example.Teacher(name='p2')] jsn = Example.Json(label='json', tags=['t1', 't2'], nest=Example.Json.Nest(name='n'), nests=[Example.Json.Nest(name='n1'), Example.Json.Nest(name='n2')]) dt = datetime.fromtimestamp(time.mktime(datetime.now().timetuple())) example = Example(name='example 1', type='ex', date=dt, bool_true=True, bool_false=False, lessons=['less1', 'less2'], teacher=teacher, student=student, professors=professors, properties={'test': 'true'}, jsn=jsn) sel = example.serialize() self.assertEqual( to_str(expected_xml_template % utils.gen_rfc822(dt, localtime=True)), to_str(sel)) parsed_example = Example.parse(sel) self.assertEqual(example.name, parsed_example.name) self.assertEqual(example.type, parsed_example.type) self.assertEqual(example.date, parsed_example.date) self.assertEqual(example.bool_true, parsed_example.bool_true) self.assertEqual(example.bool_false, parsed_example.bool_false) self.assertSequenceEqual(example.lessons, parsed_example.lessons) self.assertEqual(example.teacher, parsed_example.teacher) self.assertEqual(example.student, parsed_example.student) self.assertSequenceEqual(example.professors, parsed_example.professors) self.assertTrue(len(example.properties) == len(parsed_example.properties) and any(example.properties[it] == parsed_example.properties[it]) for it in example.properties) self.assertEqual(example.jsn.label, parsed_example.jsn.label) self.assertEqual(example.jsn.tags, parsed_example.jsn.tags) self.assertEqual(example.jsn.nest, parsed_example.jsn.nest) self.assertSequenceEqual(example.jsn.nests, parsed_example.jsn.nests) def testPropertyOverride(self): def gen_objs(marker): assert marker > 0 if marker >= 3: return LIST_OBJ_LAST_TMPL % 3 else: return LIST_OBJ_TMPL % (marker, marker) class Objs(XMLSerializableModel): skip_null = False marker = XMLNodeField('marker') obj = XMLNodeField('obj') objs = Objs() i = 1 while True: objs.parse(gen_objs(i), obj=objs) if objs.marker is None: break i += 1 self.assertEqual(i, 3) if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testName'] unittest.main()
2,828
1,738
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ // Original file Copyright Crytek GMBH or its affiliates, used under license. #include "StdAfx.h" #include "SelectionTree_RefBrowser.h" #include "CustomFileDialog.h" IMPLEMENT_DYNAMIC(CSelectionTree_RefBrowser, CDialog) BEGIN_MESSAGE_MAP(CSelectionTree_RefBrowser, CDialog) ON_NOTIFY(TVN_SELCHANGED, IDC_BST_REFTREE, OnSelChanged) ON_BN_CLICKED(IDC_BST_SHOWCONTENTS, OnShowContents) ON_WM_SIZE() ON_WM_HSCROLL() END_MESSAGE_MAP() CSelectionTree_RefBrowser::CSelectionTree_RefBrowser(CWnd* pParent /*=NULL*/) : CDialog( CSelectionTree_RefBrowser::IDD, pParent ) , m_refType( eSTTI_Undefined ) { } CSelectionTree_RefBrowser::~CSelectionTree_RefBrowser() { } void CSelectionTree_RefBrowser::Init( ESelectionTreeTypeId type ) { m_refType = type; } const char* CSelectionTree_RefBrowser::GetSelectedRef() { return m_SelectedRef.length() > 0 ? m_SelectedRef.c_str() : NULL; } void CSelectionTree_RefBrowser::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_BST_REFTREE, m_RefTree); } BOOL CSelectionTree_RefBrowser::OnInitDialog() { CDialog::OnInitDialog(); CButton* rb = ( CButton* )GetDlgItem( IDC_BST_SHOWCONTENTS ); rb->ShowWindow(false); LoadReferences(); return TRUE; } void CSelectionTree_RefBrowser::OnSelChanged( NMHDR *pNMHDR, LRESULT *pResult ) { HTREEITEM item = m_RefTree.GetSelectedItem(); if( item ) { m_SelectedRef = m_RefNames[ item ]; } else { m_SelectedRef = ""; } } void CSelectionTree_RefBrowser::OnShowContents() { CButton* rb = ( CButton* )GetDlgItem( IDC_BST_SHOWCONTENTS ); LoadReferences(); } void CSelectionTree_RefBrowser::LoadReferences() { assert( m_refType != eSTTI_Undefined ); m_RefTree.DeleteAllItems(); TSelectionTreeInfoList infoList; GetIEditor()->GetSelectionTreeManager()->GetInfoList( infoList ); for ( TSelectionTreeInfoList::const_iterator it = infoList.begin(); it != infoList.end(); ++it ) { const SSelectionTreeInfo& info = *it; if ( !info.IsTree ) { const int blockCount = info.GetBlockCountById( m_refType ); for ( int i = 0; i < blockCount; ++i ) { SSelectionTreeBlockInfo blockInfo; bool ok = info.GetBlockById( blockInfo, m_refType, i); assert(ok); if ( ok ) { HTREEITEM item = m_RefTree.InsertItem( blockInfo.Name , 0, 0, TVI_ROOT, TVI_SORT ); m_RefNames[ item ] = blockInfo.Name; } } } } }
1,121
1,350
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.security.keyvault.keys.implementation; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import java.io.IOException; import java.util.Base64; /** * The base64 URL JSON deserializer. */ public class Base64UrlJsonDeserializer extends JsonDeserializer<byte[]> { @Override public byte[] deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { String text = jsonParser.getText(); if (text != null) { return Base64.getUrlDecoder().decode(text); } return null; } }
276
573
<gh_stars>100-1000 /* This file is part of the dynarmic project. * Copyright (c) 2018 MerryMage * SPDX-License-Identifier: 0BSD */ #include "dynarmic/frontend/A64/translate/impl/impl.h" namespace Dynarmic::A64 { static bool LoadStoreRegisterImmediate(TranslatorVisitor& v, bool wback, bool postindex, size_t scale, u64 offset, Imm<2> size, Imm<2> opc, Reg Rn, Reg Rt) { IR::MemOp memop; bool signed_ = false; size_t regsize = 0; if (opc.Bit<1>() == 0) { memop = opc.Bit<0>() ? IR::MemOp::LOAD : IR::MemOp::STORE; regsize = size == 0b11 ? 64 : 32; signed_ = false; } else if (size == 0b11) { memop = IR::MemOp::PREFETCH; ASSERT(!opc.Bit<0>()); } else { memop = IR::MemOp::LOAD; ASSERT(!(size == 0b10 && opc.Bit<0>() == 1)); regsize = opc.Bit<0>() ? 32 : 64; signed_ = true; } if (memop == IR::MemOp::LOAD && wback && Rn == Rt && Rn != Reg::R31) { return v.UnpredictableInstruction(); } if (memop == IR::MemOp::STORE && wback && Rn == Rt && Rn != Reg::R31) { return v.UnpredictableInstruction(); } // TODO: Check SP alignment IR::U64 address = Rn == Reg::SP ? IR::U64(v.SP(64)) : IR::U64(v.X(64, Rn)); if (!postindex) { address = v.ir.Add(address, v.ir.Imm64(offset)); } const size_t datasize = 8 << scale; switch (memop) { case IR::MemOp::STORE: { const auto data = v.X(datasize, Rt); v.Mem(address, datasize / 8, IR::AccType::NORMAL, data); break; } case IR::MemOp::LOAD: { const auto data = v.Mem(address, datasize / 8, IR::AccType::NORMAL); if (signed_) { v.X(regsize, Rt, v.SignExtend(data, regsize)); } else { v.X(regsize, Rt, v.ZeroExtend(data, regsize)); } break; } case IR::MemOp::PREFETCH: // Prefetch(address, Rt) break; } if (wback) { if (postindex) { address = v.ir.Add(address, v.ir.Imm64(offset)); } if (Rn == Reg::SP) { v.SP(64, address); } else { v.X(64, Rn, address); } } return true; } bool TranslatorVisitor::STRx_LDRx_imm_1(Imm<2> size, Imm<2> opc, Imm<9> imm9, bool not_postindex, Reg Rn, Reg Rt) { const bool wback = true; const bool postindex = !not_postindex; const size_t scale = size.ZeroExtend<size_t>(); const u64 offset = imm9.SignExtend<u64>(); return LoadStoreRegisterImmediate(*this, wback, postindex, scale, offset, size, opc, Rn, Rt); } bool TranslatorVisitor::STRx_LDRx_imm_2(Imm<2> size, Imm<2> opc, Imm<12> imm12, Reg Rn, Reg Rt) { const bool wback = false; const bool postindex = false; const size_t scale = size.ZeroExtend<size_t>(); const u64 offset = imm12.ZeroExtend<u64>() << scale; return LoadStoreRegisterImmediate(*this, wback, postindex, scale, offset, size, opc, Rn, Rt); } bool TranslatorVisitor::STURx_LDURx(Imm<2> size, Imm<2> opc, Imm<9> imm9, Reg Rn, Reg Rt) { const bool wback = false; const bool postindex = false; const size_t scale = size.ZeroExtend<size_t>(); const u64 offset = imm9.SignExtend<u64>(); return LoadStoreRegisterImmediate(*this, wback, postindex, scale, offset, size, opc, Rn, Rt); } bool TranslatorVisitor::PRFM_imm([[maybe_unused]] Imm<12> imm12, [[maybe_unused]] Reg Rn, [[maybe_unused]] Reg Rt) { // Currently a NOP (which is valid behavior, as indicated by // the ARMv8 architecture reference manual) return true; } bool TranslatorVisitor::PRFM_unscaled_imm([[maybe_unused]] Imm<9> imm9, [[maybe_unused]] Reg Rn, [[maybe_unused]] Reg Rt) { // Currently a NOP (which is valid behavior, as indicated by // the ARMv8 architecture reference manual) return true; } static bool LoadStoreSIMD(TranslatorVisitor& v, bool wback, bool postindex, size_t scale, u64 offset, IR::MemOp memop, Reg Rn, Vec Vt) { const auto acctype = IR::AccType::VEC; const size_t datasize = 8 << scale; IR::U64 address; if (Rn == Reg::SP) { // TODO: Check SP Alignment address = v.SP(64); } else { address = v.X(64, Rn); } if (!postindex) { address = v.ir.Add(address, v.ir.Imm64(offset)); } switch (memop) { case IR::MemOp::STORE: if (datasize == 128) { const IR::U128 data = v.V(128, Vt); v.Mem(address, 16, acctype, data); } else { const IR::UAny data = v.ir.VectorGetElement(datasize, v.V(128, Vt), 0); v.Mem(address, datasize / 8, acctype, data); } break; case IR::MemOp::LOAD: if (datasize == 128) { const IR::U128 data = v.Mem(address, 16, acctype); v.V(128, Vt, data); } else { const IR::UAny data = v.Mem(address, datasize / 8, acctype); v.V(128, Vt, v.ir.ZeroExtendToQuad(data)); } break; default: UNREACHABLE(); } if (wback) { if (postindex) { address = v.ir.Add(address, v.ir.Imm64(offset)); } if (Rn == Reg::SP) { v.SP(64, address); } else { v.X(64, Rn, address); } } return true; } bool TranslatorVisitor::STR_imm_fpsimd_1(Imm<2> size, Imm<1> opc_1, Imm<9> imm9, bool not_postindex, Reg Rn, Vec Vt) { const size_t scale = concatenate(opc_1, size).ZeroExtend<size_t>(); if (scale > 4) { return UnallocatedEncoding(); } const bool wback = true; const bool postindex = !not_postindex; const u64 offset = imm9.SignExtend<u64>(); return LoadStoreSIMD(*this, wback, postindex, scale, offset, IR::MemOp::STORE, Rn, Vt); } bool TranslatorVisitor::STR_imm_fpsimd_2(Imm<2> size, Imm<1> opc_1, Imm<12> imm12, Reg Rn, Vec Vt) { const size_t scale = concatenate(opc_1, size).ZeroExtend<size_t>(); if (scale > 4) { return UnallocatedEncoding(); } const bool wback = false; const bool postindex = false; const u64 offset = imm12.ZeroExtend<u64>() << scale; return LoadStoreSIMD(*this, wback, postindex, scale, offset, IR::MemOp::STORE, Rn, Vt); } bool TranslatorVisitor::LDR_imm_fpsimd_1(Imm<2> size, Imm<1> opc_1, Imm<9> imm9, bool not_postindex, Reg Rn, Vec Vt) { const size_t scale = concatenate(opc_1, size).ZeroExtend<size_t>(); if (scale > 4) { return UnallocatedEncoding(); } const bool wback = true; const bool postindex = !not_postindex; const u64 offset = imm9.SignExtend<u64>(); return LoadStoreSIMD(*this, wback, postindex, scale, offset, IR::MemOp::LOAD, Rn, Vt); } bool TranslatorVisitor::LDR_imm_fpsimd_2(Imm<2> size, Imm<1> opc_1, Imm<12> imm12, Reg Rn, Vec Vt) { const size_t scale = concatenate(opc_1, size).ZeroExtend<size_t>(); if (scale > 4) { return UnallocatedEncoding(); } const bool wback = false; const bool postindex = false; const u64 offset = imm12.ZeroExtend<u64>() << scale; return LoadStoreSIMD(*this, wback, postindex, scale, offset, IR::MemOp::LOAD, Rn, Vt); } bool TranslatorVisitor::STUR_fpsimd(Imm<2> size, Imm<1> opc_1, Imm<9> imm9, Reg Rn, Vec Vt) { const size_t scale = concatenate(opc_1, size).ZeroExtend<size_t>(); if (scale > 4) { return UnallocatedEncoding(); } const bool wback = false; const bool postindex = false; const u64 offset = imm9.SignExtend<u64>(); return LoadStoreSIMD(*this, wback, postindex, scale, offset, IR::MemOp::STORE, Rn, Vt); } bool TranslatorVisitor::LDUR_fpsimd(Imm<2> size, Imm<1> opc_1, Imm<9> imm9, Reg Rn, Vec Vt) { const size_t scale = concatenate(opc_1, size).ZeroExtend<size_t>(); if (scale > 4) { return UnallocatedEncoding(); } const bool wback = false; const bool postindex = false; const u64 offset = imm9.SignExtend<u64>(); return LoadStoreSIMD(*this, wback, postindex, scale, offset, IR::MemOp::LOAD, Rn, Vt); } } // namespace Dynarmic::A64
3,663
2,151
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.app; import android.Manifest; import android.annotation.SystemApi; import android.app.usage.UsageStatsManager; import android.content.Context; import android.media.AudioAttributes.AttributeUsage; import android.os.Binder; import android.os.IBinder; import android.os.Parcel; import android.os.Parcelable; import android.os.Process; import android.os.RemoteException; import android.os.UserHandle; import android.os.UserManager; import android.util.ArrayMap; import com.android.internal.app.IAppOpsCallback; import com.android.internal.app.IAppOpsService; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * API for interacting with "application operation" tracking. * * <p>This API is not generally intended for third party application developers; most * features are only available to system applications. Obtain an instance of it through * {@link Context#getSystemService(String) Context.getSystemService} with * {@link Context#APP_OPS_SERVICE Context.APP_OPS_SERVICE}.</p> */ public class AppOpsManager { /** * <p>App ops allows callers to:</p> * * <ul> * <li> Note when operations are happening, and find out if they are allowed for the current * caller.</li> * <li> Disallow specific apps from doing specific operations.</li> * <li> Collect all of the current information about operations that have been executed or * are not being allowed.</li> * <li> Monitor for changes in whether an operation is allowed.</li> * </ul> * * <p>Each operation is identified by a single integer; these integers are a fixed set of * operations, enumerated by the OP_* constants. * * <p></p>When checking operations, the result is a "mode" integer indicating the current * setting for the operation under that caller: MODE_ALLOWED, MODE_IGNORED (don't execute * the operation but fake its behavior enough so that the caller doesn't crash), * MODE_ERRORED (throw a SecurityException back to the caller; the normal operation calls * will do this for you). */ final Context mContext; final IAppOpsService mService; final ArrayMap<OnOpChangedListener, IAppOpsCallback> mModeWatchers = new ArrayMap<OnOpChangedListener, IAppOpsCallback>(); static IBinder sToken; /** * Result from {@link #checkOp}, {@link #noteOp}, {@link #startOp}: the given caller is * allowed to perform the given operation. */ public static final int MODE_ALLOWED = 0; /** * Result from {@link #checkOp}, {@link #noteOp}, {@link #startOp}: the given caller is * not allowed to perform the given operation, and this attempt should * <em>silently fail</em> (it should not cause the app to crash). */ public static final int MODE_IGNORED = 1; /** * Result from {@link #checkOpNoThrow}, {@link #noteOpNoThrow}, {@link #startOpNoThrow}: the * given caller is not allowed to perform the given operation, and this attempt should * cause it to have a fatal error, typically a {@link SecurityException}. */ public static final int MODE_ERRORED = 2; /** * Result from {@link #checkOp}, {@link #noteOp}, {@link #startOp}: the given caller should * use its default security check. This mode is not normally used; it should only be used * with appop permissions, and callers must explicitly check for it and deal with it. */ public static final int MODE_DEFAULT = 3; // when adding one of these: // - increment _NUM_OP // - add rows to sOpToSwitch, sOpToString, sOpNames, sOpToPerms, sOpDefault // - add descriptive strings to Settings/res/values/arrays.xml // - add the op to the appropriate template in AppOpsState.OpsTemplate (settings app) /** @hide No operation specified. */ public static final int OP_NONE = -1; /** @hide Access to coarse location information. */ public static final int OP_COARSE_LOCATION = 0; /** @hide Access to fine location information. */ public static final int OP_FINE_LOCATION = 1; /** @hide Causing GPS to run. */ public static final int OP_GPS = 2; /** @hide */ public static final int OP_VIBRATE = 3; /** @hide */ public static final int OP_READ_CONTACTS = 4; /** @hide */ public static final int OP_WRITE_CONTACTS = 5; /** @hide */ public static final int OP_READ_CALL_LOG = 6; /** @hide */ public static final int OP_WRITE_CALL_LOG = 7; /** @hide */ public static final int OP_READ_CALENDAR = 8; /** @hide */ public static final int OP_WRITE_CALENDAR = 9; /** @hide */ public static final int OP_WIFI_SCAN = 10; /** @hide */ public static final int OP_POST_NOTIFICATION = 11; /** @hide */ public static final int OP_NEIGHBORING_CELLS = 12; /** @hide */ public static final int OP_CALL_PHONE = 13; /** @hide */ public static final int OP_READ_SMS = 14; /** @hide */ public static final int OP_WRITE_SMS = 15; /** @hide */ public static final int OP_RECEIVE_SMS = 16; /** @hide */ public static final int OP_RECEIVE_EMERGECY_SMS = 17; /** @hide */ public static final int OP_RECEIVE_MMS = 18; /** @hide */ public static final int OP_RECEIVE_WAP_PUSH = 19; /** @hide */ public static final int OP_SEND_SMS = 20; /** @hide */ public static final int OP_READ_ICC_SMS = 21; /** @hide */ public static final int OP_WRITE_ICC_SMS = 22; /** @hide */ public static final int OP_WRITE_SETTINGS = 23; /** @hide */ public static final int OP_SYSTEM_ALERT_WINDOW = 24; /** @hide */ public static final int OP_ACCESS_NOTIFICATIONS = 25; /** @hide */ public static final int OP_CAMERA = 26; /** @hide */ public static final int OP_RECORD_AUDIO = 27; /** @hide */ public static final int OP_PLAY_AUDIO = 28; /** @hide */ public static final int OP_READ_CLIPBOARD = 29; /** @hide */ public static final int OP_WRITE_CLIPBOARD = 30; /** @hide */ public static final int OP_TAKE_MEDIA_BUTTONS = 31; /** @hide */ public static final int OP_TAKE_AUDIO_FOCUS = 32; /** @hide */ public static final int OP_AUDIO_MASTER_VOLUME = 33; /** @hide */ public static final int OP_AUDIO_VOICE_VOLUME = 34; /** @hide */ public static final int OP_AUDIO_RING_VOLUME = 35; /** @hide */ public static final int OP_AUDIO_MEDIA_VOLUME = 36; /** @hide */ public static final int OP_AUDIO_ALARM_VOLUME = 37; /** @hide */ public static final int OP_AUDIO_NOTIFICATION_VOLUME = 38; /** @hide */ public static final int OP_AUDIO_BLUETOOTH_VOLUME = 39; /** @hide */ public static final int OP_WAKE_LOCK = 40; /** @hide Continually monitoring location data. */ public static final int OP_MONITOR_LOCATION = 41; /** @hide Continually monitoring location data with a relatively high power request. */ public static final int OP_MONITOR_HIGH_POWER_LOCATION = 42; /** @hide Retrieve current usage stats via {@link UsageStatsManager}. */ public static final int OP_GET_USAGE_STATS = 43; /** @hide */ public static final int OP_MUTE_MICROPHONE = 44; /** @hide */ public static final int OP_TOAST_WINDOW = 45; /** @hide Capture the device's display contents and/or audio */ public static final int OP_PROJECT_MEDIA = 46; /** @hide Activate a VPN connection without user intervention. */ public static final int OP_ACTIVATE_VPN = 47; /** @hide Access the WallpaperManagerAPI to write wallpapers. */ public static final int OP_WRITE_WALLPAPER = 48; /** @hide Received the assist structure from an app. */ public static final int OP_ASSIST_STRUCTURE = 49; /** @hide Received a screenshot from assist. */ public static final int OP_ASSIST_SCREENSHOT = 50; /** @hide Read the phone state. */ public static final int OP_READ_PHONE_STATE = 51; /** @hide Add voicemail messages to the voicemail content provider. */ public static final int OP_ADD_VOICEMAIL = 52; /** @hide Access APIs for SIP calling over VOIP or WiFi. */ public static final int OP_USE_SIP = 53; /** @hide Intercept outgoing calls. */ public static final int OP_PROCESS_OUTGOING_CALLS = 54; /** @hide User the fingerprint API. */ public static final int OP_USE_FINGERPRINT = 55; /** @hide Access to body sensors such as heart rate, etc. */ public static final int OP_BODY_SENSORS = 56; /** @hide Read previously received cell broadcast messages. */ public static final int OP_READ_CELL_BROADCASTS = 57; /** @hide Inject mock location into the system. */ public static final int OP_MOCK_LOCATION = 58; /** @hide Read external storage. */ public static final int OP_READ_EXTERNAL_STORAGE = 59; /** @hide Write external storage. */ public static final int OP_WRITE_EXTERNAL_STORAGE = 60; /** @hide Turned on the screen. */ public static final int OP_TURN_SCREEN_ON = 61; /** @hide Get device accounts. */ public static final int OP_GET_ACCOUNTS = 62; /** @hide Control whether an application is allowed to run in the background. */ public static final int OP_RUN_IN_BACKGROUND = 63; /** @hide */ public static final int _NUM_OP = 64; /** Access to coarse location information. */ public static final String OPSTR_COARSE_LOCATION = "android:coarse_location"; /** Access to fine location information. */ public static final String OPSTR_FINE_LOCATION = "android:fine_location"; /** Continually monitoring location data. */ public static final String OPSTR_MONITOR_LOCATION = "android:monitor_location"; /** Continually monitoring location data with a relatively high power request. */ public static final String OPSTR_MONITOR_HIGH_POWER_LOCATION = "android:monitor_location_high_power"; /** Access to {@link android.app.usage.UsageStatsManager}. */ public static final String OPSTR_GET_USAGE_STATS = "android:get_usage_stats"; /** Activate a VPN connection without user intervention. @hide */ @SystemApi public static final String OPSTR_ACTIVATE_VPN = "android:activate_vpn"; /** Allows an application to read the user's contacts data. */ public static final String OPSTR_READ_CONTACTS = "android:read_contacts"; /** Allows an application to write to the user's contacts data. */ public static final String OPSTR_WRITE_CONTACTS = "android:write_contacts"; /** Allows an application to read the user's call log. */ public static final String OPSTR_READ_CALL_LOG = "android:read_call_log"; /** Allows an application to write to the user's call log. */ public static final String OPSTR_WRITE_CALL_LOG = "android:write_call_log"; /** Allows an application to read the user's calendar data. */ public static final String OPSTR_READ_CALENDAR = "android:read_calendar"; /** Allows an application to write to the user's calendar data. */ public static final String OPSTR_WRITE_CALENDAR = "android:write_calendar"; /** Allows an application to initiate a phone call. */ public static final String OPSTR_CALL_PHONE = "android:call_phone"; /** Allows an application to read SMS messages. */ public static final String OPSTR_READ_SMS = "android:read_sms"; /** Allows an application to receive SMS messages. */ public static final String OPSTR_RECEIVE_SMS = "android:receive_sms"; /** Allows an application to receive MMS messages. */ public static final String OPSTR_RECEIVE_MMS = "android:receive_mms"; /** Allows an application to receive WAP push messages. */ public static final String OPSTR_RECEIVE_WAP_PUSH = "android:receive_wap_push"; /** Allows an application to send SMS messages. */ public static final String OPSTR_SEND_SMS = "android:send_sms"; /** Required to be able to access the camera device. */ public static final String OPSTR_CAMERA = "android:camera"; /** Required to be able to access the microphone device. */ public static final String OPSTR_RECORD_AUDIO = "android:record_audio"; /** Required to access phone state related information. */ public static final String OPSTR_READ_PHONE_STATE = "android:read_phone_state"; /** Required to access phone state related information. */ public static final String OPSTR_ADD_VOICEMAIL = "android:add_voicemail"; /** Access APIs for SIP calling over VOIP or WiFi */ public static final String OPSTR_USE_SIP = "android:use_sip"; /** Use the fingerprint API. */ public static final String OPSTR_USE_FINGERPRINT = "android:use_fingerprint"; /** Access to body sensors such as heart rate, etc. */ public static final String OPSTR_BODY_SENSORS = "android:body_sensors"; /** Read previously received cell broadcast messages. */ public static final String OPSTR_READ_CELL_BROADCASTS = "android:read_cell_broadcasts"; /** Inject mock location into the system. */ public static final String OPSTR_MOCK_LOCATION = "android:mock_location"; /** Read external storage. */ public static final String OPSTR_READ_EXTERNAL_STORAGE = "android:read_external_storage"; /** Write external storage. */ public static final String OPSTR_WRITE_EXTERNAL_STORAGE = "android:write_external_storage"; /** Required to draw on top of other apps. */ public static final String OPSTR_SYSTEM_ALERT_WINDOW = "android:system_alert_window"; /** Required to write/modify/update system settingss. */ public static final String OPSTR_WRITE_SETTINGS = "android:write_settings"; /** @hide Get device accounts. */ public static final String OPSTR_GET_ACCOUNTS = "android:get_accounts"; private static final int[] RUNTIME_PERMISSIONS_OPS = { // Contacts OP_READ_CONTACTS, OP_WRITE_CONTACTS, OP_GET_ACCOUNTS, // Calendar OP_READ_CALENDAR, OP_WRITE_CALENDAR, // SMS OP_SEND_SMS, OP_RECEIVE_SMS, OP_READ_SMS, OP_RECEIVE_WAP_PUSH, OP_RECEIVE_MMS, OP_READ_CELL_BROADCASTS, // Storage OP_READ_EXTERNAL_STORAGE, OP_WRITE_EXTERNAL_STORAGE, // Location OP_COARSE_LOCATION, OP_FINE_LOCATION, // Phone OP_READ_PHONE_STATE, OP_CALL_PHONE, OP_READ_CALL_LOG, OP_WRITE_CALL_LOG, OP_ADD_VOICEMAIL, OP_USE_SIP, OP_PROCESS_OUTGOING_CALLS, // Microphone OP_RECORD_AUDIO, // Camera OP_CAMERA, // Body sensors OP_BODY_SENSORS }; /** * This maps each operation to the operation that serves as the * switch to determine whether it is allowed. Generally this is * a 1:1 mapping, but for some things (like location) that have * multiple low-level operations being tracked that should be * presented to the user as one switch then this can be used to * make them all controlled by the same single operation. */ private static int[] sOpToSwitch = new int[] { OP_COARSE_LOCATION, OP_COARSE_LOCATION, OP_COARSE_LOCATION, OP_VIBRATE, OP_READ_CONTACTS, OP_WRITE_CONTACTS, OP_READ_CALL_LOG, OP_WRITE_CALL_LOG, OP_READ_CALENDAR, OP_WRITE_CALENDAR, OP_COARSE_LOCATION, OP_POST_NOTIFICATION, OP_COARSE_LOCATION, OP_CALL_PHONE, OP_READ_SMS, OP_WRITE_SMS, OP_RECEIVE_SMS, OP_RECEIVE_SMS, OP_RECEIVE_SMS, OP_RECEIVE_SMS, OP_SEND_SMS, OP_READ_SMS, OP_WRITE_SMS, OP_WRITE_SETTINGS, OP_SYSTEM_ALERT_WINDOW, OP_ACCESS_NOTIFICATIONS, OP_CAMERA, OP_RECORD_AUDIO, OP_PLAY_AUDIO, OP_READ_CLIPBOARD, OP_WRITE_CLIPBOARD, OP_TAKE_MEDIA_BUTTONS, OP_TAKE_AUDIO_FOCUS, OP_AUDIO_MASTER_VOLUME, OP_AUDIO_VOICE_VOLUME, OP_AUDIO_RING_VOLUME, OP_AUDIO_MEDIA_VOLUME, OP_AUDIO_ALARM_VOLUME, OP_AUDIO_NOTIFICATION_VOLUME, OP_AUDIO_BLUETOOTH_VOLUME, OP_WAKE_LOCK, OP_COARSE_LOCATION, OP_COARSE_LOCATION, OP_GET_USAGE_STATS, OP_MUTE_MICROPHONE, OP_TOAST_WINDOW, OP_PROJECT_MEDIA, OP_ACTIVATE_VPN, OP_WRITE_WALLPAPER, OP_ASSIST_STRUCTURE, OP_ASSIST_SCREENSHOT, OP_READ_PHONE_STATE, OP_ADD_VOICEMAIL, OP_USE_SIP, OP_PROCESS_OUTGOING_CALLS, OP_USE_FINGERPRINT, OP_BODY_SENSORS, OP_READ_CELL_BROADCASTS, OP_MOCK_LOCATION, OP_READ_EXTERNAL_STORAGE, OP_WRITE_EXTERNAL_STORAGE, OP_TURN_SCREEN_ON, OP_GET_ACCOUNTS, OP_RUN_IN_BACKGROUND, }; /** * This maps each operation to the public string constant for it. * If it doesn't have a public string constant, it maps to null. */ private static String[] sOpToString = new String[] { OPSTR_COARSE_LOCATION, OPSTR_FINE_LOCATION, null, null, OPSTR_READ_CONTACTS, OPSTR_WRITE_CONTACTS, OPSTR_READ_CALL_LOG, OPSTR_WRITE_CALL_LOG, OPSTR_READ_CALENDAR, OPSTR_WRITE_CALENDAR, null, null, null, OPSTR_CALL_PHONE, OPSTR_READ_SMS, null, OPSTR_RECEIVE_SMS, null, OPSTR_RECEIVE_MMS, OPSTR_RECEIVE_WAP_PUSH, OPSTR_SEND_SMS, null, null, OPSTR_WRITE_SETTINGS, OPSTR_SYSTEM_ALERT_WINDOW, null, OPSTR_CAMERA, OPSTR_RECORD_AUDIO, null, null, null, null, null, null, null, null, null, null, null, null, null, OPSTR_MONITOR_LOCATION, OPSTR_MONITOR_HIGH_POWER_LOCATION, OPSTR_GET_USAGE_STATS, null, null, null, OPSTR_ACTIVATE_VPN, null, null, null, OPSTR_READ_PHONE_STATE, OPSTR_ADD_VOICEMAIL, OPSTR_USE_SIP, null, OPSTR_USE_FINGERPRINT, OPSTR_BODY_SENSORS, OPSTR_READ_CELL_BROADCASTS, OPSTR_MOCK_LOCATION, OPSTR_READ_EXTERNAL_STORAGE, OPSTR_WRITE_EXTERNAL_STORAGE, null, OPSTR_GET_ACCOUNTS, null, }; /** * This provides a simple name for each operation to be used * in debug output. */ private static String[] sOpNames = new String[] { "COARSE_LOCATION", "FINE_LOCATION", "GPS", "VIBRATE", "READ_CONTACTS", "WRITE_CONTACTS", "READ_CALL_LOG", "WRITE_CALL_LOG", "READ_CALENDAR", "WRITE_CALENDAR", "WIFI_SCAN", "POST_NOTIFICATION", "NEIGHBORING_CELLS", "CALL_PHONE", "READ_SMS", "WRITE_SMS", "RECEIVE_SMS", "RECEIVE_EMERGECY_SMS", "RECEIVE_MMS", "RECEIVE_WAP_PUSH", "SEND_SMS", "READ_ICC_SMS", "WRITE_ICC_SMS", "WRITE_SETTINGS", "SYSTEM_ALERT_WINDOW", "ACCESS_NOTIFICATIONS", "CAMERA", "RECORD_AUDIO", "PLAY_AUDIO", "READ_CLIPBOARD", "WRITE_CLIPBOARD", "TAKE_MEDIA_BUTTONS", "TAKE_AUDIO_FOCUS", "AUDIO_MASTER_VOLUME", "AUDIO_VOICE_VOLUME", "AUDIO_RING_VOLUME", "AUDIO_MEDIA_VOLUME", "AUDIO_ALARM_VOLUME", "AUDIO_NOTIFICATION_VOLUME", "AUDIO_BLUETOOTH_VOLUME", "WAKE_LOCK", "MONITOR_LOCATION", "MONITOR_HIGH_POWER_LOCATION", "GET_USAGE_STATS", "MUTE_MICROPHONE", "TOAST_WINDOW", "PROJECT_MEDIA", "ACTIVATE_VPN", "WRITE_WALLPAPER", "ASSIST_STRUCTURE", "ASSIST_SCREENSHOT", "OP_READ_PHONE_STATE", "ADD_VOICEMAIL", "USE_SIP", "PROCESS_OUTGOING_CALLS", "USE_FINGERPRINT", "BODY_SENSORS", "READ_CELL_BROADCASTS", "MOCK_LOCATION", "READ_EXTERNAL_STORAGE", "WRITE_EXTERNAL_STORAGE", "TURN_ON_SCREEN", "GET_ACCOUNTS", "RUN_IN_BACKGROUND", }; /** * This optionally maps a permission to an operation. If there * is no permission associated with an operation, it is null. */ private static String[] sOpPerms = new String[] { android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION, null, android.Manifest.permission.VIBRATE, android.Manifest.permission.READ_CONTACTS, android.Manifest.permission.WRITE_CONTACTS, android.Manifest.permission.READ_CALL_LOG, android.Manifest.permission.WRITE_CALL_LOG, android.Manifest.permission.READ_CALENDAR, android.Manifest.permission.WRITE_CALENDAR, android.Manifest.permission.ACCESS_WIFI_STATE, null, // no permission required for notifications null, // neighboring cells shares the coarse location perm android.Manifest.permission.CALL_PHONE, android.Manifest.permission.READ_SMS, null, // no permission required for writing sms android.Manifest.permission.RECEIVE_SMS, android.Manifest.permission.RECEIVE_EMERGENCY_BROADCAST, android.Manifest.permission.RECEIVE_MMS, android.Manifest.permission.RECEIVE_WAP_PUSH, android.Manifest.permission.SEND_SMS, android.Manifest.permission.READ_SMS, null, // no permission required for writing icc sms android.Manifest.permission.WRITE_SETTINGS, android.Manifest.permission.SYSTEM_ALERT_WINDOW, android.Manifest.permission.ACCESS_NOTIFICATIONS, android.Manifest.permission.CAMERA, android.Manifest.permission.RECORD_AUDIO, null, // no permission for playing audio null, // no permission for reading clipboard null, // no permission for writing clipboard null, // no permission for taking media buttons null, // no permission for taking audio focus null, // no permission for changing master volume null, // no permission for changing voice volume null, // no permission for changing ring volume null, // no permission for changing media volume null, // no permission for changing alarm volume null, // no permission for changing notification volume null, // no permission for changing bluetooth volume android.Manifest.permission.WAKE_LOCK, null, // no permission for generic location monitoring null, // no permission for high power location monitoring android.Manifest.permission.PACKAGE_USAGE_STATS, null, // no permission for muting/unmuting microphone null, // no permission for displaying toasts null, // no permission for projecting media null, // no permission for activating vpn null, // no permission for supporting wallpaper null, // no permission for receiving assist structure null, // no permission for receiving assist screenshot Manifest.permission.READ_PHONE_STATE, Manifest.permission.ADD_VOICEMAIL, Manifest.permission.USE_SIP, Manifest.permission.PROCESS_OUTGOING_CALLS, Manifest.permission.USE_FINGERPRINT, Manifest.permission.BODY_SENSORS, Manifest.permission.READ_CELL_BROADCASTS, null, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, null, // no permission for turning the screen on Manifest.permission.GET_ACCOUNTS, null, // no permission for running in background }; /** * Specifies whether an Op should be restricted by a user restriction. * Each Op should be filled with a restriction string from UserManager or * null to specify it is not affected by any user restriction. */ private static String[] sOpRestrictions = new String[] { UserManager.DISALLOW_SHARE_LOCATION, //COARSE_LOCATION UserManager.DISALLOW_SHARE_LOCATION, //FINE_LOCATION UserManager.DISALLOW_SHARE_LOCATION, //GPS null, //VIBRATE null, //READ_CONTACTS null, //WRITE_CONTACTS UserManager.DISALLOW_OUTGOING_CALLS, //READ_CALL_LOG UserManager.DISALLOW_OUTGOING_CALLS, //WRITE_CALL_LOG null, //READ_CALENDAR null, //WRITE_CALENDAR UserManager.DISALLOW_SHARE_LOCATION, //WIFI_SCAN null, //POST_NOTIFICATION null, //NEIGHBORING_CELLS null, //CALL_PHONE UserManager.DISALLOW_SMS, //READ_SMS UserManager.DISALLOW_SMS, //WRITE_SMS UserManager.DISALLOW_SMS, //RECEIVE_SMS null, //RECEIVE_EMERGENCY_SMS UserManager.DISALLOW_SMS, //RECEIVE_MMS null, //RECEIVE_WAP_PUSH UserManager.DISALLOW_SMS, //SEND_SMS UserManager.DISALLOW_SMS, //READ_ICC_SMS UserManager.DISALLOW_SMS, //WRITE_ICC_SMS null, //WRITE_SETTINGS UserManager.DISALLOW_CREATE_WINDOWS, //SYSTEM_ALERT_WINDOW null, //ACCESS_NOTIFICATIONS UserManager.DISALLOW_CAMERA, //CAMERA UserManager.DISALLOW_RECORD_AUDIO, //RECORD_AUDIO null, //PLAY_AUDIO null, //READ_CLIPBOARD null, //WRITE_CLIPBOARD null, //TAKE_MEDIA_BUTTONS null, //TAKE_AUDIO_FOCUS UserManager.DISALLOW_ADJUST_VOLUME, //AUDIO_MASTER_VOLUME UserManager.DISALLOW_ADJUST_VOLUME, //AUDIO_VOICE_VOLUME UserManager.DISALLOW_ADJUST_VOLUME, //AUDIO_RING_VOLUME UserManager.DISALLOW_ADJUST_VOLUME, //AUDIO_MEDIA_VOLUME UserManager.DISALLOW_ADJUST_VOLUME, //AUDIO_ALARM_VOLUME UserManager.DISALLOW_ADJUST_VOLUME, //AUDIO_NOTIFICATION_VOLUME UserManager.DISALLOW_ADJUST_VOLUME, //AUDIO_BLUETOOTH_VOLUME null, //WAKE_LOCK UserManager.DISALLOW_SHARE_LOCATION, //MONITOR_LOCATION UserManager.DISALLOW_SHARE_LOCATION, //MONITOR_HIGH_POWER_LOCATION null, //GET_USAGE_STATS UserManager.DISALLOW_UNMUTE_MICROPHONE, // MUTE_MICROPHONE UserManager.DISALLOW_CREATE_WINDOWS, // TOAST_WINDOW null, //PROJECT_MEDIA null, // ACTIVATE_VPN UserManager.DISALLOW_WALLPAPER, // WRITE_WALLPAPER null, // ASSIST_STRUCTURE null, // ASSIST_SCREENSHOT null, // READ_PHONE_STATE null, // ADD_VOICEMAIL null, // USE_SIP null, // PROCESS_OUTGOING_CALLS null, // USE_FINGERPRINT null, // BODY_SENSORS null, // READ_CELL_BROADCASTS null, // MOCK_LOCATION null, // READ_EXTERNAL_STORAGE null, // WRITE_EXTERNAL_STORAGE null, // TURN_ON_SCREEN null, // GET_ACCOUNTS null, // RUN_IN_BACKGROUND }; /** * This specifies whether each option should allow the system * (and system ui) to bypass the user restriction when active. */ private static boolean[] sOpAllowSystemRestrictionBypass = new boolean[] { true, //COARSE_LOCATION true, //FINE_LOCATION false, //GPS false, //VIBRATE false, //READ_CONTACTS false, //WRITE_CONTACTS false, //READ_CALL_LOG false, //WRITE_CALL_LOG false, //READ_CALENDAR false, //WRITE_CALENDAR true, //WIFI_SCAN false, //POST_NOTIFICATION false, //NEIGHBORING_CELLS false, //CALL_PHONE false, //READ_SMS false, //WRITE_SMS false, //RECEIVE_SMS false, //RECEIVE_EMERGECY_SMS false, //RECEIVE_MMS false, //RECEIVE_WAP_PUSH false, //SEND_SMS false, //READ_ICC_SMS false, //WRITE_ICC_SMS false, //WRITE_SETTINGS true, //SYSTEM_ALERT_WINDOW false, //ACCESS_NOTIFICATIONS false, //CAMERA false, //RECORD_AUDIO false, //PLAY_AUDIO false, //READ_CLIPBOARD false, //WRITE_CLIPBOARD false, //TAKE_MEDIA_BUTTONS false, //TAKE_AUDIO_FOCUS false, //AUDIO_MASTER_VOLUME false, //AUDIO_VOICE_VOLUME false, //AUDIO_RING_VOLUME false, //AUDIO_MEDIA_VOLUME false, //AUDIO_ALARM_VOLUME false, //AUDIO_NOTIFICATION_VOLUME false, //AUDIO_BLUETOOTH_VOLUME false, //WAKE_LOCK false, //MONITOR_LOCATION false, //MONITOR_HIGH_POWER_LOCATION false, //GET_USAGE_STATS false, //MUTE_MICROPHONE true, //TOAST_WINDOW false, //PROJECT_MEDIA false, //ACTIVATE_VPN false, //WALLPAPER false, //ASSIST_STRUCTURE false, //ASSIST_SCREENSHOT false, //READ_PHONE_STATE false, //ADD_VOICEMAIL false, // USE_SIP false, // PROCESS_OUTGOING_CALLS false, // USE_FINGERPRINT false, // BODY_SENSORS false, // READ_CELL_BROADCASTS false, // MOCK_LOCATION false, // READ_EXTERNAL_STORAGE false, // WRITE_EXTERNAL_STORAGE false, // TURN_ON_SCREEN false, // GET_ACCOUNTS false, // RUN_IN_BACKGROUND }; /** * This specifies the default mode for each operation. */ private static int[] sOpDefaultMode = new int[] { AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_IGNORED, // OP_WRITE_SMS AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_DEFAULT, // OP_WRITE_SETTINGS AppOpsManager.MODE_DEFAULT, // OP_SYSTEM_ALERT_WINDOW AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_DEFAULT, // OP_GET_USAGE_STATS AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_IGNORED, // OP_PROJECT_MEDIA AppOpsManager.MODE_IGNORED, // OP_ACTIVATE_VPN AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ERRORED, // OP_MOCK_LOCATION AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, // OP_TURN_ON_SCREEN AppOpsManager.MODE_ALLOWED, AppOpsManager.MODE_ALLOWED, // OP_RUN_IN_BACKGROUND }; /** * This specifies whether each option is allowed to be reset * when resetting all app preferences. Disable reset for * app ops that are under strong control of some part of the * system (such as OP_WRITE_SMS, which should be allowed only * for whichever app is selected as the current SMS app). */ private static boolean[] sOpDisableReset = new boolean[] { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, // OP_WRITE_SMS false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, }; /** * Mapping from an app op name to the app op code. */ private static HashMap<String, Integer> sOpStrToOp = new HashMap<>(); /** * Mapping from a permission to the corresponding app op. */ private static HashMap<String, Integer> sRuntimePermToOp = new HashMap<>(); static { if (sOpToSwitch.length != _NUM_OP) { throw new IllegalStateException("sOpToSwitch length " + sOpToSwitch.length + " should be " + _NUM_OP); } if (sOpToString.length != _NUM_OP) { throw new IllegalStateException("sOpToString length " + sOpToString.length + " should be " + _NUM_OP); } if (sOpNames.length != _NUM_OP) { throw new IllegalStateException("sOpNames length " + sOpNames.length + " should be " + _NUM_OP); } if (sOpPerms.length != _NUM_OP) { throw new IllegalStateException("sOpPerms length " + sOpPerms.length + " should be " + _NUM_OP); } if (sOpDefaultMode.length != _NUM_OP) { throw new IllegalStateException("sOpDefaultMode length " + sOpDefaultMode.length + " should be " + _NUM_OP); } if (sOpDisableReset.length != _NUM_OP) { throw new IllegalStateException("sOpDisableReset length " + sOpDisableReset.length + " should be " + _NUM_OP); } if (sOpRestrictions.length != _NUM_OP) { throw new IllegalStateException("sOpRestrictions length " + sOpRestrictions.length + " should be " + _NUM_OP); } if (sOpAllowSystemRestrictionBypass.length != _NUM_OP) { throw new IllegalStateException("sOpAllowSYstemRestrictionsBypass length " + sOpRestrictions.length + " should be " + _NUM_OP); } for (int i=0; i<_NUM_OP; i++) { if (sOpToString[i] != null) { sOpStrToOp.put(sOpToString[i], i); } } for (int op : RUNTIME_PERMISSIONS_OPS) { if (sOpPerms[op] != null) { sRuntimePermToOp.put(sOpPerms[op], op); } } } /** * Retrieve the op switch that controls the given operation. * @hide */ public static int opToSwitch(int op) { return sOpToSwitch[op]; } /** * Retrieve a non-localized name for the operation, for debugging output. * @hide */ public static String opToName(int op) { if (op == OP_NONE) return "NONE"; return op < sOpNames.length ? sOpNames[op] : ("Unknown(" + op + ")"); } /** * @hide */ public static int strDebugOpToOp(String op) { for (int i=0; i<sOpNames.length; i++) { if (sOpNames[i].equals(op)) { return i; } } throw new IllegalArgumentException("Unknown operation string: " + op); } /** * Retrieve the permission associated with an operation, or null if there is not one. * @hide */ public static String opToPermission(int op) { return sOpPerms[op]; } /** * Retrieve the user restriction associated with an operation, or null if there is not one. * @hide */ public static String opToRestriction(int op) { return sOpRestrictions[op]; } /** * Retrieve the app op code for a permission, or null if there is not one. * This API is intended to be used for mapping runtime permissions to the * corresponding app op. * @hide */ public static int permissionToOpCode(String permission) { Integer boxedOpCode = sRuntimePermToOp.get(permission); return boxedOpCode != null ? boxedOpCode : OP_NONE; } /** * Retrieve whether the op allows the system (and system ui) to * bypass the user restriction. * @hide */ public static boolean opAllowSystemBypassRestriction(int op) { return sOpAllowSystemRestrictionBypass[op]; } /** * Retrieve the default mode for the operation. * @hide */ public static int opToDefaultMode(int op) { return sOpDefaultMode[op]; } /** * Retrieve whether the op allows itself to be reset. * @hide */ public static boolean opAllowsReset(int op) { return !sOpDisableReset[op]; } /** * Class holding all of the operation information associated with an app. * @hide */ public static class PackageOps implements Parcelable { private final String mPackageName; private final int mUid; private final List<OpEntry> mEntries; public PackageOps(String packageName, int uid, List<OpEntry> entries) { mPackageName = packageName; mUid = uid; mEntries = entries; } public String getPackageName() { return mPackageName; } public int getUid() { return mUid; } public List<OpEntry> getOps() { return mEntries; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(mPackageName); dest.writeInt(mUid); dest.writeInt(mEntries.size()); for (int i=0; i<mEntries.size(); i++) { mEntries.get(i).writeToParcel(dest, flags); } } PackageOps(Parcel source) { mPackageName = source.readString(); mUid = source.readInt(); mEntries = new ArrayList<OpEntry>(); final int N = source.readInt(); for (int i=0; i<N; i++) { mEntries.add(OpEntry.CREATOR.createFromParcel(source)); } } public static final Creator<PackageOps> CREATOR = new Creator<PackageOps>() { @Override public PackageOps createFromParcel(Parcel source) { return new PackageOps(source); } @Override public PackageOps[] newArray(int size) { return new PackageOps[size]; } }; } /** * Class holding the information about one unique operation of an application. * @hide */ public static class OpEntry implements Parcelable { private final int mOp; private final int mMode; private final long mTime; private final long mRejectTime; private final int mDuration; private final int mProxyUid; private final String mProxyPackageName; public OpEntry(int op, int mode, long time, long rejectTime, int duration, int proxyUid, String proxyPackage) { mOp = op; mMode = mode; mTime = time; mRejectTime = rejectTime; mDuration = duration; mProxyUid = proxyUid; mProxyPackageName = proxyPackage; } public int getOp() { return mOp; } public int getMode() { return mMode; } public long getTime() { return mTime; } public long getRejectTime() { return mRejectTime; } public boolean isRunning() { return mDuration == -1; } public int getDuration() { return mDuration == -1 ? (int)(System.currentTimeMillis()-mTime) : mDuration; } public int getProxyUid() { return mProxyUid; } public String getProxyPackageName() { return mProxyPackageName; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(mOp); dest.writeInt(mMode); dest.writeLong(mTime); dest.writeLong(mRejectTime); dest.writeInt(mDuration); dest.writeInt(mProxyUid); dest.writeString(mProxyPackageName); } OpEntry(Parcel source) { mOp = source.readInt(); mMode = source.readInt(); mTime = source.readLong(); mRejectTime = source.readLong(); mDuration = source.readInt(); mProxyUid = source.readInt(); mProxyPackageName = source.readString(); } public static final Creator<OpEntry> CREATOR = new Creator<OpEntry>() { @Override public OpEntry createFromParcel(Parcel source) { return new OpEntry(source); } @Override public OpEntry[] newArray(int size) { return new OpEntry[size]; } }; } /** * Callback for notification of changes to operation state. */ public interface OnOpChangedListener { public void onOpChanged(String op, String packageName); } /** * Callback for notification of changes to operation state. * This allows you to see the raw op codes instead of strings. * @hide */ public static class OnOpChangedInternalListener implements OnOpChangedListener { public void onOpChanged(String op, String packageName) { } public void onOpChanged(int op, String packageName) { } } AppOpsManager(Context context, IAppOpsService service) { mContext = context; mService = service; } /** * Retrieve current operation state for all applications. * * @param ops The set of operations you are interested in, or null if you want all of them. * @hide */ public List<AppOpsManager.PackageOps> getPackagesForOps(int[] ops) { try { return mService.getPackagesForOps(ops); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } } /** * Retrieve current operation state for one application. * * @param uid The uid of the application of interest. * @param packageName The name of the application of interest. * @param ops The set of operations you are interested in, or null if you want all of them. * @hide */ public List<AppOpsManager.PackageOps> getOpsForPackage(int uid, String packageName, int[] ops) { try { return mService.getOpsForPackage(uid, packageName, ops); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } } /** * Sets given app op in the specified mode for app ops in the UID. * This applies to all apps currently in the UID or installed in * this UID in the future. * * @param code The app op. * @param uid The UID for which to set the app. * @param mode The app op mode to set. * @hide */ public void setUidMode(int code, int uid, int mode) { try { mService.setUidMode(code, uid, mode); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } } /** * Sets given app op in the specified mode for app ops in the UID. * This applies to all apps currently in the UID or installed in * this UID in the future. * * @param appOp The app op. * @param uid The UID for which to set the app. * @param mode The app op mode to set. * @hide */ @SystemApi public void setUidMode(String appOp, int uid, int mode) { try { mService.setUidMode(AppOpsManager.strOpToOp(appOp), uid, mode); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } } /** @hide */ public void setUserRestriction(int code, boolean restricted, IBinder token) { setUserRestriction(code, restricted, token, /*exceptionPackages*/null); } /** @hide */ public void setUserRestriction(int code, boolean restricted, IBinder token, String[] exceptionPackages) { setUserRestrictionForUser(code, restricted, token, exceptionPackages, mContext.getUserId()); } /** @hide */ public void setUserRestrictionForUser(int code, boolean restricted, IBinder token, String[] exceptionPackages, int userId) { try { mService.setUserRestriction(code, restricted, token, userId, exceptionPackages); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } } /** @hide */ public void setMode(int code, int uid, String packageName, int mode) { try { mService.setMode(code, uid, packageName, mode); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } } /** * Set a non-persisted restriction on an audio operation at a stream-level. * Restrictions are temporary additional constraints imposed on top of the persisted rules * defined by {@link #setMode}. * * @param code The operation to restrict. * @param usage The {@link android.media.AudioAttributes} usage value. * @param mode The restriction mode (MODE_IGNORED,MODE_ERRORED) or MODE_ALLOWED to unrestrict. * @param exceptionPackages Optional list of packages to exclude from the restriction. * @hide */ public void setRestriction(int code, @AttributeUsage int usage, int mode, String[] exceptionPackages) { try { final int uid = Binder.getCallingUid(); mService.setAudioRestriction(code, usage, uid, mode, exceptionPackages); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } } /** @hide */ public void resetAllModes() { try { mService.resetAllModes(UserHandle.myUserId(), null); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } } /** * Gets the app op name associated with a given permission. * The app op name is one of the public constants defined * in this class such as {@link #OPSTR_COARSE_LOCATION}. * This API is intended to be used for mapping runtime * permissions to the corresponding app op. * * @param permission The permission. * @return The app op associated with the permission or null. */ public static String permissionToOp(String permission) { final Integer opCode = sRuntimePermToOp.get(permission); if (opCode == null) { return null; } return sOpToString[opCode]; } /** * Monitor for changes to the operating mode for the given op in the given app package. * @param op The operation to monitor, one of OPSTR_*. * @param packageName The name of the application to monitor. * @param callback Where to report changes. */ public void startWatchingMode(String op, String packageName, final OnOpChangedListener callback) { startWatchingMode(strOpToOp(op), packageName, callback); } /** * Monitor for changes to the operating mode for the given op in the given app package. * @param op The operation to monitor, one of OP_*. * @param packageName The name of the application to monitor. * @param callback Where to report changes. * @hide */ public void startWatchingMode(int op, String packageName, final OnOpChangedListener callback) { synchronized (mModeWatchers) { IAppOpsCallback cb = mModeWatchers.get(callback); if (cb == null) { cb = new IAppOpsCallback.Stub() { public void opChanged(int op, int uid, String packageName) { if (callback instanceof OnOpChangedInternalListener) { ((OnOpChangedInternalListener)callback).onOpChanged(op, packageName); } if (sOpToString[op] != null) { callback.onOpChanged(sOpToString[op], packageName); } } }; mModeWatchers.put(callback, cb); } try { mService.startWatchingMode(op, packageName, cb); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } } } /** * Stop monitoring that was previously started with {@link #startWatchingMode}. All * monitoring associated with this callback will be removed. */ public void stopWatchingMode(OnOpChangedListener callback) { synchronized (mModeWatchers) { IAppOpsCallback cb = mModeWatchers.get(callback); if (cb != null) { try { mService.stopWatchingMode(cb); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } } } } private String buildSecurityExceptionMsg(int op, int uid, String packageName) { return packageName + " from uid " + uid + " not allowed to perform " + sOpNames[op]; } /** * {@hide} */ public static int strOpToOp(String op) { Integer val = sOpStrToOp.get(op); if (val == null) { throw new IllegalArgumentException("Unknown operation string: " + op); } return val; } /** * Do a quick check for whether an application might be able to perform an operation. * This is <em>not</em> a security check; you must use {@link #noteOp(String, int, String)} * or {@link #startOp(String, int, String)} for your actual security checks, which also * ensure that the given uid and package name are consistent. This function can just be * used for a quick check to see if an operation has been disabled for the application, * as an early reject of some work. This does not modify the time stamp or other data * about the operation. * @param op The operation to check. One of the OPSTR_* constants. * @param uid The user id of the application attempting to perform the operation. * @param packageName The name of the application attempting to perform the operation. * @return Returns {@link #MODE_ALLOWED} if the operation is allowed, or * {@link #MODE_IGNORED} if it is not allowed and should be silently ignored (without * causing the app to crash). * @throws SecurityException If the app has been configured to crash on this op. */ public int checkOp(String op, int uid, String packageName) { return checkOp(strOpToOp(op), uid, packageName); } /** * Like {@link #checkOp} but instead of throwing a {@link SecurityException} it * returns {@link #MODE_ERRORED}. */ public int checkOpNoThrow(String op, int uid, String packageName) { return checkOpNoThrow(strOpToOp(op), uid, packageName); } /** * Make note of an application performing an operation. Note that you must pass * in both the uid and name of the application to be checked; this function will verify * that these two match, and if not, return {@link #MODE_IGNORED}. If this call * succeeds, the last execution time of the operation for this app will be updated to * the current time. * @param op The operation to note. One of the OPSTR_* constants. * @param uid The user id of the application attempting to perform the operation. * @param packageName The name of the application attempting to perform the operation. * @return Returns {@link #MODE_ALLOWED} if the operation is allowed, or * {@link #MODE_IGNORED} if it is not allowed and should be silently ignored (without * causing the app to crash). * @throws SecurityException If the app has been configured to crash on this op. */ public int noteOp(String op, int uid, String packageName) { return noteOp(strOpToOp(op), uid, packageName); } /** * Like {@link #noteOp} but instead of throwing a {@link SecurityException} it * returns {@link #MODE_ERRORED}. */ public int noteOpNoThrow(String op, int uid, String packageName) { return noteOpNoThrow(strOpToOp(op), uid, packageName); } /** * Make note of an application performing an operation on behalf of another * application when handling an IPC. Note that you must pass the package name * of the application that is being proxied while its UID will be inferred from * the IPC state; this function will verify that the calling uid and proxied * package name match, and if not, return {@link #MODE_IGNORED}. If this call * succeeds, the last execution time of the operation for the proxied app and * your app will be updated to the current time. * @param op The operation to note. One of the OPSTR_* constants. * @param proxiedPackageName The name of the application calling into the proxy application. * @return Returns {@link #MODE_ALLOWED} if the operation is allowed, or * {@link #MODE_IGNORED} if it is not allowed and should be silently ignored (without * causing the app to crash). * @throws SecurityException If the app has been configured to crash on this op. */ public int noteProxyOp(String op, String proxiedPackageName) { return noteProxyOp(strOpToOp(op), proxiedPackageName); } /** * Like {@link #noteProxyOp(String, String)} but instead * of throwing a {@link SecurityException} it returns {@link #MODE_ERRORED}. */ public int noteProxyOpNoThrow(String op, String proxiedPackageName) { return noteProxyOpNoThrow(strOpToOp(op), proxiedPackageName); } /** * Report that an application has started executing a long-running operation. Note that you * must pass in both the uid and name of the application to be checked; this function will * verify that these two match, and if not, return {@link #MODE_IGNORED}. If this call * succeeds, the last execution time of the operation for this app will be updated to * the current time and the operation will be marked as "running". In this case you must * later call {@link #finishOp(String, int, String)} to report when the application is no * longer performing the operation. * @param op The operation to start. One of the OPSTR_* constants. * @param uid The user id of the application attempting to perform the operation. * @param packageName The name of the application attempting to perform the operation. * @return Returns {@link #MODE_ALLOWED} if the operation is allowed, or * {@link #MODE_IGNORED} if it is not allowed and should be silently ignored (without * causing the app to crash). * @throws SecurityException If the app has been configured to crash on this op. */ public int startOp(String op, int uid, String packageName) { return startOp(strOpToOp(op), uid, packageName); } /** * Like {@link #startOp} but instead of throwing a {@link SecurityException} it * returns {@link #MODE_ERRORED}. */ public int startOpNoThrow(String op, int uid, String packageName) { return startOpNoThrow(strOpToOp(op), uid, packageName); } /** * Report that an application is no longer performing an operation that had previously * been started with {@link #startOp(String, int, String)}. There is no validation of input * or result; the parameters supplied here must be the exact same ones previously passed * in when starting the operation. */ public void finishOp(String op, int uid, String packageName) { finishOp(strOpToOp(op), uid, packageName); } /** * Do a quick check for whether an application might be able to perform an operation. * This is <em>not</em> a security check; you must use {@link #noteOp(int, int, String)} * or {@link #startOp(int, int, String)} for your actual security checks, which also * ensure that the given uid and package name are consistent. This function can just be * used for a quick check to see if an operation has been disabled for the application, * as an early reject of some work. This does not modify the time stamp or other data * about the operation. * @param op The operation to check. One of the OP_* constants. * @param uid The user id of the application attempting to perform the operation. * @param packageName The name of the application attempting to perform the operation. * @return Returns {@link #MODE_ALLOWED} if the operation is allowed, or * {@link #MODE_IGNORED} if it is not allowed and should be silently ignored (without * causing the app to crash). * @throws SecurityException If the app has been configured to crash on this op. * @hide */ public int checkOp(int op, int uid, String packageName) { try { int mode = mService.checkOperation(op, uid, packageName); if (mode == MODE_ERRORED) { throw new SecurityException(buildSecurityExceptionMsg(op, uid, packageName)); } return mode; } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } } /** * Like {@link #checkOp} but instead of throwing a {@link SecurityException} it * returns {@link #MODE_ERRORED}. * @hide */ public int checkOpNoThrow(int op, int uid, String packageName) { try { return mService.checkOperation(op, uid, packageName); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } } /** * Do a quick check to validate if a package name belongs to a UID. * * @throws SecurityException if the package name doesn't belong to the given * UID, or if ownership cannot be verified. */ public void checkPackage(int uid, String packageName) { try { if (mService.checkPackage(uid, packageName) != MODE_ALLOWED) { throw new SecurityException( "Package " + packageName + " does not belong to " + uid); } } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } } /** * Like {@link #checkOp} but at a stream-level for audio operations. * @hide */ public int checkAudioOp(int op, int stream, int uid, String packageName) { try { final int mode = mService.checkAudioOperation(op, stream, uid, packageName); if (mode == MODE_ERRORED) { throw new SecurityException(buildSecurityExceptionMsg(op, uid, packageName)); } return mode; } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } } /** * Like {@link #checkAudioOp} but instead of throwing a {@link SecurityException} it * returns {@link #MODE_ERRORED}. * @hide */ public int checkAudioOpNoThrow(int op, int stream, int uid, String packageName) { try { return mService.checkAudioOperation(op, stream, uid, packageName); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } } /** * Make note of an application performing an operation. Note that you must pass * in both the uid and name of the application to be checked; this function will verify * that these two match, and if not, return {@link #MODE_IGNORED}. If this call * succeeds, the last execution time of the operation for this app will be updated to * the current time. * @param op The operation to note. One of the OP_* constants. * @param uid The user id of the application attempting to perform the operation. * @param packageName The name of the application attempting to perform the operation. * @return Returns {@link #MODE_ALLOWED} if the operation is allowed, or * {@link #MODE_IGNORED} if it is not allowed and should be silently ignored (without * causing the app to crash). * @throws SecurityException If the app has been configured to crash on this op. * @hide */ public int noteOp(int op, int uid, String packageName) { try { int mode = mService.noteOperation(op, uid, packageName); if (mode == MODE_ERRORED) { throw new SecurityException(buildSecurityExceptionMsg(op, uid, packageName)); } return mode; } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } } /** * Make note of an application performing an operation on behalf of another * application when handling an IPC. Note that you must pass the package name * of the application that is being proxied while its UID will be inferred from * the IPC state; this function will verify that the calling uid and proxied * package name match, and if not, return {@link #MODE_IGNORED}. If this call * succeeds, the last execution time of the operation for the proxied app and * your app will be updated to the current time. * @param op The operation to note. One of the OPSTR_* constants. * @param proxiedPackageName The name of the application calling into the proxy application. * @return Returns {@link #MODE_ALLOWED} if the operation is allowed, or * {@link #MODE_IGNORED} if it is not allowed and should be silently ignored (without * causing the app to crash). * @throws SecurityException If the proxy or proxied app has been configured to * crash on this op. * * @hide */ public int noteProxyOp(int op, String proxiedPackageName) { int mode = noteProxyOpNoThrow(op, proxiedPackageName); if (mode == MODE_ERRORED) { throw new SecurityException("Proxy package " + mContext.getOpPackageName() + " from uid " + Process.myUid() + " or calling package " + proxiedPackageName + " from uid " + Binder.getCallingUid() + " not allowed to perform " + sOpNames[op]); } return mode; } /** * Like {@link #noteProxyOp(int, String)} but instead * of throwing a {@link SecurityException} it returns {@link #MODE_ERRORED}. * @hide */ public int noteProxyOpNoThrow(int op, String proxiedPackageName) { try { return mService.noteProxyOperation(op, mContext.getOpPackageName(), Binder.getCallingUid(), proxiedPackageName); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } } /** * Like {@link #noteOp} but instead of throwing a {@link SecurityException} it * returns {@link #MODE_ERRORED}. * @hide */ public int noteOpNoThrow(int op, int uid, String packageName) { try { return mService.noteOperation(op, uid, packageName); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } } /** @hide */ public int noteOp(int op) { return noteOp(op, Process.myUid(), mContext.getOpPackageName()); } /** @hide */ public static IBinder getToken(IAppOpsService service) { synchronized (AppOpsManager.class) { if (sToken != null) { return sToken; } try { sToken = service.getToken(new Binder()); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } return sToken; } } /** * Report that an application has started executing a long-running operation. Note that you * must pass in both the uid and name of the application to be checked; this function will * verify that these two match, and if not, return {@link #MODE_IGNORED}. If this call * succeeds, the last execution time of the operation for this app will be updated to * the current time and the operation will be marked as "running". In this case you must * later call {@link #finishOp(int, int, String)} to report when the application is no * longer performing the operation. * @param op The operation to start. One of the OP_* constants. * @param uid The user id of the application attempting to perform the operation. * @param packageName The name of the application attempting to perform the operation. * @return Returns {@link #MODE_ALLOWED} if the operation is allowed, or * {@link #MODE_IGNORED} if it is not allowed and should be silently ignored (without * causing the app to crash). * @throws SecurityException If the app has been configured to crash on this op. * @hide */ public int startOp(int op, int uid, String packageName) { try { int mode = mService.startOperation(getToken(mService), op, uid, packageName); if (mode == MODE_ERRORED) { throw new SecurityException(buildSecurityExceptionMsg(op, uid, packageName)); } return mode; } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } } /** * Like {@link #startOp} but instead of throwing a {@link SecurityException} it * returns {@link #MODE_ERRORED}. * @hide */ public int startOpNoThrow(int op, int uid, String packageName) { try { return mService.startOperation(getToken(mService), op, uid, packageName); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } } /** @hide */ public int startOp(int op) { return startOp(op, Process.myUid(), mContext.getOpPackageName()); } /** * Report that an application is no longer performing an operation that had previously * been started with {@link #startOp(int, int, String)}. There is no validation of input * or result; the parameters supplied here must be the exact same ones previously passed * in when starting the operation. * @hide */ public void finishOp(int op, int uid, String packageName) { try { mService.finishOperation(getToken(mService), op, uid, packageName); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } } /** @hide */ public void finishOp(int op) { finishOp(op, Process.myUid(), mContext.getOpPackageName()); } }
31,105
5,169
<gh_stars>1000+ { "name": "OptionButton", "version": "0.0.1", "summary": "IBDesignable option button that have vertical stacked title and option labels for iOS and tvOS.", "description": "OptionButton\n===\n\nIBDesignable option button that have vertical stacked title and option labels for iOS and tvOS.\n\nDemo\n----\n\n![alt tag](https://github.com/cemolcay/OptionButton/blob/master/ios.png?raw=true)\n![alt tag](https://github.com/cemolcay/OptionButton/blob/master/ib.png?raw=true)\n\nRequirements\n----\n\n* Swift 3.0+\n* iOS 9.0+\n* tvOS 9.0+\n\nInstall\n----\n\n```\nuse_frameworks!\npod 'OptionButton'\n```\n\nUsage\n----\n\n* Create an instance of `OptionButton` from code, or drag and drop a `UIButton` to storyboard and change its class to `OptionButton`.\n* It is a regular UIButton subclass with a stack view that have `nameLabel` and `optionLabel`.\n* You could change the labels text, font and textColor from storyboard.\n* Also you could set other properties from code.\n* You could set the content insets from either storyboard or code by `leftInset`, `rightInset`, `topInset` and `bottomInset` properties.", "homepage": "https://github.com/cemolcay/OptionButton", "license": "MIT", "authors": { "cemolcay": "<EMAIL>" }, "social_media_url": "http://twitter.com/cemolcay", "platforms": { "ios": "9.0", "tvos": "9.0" }, "source": { "git": "https://github.com/cemolcay/OptionButton.git", "tag": "0.0.1" }, "source_files": "OptionButton/OptionButton.swift", "requires_arc": true, "pushed_with_swift_version": "3.0" }
575
433
<filename>src/main/java/org/redkale/net/client/ClientFuture.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.redkale.net.client; import java.util.Queue; import java.util.concurrent.*; import org.redkale.net.WorkThread; /** * * @author zhangjx * @param <T> 泛型 */ public class ClientFuture<T> extends CompletableFuture<T> implements Runnable { public static final ClientFuture EMPTY = new ClientFuture() { @Override public boolean complete(Object value) { return true; } @Override public boolean completeExceptionally(Throwable ex) { return true; } }; protected ClientRequest request; ScheduledFuture timeout; Queue<ClientFuture> responseQueue; public ClientFuture() { super(); } public ClientFuture(ClientRequest request) { super(); this.request = request; } @Override //JDK9+ public <U> ClientFuture<U> newIncompleteFuture() { return new ClientFuture<>(); } public <R extends ClientRequest> R getRequest() { return (R) request; } @Override public void run() { if (responseQueue != null) responseQueue.remove(this); TimeoutException ex = new TimeoutException(); WorkThread workThread = null; if (request != null) { workThread = request.workThread; request.workThread = null; } if (workThread == null || workThread == Thread.currentThread() || workThread.getState() == Thread.State.BLOCKED || workThread.getState() == Thread.State.WAITING) { this.completeExceptionally(ex); } else { workThread.execute(() -> completeExceptionally(ex)); } } }
833
422
<reponame>yangjourney/sosotest<filename>AutotestFramework/allmodels/DubboInterface.py from core.model.DubboBase import DubboBase from core.decorator.normal_functions import * from core.tools.DBTool import DBTool from core.tools.CommonFunc import * from core.const.GlobalConst import CaseLevel from core.const.GlobalConst import CaseStatus from core.const.GlobalConst import ObjTypeConst from runfunc.initial import * class DubboInterface(DubboBase): """ Http接口类,继承HttpBase,并添加接口特殊属性。 """ def __init__(self,id = 0, interfaceId = "", interfaceDebugId = ""): super(DubboInterface, self).__init__() self.objType = ObjTypeConst.INTERFACE self.id = id self.interfaceId = interfaceId self.interfaceDebugId = interfaceDebugId #基本信息 self.title = "" self.desc = "" self.businessLine = "" #ywx self.modules = "" #mk self.level = CaseLevel.MIDIUM #优先级 self.status = CaseStatus.UN_AUDIT #用例状态 未审核 审核通过 审核未通过 任务添加只能添加审核通过的用例 @take_time @catch_exception def generateByInterfaceDebugId(self): """ 根据interfaceDebugId从tb_http_interface_debug获取调试数据。 Returns: 执行结果 """ # colstr = "id, httpConfKey, serviceConfKey, alias, httpConfDesc, httpConf, state, addBy, modBy, addTime, modTime" sql = """ SELECT * FROM tb2_dubbo_interface_debug where id = %d """ % (self.interfaceDebugId) self.globalDB.initGlobalDBConf() res = self.globalDB.execute_sql(sql) self.globalDB.release() if res: tmpInterface = res[0] self.id = tmpInterface['id'] if "interfaceId" in tmpInterface.keys(): self.interfaceId = tmpInterface['interfaceId'] else: self.interfaceId = "" self.traceId = md5("%s-%s" % (self.interfaceId, get_current_time())) self.execStatus = tmpInterface['execStatus'] self.title = tmpInterface['title'] self.desc = tmpInterface['casedesc'] self.state = tmpInterface['state'] self.addBy = tmpInterface['addBy'] self.modBy = tmpInterface['modBy'] self.addTime = tmpInterface['addTime'] self.modTime = tmpInterface['modTime'] self.businessLineId = tmpInterface['businessLineId'] self.modules = tmpInterface['moduleId'] self.level = tmpInterface['caselevel'] # 优先级 self.status = tmpInterface['status'] # 用例状态 未审核 审核通过 审核未通过 任务添加只能添加审核通过的用例 self.varsPre = tmpInterface['varsPre'] # 前置变量 self.useCustomUri = tmpInterface['useCustomUri'] self.customUri = tmpInterface['customUri'] self.dubboSystem = tmpInterface['dubboSystem'] self.dubboService = tmpInterface['dubboService'] # 接口 interface self.dubboMethod = tmpInterface['dubboMethod'] self.dubboParam = tmpInterface['dubboParams'] # key1=value1&key2=value2 self.encoding = tmpInterface['encoding'] # key1=value1&key2=value2 self.version = tmpInterface['version'].strip() self.varsPost = tmpInterface['varsPost'] # 后置变量 self.httprequestTimeout = tmpInterface['timeout'] self.actualResult = tmpInterface['actualResult'] # 实际结果 self.assertResult = tmpInterface['assertResult'] # 断言结果 self.testResult = tmpInterface['testResult'] # 测试结果 self.beforeExecuteTakeTime = tmpInterface['beforeExecuteTakeTime'] self.afterExecuteTakeTime = tmpInterface['afterExecuteTakeTime'] self.executeTakeTime = tmpInterface['executeTakeTime'] self.totalTakeTime = tmpInterface['totalTakeTime'] self.httpConfKey = tmpInterface['httpConfKey'] self.confHttpLayer.key = self.httpConfKey self.confHttpLayer.generate_http_conf_by_key() self.varsStr = "" # 变量string self.varsPool = {} # 变量dict 变量池,包括varsPre的和varsPost的 self.headerDict = {} #header json字符串转换成的dict return True else: return False @take_time @catch_exception def generateByInterfaceDebugIdForRedis(self): """ 根据interfaceDebugId从tb_http_interface_debug获取调试数据。 Returns: 执行结果 """ self.serviceRedis.initRedisConf() try: tmpInterface = json.loads(self.serviceRedis.get_data(self.interfaceDebugId)) except Exception as e: return False if tmpInterface: if "interfaceId" in tmpInterface.keys(): self.interfaceId = tmpInterface['interfaceId'] else: self.interfaceId = "" self.traceId = md5("%s-%s" % (self.interfaceId, get_current_time())) self.execStatus = tmpInterface['execStatus'] self.title = tmpInterface['title'] self.desc = tmpInterface['casedesc'] self.businessLineId = tmpInterface['businessLineId'] self.modules = tmpInterface['moduleId'] self.level = tmpInterface['caselevel'] # 优先级 # self.status = tmpInterface['status'] # 用例状态 未审核 审核通过 审核未通过 任务添加只能添加审核通过的用例 self.varsPre = tmpInterface['varsPre'] # 前置变量 self.useCustomUri = tmpInterface['useCustomUri'] self.customUri = tmpInterface['customUri'] self.dubboSystem = tmpInterface['dubboSystem'] self.dubboService = tmpInterface['dubboService'] # 接口 interface self.dubboMethod = tmpInterface['dubboMethod'] self.dubboParam = tmpInterface['dubboParams'] # key1=value1&key2=value2 self.encoding = tmpInterface['encoding'] # key1=value1&key2=value2 self.version = tmpInterface['version'].strip() self.varsPost = tmpInterface['varsPost'] # 后置变量 self.httprequestTimeout = tmpInterface['timeout'] self.actualResult = tmpInterface['actualResult'] # 实际结果 self.assertResult = tmpInterface['assertResult'] # 断言结果 self.testResult = tmpInterface['testResult'] # 测试结果 self.beforeExecuteTakeTime = tmpInterface['beforeExecuteTakeTime'] self.afterExecuteTakeTime = tmpInterface['afterExecuteTakeTime'] self.executeTakeTime = tmpInterface['executeTakeTime'] self.totalTakeTime = tmpInterface['totalTakeTime'] self.httpConfKey = tmpInterface['httpConfKey'] self.confHttpLayer.key = self.httpConfKey self.confHttpLayer.generate_http_conf_by_key() self.varsStr = "" # 变量string self.varsPool = {} # 变量dict 变量池,包括varsPre的和varsPost的 self.headerDict = {} # header json字符串转换成的dict return True else: return False def generateByInterfaceId(self): """ 从tb_http_interface表根绝interfaceId获取并给属性赋值。 Returns: 执行结果 """ # colstr = "id, httpConfKey, serviceConfKey, alias, httpConfDesc, httpConf, state, addBy, modBy, addTime, modTime" self.traceId = md5("%s-%s" % (self.interfaceId, get_current_time())) if self.version == "CurrentVersion": sql = """ SELECT * FROM tb2_dubbo_interface where interfaceId = '%s' and state = 1 """ % (self.interfaceId) else: sql = """ SELECT * FROM tb_version_http_interface where interfaceId = '%s' and versionName='%s' and state = 1 """ % (self.interfaceId,self.version) self.globalDB.initGlobalDBConf() res = self.globalDB.execute_sql(sql) self.globalDB.release() if res: tmpInterface = res[0] self.id = tmpInterface['id'] self.title = tmpInterface['title'] self.desc = tmpInterface['casedesc'] self.state = tmpInterface['state'] self.addBy = tmpInterface['addBy'] self.modBy = tmpInterface['modBy'] self.addTime = tmpInterface['addTime'] self.modTime = tmpInterface['modTime'] self.businessLineId = tmpInterface['businessLineId'] self.modules = tmpInterface['moduleId'] self.level = tmpInterface['caselevel'] # 优先级 self.status = tmpInterface['status'] # 用例状态 未审核 审核通过 审核未通过 任务添加只能添加审核通过的用例 self.varsPre = tmpInterface['varsPre'] # 前置变量 self.useCustomUri = tmpInterface['useCustomUri'] self.customUri = tmpInterface['customUri'] self.dubboSystem = tmpInterface['dubboSystem'] self.dubboService = tmpInterface['dubboService'] # 接口 interface self.dubboMethod = tmpInterface['dubboMethod'] self.dubboParam = tmpInterface['dubboParams'] # key1=value1&key2=value2 self.encoding = tmpInterface['encoding'] self.varsPost = tmpInterface['varsPost'] # 后置变量 self.requestTimeout = tmpInterface['timeout'] return True else: return False def generateByInterfaceDict(self,interfaceDict): """ 根据传入的interfaceDict生成interface对象。 Returns: 执行结果 """ tmpInterface = interfaceDict self.id = tmpInterface['id'] self.interfaceId = tmpInterface['interfaceId'] self.traceId = md5("%s-%s" % (self.interfaceId, get_current_time())) self.title = tmpInterface['title'] self.desc = tmpInterface['casedesc'] self.state = tmpInterface['state'] self.addBy = tmpInterface['addBy'] self.modBy = tmpInterface['modBy'] self.addTime = tmpInterface['addTime'] self.modTime = tmpInterface['modTime'] self.businessLineId = tmpInterface['businessLineId'] self.modules = tmpInterface['moduleId'] self.level = tmpInterface['caselevel'] # 优先级 self.status = tmpInterface['status'] # 用例状态 未审核 审核通过 审核未通过 任务添加只能添加审核通过的用例 self.varsPre = tmpInterface['varsPre'] # 前置变量 self.dubboSystem = tmpInterface['dubboSystem'] self.dubboService = tmpInterface['dubboService'] # 接口 interface self.dubboMethod = tmpInterface['dubboMethod'] # 接口 interface self.dubboParam = tmpInterface['dubboParams'] # key1=value1&key2=value2 self.encoding = tmpInterface['encoding'] self.varsPost = tmpInterface['varsPost'] # 后置变量 self.dubborequestTimeout = tmpInterface['timeout'] self.version = tmpInterface['version'] @catch_exception def updateByInterfaceDebugId(self): """ 更新执行结果到tb_http_interface_debug表 Returns: 无 """ # colstr = "id, httpConfKey, serviceConfKey, alias, httpConfDesc, httpConf, state, addBy, modBy, addTime, modTime" self.testResult = self.testResult == None and "没有生成测试结果" or self.testResult self.actualResult = self.actualResult == None and "没有实际返回结果" or self.actualResult self.assertResult = self.assertResult == None and "没有断言结果" or self.assertResult self.varsPre = self.varsPre == None and "未发现前置变量" or self.varsPre self.varsPost = self.varsPost == None and "未发现后置变量" or self.varsPost # # sql = """ UPDATE tb2_dubbo_interface_debug SET dubboSystem='%s',dubboService='%s',dubboMethod='%s',dubboParams = '%s',testResult='%s',actualResult='%s',assertResult='%s', # beforeExecuteTakeTime=%d,afterExecuteTakeTime=%d, executeTakeTime=%d, totalTakeTime=%d,varsPre='%s',varsPost='%s', execStatus = 3,modTime='%s' WHERE id=%d""" \ # % ("%s(%s:%s)" % (self.dubboSystem,self.dubboTelnetHost,str(self.dubboTelnetPort)),replacedForIntoDB(self.dubboService),replacedForIntoDB(self.dubboMethod),replacedForIntoDB(self.dubboParam) ,self.testResult,self.actualResult,self.assertResult,int(self.beforeExecuteTakeTime),int(self.afterExecuteTakeTime),int(self.executeTakeTime), # int(self.totalTakeTime),self.varsPre,self.varsPost,get_current_time(),self.interfaceDebugId) # logging.debug(sql) try: # self.globalDB.initGlobalDBConf() # res = self.globalDB.execute_sql(sql) # if res == False: # sql = """ UPDATE tb2_dubbo_interface_debug SET dubboSystem='%s',dubboService='%s',dubboMethod='%s',dubboParams = '%s',testResult='%s',actualResult='%s',assertResult='%s', # beforeExecuteTakeTime=%d,afterExecuteTakeTime=%d, executeTakeTime=%d, totalTakeTime=%d,varsPre='%s',varsPost='%s', execStatus = 3,modTime='%s' WHERE id=%d""" \ # % ("%s(%s:%s)" % (self.dubboSystem,self.dubboTelnetHost,str(self.dubboTelnetPort)),self.dubboService,self.dubboMethod,replacedForIntoDB(self.dubboParam) ,"EXCEPTION:请联系管理员!", # "EXCEPTION:请联系管理员!","EXCEPTION:请联系管理员!", # int(self.beforeExecuteTakeTime),int(self.afterExecuteTakeTime),int(self.executeTakeTime), # int(self.totalTakeTime),"EXCEPTION:请联系管理员!","EXCEPTION:请联系管理员!", # get_current_time(),self.interfaceDebugId) # # self.globalDB.execute_sql(sql) redisDictData = json.loads(self.serviceRedis.get_data(self.interfaceDebugId)) redisDictData['execStatus'] = 3 redisDictData['dubboSystem'] = "%s(%s:%s)" % (self.dubboSystem,self.dubboTelnetHost,str(self.dubboTelnetPort)) redisDictData['dubboService'] = self.dubboService redisDictData['dubboParams'] = self.dubboParam redisDictData['dubboMethod'] = self.dubboMethod redisDictData['version'] = self.version redisDictData['varsPre'] = self.varsPre # 后置变量 redisDictData['varsPost'] = self.varsPost # 后置变量 redisDictData['timeout'] = self.httprequestTimeout redisDictData['actualResult'] = self.actualResult # 实际结果 redisDictData['assertResult'] = self.assertResult # 断言结果 redisDictData['testResult'] = self.testResult # 测试结果 redisDictData['beforeExecuteTakeTime'] = self.beforeExecuteTakeTime redisDictData['afterExecuteTakeTime'] = self.afterExecuteTakeTime redisDictData['executeTakeTime'] = self.executeTakeTime redisDictData['totalTakeTime'] = self.totalTakeTime self.serviceRedis.set_data(self.interfaceDebugId, json.dumps(redisDictData), 60 * 60) except Exception as e: logging.error(traceback.format_exc()) finally: tcpStr = '{"do":9,"InterfaceDebugId":"%s","protocol":"%s"}' % (self.interfaceDebugId, self.protocol) if sendTcp(TcpServerConf.ip, TcpServerConf.port, tcpStr): logging.info("%s 调试完毕通知主服务成功" % self.interfaceDebugId) else: logging.info("%s 调试完毕通知主服务失败" % self.interfaceDebugId) self.globalDB.release() @take_time def executeInterface(self): """ 执行接口 Returns: 无 """ logging.debug("####################################################DUBBO接口用例INTERFACE:%s开始执行在环境[%s]执行人[%s]####################################################" % (self.interfaceId,self.confHttpLayer.key,self.addBy)) super(DubboInterface, self).execute() logging.debug("####################################################DUBBO接口用例:%s结束执行[%s]####################################################" % (self.interfaceId,self.addBy)) if __name__ == "__main__": pass
7,870
5,813
<gh_stars>1000+ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.druid.query.groupby.having; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.druid.jackson.DefaultObjectMapper; import org.apache.druid.java.util.common.granularity.Granularities; import org.apache.druid.query.dimension.DefaultDimensionSpec; import org.apache.druid.query.filter.SelectorDimFilter; import org.apache.druid.query.groupby.GroupByQuery; import org.apache.druid.query.groupby.ResultRow; import org.apache.druid.segment.column.ColumnType; import org.hamcrest.CoreMatchers; import org.junit.Assert; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.internal.matchers.ThrowableMessageMatcher; import org.junit.rules.ExpectedException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class DimFilterHavingSpecTest { @Rule public ExpectedException expectedException = ExpectedException.none(); @Test public void testSimple() { final DimFilterHavingSpec havingSpec = new DimFilterHavingSpec(new SelectorDimFilter("foo", "bar", null), null); havingSpec.setQuery( GroupByQuery.builder() .setDataSource("dummy") .setInterval("1000/3000") .setDimensions(DefaultDimensionSpec.of("foo")) .setGranularity(Granularities.ALL) .build() ); Assert.assertTrue(havingSpec.eval(ResultRow.of("bar"))); Assert.assertFalse(havingSpec.eval(ResultRow.of("baz"))); } @Test public void testRowSignature() { final DimFilterHavingSpec havingSpec = new DimFilterHavingSpec(new SelectorDimFilter("foo", "1", null), null); havingSpec.setQuery( GroupByQuery.builder() .setDataSource("dummy") .setInterval("1000/3000") .setGranularity(Granularities.ALL) .setDimensions(new DefaultDimensionSpec("foo", "foo", ColumnType.LONG)) .build() ); Assert.assertTrue(havingSpec.eval(ResultRow.of(1L))); Assert.assertFalse(havingSpec.eval(ResultRow.of(2L))); } @Test(timeout = 60_000L) @Ignore // Doesn't always pass. The check in "eval" is best effort and not guaranteed to detect concurrent usage. public void testConcurrentUsage() throws Exception { final ExecutorService exec = Executors.newFixedThreadPool(2); final DimFilterHavingSpec havingSpec = new DimFilterHavingSpec(new SelectorDimFilter("foo", "1", null), null); final List<Future<?>> futures = new ArrayList<>(); for (int i = 0; i < 2; i++) { final ResultRow row = ResultRow.of(String.valueOf(i)); futures.add( exec.submit( () -> { havingSpec.setQuery(GroupByQuery.builder().setDimensions(DefaultDimensionSpec.of("foo")).build()); while (!Thread.interrupted()) { havingSpec.eval(row); } } ) ); } expectedException.expect(ExecutionException.class); expectedException.expectCause(CoreMatchers.<IllegalStateException>instanceOf(IllegalStateException.class)); expectedException.expectCause( ThrowableMessageMatcher.hasMessage(CoreMatchers.containsString("concurrent 'eval' calls not permitted")) ); try { for (Future<?> future : futures) { future.get(); } } finally { exec.shutdownNow(); } // Not reached Assert.assertTrue(false); } @Test public void testSerde() throws Exception { final DimFilterHavingSpec havingSpec = new DimFilterHavingSpec(new SelectorDimFilter("foo", "1", null), false); final ObjectMapper objectMapper = new DefaultObjectMapper(); Assert.assertEquals( havingSpec, objectMapper.readValue(objectMapper.writeValueAsBytes(havingSpec), HavingSpec.class) ); } }
1,787
502
/* * 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.iceberg.mr.hive.vector; import java.util.List; import java.util.Map; import org.apache.iceberg.MetadataColumns; import org.apache.iceberg.parquet.TypeWithSchemaVisitor; import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList; import org.apache.iceberg.relocated.com.google.common.collect.Lists; import org.apache.iceberg.relocated.com.google.common.collect.Maps; import org.apache.iceberg.types.Types; import org.apache.parquet.schema.GroupType; import org.apache.parquet.schema.MessageType; import org.apache.parquet.schema.Type; /** * Collects the top level field names from Parquet schema. During schema visit it translates the expected schema's * field names to what fields the visitor can match in the file schema to support column renames. */ class ParquetSchemaFieldNameVisitor extends TypeWithSchemaVisitor<Type> { private final MessageType originalFileSchema; private final Map<Integer, Type> typesById = Maps.newHashMap(); private StringBuilder sb = new StringBuilder(); private static final String DUMMY_COL_NAME = "<<DUMMY_FOR_RECREATED_FIELD_IN_FILESCHEMA>>"; ParquetSchemaFieldNameVisitor(MessageType originalFileSchema) { this.originalFileSchema = originalFileSchema; } @Override public Type message(Types.StructType expected, MessageType prunedFileSchema, List<Type> fields) { return this.struct(expected, prunedFileSchema.asGroupType(), fields); } @Override public Type struct(Types.StructType expected, GroupType struct, List<Type> fields) { boolean isMessageType = struct instanceof MessageType; List<Types.NestedField> expectedFields = expected != null ? expected.fields() : ImmutableList.of(); List<Type> types = Lists.newArrayListWithExpectedSize(expectedFields.size()); for (Types.NestedField field : expectedFields) { int id = field.fieldId(); if (MetadataColumns.metadataFieldIds().contains(id)) { continue; } Type fieldInPrunedFileSchema = typesById.get(id); if (fieldInPrunedFileSchema == null) { if (!originalFileSchema.containsField(field.name())) { // Must be a new field - it isn't in this parquet file yet, so add the new field name instead of null appendToColNamesList(isMessageType, field.name()); } else { // This field is found in the parquet file with a different ID, so it must have been recreated since. // Inserting a dummy col name to force Hive Parquet reader returning null for this column. appendToColNamesList(isMessageType, DUMMY_COL_NAME); } } else { // Already present column in this parquet file, add the original name types.add(fieldInPrunedFileSchema); appendToColNamesList(isMessageType, fieldInPrunedFileSchema.getName()); } } if (!isMessageType) { GroupType groupType = new GroupType(Type.Repetition.REPEATED, fieldNames.peek(), types); typesById.put(struct.getId().intValue(), groupType); return groupType; } else { return new MessageType("table", types); } } private void appendToColNamesList(boolean isMessageType, String colName) { if (isMessageType) { sb.append(colName).append(','); } } @Override public Type primitive(org.apache.iceberg.types.Type.PrimitiveType expected, org.apache.parquet.schema.PrimitiveType primitive) { typesById.put(primitive.getId().intValue(), primitive); return primitive; } @Override public Type list(Types.ListType iList, GroupType array, Type element) { typesById.put(array.getId().intValue(), array); return array; } @Override public Type map(Types.MapType iMap, GroupType map, Type key, Type value) { typesById.put(map.getId().intValue(), map); return map; } public String retrieveColumnNameList() { sb.setLength(sb.length() - 1); return sb.toString(); } }
1,531
1,233
<filename>compiler/src/main/java/com/github/mustachejava/reflect/MissingWrapper.java package com.github.mustachejava.reflect; import static java.util.Arrays.asList; /** * Used to mark a wrapper this is only guarding a complete miss. */ public class MissingWrapper extends GuardedWrapper { private final String name; public MissingWrapper(String name, Guard[] guards) { super(guards); this.name = name; } public String toString() { return "[Missing: " + name + " Guards: " + asList(guards) + "]"; } }
168
679
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_drawinglayer.hxx" #include <drawinglayer/primitive3d/hatchtextureprimitive3d.hxx> #include <drawinglayer/primitive3d/polypolygonprimitive3d.hxx> #include <basegfx/polygon/b2dpolypolygon.hxx> #include <basegfx/polygon/b3dpolygon.hxx> #include <basegfx/polygon/b2dpolygon.hxx> #include <basegfx/polygon/b2dpolypolygontools.hxx> #include <basegfx/range/b2drange.hxx> #include <drawinglayer/texture/texture.hxx> #include <basegfx/polygon/b2dpolygonclipper.hxx> #include <basegfx/matrix/b3dhommatrix.hxx> #include <drawinglayer/primitive3d/polygonprimitive3d.hxx> #include <drawinglayer/primitive3d/drawinglayer_primitivetypes3d.hxx> ////////////////////////////////////////////////////////////////////////////// using namespace com::sun::star; ////////////////////////////////////////////////////////////////////////////// namespace drawinglayer { namespace primitive3d { Primitive3DSequence HatchTexturePrimitive3D::impCreate3DDecomposition() const { Primitive3DSequence aRetval; if(getChildren().hasElements()) { const Primitive3DSequence aSource(getChildren()); const sal_uInt32 nSourceCount(aSource.getLength()); std::vector< Primitive3DReference > aDestination; for(sal_uInt32 a(0); a < nSourceCount; a++) { // get reference const Primitive3DReference xReference(aSource[a]); if(xReference.is()) { // try to cast to BasePrimitive2D implementation const BasePrimitive3D* pBasePrimitive = dynamic_cast< const BasePrimitive3D* >(xReference.get()); if(pBasePrimitive) { // it is a BasePrimitive3D implementation, use getPrimitive3DID() call for switch // not all content is needed, remove transparencies and ModifiedColorPrimitives switch(pBasePrimitive->getPrimitive3DID()) { case PRIMITIVE3D_ID_POLYPOLYGONMATERIALPRIMITIVE3D : { // polyPolygonMaterialPrimitive3D, check texturing and hatching const PolyPolygonMaterialPrimitive3D& rPrimitive = static_cast< const PolyPolygonMaterialPrimitive3D& >(*pBasePrimitive); const basegfx::B3DPolyPolygon aFillPolyPolygon(rPrimitive.getB3DPolyPolygon()); if(maHatch.isFillBackground()) { // add original primitive for background aDestination.push_back(xReference); } if(aFillPolyPolygon.areTextureCoordinatesUsed()) { const sal_uInt32 nPolyCount(aFillPolyPolygon.count()); basegfx::B2DPolyPolygon aTexPolyPolygon; basegfx::B2DPoint a2N; basegfx::B2DVector a2X, a2Y; basegfx::B3DPoint a3N; basegfx::B3DVector a3X, a3Y; bool b2N(false), b2X(false), b2Y(false); for(sal_uInt32 b(0); b < nPolyCount; b++) { const basegfx::B3DPolygon aPartPoly(aFillPolyPolygon.getB3DPolygon(b)); const sal_uInt32 nPointCount(aPartPoly.count()); basegfx::B2DPolygon aTexPolygon; for(sal_uInt32 c(0); c < nPointCount; c++) { const basegfx::B2DPoint a2Candidate(aPartPoly.getTextureCoordinate(c)); if(!b2N) { a2N = a2Candidate; a3N = aPartPoly.getB3DPoint(c); b2N = true; } else if(!b2X && !a2N.equal(a2Candidate)) { a2X = a2Candidate - a2N; a3X = aPartPoly.getB3DPoint(c) - a3N; b2X = true; } else if(!b2Y && !a2N.equal(a2Candidate) && !a2X.equal(a2Candidate)) { a2Y = a2Candidate - a2N; const double fCross(a2X.cross(a2Y)); if(!basegfx::fTools::equalZero(fCross)) { a3Y = aPartPoly.getB3DPoint(c) - a3N; b2Y = true; } } aTexPolygon.append(a2Candidate); } aTexPolygon.setClosed(true); aTexPolyPolygon.append(aTexPolygon); } if(b2N && b2X && b2Y) { // found two linearly independent 2D vectors // get 2d range of texture coordinates const basegfx::B2DRange aOutlineRange(basegfx::tools::getRange(aTexPolyPolygon)); const basegfx::BColor aHatchColor(getHatch().getColor()); const double fAngle(getHatch().getAngle()); ::std::vector< basegfx::B2DHomMatrix > aMatrices; // get hatch transformations switch(getHatch().getStyle()) { case attribute::HATCHSTYLE_TRIPLE: { // rotated 45 degrees texture::GeoTexSvxHatch aHatch( aOutlineRange, aOutlineRange, getHatch().getDistance(), fAngle - F_PI4); aHatch.appendTransformations(aMatrices); } case attribute::HATCHSTYLE_DOUBLE: { // rotated 90 degrees texture::GeoTexSvxHatch aHatch( aOutlineRange, aOutlineRange, getHatch().getDistance(), fAngle - F_PI2); aHatch.appendTransformations(aMatrices); } case attribute::HATCHSTYLE_SINGLE: { // angle as given texture::GeoTexSvxHatch aHatch( aOutlineRange, aOutlineRange, getHatch().getDistance(), fAngle); aHatch.appendTransformations(aMatrices); } } // create geometry from unit line basegfx::B2DPolyPolygon a2DHatchLines; basegfx::B2DPolygon a2DUnitLine; a2DUnitLine.append(basegfx::B2DPoint(0.0, 0.0)); a2DUnitLine.append(basegfx::B2DPoint(1.0, 0.0)); for(sal_uInt32 c(0); c < aMatrices.size(); c++) { const basegfx::B2DHomMatrix& rMatrix = aMatrices[c]; basegfx::B2DPolygon aNewLine(a2DUnitLine); aNewLine.transform(rMatrix); a2DHatchLines.append(aNewLine); } if(a2DHatchLines.count()) { // clip against texture polygon a2DHatchLines = basegfx::tools::clipPolyPolygonOnPolyPolygon(a2DHatchLines, aTexPolyPolygon, true, true); } if(a2DHatchLines.count()) { // create 2d matrix with 2d vectors as column vectors and 2d point as offset, this represents // a coordinate system transformation from unit coordinates to the new coordinate system basegfx::B2DHomMatrix a2D; a2D.set(0, 0, a2X.getX()); a2D.set(1, 0, a2X.getY()); a2D.set(0, 1, a2Y.getX()); a2D.set(1, 1, a2Y.getY()); a2D.set(0, 2, a2N.getX()); a2D.set(1, 2, a2N.getY()); // invert that transformation, so we have a back-transformation from texture coordinates // to unit coordinates a2D.invert(); a2DHatchLines.transform(a2D); // expand back-transformated geometry tpo 3D basegfx::B3DPolyPolygon a3DHatchLines(basegfx::tools::createB3DPolyPolygonFromB2DPolyPolygon(a2DHatchLines, 0.0)); // create 3d matrix with 3d vectors as column vectors (0,0,1 as Z) and 3d point as offset, this represents // a coordinate system transformation from unit coordinates to the object's 3d coordinate system basegfx::B3DHomMatrix a3D; a3D.set(0, 0, a3X.getX()); a3D.set(1, 0, a3X.getY()); a3D.set(2, 0, a3X.getZ()); a3D.set(0, 1, a3Y.getX()); a3D.set(1, 1, a3Y.getY()); a3D.set(2, 1, a3Y.getZ()); a3D.set(0, 3, a3N.getX()); a3D.set(1, 3, a3N.getY()); a3D.set(2, 3, a3N.getZ()); // transform hatch lines to 3D object coordinates a3DHatchLines.transform(a3D); // build primitives from this geometry const sal_uInt32 nHatchLines(a3DHatchLines.count()); for(sal_uInt32 d(0); d < nHatchLines; d++) { const Primitive3DReference xRef(new PolygonHairlinePrimitive3D(a3DHatchLines.getB3DPolygon(d), aHatchColor)); aDestination.push_back(xRef); } } } } break; } default : { // add reference to result aDestination.push_back(xReference); break; } } } else { // unknown implementation, add to result aDestination.push_back(xReference); } } } // prepare return value const sal_uInt32 nDestSize(aDestination.size()); aRetval.realloc(nDestSize); for(sal_uInt32 b(0); b < nDestSize; b++) { aRetval[b] = aDestination[b]; } } return aRetval; } HatchTexturePrimitive3D::HatchTexturePrimitive3D( const attribute::FillHatchAttribute& rHatch, const Primitive3DSequence& rChildren, const basegfx::B2DVector& rTextureSize, bool bModulate, bool bFilter) : TexturePrimitive3D(rChildren, rTextureSize, bModulate, bFilter), maHatch(rHatch), maBuffered3DDecomposition() { } bool HatchTexturePrimitive3D::operator==(const BasePrimitive3D& rPrimitive) const { if(TexturePrimitive3D::operator==(rPrimitive)) { const HatchTexturePrimitive3D& rCompare = (HatchTexturePrimitive3D&)rPrimitive; return (getHatch() == rCompare.getHatch()); } return false; } Primitive3DSequence HatchTexturePrimitive3D::get3DDecomposition(const geometry::ViewInformation3D& /*rViewInformation*/) const { ::osl::MutexGuard aGuard( m_aMutex ); if(!getBuffered3DDecomposition().hasElements()) { const Primitive3DSequence aNewSequence(impCreate3DDecomposition()); const_cast< HatchTexturePrimitive3D* >(this)->setBuffered3DDecomposition(aNewSequence); } return getBuffered3DDecomposition(); } // provide unique ID ImplPrimitrive3DIDBlock(HatchTexturePrimitive3D, PRIMITIVE3D_ID_HATCHTEXTUREPRIMITIVE3D) } // end of namespace primitive3d } // end of namespace drawinglayer ////////////////////////////////////////////////////////////////////////////// // eof
11,830
591
<filename>src/Engine/resource/esrc_ecoObj.h /* * ========================= esrc_ecoObj.h ========================== * -- tpr -- * CREATE -- 2019.04.19 * MODIFY -- * ---------------------------------------------------------- */ #ifndef TPR_ESRC_ECO_OBJ_H #define TPR_ESRC_ECO_OBJ_H //-------------------- CPP --------------------// #include <unordered_map> #include <utility> //- pair #include <memory> //-------------------- Engine --------------------// #include "EcoObj.h" #include "IntVec.h" #include "sectionKey.h" #include "EcoObj_ReadOnly.h" #include "GoSpecData.h" #include "esrc_ecoObjMemState.h" namespace esrc {//------------------ namespace: esrc -------------------------// void init_ecoObjs()noexcept; void moveIn_ecoObjUPtr_from_job( sectionKey_t ecoObjKey_, std::unique_ptr<EcoObj> ecoObjUPtr_ ); void del_ecoObjs_tooFarAway()noexcept; //-- 更加精细的 元素数据 只读访问 接口 [值传递] -- std::unique_ptr<EcoObj_ReadOnly> get_ecoObj_readOnly( sectionKey_t sectionkey_ )noexcept; EcoObj &get_ecoObjRef( sectionKey_t sectionkey_ )noexcept; }//---------------------- namespace: esrc -------------------------// #endif
518
903
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.smithy.cli; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.not; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import software.amazon.smithy.cli.commands.BuildCommand; import software.amazon.smithy.cli.commands.ValidateCommand; public class CliTest { @Test public void noArgsPrintsMainHelp() throws Exception { Cli cli = new Cli("mytest"); PrintStream out = System.out; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PrintStream printStream = new PrintStream(outputStream); System.setOut(printStream); cli.run(new String[]{}); System.setOut(out); String help = outputStream.toString("UTF-8"); assertThat(help, containsString("mytest")); } @Test public void printsMainHelp() throws Exception { Cli cli = new Cli("mytest"); cli.addCommand(new BuildCommand()); cli.addCommand(new ValidateCommand()); PrintStream out = System.out; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PrintStream printStream = new PrintStream(outputStream); System.setOut(printStream); cli.run(new String[]{"--help"}); System.setOut(out); String help = outputStream.toString("UTF-8"); assertThat(help, containsString("build")); assertThat(help, containsString("validate")); assertThat(help, containsString("mytest")); } @Test public void printsSubcommandHelp() throws Exception { Cli cli = new Cli("mytest"); cli.addCommand(new BuildCommand()); cli.addCommand(new ValidateCommand()); PrintStream out = System.out; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PrintStream printStream = new PrintStream(outputStream); System.setOut(printStream); cli.run(new String[]{"validate", "--help"}); System.setOut(out); String help = outputStream.toString("UTF-8"); assertThat(help, containsString("validate")); assertThat(help, containsString("--help")); assertThat(help, containsString("--debug")); assertThat(help, containsString("--no-color")); } @Test public void showsStacktrace() throws Exception { Cli cli = new Cli("mytest"); PrintStream out = System.out; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PrintStream printStream = new PrintStream(outputStream); System.setOut(printStream); try { cli.run(new String[]{"invalid", "--stacktrace"}); Assertions.fail("Expected to throw"); } catch (RuntimeException e) { } System.setOut(out); String help = outputStream.toString("UTF-8"); assertThat(help, containsString("Unknown command or argument")); } @Test public void canDisableLogging() throws Exception { Cli cli = new Cli("mytest"); cli.addCommand(new BuildCommand()); PrintStream err = System.err; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PrintStream printStream = new PrintStream(outputStream); try { System.setErr(printStream); cli.run(new String[]{"build", "--logging", "OFF"}); String result = outputStream.toString("UTF-8"); assertThat(result, not(containsString("INFO -"))); } finally { System.setErr(err); } } @Test public void canEnableLoggingViaLogLevel() throws Exception { Cli cli = new Cli("mytest"); cli.addCommand(new BuildCommand()); PrintStream err = System.err; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PrintStream printStream = new PrintStream(outputStream); try { System.setErr(printStream); cli.run(new String[]{"build", "--logging", "INFO"}); String result = outputStream.toString("UTF-8"); assertThat(result, containsString("INFO -")); } finally { System.setErr(err); } } @Test public void canEnableLogging() throws Exception { Cli cli = new Cli("mytest"); cli.setConfigureLogging(true); cli.addCommand(new BuildCommand()); PrintStream err = System.err; try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PrintStream printStream = new PrintStream(outputStream); System.setErr(printStream); cli.run(new String[]{"build"}); String result = outputStream.toString("UTF-8"); assertThat(result, containsString("INFO -")); } finally { System.setErr(err); } } @Test public void canEnableDebugLogging() throws Exception { Cli cli = new Cli("mytest"); cli.addCommand(new BuildCommand()); PrintStream err = System.err; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PrintStream printStream = new PrintStream(outputStream); try { System.setErr(printStream); cli.run(new String[]{"build", "--debug"}); String result = outputStream.toString("UTF-8"); assertThat(result, containsString("FINE -")); } finally { System.setErr(err); } } }
2,440
401
<reponame>rocaej/echoprint-server /* * Copyright (c) 2016 Spotify AB. * * 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.spotify.echoprintserver; import com.spotify.echoprintserver.nativelib.IndexCreationException; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.*; /** * A pure-Java implementation of the inverted index creation routine. */ public class InvertedIndexBlockMaker { /** * Construct an index block from a list of code sequences. * * @return binary index representation, to be serialized as-is on disk. * @throws IOException An index block cannot contain more than 65535 songs, any attempt to * do that will result in an exception being thrown. */ public static byte[] fromCodeSequences(List<Integer[]> codeSequences) throws IOException, IndexCreationException { if(codeSequences.size() > 65535) throw new IndexCreationException("an index block cannot contain more than 2^16 - 1 songs"); List<Integer[]> sortedUniqueCodeSequences = new LinkedList<>(); for (Integer[] codeSequence : codeSequences) { TreeSet<Integer> codeSet = new TreeSet<>(Arrays.asList(codeSequence)); sortedUniqueCodeSequences.add(codeSet.toArray(new Integer[codeSet.size()])); } // inverted mapping code -> [songs] Map<Integer, List<Integer>> code2songs = new TreeMap<Integer, List<Integer>>(); ListIterator<Integer[]> it = sortedUniqueCodeSequences.listIterator(); while (it.hasNext()) { int songIndex = it.nextIndex(); Integer[] songCodes = it.next(); for (Integer code : songCodes) { if (!code2songs.containsKey(code)) code2songs.put(code, new ArrayList<Integer>()); code2songs.get(code).add(songIndex); } } List<Integer> codeSet = new ArrayList<Integer>(code2songs.keySet()); Collections.sort(codeSet); Integer nCodes = codeSet.size(); Integer nSongs = sortedUniqueCodeSequences.size(); List<Integer> codeLengths = new ArrayList<Integer>(nCodes); for (Integer c : codeSet) codeLengths.add(code2songs.get(c).size()); List<Integer> songLengths = new ArrayList<Integer>(nSongs); for (Integer[] codes : sortedUniqueCodeSequences) songLengths.add(codes.length); ByteArrayOutputStream out = new ByteArrayOutputStream(); out.write(ByteFunctions.asUint32Array(nCodes)); out.write(ByteFunctions.asUint32Array(nSongs)); out.write(ByteFunctions.asUint32Array(codeSet)); out.write(ByteFunctions.asUint32Array(codeLengths)); out.write(ByteFunctions.asUint32Array(songLengths)); for (Integer c : codeSet) out.write(ByteFunctions.asUint16Array(code2songs.get(c))); return out.toByteArray(); } }
1,154
2,079
<gh_stars>1000+ /*============================================================================== * Utilities for single thread test and benchmark. * * Copyright (C) 2018 YaoYuan <<EMAIL>>. * Released under the MIT license (MIT). *============================================================================*/ #include "yy_test_utils.h" #define REPEAT_2(x) x x #define REPEAT_4(x) REPEAT_2(REPEAT_2(x)) #define REPEAT_8(x) REPEAT_2(REPEAT_4(x)) #define REPEAT_16(x) REPEAT_2(REPEAT_8(x)) #define REPEAT_32(x) REPEAT_2(REPEAT_16(x)) #define REPEAT_64(x) REPEAT_2(REPEAT_32(x)) #define REPEAT_128(x) REPEAT_2(REPEAT_64(x)) #define REPEAT_256(x) REPEAT_2(REPEAT_128(x)) #define REPEAT_512(x) REPEAT_2(REPEAT_256(x)) /*============================================================================== * CPU *============================================================================*/ bool yy_cpu_setup_priority(void) { #if defined(_WIN32) BOOL ret1 = SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS); BOOL ret2 = SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL); return ret1 && ret2; #else int policy; struct sched_param param; pthread_t thread = pthread_self(); pthread_getschedparam(thread, &policy, &param); param.sched_priority = sched_get_priority_max(policy); if (param.sched_priority != -1) { return pthread_setschedparam(pthread_self(), policy, &param) == 0; } return false; #endif } void yy_cpu_spin(f64 second) { f64 end = yy_time_get_seconds() + second; while (yy_time_get_seconds() < end) { volatile int x = 0; while (x < 1000) x++; } } #define YY_CPU_RUN_INST_COUNT_A (8192 * 4 * (32 + 64)) #define YY_CPU_RUN_INST_COUNT_B (8192 * 4 * (128)) /* These functions contains some `add` instructions with data dependence. This file should be compiled with optimization flag on. We hope that each line of the code in the inner loop may compiled as an `add` instruction, each `add` instruction takes 1 cycle, and inner kernel can fit in the L1i cache. Try: https://godbolt.org/z/d3GP1b */ u32 yy_cpu_run_seq_vals[8]; void yy_cpu_run_seq_a(void) { u32 loop = 8192; u32 v1 = yy_cpu_run_seq_vals[1]; u32 v2 = yy_cpu_run_seq_vals[2]; u32 v3 = yy_cpu_run_seq_vals[3]; u32 v4 = yy_cpu_run_seq_vals[4]; do { REPEAT_32( v1 += v4; v2 += v1; v3 += v2; v4 += v3; ) REPEAT_64( v1 += v4; v2 += v1; v3 += v2; v4 += v3; ) } while (--loop); yy_cpu_run_seq_vals[0] = v1; } void yy_cpu_run_seq_b(void) { u32 loop = 8192; u32 v1 = yy_cpu_run_seq_vals[1]; u32 v2 = yy_cpu_run_seq_vals[2]; u32 v3 = yy_cpu_run_seq_vals[3]; u32 v4 = yy_cpu_run_seq_vals[4]; do { REPEAT_128( v1 += v4; v2 += v1; v3 += v2; v4 += v3; ) } while (--loop); yy_cpu_run_seq_vals[0] = v1; } static u64 yy_cycle_per_sec = 0; static u64 yy_tick_per_sec = 0; void yy_cpu_measure_freq(void) { #define warmup_count 8 #define measure_count 128 yy_time p1, p2; u64 ticks_a[measure_count]; u64 ticks_b[measure_count]; /* warm up CPU caches and stabilize the frequency */ for (int i = 0; i < warmup_count; i++) { yy_cpu_run_seq_a(); yy_cpu_run_seq_b(); yy_time_get_current(&p1); yy_time_get_ticks(); } /* run sequence a and b repeatedly, record ticks and times */ yy_time_get_current(&p1); u64 t1 = yy_time_get_ticks(); for (int i = 0; i < measure_count; i++) { u64 s1 = yy_time_get_ticks(); yy_cpu_run_seq_a(); u64 s2 = yy_time_get_ticks(); yy_cpu_run_seq_b(); u64 s3 = yy_time_get_ticks(); ticks_a[i] = s2 - s1; ticks_b[i] = s3 - s2; } u64 t2 = yy_time_get_ticks(); yy_time_get_current(&p2); /* calculate tick count per second, this value is high precision */ f64 total_seconds = yy_time_to_seconds(&p2) - yy_time_to_seconds(&p1); u64 total_ticks = t2 - t1; yy_tick_per_sec = (u64)((f64)total_ticks / total_seconds); /* find the minimum ticks of each sequence to avoid inaccurate values caused by context switching, etc. */ for (int i = 1; i < measure_count; i++) { if (ticks_a[i] < ticks_a[0]) ticks_a[0] = ticks_a[i]; if (ticks_b[i] < ticks_b[0]) ticks_b[0] = ticks_b[i]; } /* use the difference between two sequences to eliminate the overhead of loops and function calls */ u64 one_ticks = ticks_b[0] - ticks_a[0]; u64 one_insts = YY_CPU_RUN_INST_COUNT_B - YY_CPU_RUN_INST_COUNT_A; yy_cycle_per_sec = (u64)((f64)one_insts / (f64)one_ticks * (f64)yy_tick_per_sec); #undef warmup_count #undef measure_count } u64 yy_cpu_get_freq(void) { return yy_cycle_per_sec; } u64 yy_cpu_get_tick_per_sec(void) { return yy_tick_per_sec; } f64 yy_cpu_get_cycle_per_tick(void) { return (f64)yy_cycle_per_sec / (f64)yy_tick_per_sec; } /*============================================================================== * Environment *============================================================================*/ const char *yy_env_get_os_desc(void) { #if defined(__MINGW64__) return "Windows (MinGW-w64)"; #elif defined(__MINGW32__) return "Windows (MinGW)"; #elif defined(__CYGWIN__) && defined(ARCH_64_DEFINED) return "Windows (Cygwin x64)"; #elif defined(__CYGWIN__) return "Windows (Cygwin x86)"; #elif defined(_WIN64) return "Windows 64-bit"; #elif defined(_WIN32) return "Windows 32-bit"; #elif defined(__APPLE__) # if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE # if defined(YY_ARCH_64) return "iOS 64-bit"; # else return "iOS 32-bit"; # endif # elif defined(TARGET_OS_OSX) && TARGET_OS_OSX # if defined(YY_ARCH_64) return "macOS 64-bit"; # else return "macOS 32-bit"; # endif # else # if defined(YY_ARCH_64) return "Apple OS 64-bit"; # else return "Apple OS 32-bit"; # endif # endif #elif defined(__ANDROID__) # if defined(YY_ARCH_64) return "Android 64-bit"; # else return "Android 32-bit"; # endif #elif defined(__linux__) || defined(__linux) || defined(__gnu_linux__) # if defined(YY_ARCH_64) return "Linux 64-bit"; # else return "Linux 32-bit"; # endif #elif defined(__BSD__) || defined(__FreeBSD__) # if defined(YY_ARCH_64) return "BSD 64-bit"; # else return "BSD 32-bit"; # endif #else # if defined(YY_ARCH_64) return "Unknown OS 64-bit"; # else return "Unknown OS 32-bit"; # endif #endif } const char *yy_env_get_cpu_desc(void) { #if defined(__APPLE__) static char brand[256] = {0}; size_t size = sizeof(brand); static bool finished = false; struct utsname sysinfo; if (finished) return brand; /* works for macOS */ if (sysctlbyname("machdep.cpu.brand_string", (void *)brand, &size, NULL, 0) == 0) { if (strlen(brand) > 0) finished = true; } /* works for iOS, returns device model such as "iPhone9,1 ARM64_T8010" */ if (!finished) { uname(&sysinfo); const char *model = sysinfo.machine; const char *cpu = sysinfo.version; if (cpu) { cpu = strstr(cpu, "RELEASE_"); if (cpu) cpu += 8; } if (model || cpu) { snprintf(brand, sizeof(brand), "%s %s", model ? model : "", cpu ? cpu : ""); finished = true; } } if (!finished) { snprintf(brand, sizeof(brand), "Unknown CPU"); finished = true; } return brand; #elif defined(_WIN32) #if defined(__x86_64__) || defined(__amd64__) || \ defined(_M_IX86) || defined(_M_AMD64) static char brand[0x40] = { 0 }; static bool finished = false; int cpui[4] = { 0 }; int nexids, i; if (finished) return brand; __cpuid(cpui, 0x80000000); nexids = cpui[0]; if (nexids >= 0x80000004) { for (i = 2; i <= 4; i++) { memset(cpui, 0, sizeof(cpui)); __cpuidex(cpui, i + 0x80000000, 0); memcpy(brand + (i - 2) * sizeof(cpui), cpui, sizeof(cpui)); } finished = true; } if (!finished || strlen(brand) == 0) { snprintf(brand, sizeof(brand), "Unknown CPU"); finished = true; } return brand; # else return "Unknown CPU"; # endif #else # define BUF_LENGTH 1024 static char buf[BUF_LENGTH], *res = NULL; static bool finished = false; const char *prefixes[] = { "model name", /* x86 */ "CPU part", /* arm */ "cpu model\t",/* mips */ "cpu\t" /* powerpc */ }; int i, len; FILE *fp; if (res) return res; fp = fopen("/proc/cpuinfo", "r"); if (fp) { while (!res) { memset(buf, 0, BUF_LENGTH); if (fgets(buf, BUF_LENGTH - 1, fp) == NULL) break; for (i = 0; i < (int)(sizeof(prefixes) / sizeof(char *)) && !res; i++) { if (strncmp(prefixes[i], buf, strlen(prefixes[i])) == 0) { res = buf + strlen(prefixes[i]); } } } fclose(fp); } if (res) { while (*res == ' ' || *res == '\t' || *res == ':') res++; for (i = 0, len = (int)strlen(res); i < len; i++) { if (res[i] == '\t') res[i] = ' '; if (res[i] == '\r' || res[i] == '\n') res[i] = '\0'; } } else { res = "Unknown CPU"; } finished = true; return res; #endif } const char *yy_env_get_compiler_desc(void) { static char buf[512] = {0}; static bool finished = false; if (finished) return buf; #if defined(__ICL) || defined(__ICC) || defined(__INTEL_COMPILER) int v, r; /* version, revision */ # if defined(__INTEL_COMPILER) v = __INTEL_COMPILER; # elif defined(__ICC) v = __ICC; # else v = __ICL; # endif r = (v - (v / 100) * 100) / 10; v = v / 100; snprintf(buf, sizeof(buf), "Intel C++ Compiler %d.%d", v, r); #elif defined(__ARMCC_VERSION) int v, r; v = __ARMCC_VERSION; /* PVVbbbb or Mmmuuxx */ r = (v - (v / 1000000) * 1000000) / 1000; v = v / 1000000; snprintf(buf, sizeof(buf), "ARM Compiler %d.%d", v, r); #elif defined(_MSC_VER) /* https://docs.microsoft.com/en-us/cpp/preprocessor/predefined-macros */ const char *vc; # if _MSC_VER >= 1930 vc = ""; # elif _MSC_VER >= 1920 vc = " 2019"; # elif _MSC_VER >= 1910 vc = " 2017"; # elif _MSC_VER >= 1900 vc = " 2015"; # elif _MSC_VER >= 1800 vc = " 2013"; # elif _MSC_VER >= 1700 vc = " 2012"; # elif _MSC_VER >= 1600 vc = " 2010"; # elif _MSC_VER >= 1500 vc = " 2008"; # elif _MSC_VER >= 1400 vc = " 2005"; # elif _MSC_VER >= 1310 vc = " 7.1"; # elif _MSC_VER >= 1300 vc = " 7.0"; # elif _MSC_VER >= 1200 vc = " 6.0"; # else vc = ""; # endif snprintf(buf, sizeof(buf), "Microsoft Visual C++%s (%d)", vc, _MSC_VER); #elif defined(__clang__) # if defined(__apple_build_version__) /* Apple versions: https://en.wikipedia.org/wiki/Xcode#Latest_versions */ snprintf(buf, sizeof(buf), "Clang %d.%d.%d (Apple version)", __clang_major__, __clang_minor__, __clang_patchlevel__); # else snprintf(buf, sizeof(buf), "Clang %d.%d.%d", __clang_major__, __clang_minor__, __clang_patchlevel__); # endif #elif defined(__GNUC__) const char *ext; # if defined(__CYGWIN__) ext = " (Cygwin)"; # elif defined(__MINGW64__) ext = " (MinGW-w64)"; # elif defined(__MINGW32__) ext = " (MinGW)"; # else ext = ""; # endif # if defined(__GNUC_PATCHLEVEL__) snprintf(buf, sizeof(buf), "GCC %d.%d.%d%s", __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__, ext); # else snprintf(buf, sizeof(buf), "GCC %d.%d%s", __GNUC__, __GNUC_MINOR__, ext); # endif #else snprintf(buf, sizeof(buf), "Unknown Compiler"); #endif finished = true; return buf; } /*============================================================================== * Random Number Generator * PCG random: http://www.pcg-random.org * A fixed seed should be used to ensure repeatability of the test or benchmark. *============================================================================*/ #define YY_RANDOM_STATE_INIT (((u64)0x853C49E6U << 32) + 0x748FEA9BU) #define YY_RANDOM_INC_INIT (((u64)0xDA3E39CBU << 32) + 0x94B95BDBU) #define YY_RANDOM_MUL (((u64)0x5851F42DU << 32) + 0x4C957F2DU) static u64 yy_random_state = YY_RANDOM_STATE_INIT; static u64 yy_random_inc = YY_RANDOM_INC_INIT; void yy_random_reset(void) { yy_random_state = YY_RANDOM_STATE_INIT; yy_random_inc = YY_RANDOM_INC_INIT; } u32 yy_random32(void) { u32 xorshifted, rot; u64 oldstate = yy_random_state; yy_random_state = oldstate * YY_RANDOM_MUL + yy_random_inc; xorshifted = (u32)(((oldstate >> 18) ^ oldstate) >> 27); rot = (u32)(oldstate >> 59); return (xorshifted >> rot) | (xorshifted << (((u32)-(i32)rot) & 31)); } u32 yy_random32_uniform(u32 bound) { u32 r, threshold = (u32)(-(i32)bound) % bound; if (bound < 2) return 0; while (true) { r = yy_random32(); if (r >= threshold) return r % bound; } } u32 yy_random32_range(u32 min, u32 max) { return yy_random32_uniform(max - min + 1) + min; } u64 yy_random64(void) { return (u64)yy_random32() << 32 | yy_random32(); } u64 yy_random64_uniform(u64 bound) { u64 r, threshold = ((u64)-(i64)bound) % bound; if (bound < 2) return 0; while (true) { r = yy_random64(); if (r >= threshold) return r % bound; } } u64 yy_random64_range(u64 min, u64 max) { return yy_random64_uniform(max - min + 1) + min; } /*============================================================================== * File Utils *============================================================================*/ bool yy_path_combine(char *buf, const char *path, ...) { if (!buf) return false; *buf = '\0'; if (!path) return false; usize len = strlen(path); memmove(buf, path, len); const char *hdr = buf; buf += len; va_list args; va_start(args, path); while (true) { const char *item = va_arg(args, const char *); if (!item) break; if (buf > hdr && *(buf - 1) != YY_DIR_SEPARATOR) { *buf++ = YY_DIR_SEPARATOR; } len = strlen(item); if (len && *item == YY_DIR_SEPARATOR) { len--; item++; } memmove(buf, item, len); buf += len; } va_end(args); *buf = '\0'; return true; } bool yy_path_remove_last(char *buf, const char *path) { usize len = path ? strlen(path) : 0; if (!buf) return false; *buf = '\0'; if (len == 0) return false; const char *cur = path + len - 1; if (*cur == YY_DIR_SEPARATOR) cur--; for (; cur >= path; cur--) { if (*cur == YY_DIR_SEPARATOR) break; } len = cur + 1 - path; memmove(buf, path, len); buf[len] = '\0'; return len > 0; } bool yy_path_get_last(char *buf, const char *path) { usize len = path ? strlen(path) : 0; const char *end, *cur; if (!buf) return false; *buf = '\0'; if (len == 0) return false; end = path + len - 1; if (*end == YY_DIR_SEPARATOR) end--; for (cur = end; cur >= path; cur--) { if (*cur == YY_DIR_SEPARATOR) break; } len = end - cur; memmove(buf, cur + 1, len); buf[len] = '\0'; return len > 0; } bool yy_path_append_ext(char *buf, const char *path, const char *ext) { usize len = path ? strlen(path) : 0; char tmp[YY_MAX_PATH]; char *cur = tmp; if (!buf) return false; memcpy(cur, path, len); cur += len; *cur++ = '.'; len = ext ? strlen(ext) : 0; memcpy(cur, ext, len); cur += len; *cur++ = '\0'; memcpy(buf, tmp, cur - tmp); return true; } bool yy_path_remove_ext(char *buf, const char *path) { usize len = path ? strlen(path) : 0; if (!buf) return false; memmove(buf, path, len + 1); for (char *cur = buf + len; cur >= buf; cur--) { if (*cur == YY_DIR_SEPARATOR) break; if (*cur == '.') { *cur = '\0'; return true; } } return false; } bool yy_path_get_ext(char *buf, const char *path) { usize len = path ? strlen(path) : 0; if (!buf) return false; for (const char *cur = path + len; cur >= path; cur--) { if (*cur == YY_DIR_SEPARATOR) break; if (*cur == '.') { memmove(buf, cur + 1, len - (cur - path)); return true; } } *buf = '\0'; return false; } bool yy_path_exist(const char *path) { if (!path || !strlen(path)) return false; #ifdef _WIN32 DWORD attrs = GetFileAttributesA(path); return attrs != INVALID_FILE_ATTRIBUTES; #else struct stat attr; if (stat(path, &attr) != 0) return false; return true; #endif } bool yy_path_is_dir(const char *path) { if (!path || !strlen(path)) return false; #ifdef _WIN32 DWORD attrs = GetFileAttributesA(path); return (attrs & FILE_ATTRIBUTE_DIRECTORY) != 0; #else struct stat attr; if (stat(path, &attr) != 0) return false; return S_ISDIR(attr.st_mode); #endif } static int strcmp_func(void const *a, void const *b) { char const *astr = *(char const **)a; char const *bstr = *(char const **)b; return strcmp(astr, bstr); } char **yy_dir_read_opts(const char *path, int *count, bool full) { #ifdef _WIN32 struct _finddata_t entry; intptr_t handle; int idx = 0, alc = 0; char **names = NULL, **names_tmp, *search; usize path_len = path ? strlen(path) : 0; if (count) *count = 0; if (path_len == 0) return NULL; search = malloc(path_len + 3); if (!search) return NULL; memcpy(search, path, path_len); if (search[path_len - 1] == '\\') path_len--; memcpy(search + path_len, "\\*\0", 3); handle = _findfirst(search, &entry); if (handle == -1) goto fail; alc = 4; names = malloc(alc * sizeof(char*)); if (!names) goto fail; do { char *name = (char *)entry.name; if (!name || !strlen(name)) continue; if (strcmp(name, ".") == 0 || strcmp(name, "..") == 0) continue; name = _strdup(name); if (!name) goto fail; if (idx + 1 >= alc) { alc *= 2; names_tmp = realloc(names, alc * sizeof(char*)); if (!names_tmp) goto fail; names = names_tmp; } if (full) { char *fullpath = malloc(strlen(path) + strlen(name) + 4); if (!fullpath) goto fail; yy_path_combine(fullpath, path, name, NULL); free(name); if (fullpath) name = fullpath; else break; } names[idx] = name; idx++; } while (_findnext(handle, &entry) == 0); _findclose(handle); if (idx > 1) qsort(names, idx, sizeof(char *), strcmp_func); names[idx] = NULL; if (count) *count = idx; return names; fail: if (handle != -1)_findclose(handle); if (search) free(search); if (names) free(names); return NULL; #else DIR *dir = NULL; struct dirent *entry; int idx = 0, alc = 0; char **names = NULL, **names_tmp; if (count) *count = 0; if (!path || !strlen(path) || !(dir = opendir(path))) { goto fail; } alc = 4; names = calloc(1, alc * sizeof(char *)); if (!names) goto fail; while ((entry = readdir(dir))) { char *name = (char *)entry->d_name; if (!name || !strlen(name)) continue; if (strcmp(name, ".") == 0 || strcmp(name, "..") == 0) continue; if (idx + 1 >= alc) { alc *= 2; names_tmp = realloc(names, alc * sizeof(char *)); if (!names_tmp) goto fail; names = names_tmp; } name = strdup(name); if (!name) goto fail; if (full) { char *fullpath = malloc(strlen(path) + strlen(name) + 4); if (!fullpath) goto fail; yy_path_combine(fullpath, path, name, NULL); free(name); if (fullpath) name = fullpath; else break; } names[idx] = name; idx++; } closedir(dir); if (idx > 1) qsort(names, idx, sizeof(char *), strcmp_func); names[idx] = NULL; if (count) *count = idx; return names; fail: if (dir) closedir(dir); yy_dir_free(names); return NULL; #endif } char **yy_dir_read(const char *path, int *count) { return yy_dir_read_opts(path, count, false); } char **yy_dir_read_full(const char *path, int *count) { return yy_dir_read_opts(path, count, true); } void yy_dir_free(char **names) { if (names) { for (int i = 0; ; i++) { if (names[i]) free(names[i]); else break; } free(names); } } bool yy_file_read(const char *path, u8 **dat, usize *len) { return yy_file_read_with_padding(path, dat, len, 1); // for string } bool yy_file_read_with_padding(const char *path, u8 **dat, usize *len, usize padding) { if (!path || !strlen(path)) return false; if (!dat || !len) return false; FILE *file = NULL; #if _MSC_VER >= 1400 if (fopen_s(&file, path, "rb") != 0) return false; #else file = fopen(path, "rb"); #endif if (file == NULL) return false; if (fseek(file, 0, SEEK_END) != 0) { fclose(file); return false; } long file_size = ftell(file); if (file_size < 0) { fclose(file); return false; } if (fseek(file, 0, SEEK_SET) != 0) { fclose(file); return false; } void *buf = malloc((usize)file_size + padding); if (buf == NULL) { fclose(file); return false; } if (file_size > 0) { #if _MSC_VER >= 1400 if (fread_s(buf, file_size, file_size, 1, file) != 1) { free(buf); fclose(file); return false; } #else if (fread(buf, file_size, 1, file) != 1) { free(buf); fclose(file); return false; } #endif } fclose(file); memset((char *)buf + file_size, 0, padding); *dat = (u8 *)buf; *len = (usize)file_size; return true; } bool yy_file_write(const char *path, u8 *dat, usize len) { if (!path || !strlen(path)) return false; if (len && !dat) return false; FILE *file = NULL; #if _MSC_VER >= 1400 if (fopen_s(&file, path, "wb") != 0) return false; #else file = fopen(path, "wb"); #endif if (file == NULL) return false; if (fwrite(dat, len, 1, file) != 1) { fclose(file); return false; } if (fclose(file) != 0) { file = NULL; return false; } return true; } bool yy_file_delete(const char *path) { if (!path || !*path) return false; return remove(path) == 0; } /*============================================================================== * String Utils *============================================================================*/ char *yy_str_copy(const char *str) { if (!str) return NULL; usize len = strlen(str) + 1; char *dup = malloc(len); if (dup) memcpy(dup, str, len); return dup; } bool yy_str_contains(const char *str, const char *search) { if (!str || !search) return false; return strstr(str, search) != NULL; } bool yy_str_has_prefix(const char *str, const char *prefix) { if (!str || !prefix) return false; usize len1 = strlen(str); usize len2 = strlen(prefix); if (len2 > len1) return false; return memcmp(str, prefix, len2) == 0; } bool yy_str_has_suffix(const char *str, const char *suffix) { if (!str || !suffix) return false; usize len1 = strlen(str); usize len2 = strlen(suffix); if (len2 > len1) return false; return memcmp(str + (len1 - len2), suffix, len2) == 0; } /*============================================================================== * Memory Buffer *============================================================================*/ bool yy_buf_init(yy_buf *buf, usize len) { if (!buf) return false; if (len < 16) len = 16; memset(buf, 0, sizeof(yy_buf)); buf->hdr = malloc(len); if (!buf->hdr) return false; buf->cur = buf->hdr; buf->end = buf->hdr + len; buf->need_free = true; return true; } void yy_buf_release(yy_buf *buf) { if (!buf || !buf->hdr) return; if (buf->need_free) free(buf->hdr); memset(buf, 0, sizeof(yy_buf)); } usize yy_buf_len(yy_buf *buf) { if (!buf) return 0; return buf->cur - buf->hdr; } bool yy_buf_grow(yy_buf *buf, usize len) { if (!buf) return false; if ((usize)(buf->end - buf->cur) >= len) return true; if (!buf->hdr) return yy_buf_init(buf, len); usize use = buf->cur - buf->hdr; usize alc = buf->end - buf->hdr; do { if (alc * 2 < alc) return false; /* overflow */ alc *= 2; } while (alc - use < len); u8 *tmp = (u8 *)realloc(buf->hdr, alc); if (!tmp) return false; buf->cur = tmp + (buf->cur - buf->hdr); buf->hdr = tmp; buf->end = tmp + alc; return true; } bool yy_buf_append(yy_buf *buf, u8 *dat, usize len) { if (!buf) return false; if (len == 0) return true; if (!dat) return false; if (!yy_buf_grow(buf, len)) return false; memcpy(buf->cur, dat, len); buf->cur += len; return true; } /*============================================================================== * String Builder *============================================================================*/ bool yy_sb_init(yy_sb *sb, usize len) { return yy_buf_init(sb, len); } void yy_sb_release(yy_sb *sb) { yy_buf_release(sb); } usize yy_sb_get_len(yy_sb *sb) { if (!sb) return 0; return sb->cur - sb->hdr; } char *yy_sb_get_str(yy_sb *sb) { if (!sb || !sb->hdr) return NULL; if (sb->cur >= sb->end) { if (!yy_buf_grow(sb, 1)) return NULL; } *sb->cur = '\0'; return (char *)sb->hdr; } char *yy_sb_copy_str(yy_sb *sb, usize *len) { if (!sb || !sb->hdr) return NULL; usize sb_len = sb->cur - sb->hdr; char *str = (char *)malloc(sb_len + 1); if (!str) return NULL; memcpy(str, sb->hdr, sb_len); str[sb_len] = '\0'; if (len) *len = sb_len; return str; } bool yy_sb_append(yy_sb *sb, const char *str) { if (!str) return false; usize len = strlen(str); if (!yy_buf_grow(sb, len + 1)) return false; memcpy(sb->cur, str, len); sb->cur += len; return true; } bool yy_sb_append_html(yy_sb *sb, const char *str) { if (!sb || !str) return false; const char *cur = str; usize hdr_pos = sb->cur - sb->hdr; while (true) { usize esc_len; const char *esc; if (*cur == '\0') break; switch (*cur) { case '"': esc = "&quot;"; esc_len = 6; break; case '&': esc = "&amp;"; esc_len = 5; break; case '\'': esc = "&#39;"; esc_len = 5; break; case '<': esc = "&lt;"; esc_len = 4; break; case '>': esc = "&gt;"; esc_len = 4; break; default: esc = NULL; esc_len = 0; break; } if (esc_len) { usize len = cur - str; if (!yy_buf_grow(sb, len + esc_len + 1)) { sb->cur = sb->hdr + hdr_pos; return false; } memcpy(sb->cur, str, len); sb->cur += len; memcpy(sb->cur, esc, esc_len); sb->cur += esc_len; str = cur + 1; } cur++; } if (cur != str) { if (!yy_sb_append(sb, str)) { sb->cur = sb->hdr + hdr_pos; return false; } } return true; } bool yy_sb_append_esc(yy_sb *sb, char esc, const char *str) { if (!sb || !str) return false; const char *cur = str; usize hdr_pos = sb->cur - sb->hdr; while (true) { char c = *cur; if (c == '\0') break; if (c == '\\') { if (*(cur++) == '\0') break; else continue; } if (c == esc) { usize len = cur - str + 2; if (!yy_buf_grow(sb, len + 1)) { sb->cur = sb->hdr + hdr_pos; return false; } memcpy(sb->cur, str, len - 2); sb->cur[len - 2] = '\\'; sb->cur[len - 1] = esc; sb->cur += len; str = cur + 1; } cur++; } if (cur != str) { if (!yy_sb_append(sb, str)) { sb->cur = sb->hdr + hdr_pos; return false; } } return true; } bool yy_sb_printf(yy_sb *sb, const char *fmt, ...) { if (!sb || !fmt) return false; usize incr_size = 64; int len = 0; do { if (!yy_buf_grow(sb, incr_size + 1)) return false; va_list args; va_start(args, fmt); len = vsnprintf((char *)sb->cur, incr_size, fmt, args); va_end(args); if (len < 0) return false; /* error */ if ((usize)len < incr_size) break; /* success */ if (incr_size * 2 < incr_size) return false; /* overflow */ incr_size *= 2; } while (true); sb->cur += len; return true; } /*============================================================================== * Data Reader *============================================================================*/ bool yy_dat_init_with_file(yy_dat *dat, const char *path) { u8 *mem; usize len; if (!dat) return false; memset(dat, 0, sizeof(yy_dat)); if (!yy_file_read(path, &mem, &len)) return false; dat->hdr = mem; dat->cur = mem; dat->end = mem + len; dat->need_free = true; return true; } bool yy_dat_init_with_mem(yy_dat *dat, u8 *mem, usize len) { if (!dat) return false; if (len && !mem) return false; dat->hdr = mem; dat->cur = mem; dat->end = mem + len; dat->need_free = false; return true; } void yy_dat_release(yy_dat *dat) { yy_buf_release(dat); } void yy_dat_reset(yy_dat *dat) { if (dat) dat->cur = dat->hdr; } char *yy_dat_read_line(yy_dat *dat, usize *len) { if (len) *len = 0; if (!dat || dat->cur >= dat->end) return NULL; u8 *str = dat->cur; u8 *cur = dat->cur; u8 *end = dat->end; while (cur < end && *cur != '\r' && *cur != '\n' && *cur != '\0') cur++; if (len) *len = cur - str; if (cur < end) { if (cur + 1 < end && *cur == '\r' && cur[1] == '\n') cur += 2; else if (*cur == '\r' || *cur == '\n' || *cur == '\0') cur++; } dat->cur = cur; return (char *)str; } char *yy_dat_copy_line(yy_dat *dat, usize *len) { if (len) *len = 0; usize _len; char *_str = yy_dat_read_line(dat, &_len); if (!_str) return NULL; char *str = malloc(_len + 1); if (!str) return NULL; memcpy(str, _str, _len); str[_len] = '\0'; if (len) *len = _len; return str; }
14,729
377
// Copyright (C) 2018-2019 The DMLab2D 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. // //////////////////////////////////////////////////////////////////////////////// #include "dmlab2d/lib/env_lua_api/events.h" #include <utility> #include "dmlab2d/lib/lua/class.h" #include "dmlab2d/lib/lua/lua.h" #include "dmlab2d/lib/lua/read.h" #include "dmlab2d/lib/support/logging.h" #include "dmlab2d/lib/system/tensor/lua/tensor.h" #include "dmlab2d/lib/system/tensor/tensor_view.h" namespace deepmind::lab2d { namespace { class LuaEventsModule : public lua::Class<LuaEventsModule> { friend class Class; static const char* ClassName() { return "deepmind.lab.Events"; } public: // '*ctx' owned by the caller and should out-live this object. explicit LuaEventsModule(Events* ctx) : ctx_(ctx) {} // Registers classes metatable with Lua. static void Register(lua_State* L) { const Class::Reg methods[] = {{"add", Member<&LuaEventsModule::Add>}}; Class::Register(L, methods); } private: template <typename T> void AddTensorObservation(int id, const tensor::TensorView<T>& view) { const auto& shape = view.shape(); std::vector<int> out_shape(shape.begin(), shape.end()); std::vector<T> out_values; out_values.reserve(view.num_elements()); view.ForEach([&out_values](T v) { out_values.push_back(v); }); ctx_->AddObservation(id, std::move(out_shape), std::move(out_values)); } // Signature events:add(eventName, [obs1, [obs2 ...] ...]) // Called with an event name and a list of observations. Each observation // maybe one of string, ByteTensor, Int32Tensor, Int64Tensor or DoubleTensor. // [-(2 + #observations), 0, e] lua::NResultsOr Add(lua_State* L) { int top = lua_gettop(L); std::string name; if (!lua::Read(L, 2, &name)) { return "Event name must be a string"; } int id = ctx_->Add(std::move(name)); for (int i = 3; i <= top; ++i) { std::string string_arg; if (lua::Read(L, i, &string_arg)) { ctx_->AddObservation(id, std::move(string_arg)); } else if (auto* double_tensor = tensor::LuaTensor<double>::ReadObject(L, i)) { AddTensorObservation(id, double_tensor->tensor_view()); } else if (auto* byte_tensor = tensor::LuaTensor<unsigned char>::ReadObject(L, i)) { AddTensorObservation(id, byte_tensor->tensor_view()); } else if (auto* int32_tensor = tensor::LuaTensor<int32_t>::ReadObject(L, i)) { AddTensorObservation(id, int32_tensor->tensor_view()); } else if (auto* int64_tensor = tensor::LuaTensor<int64_t>::ReadObject(L, i)) { AddTensorObservation(id, int64_tensor->tensor_view()); } else if (lua_isnumber(L, i)) { ctx_->AddObservation(id, {}, std::vector<double>{lua_tonumber(L, i)}); } else { return "[event] - Observation type not supported. Must be one of " "string|ByteTensor|DoubleTensor."; } } return 0; } Events* ctx_; }; } // namespace lua::NResultsOr Events::Module(lua_State* L) { if (auto* ctx = static_cast<Events*>(lua_touserdata(L, lua_upvalueindex(1)))) { LuaEventsModule::Register(L); LuaEventsModule::CreateObject(L, ctx); return 1; } else { return "Missing Event context!"; } } int Events::Add(std::string name) { auto iter_inserted = name_to_id_.emplace(std::move(name), names_.size()); if (iter_inserted.second) { names_.push_back(iter_inserted.first->first.c_str()); } int id = events_.size(); events_.push_back(Event{iter_inserted.first->second}); return id; } void Events::AddObservation(int event_id, std::string string_value) { Event& event = events_[event_id]; event.observations.emplace_back(); auto& observation = event.observations.back(); observation.type = EnvCApi_ObservationString; observation.shape_id = shapes_.size(); std::vector<int> shape(1); shape[0] = string_value.size(); shapes_.emplace_back(std::move(shape)); observation.array_id = strings_.size(); strings_.push_back(std::move(string_value)); } void Events::AddObservation(int event_id, std::vector<int> shape, std::vector<double> double_tensor) { Event& event = events_[event_id]; event.observations.emplace_back(); auto& observation = event.observations.back(); observation.type = EnvCApi_ObservationDoubles; observation.shape_id = shapes_.size(); shapes_.push_back(std::move(shape)); observation.array_id = doubles_.size(); doubles_.push_back(std::move(double_tensor)); } void Events::AddObservation(int event_id, std::vector<int> shape, std::vector<unsigned char> byte_tensor) { Event& event = events_[event_id]; event.observations.emplace_back(); auto& observation = event.observations.back(); observation.type = EnvCApi_ObservationBytes; observation.shape_id = shapes_.size(); shapes_.push_back(std::move(shape)); observation.array_id = bytes_.size(); bytes_.push_back(std::move(byte_tensor)); } void Events::AddObservation(int event_id, std::vector<int> shape, std::vector<std::int32_t> int32_tensor) { Event& event = events_[event_id]; event.observations.emplace_back(); auto& observation = event.observations.back(); observation.type = EnvCApi_ObservationInt32s; observation.shape_id = shapes_.size(); shapes_.push_back(std::move(shape)); observation.array_id = int32s_.size(); int32s_.push_back(std::move(int32_tensor)); } void Events::AddObservation(int event_id, std::vector<int> shape, std::vector<std::int64_t> int64_tensor) { Event& event = events_[event_id]; event.observations.emplace_back(); auto& observation = event.observations.back(); observation.type = EnvCApi_ObservationInt64s; observation.shape_id = shapes_.size(); shapes_.push_back(std::move(shape)); observation.array_id = int64s_.size(); int64s_.push_back(std::move(int64_tensor)); } void Events::Clear() { events_.clear(); strings_.clear(); shapes_.clear(); doubles_.clear(); bytes_.clear(); int32s_.clear(); int64s_.clear(); } void Events::Export(int event_idx, EnvCApi_Event* event) { const auto& internal_event = events_[event_idx]; observations_.clear(); observations_.reserve(internal_event.observations.size()); for (const auto& observation : internal_event.observations) { observations_.emplace_back(); auto& observation_out = observations_.back(); observation_out.spec.type = observation.type; const auto& shape = shapes_[observation.shape_id]; observation_out.spec.dims = shape.size(); observation_out.spec.shape = shape.data(); switch (observation.type) { case EnvCApi_ObservationBytes: { const auto& tensor = bytes_[observation.array_id]; observation_out.payload.bytes = tensor.data(); break; } case EnvCApi_ObservationDoubles: { const auto& tensor = doubles_[observation.array_id]; observation_out.payload.doubles = tensor.data(); break; } case EnvCApi_ObservationString: { const auto& string_value = strings_[observation.array_id]; observation_out.payload.string = string_value.c_str(); break; } case EnvCApi_ObservationInt32s: { const auto& tensor = int32s_[observation.array_id]; observation_out.payload.int32s = tensor.data(); break; } case EnvCApi_ObservationInt64s: { const auto& tensor = int64s_[observation.array_id]; observation_out.payload.int64s = tensor.data(); break; } default: LOG(FATAL) << "Observation type: " << observation.type << " not supported"; } } event->id = internal_event.type_id; event->observations = observations_.data(); event->observation_count = observations_.size(); } } // namespace deepmind::lab2d
3,305
4,518
<gh_stars>1000+ from socket import * import time serverName = '192.168.3.11' # 服务器地址,本例中使用一台远程主机 serverPort = 12000 # 服务器指定的端口 clientSocket = socket(AF_INET, SOCK_DGRAM) # 创建UDP套接字,使用IPv4协议 clientSocket.settimeout(1) # 设置套接字超时值1秒 for i in range(0, 10): sendTime = time.time() message = ('Ping %d %s' % (i+1, sendTime)).encode() # 生成数据报,编码为bytes以便发送 try: clientSocket.sendto(message, (serverName, serverPort)) # 将信息发送到服务器 modifiedMessage, serverAddress = clientSocket.recvfrom(1024) # 从服务器接收信息,同时也能得到服务器地址 rtt = time.time() - sendTime # 计算往返时间 print('Sequence %d: Reply from %s RTT = %.3fs' % (i+1, serverName, rtt)) # 显示信息 except Exception as e: print('Sequence %d: Request timed out' % (i+1)) clientSocket.close() # 关闭套接字
487
1,437
import argparse import better_exceptions import sys import time from pathlib import Path import zipfile import bz2 import urllib.request import dlib import cv2 zip_names = ["train_1.zip", "train_2.zip", "train_gt.zip", "valid.zip", "valid_gt.zip"] urls = ["http://***/train_1.zip", "http://***/train_2.zip", "http://***/train_gt.zip", "http://***/valid.zip", "http://***/valid_gt.zip"] gt_pwd = b"***" dataset_root = Path(__file__).resolve().parent.joinpath("dataset") model_root = Path(__file__).resolve().parent.joinpath("model") train_image_dir = dataset_root.joinpath("train_images") validation_image_dir = dataset_root.joinpath("validation_images") train_crop_dir = dataset_root.joinpath("train_crop") validation_crop_dir = dataset_root.joinpath("validation_crop") def get_args(): parser = argparse.ArgumentParser(description="This script downloads the LAP dataset " "and preprocess for training and evaluation", formatter_class=argparse.ArgumentDefaultsHelpFormatter) subparsers = parser.add_subparsers(help="subcommands", dest="subcommand") subparsers.add_parser("download", help="Downdload the LAP dataset") subparsers.add_parser("extract", help="Unzip the LAP dataset") subparsers.add_parser("crop", help="Crop face regions using dlib") args = parser.parse_args() return parser, args def reporthook(count, block_size, total_size): global start_time if count == 0: start_time = time.time() return duration = int(time.time() - start_time) current_size = count * block_size remaining_size = total_size - current_size speed = int(current_size / (1024 * duration + 1)) percent = min(int(count * block_size * 100 / total_size), 100) remaining_time = int(duration * (remaining_size / current_size)) sys.stdout.write("\r{}%, {:6.2f}/{:6.2f}MB, {}KB/s, passed: {}s, remaining: {}s".format( percent, current_size / (1024 * 1024), total_size / (1024 * 1024), speed, duration, remaining_time)) sys.stdout.flush() def download(): dataset_root.mkdir(parents=True, exist_ok=True) # requires Python 3.5 or above for zip_name, url in zip(zip_names, urls): print("downloading {}".format(zip_name)) local_path = dataset_root.joinpath(zip_name) urllib.request.urlretrieve(url, str(local_path), reporthook) def crop(): detector_model_path = model_root.joinpath("mmod_human_face_detector.dat") if not detector_model_path.is_file(): model_root.mkdir(parents=True, exist_ok=True) # requires Python 3.5 or above detector_model_url = "http://dlib.net/files/mmod_human_face_detector.dat.bz2" detector_model_bz2 = str(detector_model_path) + ".bz2" print("downloading {}".format(detector_model_path.name)) urllib.request.urlretrieve(detector_model_url, detector_model_bz2, reporthook) with open(detector_model_bz2, "rb") as source, open(str(detector_model_path), "wb") as dest: dest.write(bz2.decompress(source.read())) detector = dlib.cnn_face_detection_model_v1(str(detector_model_path)) for image_dir, crop_dir in [[train_image_dir, train_crop_dir], [validation_image_dir, validation_crop_dir]]: for image_path in image_dir.glob("*.jpg"): frame = cv2.imread(str(image_path)) img_h, img_w, _ = frame.shape factor = 800 / max(img_h, img_w) frame_resized = cv2.resize(frame, None, fx=factor, fy=factor) frame_rgb = cv2.cvtColor(frame_resized, cv2.COLOR_BGR2RGB) dets = detector(frame_rgb, 1) if len(dets) != 1: print("{} faces were detected for {}".format(len(dets), image_path.name)) rects = [[d.rect.left(), d.rect.right(), d.rect.top(), d.rect.bottom()] for d in dets] print(rects) def extract(): for zip_name in zip_names: zip_path = dataset_root.joinpath(zip_name) password = <PASSWORD> if not zip_path.is_file(): raise RuntimeError("{} was not found. Please download the LAP dataset.".format(zip_name)) with zipfile.ZipFile(str(zip_path), "r") as f: if zip_name in ["train_1.zip", "train_2.zip"]: extract_path = train_image_dir elif zip_name == "valid.zip": extract_path = validation_image_dir else: extract_path = dataset_root if zip_name == "valid_gt.zip": password = <PASSWORD> extract_path.mkdir(parents=True, exist_ok=True) # requires Python 3.5 or above f.extractall(path=str(extract_path), pwd=password) def main(): parser, args = get_args() if args.subcommand == "download": download() elif args.subcommand == "extract": extract() elif args.subcommand == "crop": crop() else: parser.print_help() if __name__ == '__main__': main()
2,184
392
package jetbrick.template.exec.directive; import jetbrick.template.exec.AbstractJetxTest; import org.junit.Assert; import org.junit.Test; public class DirectiveIfTest extends AbstractJetxTest { @Test public void testIf() { Assert.assertEquals("a", eval("#if(true)a#end")); Assert.assertEquals("", eval("#if(false)a#end")); } @Test public void testElseIf() { Assert.assertEquals("1", eval("#set(i=1)#if(i==0)0#elseif(i==1)1#elseif(i==2)2#end")); Assert.assertEquals("9", eval("#set(i=3)#if(i==0)0#elseif(i==1)1#else()9#end")); } @Test public void testElse() { Assert.assertEquals("a", eval("#if(true)a#else()b#end")); Assert.assertEquals("b", eval("#if(false)a#else()b#end")); } }
358
348
<gh_stars>100-1000 {"nom":"Courtagnon","circ":"3ème circonscription","dpt":"Marne","inscrits":50,"abs":12,"votants":38,"blancs":5,"nuls":1,"exp":32,"res":[{"nuance":"REM","nom":"M. <NAME>","voix":28},{"nuance":"FN","nom":"<NAME>","voix":4}]}
99
11,024
/* * QuietDatabase.h * * This source file is part of the FoundationDB open source project * * Copyright 2013-2018 Apple Inc. and the FoundationDB project authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef FDBSERVER_QUIETDATABASE_H #define FDBSERVER_QUIETDATABASE_H #pragma once #include "fdbclient/NativeAPI.actor.h" #include "fdbclient/DatabaseContext.h" // for clone() #include "fdbserver/TesterInterface.actor.h" #include "fdbserver/WorkerInterface.actor.h" #include "flow/actorcompiler.h" Future<int64_t> getDataInFlight(Database const& cx, Reference<AsyncVar<struct ServerDBInfo> const> const&); Future<std::pair<int64_t, int64_t>> getTLogQueueInfo(Database const& cx, Reference<AsyncVar<struct ServerDBInfo> const> const&); Future<int64_t> getMaxStorageServerQueueSize(Database const& cx, Reference<AsyncVar<struct ServerDBInfo> const> const&); Future<int64_t> getDataDistributionQueueSize(Database const& cx, Reference<AsyncVar<struct ServerDBInfo> const> const&, bool const& reportInFlight); Future<bool> getTeamCollectionValid(Database const& cx, WorkerInterface const&); Future<bool> getTeamCollectionValid(Database const& cx, Reference<AsyncVar<struct ServerDBInfo> const> const&); Future<std::vector<StorageServerInterface>> getStorageServers(Database const& cx, bool const& use_system_priority = false); Future<std::vector<BlobWorkerInterface>> getBlobWorkers(Database const& cx, bool const& use_system_priority = false); Future<std::vector<WorkerDetails>> getWorkers(Reference<AsyncVar<ServerDBInfo> const> const& dbInfo, int const& flags = 0); Future<WorkerInterface> getMasterWorker(Database const& cx, Reference<AsyncVar<ServerDBInfo> const> const& dbInfo); Future<Void> repairDeadDatacenter(Database const& cx, Reference<AsyncVar<ServerDBInfo> const> const& dbInfo, std::string const& context); Future<std::vector<WorkerInterface>> getStorageWorkers(Database const& cx, Reference<AsyncVar<ServerDBInfo> const> const& dbInfo, bool const& localOnly); Future<std::vector<WorkerInterface>> getCoordWorkers(Database const& cx, Reference<AsyncVar<ServerDBInfo> const> const& dbInfo); #include "flow/unactorcompiler.h" #endif
1,265
317
/* SUBWIN.f -- translated by f2c (version 19970805). You must link the resulting object file with the libraries: -lf2c -lm (in that order) */ #ifdef __cplusplus extern "C" { #endif /* OTB patches: replace "f2c.h" by "otb_6S.h" */ /*#include "f2c.h"*/ #include "otb_6S.h" /* Common Block Declarations */ Extern struct { doublereal z__[34], p[34], t[34], wh[34], wo[34]; } sixs_atm__; #define sixs_atm__1 sixs_atm__ /*< subroutine subwin >*/ /* Subroutine */ int subwin_() { /* Initialized data */ static doublereal z5[34] = { 0.,1.,2.,3.,4.,5.,6.,7.,8.,9.,10.,11.,12., 13.,14.,15.,16.,17.,18.,19.,20.,21.,22.,23.,24.,25.,30.,35.,40., 45.,50.,70.,100.,99999. }; static doublereal p5[34] = { 1013.,887.8,777.5,679.8,593.2,515.8,446.7, 385.3,330.8,282.9,241.8,206.7,176.6,151.,129.1,110.3,94.31,80.58, 68.82,58.75,50.14,42.77,36.47,31.09,26.49,22.56,10.2,4.701,2.243, 1.113,.5719,.04016,3e-4,0. }; static doublereal t5[34] = { 257.1,259.1,255.9,252.7,247.7,240.9,234.1, 227.3,220.6,217.2,217.2,217.2,217.2,217.2,217.2,217.2,216.6,216., 215.4,214.8,214.1,213.6,213.,212.4,211.8,211.2,216.,222.2,234.7, 247.,259.3,245.7,210.,210. }; static doublereal wh5[34] = { 1.2,1.2,.94,.68,.41,.2,.098,.054,.011,.0084, .0055,.0038,.0026,.0018,.001,7.6e-4,6.4e-4,5.6e-4,5e-4,4.9e-4, 4.5e-4,5.1e-4,5.1e-4,5.4e-4,6e-4,6.7e-4,3.6e-4,1.1e-4,4.3e-5, 1.9e-5,6.3e-6,1.4e-7,1e-9,0. }; static doublereal wo5[34] = { 4.1e-5,4.1e-5,4.1e-5,4.3e-5,4.5e-5,4.7e-5, 4.9e-5,7.1e-5,9e-5,1.6e-4,2.4e-4,3.2e-4,4.3e-4,4.7e-4,4.9e-4, 5.6e-4,6.2e-4,6.2e-4,6.2e-4,6e-4,5.6e-4,5.1e-4,4.7e-4,4.3e-4, 3.6e-4,3.2e-4,1.5e-4,9.2e-5,4.1e-5,1.3e-5,4.3e-6,8.6e-8,4.3e-11, 0. }; integer i__; /*< real z5(34),p5(34),t5(34),wh5(34),wo5(34) >*/ /*< real z,p,t,wh,wo >*/ /*< common /sixs_atm/z(34),p(34),t(34),wh(34),wo(34) >*/ /*< integer i >*/ /* model: subarctique winter mc clatchey */ /*< >*/ /*< >*/ /*< >*/ /*< >*/ /*< >*/ /*< do 1 i=1,34 >*/ for (i__ = 1; i__ <= 34; ++i__) { /*< z(i)=z5(i) >*/ sixs_atm__1.z__[i__ - 1] = z5[i__ - 1]; /*< p(i)=p5(i) >*/ sixs_atm__1.p[i__ - 1] = p5[i__ - 1]; /*< t(i)=t5(i) >*/ sixs_atm__1.t[i__ - 1] = t5[i__ - 1]; /*< wh(i)=wh5(i) >*/ sixs_atm__1.wh[i__ - 1] = wh5[i__ - 1]; /*< wo(i)=wo5(i) >*/ sixs_atm__1.wo[i__ - 1] = wo5[i__ - 1]; /*< 1 continue >*/ /* L1: */ } /*< return >*/ return 0; /*< end >*/ } /* subwin_ */ #ifdef __cplusplus } #endif
1,616
460
<filename>trunk/win/Source/Includes/QtIncludes/include/QtDeclarative/private/qdeclarativepropertychanges_p.h<gh_stars>100-1000 #include "../../../src/declarative/util/qdeclarativepropertychanges_p.h"
72
678
/* * Copyright (C) 2018 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.mthli.slice; import android.annotation.TargetApi; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.RectF; import android.os.Build; public class CustomRoundRectDrawableWithShadow extends RoundRectDrawableWithShadow { private boolean leftTopRect = false; private boolean rightTopRect = false; private boolean leftBottomRect = false; private boolean rightBottomRect = false; private boolean leftEdgeShadow = true; private boolean topEdgeShadow = true; private boolean rightEdgeShadow = true; private boolean bottomEdgeShadow = true; @TargetApi(Build.VERSION_CODES.KITKAT) public CustomRoundRectDrawableWithShadow(Resources resources, int backgroundColor, float radius, float shadowSize, float maxShadowSize) { super(resources, backgroundColor, radius, shadowSize, maxShadowSize); init(); } private void init() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { initJellyBeanMr1(); } else { initEclairMr1(); } } private void initJellyBeanMr1() { sRoundRectHelper = new RoundRectHelper() { @Override public void drawRoundRect(Canvas canvas, RectF bounds, float radius, Paint paint) { canvas.drawRoundRect(bounds, radius, radius, paint); } }; } private void initEclairMr1() { final RectF rectF = new RectF(); sRoundRectHelper = new RoundRectHelper() { @Override public void drawRoundRect(Canvas canvas, RectF bounds, float radius, Paint paint) { float innerWidth = bounds.width() - radius * 2.0f - 1.0f; float innerHeight = bounds.height() - radius * 2.0f - 1.0f; if (radius >= 1.0f) { radius += 0.5f; rectF.set(-radius, -radius, radius, radius); int saved = canvas.save(); canvas.translate(bounds.left + radius, bounds.top + radius); canvas.drawArc(rectF, 180.0f, 90.0f, true, paint); canvas.translate(innerWidth, 0); canvas.rotate(90.0f); canvas.drawArc(rectF, 180.0f, 90.0f, true, paint); canvas.translate(innerHeight, 0.0f); canvas.rotate(90.0f); canvas.drawArc(rectF, 180.0f, 90.0f, true, paint); canvas.translate(innerWidth, 0.0f); canvas.rotate(90.0f); canvas.drawArc(rectF, 180.0f, 90.0f, true, paint); canvas.restoreToCount(saved); canvas.drawRect( bounds.left + radius - 1.0f, bounds.top, bounds.right - radius + 1.0f, bounds.top + radius, paint ); canvas.drawRect( bounds.left + radius - 1.0f, bounds.bottom - radius + 1.0f, bounds.right - radius + 1.0f, bounds.bottom, paint ); } canvas.drawRect( bounds.left, bounds.top + Math.max(0.0f, radius - 1.0f), bounds.right, bounds.bottom - radius + 1.0f, paint ); } }; } @Override public void draw(Canvas canvas) { super.draw(canvas); if (leftTopRect) { canvas.drawRect(buildLeftTopRect(), mPaint); } if (rightTopRect) { canvas.drawRect(buildRightTopRect(), mPaint); } if (rightBottomRect) { canvas.drawRect(buildRightBottomRect(), mPaint); } if (leftBottomRect) { canvas.drawRect(buildLeftBottomRect(), mPaint); } } @Override protected void drawShadow(Canvas canvas) { float top = -mCornerRadius - mShadowSize; float inset = mCornerRadius + mInsetShadow + mRawShadowSize / 2.0f; boolean suggestHorizontal = mCardBounds.width() - inset * 2.0f > 0.0f; boolean suggestVertical = mCardBounds.height() - inset * 2.0f > 0.0f; drawLeftTopShadow(canvas, inset); drawRightTopShadow(canvas, inset); drawRightBottomShadow(canvas, inset); drawLeftBottomShadow(canvas, inset); drawLeftEdgeShadow(canvas, top, inset, suggestVertical); drawTopEdgeShadow(canvas, top, inset, suggestHorizontal); drawRightEdgeShadow(canvas, top, inset, suggestVertical); drawBottomEdgeShadow(canvas, top, inset, suggestHorizontal); } @Override protected void buildComponents(Rect bounds) { float vOffset = mRawMaxShadowSize * SHADOW_MULTIPLIER; float left = leftEdgeShadow ? bounds.left + mRawMaxShadowSize : bounds.left; float top = topEdgeShadow ? bounds.top + vOffset : bounds.top; float right = rightEdgeShadow ? bounds.right - mRawMaxShadowSize : bounds.right; float bottom = bottomEdgeShadow ? bounds.bottom - vOffset : bounds.bottom; mCardBounds.set(left, top, right, bottom); buildShadowCorners(); } private RectF buildLeftTopRect() { RectF rectF = new RectF(); rectF.left = mCardBounds.left; rectF.top = mCardBounds.top; rectF.right = mCardBounds.left + mCornerRadius * 2.0f; rectF.bottom = mCardBounds.top + mCornerRadius * 2.0f; return rectF; } private RectF buildRightTopRect() { RectF rectF = new RectF(); rectF.left = mCardBounds.right - mCornerRadius * 2.0f; rectF.top = mCardBounds.top; rectF.right = mCardBounds.right; rectF.bottom = mCardBounds.top + mCornerRadius * 2.0f; return rectF; } private RectF buildRightBottomRect() { RectF rectF = new RectF(); rectF.left = mCardBounds.right - mCornerRadius * 2.0f; rectF.top = mCardBounds.bottom - mCornerRadius * 2.0f; rectF.right = mCardBounds.right; rectF.bottom = mCardBounds.bottom; return rectF; } private RectF buildLeftBottomRect() { RectF rectF = new RectF(); rectF.left = mCardBounds.left; rectF.top = mCardBounds.bottom - mCornerRadius * 2.0f; rectF.right = mCardBounds.left + mCornerRadius * 2.0f; rectF.bottom = mCardBounds.bottom; return rectF; } private void drawLeftTopShadow(Canvas canvas, float inset) { if (!leftTopRect) { int saved = canvas.save(); canvas.translate(mCardBounds.left + inset, mCardBounds.top + inset); canvas.drawPath(mCornerShadowPath, mCornerShadowPaint); canvas.restoreToCount(saved); } } private void drawRightTopShadow(Canvas canvas, float inset) { if (!rightTopRect) { int saved = canvas.save(); canvas.translate(mCardBounds.right - inset, mCardBounds.top + inset); canvas.rotate(90.0f); canvas.drawPath(mCornerShadowPath, mCornerShadowPaint); canvas.restoreToCount(saved); } } private void drawRightBottomShadow(Canvas canvas, float inset) { if (!rightBottomRect) { int saved = canvas.save(); canvas.translate(mCardBounds.right - inset, mCardBounds.bottom - inset); canvas.rotate(180.0f); canvas.drawPath(mCornerShadowPath, mCornerShadowPaint); canvas.restoreToCount(saved); } } private void drawLeftBottomShadow(Canvas canvas, float inset) { if (!leftBottomRect) { int saved = canvas.save(); canvas.translate(mCardBounds.left + inset, mCardBounds.bottom - inset); canvas.rotate(270.0f); canvas.drawPath(mCornerShadowPath, mCornerShadowPaint); canvas.restoreToCount(saved); } } private void drawLeftEdgeShadow(Canvas canvas, float top, float inset, boolean suggest) { if (suggest && leftEdgeShadow) { int saved = canvas.save(); canvas.translate(mCardBounds.left + inset, mCardBounds.bottom - inset); canvas.rotate(270.0f); canvas.drawRect(0.0f, top, mCardBounds.height() - inset * 2.0f, -mCornerRadius, mEdgeShadowPaint); canvas.restoreToCount(saved); if (leftTopRect) { saved = canvas.save(); canvas.translate(mCardBounds.left + inset, mCardBounds.top + inset); canvas.rotate(270.0f); canvas.drawRect(0.0f, top, inset, -mCornerRadius, mEdgeShadowPaint); canvas.restoreToCount(saved); } if (leftBottomRect) { saved = canvas.save(); canvas.translate(mCardBounds.left + inset, mCardBounds.bottom); canvas.rotate(270.0f); canvas.drawRect(0.0f, top, inset, -mCornerRadius, mEdgeShadowPaint); canvas.restoreToCount(saved); } } } private void drawTopEdgeShadow(Canvas canvas, float top, float inset, boolean suggest) { if (suggest && topEdgeShadow) { int saved = canvas.save(); canvas.translate(mCardBounds.left + inset, mCardBounds.top + inset); canvas.drawRect(0, top, mCardBounds.width() - inset * 2.0f, -mCornerRadius, mEdgeShadowPaint); canvas.restoreToCount(saved); if (leftTopRect) { saved = canvas.save(); canvas.translate(mCardBounds.left, mCardBounds.top + inset); canvas.drawRect(0, top, inset, -mCornerRadius, mEdgeShadowPaint); canvas.restoreToCount(saved); } if (rightTopRect) { saved = canvas.save(); canvas.translate(mCardBounds.right - inset, mCardBounds.top + inset); canvas.drawRect(0, top, inset, -mCornerRadius, mEdgeShadowPaint); canvas.restoreToCount(saved); } } } private void drawRightEdgeShadow(Canvas canvas, float top, float inset, boolean suggest) { if (suggest && rightEdgeShadow) { int saved = canvas.save(); canvas.translate(mCardBounds.right - inset, mCardBounds.top + inset); canvas.rotate(90.0f); canvas.drawRect(0.0f, top, mCardBounds.height() - inset * 2.0f, -mCornerRadius, mEdgeShadowPaint); canvas.restoreToCount(saved); if (rightTopRect) { saved = canvas.save(); canvas.translate(mCardBounds.right - inset, mCardBounds.top); canvas.rotate(90.0f); canvas.drawRect(0.0f, top, inset, -mCornerRadius, mEdgeShadowPaint); canvas.restoreToCount(saved); } if (rightBottomRect) { saved = canvas.save(); canvas.translate(mCardBounds.right - inset, mCardBounds.bottom - inset); canvas.rotate(90.0f); canvas.drawRect(0.0f, top, inset, -mCornerRadius, mEdgeShadowPaint); canvas.restoreToCount(saved); } } } private void drawBottomEdgeShadow(Canvas canvas, float top, float inset, boolean suggest) { if (suggest && bottomEdgeShadow) { int saved = canvas.save(); canvas.translate(mCardBounds.right - inset, mCardBounds.bottom - inset); canvas.rotate(180.0f); canvas.drawRect(0.0f, top, mCardBounds.width() - inset * 2.0f, -mCornerRadius + mShadowSize, mEdgeShadowPaint); canvas.restoreToCount(saved); if (leftBottomRect) { saved = canvas.save(); canvas.translate(mCardBounds.left + inset, mCardBounds.bottom - inset); canvas.rotate(180.0f); canvas.drawRect(0.0f, top, inset, -mCornerRadius + mShadowSize, mEdgeShadowPaint); canvas.restoreToCount(saved); } if (rightBottomRect) { saved = canvas.save(); canvas.translate(mCardBounds.right, mCardBounds.bottom - inset); canvas.rotate(180.0f); canvas.drawRect(0.0f, top, inset, -mCornerRadius + mShadowSize, mEdgeShadowPaint); canvas.restoreToCount(saved); } } } public void setRadius(float radius) { super.setCornerRadius(radius); } @Override public void setShadowSize(float size) { super.setShadowSize(size, mRawMaxShadowSize); } @Override public void setColor(int color) { super.setColor(color); } public void showLeftTopRect(boolean show) { this.leftTopRect = show; invalidateSelf(); } public void showRightTopRect(boolean show) { this.rightTopRect = show; invalidateSelf(); } public void showRightBottomRect(boolean show) { this.rightBottomRect = show; invalidateSelf(); } public void showLeftBottomRect(boolean show) { this.leftBottomRect = show; invalidateSelf(); } public void showLeftEdgeShadow(boolean show) { this.leftEdgeShadow = show; invalidateSelf(); } public void showTopEdgeShadow(boolean show) { this.topEdgeShadow = show; invalidateSelf(); } public void showRightEdgeShadow(boolean show) { this.rightEdgeShadow = show; invalidateSelf(); } public void showBottomEdgeShadow(boolean show) { this.bottomEdgeShadow = show; invalidateSelf(); } }
6,943
14,668
<gh_stars>1000+ // Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef IOS_CHROME_BROWSER_UI_INCOGNITO_REAUTH_INCOGNITO_REAUTH_VIEW_H_ #define IOS_CHROME_BROWSER_UI_INCOGNITO_REAUTH_INCOGNITO_REAUTH_VIEW_H_ #import <UIKit/UIKit.h> // The view that is used to overlay over non-authorized incognito content. @interface IncognitoReauthView : UIView // Button that allows biometric authentication. // Will auto-adjust its string based on the available authentication methods on // the user's device. @property(nonatomic, strong, readonly) UIButton* authenticateButton; // The button to go to the tab switcher. @property(nonatomic, strong, readonly) UIButton* tabSwitcherButton; // The image view with the incognito logo. @property(nonatomic, strong, readonly) UIView* logoView; @end #endif // IOS_CHROME_BROWSER_UI_INCOGNITO_REAUTH_INCOGNITO_REAUTH_VIEW_H_
335
679
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_filter.hxx" #include "svgfontexport.hxx" #include "svgwriter.hxx" #include <vcl/unohelp.hxx> // ----------- // - statics - // ----------- static const char aXMLElemG[] = "g"; static const char aXMLElemDefs[] = "defs"; static const char aXMLElemLine[] = "line"; static const char aXMLElemRect[] = "rect"; static const char aXMLElemEllipse[] = "ellipse"; static const char aXMLElemPath[] = "path"; static const char aXMLElemPolygon[] = "polygon"; static const char aXMLElemPolyLine[] = "polyline"; static const char aXMLElemText[] = "text"; static const char aXMLElemTSpan[] = "tspan"; static const char aXMLElemImage[] = "image"; static const char aXMLElemLinearGradient[] = "linearGradient"; static const char aXMLElemRadialGradient[] = "radialGradient"; static const char aXMLElemStop[] = "stop"; // ----------------------------------------------------------------------------- static const char aXMLAttrTransform[] = "transform"; static const char aXMLAttrStyle[] = "style"; static const char aXMLAttrId[] = "id"; static const char aXMLAttrD[] = "d"; static const char aXMLAttrX[] = "x"; static const char aXMLAttrY[] = "y"; static const char aXMLAttrX1[] = "x1"; static const char aXMLAttrY1[] = "y1"; static const char aXMLAttrX2[] = "x2"; static const char aXMLAttrY2[] = "y2"; static const char aXMLAttrCX[] = "cx"; static const char aXMLAttrCY[] = "cy"; static const char aXMLAttrR[] = "r"; static const char aXMLAttrRX[] = "rx"; static const char aXMLAttrRY[] = "ry"; static const char aXMLAttrWidth[] = "width"; static const char aXMLAttrHeight[] = "height"; static const char aXMLAttrPoints[] = "points"; static const char aXMLAttrStroke[] = "stroke"; static const char aXMLAttrStrokeOpacity[] = "stroke-opacity"; static const char aXMLAttrStrokeWidth[] = "stroke-width"; static const char aXMLAttrStrokeDashArray[] = "stroke-dasharray"; static const char aXMLAttrFill[] = "fill"; static const char aXMLAttrFillOpacity[] = "fill-opacity"; static const char aXMLAttrFontFamily[] = "font-family"; static const char aXMLAttrFontSize[] = "font-size"; static const char aXMLAttrFontStyle[] = "font-style"; static const char aXMLAttrFontWeight[] = "font-weight"; static const char aXMLAttrTextDecoration[] = "text-decoration"; static const char aXMLAttrXLinkHRef[] = "xlink:href"; static const char aXMLAttrGradientUnits[] = "gradientUnits"; static const char aXMLAttrOffset[] = "offset"; static const char aXMLAttrStopColor[] = "stop-color"; // added support for LineJoin and LineCap static const char aXMLAttrStrokeLinejoin[] = "stroke-linejoin"; static const char aXMLAttrStrokeLinecap[] = "stroke-linecap"; // ----------------------------------------------------------------------------- static const sal_Unicode pBase64[] = { //0 1 2 3 4 5 6 7 'A','B','C','D','E','F','G','H', // 0 'I','J','K','L','M','N','O','P', // 1 'Q','R','S','T','U','V','W','X', // 2 'Y','Z','a','b','c','d','e','f', // 3 'g','h','i','j','k','l','m','n', // 4 'o','p','q','r','s','t','u','v', // 5 'w','x','y','z','0','1','2','3', // 6 '4','5','6','7','8','9','+','/' // 7 }; // ---------------------- // - SVGAttributeWriter - // ---------------------- SVGAttributeWriter::SVGAttributeWriter( SVGExport& rExport, SVGFontExport& rFontExport ) : mrExport( rExport ), mrFontExport( rFontExport ), mpElemFont( NULL ), mpElemPaint( NULL ) { } // ----------------------------------------------------------------------------- SVGAttributeWriter::~SVGAttributeWriter() { delete mpElemPaint; delete mpElemFont; } // ----------------------------------------------------------------------------- double SVGAttributeWriter::ImplRound( double fValue, sal_Int32 nDecs ) { return( floor( fValue * pow( 10.0, (int)nDecs ) + 0.5 ) / pow( 10.0, (int)nDecs ) ); } // ----------------------------------------------------------------------------- void SVGAttributeWriter::ImplGetColorStr( const Color& rColor, ::rtl::OUString& rColorStr ) { if( rColor.GetTransparency() == 255 ) rColorStr = B2UCONST( "none" ); else { rColorStr = B2UCONST( "rgb(" ); rColorStr += ::rtl::OUString::valueOf( static_cast< sal_Int32 >( rColor.GetRed() ) ); rColorStr += B2UCONST( "," ); rColorStr += ::rtl::OUString::valueOf( static_cast< sal_Int32 >( rColor.GetGreen() ) ); rColorStr += B2UCONST( "," ); rColorStr += ::rtl::OUString::valueOf( static_cast< sal_Int32 >( rColor.GetBlue() ) ); rColorStr += B2UCONST( ")" ); } } // ----------------------------------------------------------------------------- void SVGAttributeWriter::AddColorAttr( const char* pColorAttrName, const char* pColorOpacityAttrName, const Color& rColor ) { ::rtl::OUString aColor, aColorOpacity; ImplGetColorStr( rColor, aColor ); if( rColor.GetTransparency() > 0 && rColor.GetTransparency() < 255 ) aColorOpacity = ::rtl::OUString::valueOf( ImplRound( ( 255.0 - rColor.GetTransparency() ) / 255.0 ) ); mrExport.AddAttribute( XML_NAMESPACE_NONE, pColorAttrName, aColor ); if( aColorOpacity.getLength() && mrExport.IsUseOpacity() ) mrExport.AddAttribute( XML_NAMESPACE_NONE, pColorOpacityAttrName, aColorOpacity ); } // ----------------------------------------------------------------------------- void SVGAttributeWriter::AddPaintAttr( const Color& rLineColor, const Color& rFillColor, const Rectangle* pObjBoundRect, const Gradient* pFillGradient ) { // Fill if( pObjBoundRect && pFillGradient ) { ::rtl::OUString aGradientId; AddGradientDef( *pObjBoundRect, *pFillGradient, aGradientId ); if( aGradientId.getLength() ) { ::rtl::OUString aGradientURL( B2UCONST( "url(#" ) ); mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrFill, ( aGradientURL += aGradientId ) += B2UCONST( ")" ) ); } } else AddColorAttr( aXMLAttrFill, aXMLAttrFillOpacity, rFillColor ); // Stroke AddColorAttr( aXMLAttrStroke, aXMLAttrStrokeOpacity, rLineColor ); } // ----------------------------------------------------------------------------- void SVGAttributeWriter::AddGradientDef( const Rectangle& rObjRect, const Gradient& rGradient, ::rtl::OUString& rGradientId ) { if( rObjRect.GetWidth() && rObjRect.GetHeight() && ( rGradient.GetStyle() == GRADIENT_LINEAR || rGradient.GetStyle() == GRADIENT_AXIAL || rGradient.GetStyle() == GRADIENT_RADIAL || rGradient.GetStyle() == GRADIENT_ELLIPTICAL ) ) { SvXMLElementExport aDesc( mrExport, XML_NAMESPACE_NONE, aXMLElemDefs, sal_True, sal_True ); Color aStartColor( rGradient.GetStartColor() ), aEndColor( rGradient.GetEndColor() ); sal_uInt16 nAngle = rGradient.GetAngle() % 3600; Point aObjRectCenter( rObjRect.Center() ); Polygon aPoly( rObjRect ); static sal_Int32 nCurGradientId = 1; aPoly.Rotate( aObjRectCenter, nAngle ); Rectangle aRect( aPoly.GetBoundRect() ); // adjust start/end colors with intensities aStartColor.SetRed( (sal_uInt8)( ( (long) aStartColor.GetRed() * rGradient.GetStartIntensity() ) / 100 ) ); aStartColor.SetGreen( (sal_uInt8)( ( (long) aStartColor.GetGreen() * rGradient.GetStartIntensity() ) / 100 ) ); aStartColor.SetBlue( (sal_uInt8)( ( (long) aStartColor.GetBlue() * rGradient.GetStartIntensity() ) / 100 ) ); aEndColor.SetRed( (sal_uInt8)( ( (long) aEndColor.GetRed() * rGradient.GetEndIntensity() ) / 100 ) ); aEndColor.SetGreen( (sal_uInt8)( ( (long) aEndColor.GetGreen() * rGradient.GetEndIntensity() ) / 100 ) ); aEndColor.SetBlue( (sal_uInt8)( ( (long) aEndColor.GetBlue() * rGradient.GetEndIntensity() ) / 100 ) ); mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrId, ( rGradientId = B2UCONST( "Gradient_" ) ) += ::rtl::OUString::valueOf( nCurGradientId++ ) ); { ::std::auto_ptr< SvXMLElementExport > apGradient; ::rtl::OUString aColorStr; if( rGradient.GetStyle() == GRADIENT_LINEAR || rGradient.GetStyle() == GRADIENT_AXIAL ) { Polygon aLinePoly( 2 ); aLinePoly[ 0 ] = Point( aObjRectCenter.X(), aRect.Top() ); aLinePoly[ 1 ] = Point( aObjRectCenter.X(), aRect.Bottom() ); aLinePoly.Rotate( aObjRectCenter, nAngle ); mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrGradientUnits, B2UCONST( "userSpaceOnUse" ) ); mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrX1, ::rtl::OUString::valueOf( aLinePoly[ 0 ].X() ) ); mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrY1, ::rtl::OUString::valueOf( aLinePoly[ 0 ].Y() ) ); mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrX2, ::rtl::OUString::valueOf( aLinePoly[ 1 ].X() ) ); mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrY2, ::rtl::OUString::valueOf( aLinePoly[ 1 ].Y() ) ); apGradient.reset( new SvXMLElementExport( mrExport, XML_NAMESPACE_NONE, aXMLElemLinearGradient, sal_True, sal_True ) ); // write stop values double fBorder = static_cast< double >( rGradient.GetBorder() ) * ( ( rGradient.GetStyle() == GRADIENT_AXIAL ) ? 0.005 : 0.01 ); ImplGetColorStr( ( rGradient.GetStyle() == GRADIENT_AXIAL ) ? aEndColor : aStartColor, aColorStr ); mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrOffset, ::rtl::OUString::valueOf( fBorder ) ); mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrStopColor, aColorStr ); { SvXMLElementExport aDesc2( mrExport, XML_NAMESPACE_NONE, aXMLElemStop, sal_True, sal_True ); } if( rGradient.GetStyle() == GRADIENT_AXIAL ) { ImplGetColorStr( aStartColor, aColorStr ); mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrOffset, ::rtl::OUString::valueOf( 0.5 ) ); mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrStopColor, aColorStr ); { SvXMLElementExport aDesc3( mrExport, XML_NAMESPACE_NONE, aXMLElemStop, sal_True, sal_True ); } } if( rGradient.GetStyle() != GRADIENT_AXIAL ) fBorder = 0.0; ImplGetColorStr( aEndColor, aColorStr ); mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrOffset, ::rtl::OUString::valueOf( ImplRound( 1.0 - fBorder ) ) ); mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrStopColor, aColorStr ); { SvXMLElementExport aDesc4( mrExport, XML_NAMESPACE_NONE, aXMLElemStop, sal_True, sal_True ); } } else { const double fCenterX = rObjRect.Left() + rObjRect.GetWidth() * rGradient.GetOfsX() * 0.01; const double fCenterY = rObjRect.Top() + rObjRect.GetHeight() * rGradient.GetOfsY() * 0.01; const double fRadius = sqrt( static_cast< double >( rObjRect.GetWidth() ) * rObjRect.GetWidth() + rObjRect.GetHeight() * rObjRect.GetHeight() ) * 0.5; mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrGradientUnits, B2UCONST( "userSpaceOnUse" ) ); mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrCX, ::rtl::OUString::valueOf( ImplRound( fCenterX ) ) ); mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrCY, ::rtl::OUString::valueOf( ImplRound( fCenterY ) ) ); mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrR, ::rtl::OUString::valueOf( ImplRound( fRadius ) ) ); apGradient.reset( new SvXMLElementExport( mrExport, XML_NAMESPACE_NONE, aXMLElemRadialGradient, sal_True, sal_True ) ); // write stop values ImplGetColorStr( aEndColor, aColorStr ); mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrOffset, ::rtl::OUString::valueOf( 0.0 ) ); mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrStopColor, aColorStr ); { SvXMLElementExport aDesc5( mrExport, XML_NAMESPACE_NONE, aXMLElemStop, sal_True, sal_True ); } ImplGetColorStr( aStartColor, aColorStr ); mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrOffset, ::rtl::OUString::valueOf( ImplRound( 1.0 - rGradient.GetBorder() * 0.01 ) ) ); mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrStopColor, aColorStr ); { SvXMLElementExport aDesc6( mrExport, XML_NAMESPACE_NONE, aXMLElemStop, sal_True, sal_True ); } } } } else rGradientId = ::rtl::OUString(); } // ----------------------------------------------------------------------------- void SVGAttributeWriter::SetFontAttr( const Font& rFont ) { if( !mpElemFont || ( rFont != maCurFont ) ) { ::rtl::OUString aFontStyle, aFontWeight, aTextDecoration; sal_Int32 nFontWeight; delete mpElemPaint, mpElemPaint = NULL; delete mpElemFont; maCurFont = rFont; // Font Family mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrFontFamily, mrFontExport.GetMappedFontName( rFont.GetName() ) ); // Font Size mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrFontSize, ::rtl::OUString::valueOf( rFont.GetHeight() ) ); // Font Style if( rFont.GetItalic() != ITALIC_NONE ) { if( rFont.GetItalic() == ITALIC_OBLIQUE ) aFontStyle = B2UCONST( "oblique" ); else aFontStyle = B2UCONST( "italic" ); } else aFontStyle = B2UCONST( "normal" ); mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrFontStyle, aFontStyle ); // Font Weight switch( rFont.GetWeight() ) { case WEIGHT_THIN: nFontWeight = 100; break; case WEIGHT_ULTRALIGHT: nFontWeight = 200; break; case WEIGHT_LIGHT: nFontWeight = 300; break; case WEIGHT_SEMILIGHT: nFontWeight = 400; break; case WEIGHT_NORMAL: nFontWeight = 400; break; case WEIGHT_MEDIUM: nFontWeight = 500; break; case WEIGHT_SEMIBOLD: nFontWeight = 600; break; case WEIGHT_BOLD: nFontWeight = 700; break; case WEIGHT_ULTRABOLD: nFontWeight = 800; break; case WEIGHT_BLACK: nFontWeight = 900; break; default: nFontWeight = 400; break; } mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrFontWeight, ::rtl::OUString::valueOf( nFontWeight ) ); if( mrExport.IsUseNativeTextDecoration() ) { if( rFont.GetUnderline() != UNDERLINE_NONE || rFont.GetStrikeout() != STRIKEOUT_NONE ) { if( rFont.GetUnderline() != UNDERLINE_NONE ) aTextDecoration = B2UCONST( "underline " ); if( rFont.GetStrikeout() != STRIKEOUT_NONE ) aTextDecoration += B2UCONST( "line-through " ); } else aTextDecoration = B2UCONST( "none" ); mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrTextDecoration, aTextDecoration ); } mpElemFont = new SvXMLElementExport( mrExport, XML_NAMESPACE_NONE, aXMLElemG, sal_True, sal_True ); } } // ------------------- // - SVGActionWriter - // ------------------- SVGActionWriter::SVGActionWriter( SVGExport& rExport, SVGFontExport& rFontExport ) : mrExport( rExport ), mrFontExport( rFontExport ), mpContext( NULL ), mnInnerMtfCount( 0 ), mbClipAttrChanged( sal_False ) { mpVDev = new VirtualDevice; mpVDev->EnableOutput( sal_False ); maTargetMapMode = MAP_100TH_MM; } // ----------------------------------------------------------------------------- SVGActionWriter::~SVGActionWriter() { DBG_ASSERT( !mpContext, "Not all contexts are closed" ); delete mpVDev; } // ----------------------------------------------------------------------------- long SVGActionWriter::ImplMap( sal_Int32 nVal ) const { Size aSz( nVal, nVal ); return( ImplMap( aSz, aSz ).Width() ); } // ----------------------------------------------------------------------------- Point& SVGActionWriter::ImplMap( const Point& rPt, Point& rDstPt ) const { return( rDstPt = mpVDev->LogicToLogic( rPt, mpVDev->GetMapMode(), maTargetMapMode ) ); } // ----------------------------------------------------------------------------- Size& SVGActionWriter::ImplMap( const Size& rSz, Size& rDstSz ) const { return( rDstSz = mpVDev->LogicToLogic( rSz, mpVDev->GetMapMode(), maTargetMapMode ) ); } // ----------------------------------------------------------------------------- Rectangle& SVGActionWriter::ImplMap( const Rectangle& rRect, Rectangle& rDstRect ) const { Point aTL( rRect.TopLeft() ); Size aSz( rRect.GetSize() ); return( rDstRect = Rectangle( ImplMap( aTL, aTL ), ImplMap( aSz, aSz ) ) ); } // ----------------------------------------------------------------------------- Polygon& SVGActionWriter::ImplMap( const Polygon& rPoly, Polygon& rDstPoly ) const { rDstPoly = Polygon( rPoly.GetSize() ); for( sal_uInt16 i = 0, nSize = rPoly.GetSize(); i < nSize; ++i ) { ImplMap( rPoly[ i ], rDstPoly[ i ] ); rDstPoly.SetFlags( i, rPoly.GetFlags( i ) ); } return( rDstPoly ); } // ----------------------------------------------------------------------------- PolyPolygon& SVGActionWriter::ImplMap( const PolyPolygon& rPolyPoly, PolyPolygon& rDstPolyPoly ) const { Polygon aPoly; rDstPolyPoly = PolyPolygon(); for( sal_uInt16 i = 0, nCount = rPolyPoly.Count(); i < nCount; ++i ) { rDstPolyPoly.Insert( ImplMap( rPolyPoly[ i ], aPoly ) ); } return( rDstPolyPoly ); } // ----------------------------------------------------------------------------- ::rtl::OUString SVGActionWriter::GetPathString( const PolyPolygon& rPolyPoly, sal_Bool bLine ) { ::rtl::OUString aPathData; const ::rtl::OUString aBlank( B2UCONST( " " ) ); const ::rtl::OUString aComma( B2UCONST( "," ) ); Point aPolyPoint; for( long i = 0, nCount = rPolyPoly.Count(); i < nCount; i++ ) { const Polygon& rPoly = rPolyPoly[ (sal_uInt16) i ]; sal_uInt16 n = 1, nSize = rPoly.GetSize(); if( nSize > 1 ) { aPathData += B2UCONST( "M " ); aPathData += ::rtl::OUString::valueOf( ( aPolyPoint = rPoly[ 0 ] ).X() ); aPathData += aComma; aPathData += ::rtl::OUString::valueOf( aPolyPoint.Y() ); sal_Char nCurrentMode = 0; const bool bClose(!bLine || rPoly[0] == rPoly[nSize - 1]); while( n < nSize ) { aPathData += aBlank; if ( ( rPoly.GetFlags( n ) == POLY_CONTROL ) && ( ( n + 2 ) < nSize ) ) { if ( nCurrentMode != 'C' ) { nCurrentMode = 'C'; aPathData += B2UCONST( "C " ); } for ( int j = 0; j < 3; j++ ) { if ( j ) aPathData += aBlank; aPathData += ::rtl::OUString::valueOf( ( aPolyPoint = rPoly[ n++ ] ).X() ); aPathData += aComma; aPathData += ::rtl::OUString::valueOf( aPolyPoint.Y() ); } } else { if ( nCurrentMode != 'L' ) { nCurrentMode = 'L'; aPathData += B2UCONST( "L " ); } aPathData += ::rtl::OUString::valueOf( ( aPolyPoint = rPoly[ n++ ] ).X() ); aPathData += aComma; aPathData += ::rtl::OUString::valueOf( aPolyPoint.Y() ); } } if(bClose) aPathData += B2UCONST( " Z" ); if( i < ( nCount - 1 ) ) aPathData += aBlank; } } return aPathData; } // ----------------------------------------------------------------------------- void SVGActionWriter::ImplWriteLine( const Point& rPt1, const Point& rPt2, const Color* pLineColor, sal_Bool bApplyMapping ) { Point aPt1, aPt2; if( bApplyMapping ) { ImplMap( rPt1, aPt1 ); ImplMap( rPt2, aPt2 ); } else { aPt1 = rPt1; aPt2 = rPt2; } mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrX1, ::rtl::OUString::valueOf( aPt1.X() ) ); mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrY1, ::rtl::OUString::valueOf( aPt1.Y() ) ); mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrX2, ::rtl::OUString::valueOf( aPt2.X() ) ); mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrY2, ::rtl::OUString::valueOf( aPt2.Y() ) ); if( pLineColor ) { // !!! mrExport.AddAttribute( XML_NAMESPACE_NONE, ... ) DBG_ERROR( "SVGActionWriter::ImplWriteLine: Line color not implemented" ); } { SvXMLElementExport aElem( mrExport, XML_NAMESPACE_NONE, aXMLElemLine, sal_True, sal_True ); } } // ----------------------------------------------------------------------------- void SVGActionWriter::ImplWriteRect( const Rectangle& rRect, long nRadX, long nRadY, sal_Bool bApplyMapping ) { Rectangle aRect; if( bApplyMapping ) ImplMap( rRect, aRect ); else aRect = rRect; mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrX, ::rtl::OUString::valueOf( aRect.Left() ) ); mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrY, ::rtl::OUString::valueOf( aRect.Top() ) ); mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrWidth, ::rtl::OUString::valueOf( aRect.GetWidth() ) ); mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrHeight, ::rtl::OUString::valueOf( aRect.GetHeight() ) ); if( nRadX ) mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrRX, ::rtl::OUString::valueOf( bApplyMapping ? ImplMap( nRadX ) : nRadX ) ); if( nRadY ) mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrRY, ::rtl::OUString::valueOf( bApplyMapping ? ImplMap( nRadY ) : nRadY ) ); { SvXMLElementExport aElem( mrExport, XML_NAMESPACE_NONE, aXMLElemRect, sal_True, sal_True ); } } // ----------------------------------------------------------------------------- void SVGActionWriter::ImplWriteEllipse( const Point& rCenter, long nRadX, long nRadY, sal_Bool bApplyMapping ) { Point aCenter; if( bApplyMapping ) ImplMap( rCenter, aCenter ); else aCenter = rCenter; mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrCX, ::rtl::OUString::valueOf( aCenter.X() ) ); mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrCY, ::rtl::OUString::valueOf( aCenter.Y() ) ); mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrRX, ::rtl::OUString::valueOf( bApplyMapping ? ImplMap( nRadX ) : nRadX ) ); mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrRY, ::rtl::OUString::valueOf( bApplyMapping ? ImplMap( nRadY ) : nRadY ) ); { SvXMLElementExport aElem( mrExport, XML_NAMESPACE_NONE, aXMLElemEllipse, sal_True, sal_True ); } } // ----------------------------------------------------------------------------- void SVGActionWriter::ImplWritePolyPolygon( const PolyPolygon& rPolyPoly, sal_Bool bLineOnly, sal_Bool bApplyMapping ) { PolyPolygon aPolyPoly; if( bApplyMapping ) ImplMap( rPolyPoly, aPolyPoly ); else aPolyPoly = rPolyPoly; if( mrExport.hasClip() ) { const ::basegfx::B2DPolyPolygon aB2DPolyPoly( ::basegfx::tools::correctOrientations( aPolyPoly.getB2DPolyPolygon() ) ); aPolyPoly = PolyPolygon( ::basegfx::tools::clipPolyPolygonOnPolyPolygon( *mrExport.getCurClip(), aB2DPolyPoly, sal_False, sal_False ) ); } // add path data attribute mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrD, GetPathString( aPolyPoly, bLineOnly ) ); { // write polyline/polygon element SvXMLElementExport aElem( mrExport, XML_NAMESPACE_NONE, aXMLElemPath, sal_True, sal_True ); } } // ----------------------------------------------------------------------------- void SVGActionWriter::ImplWriteShape( const SVGShapeDescriptor& rShape, sal_Bool bApplyMapping ) { PolyPolygon aPolyPoly; if( bApplyMapping ) ImplMap( rShape.maShapePolyPoly, aPolyPoly ); else aPolyPoly = rShape.maShapePolyPoly; const sal_Bool bLineOnly = ( rShape.maShapeFillColor == Color( COL_TRANSPARENT ) ) && ( !rShape.mapShapeGradient.get() ); Rectangle aBoundRect( aPolyPoly.GetBoundRect() ); mpContext->AddPaintAttr( rShape.maShapeLineColor, rShape.maShapeFillColor, &aBoundRect, rShape.mapShapeGradient.get() ); if( rShape.maId.getLength() ) mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrId, rShape.maId ); if( rShape.mnStrokeWidth ) { sal_Int32 nStrokeWidth = ( bApplyMapping ? ImplMap( rShape.mnStrokeWidth ) : rShape.mnStrokeWidth ); mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrStrokeWidth, ::rtl::OUString::valueOf( nStrokeWidth ) ); } // support for LineJoin switch(rShape.maLineJoin) { default: // B2DLINEJOIN_NONE, B2DLINEJOIN_MIDDLE case basegfx::B2DLINEJOIN_MITER: { // miter is Svg default, so no need to write until the exporter might write styles. // If this happens, activate here // mrExport.AddAttribute(XML_NAMESPACE_NONE, aXMLAttrStrokeLinejoin, ::rtl::OUString::createFromAscii("miter")); break; } case basegfx::B2DLINEJOIN_BEVEL: { mrExport.AddAttribute(XML_NAMESPACE_NONE, aXMLAttrStrokeLinejoin, ::rtl::OUString::createFromAscii("bevel")); break; } case basegfx::B2DLINEJOIN_ROUND: { mrExport.AddAttribute(XML_NAMESPACE_NONE, aXMLAttrStrokeLinejoin, ::rtl::OUString::createFromAscii("round")); break; } } // support for LineCap switch(rShape.maLineCap) { default: /* com::sun::star::drawing::LineCap_BUTT */ { // butt is Svg default, so no need to write until the exporter might write styles. // If this happens, activate here // mrExport.AddAttribute(XML_NAMESPACE_NONE, aXMLAttrStrokeLinecap, ::rtl::OUString::createFromAscii("butt")); break; } case com::sun::star::drawing::LineCap_ROUND: { mrExport.AddAttribute(XML_NAMESPACE_NONE, aXMLAttrStrokeLinecap, ::rtl::OUString::createFromAscii("round")); break; } case com::sun::star::drawing::LineCap_SQUARE: { mrExport.AddAttribute(XML_NAMESPACE_NONE, aXMLAttrStrokeLinecap, ::rtl::OUString::createFromAscii("square")); break; } } if( rShape.maDashArray.size() ) { const ::rtl::OUString aComma( B2UCONST( "," ) ); ::rtl::OUString aDashArrayStr; for( unsigned int k = 0; k < rShape.maDashArray.size(); ++k ) { const sal_Int32 nDash = ( bApplyMapping ? ImplMap( FRound( rShape.maDashArray[ k ] ) ) : FRound( rShape.maDashArray[ k ] ) ); if( k ) aDashArrayStr += aComma; aDashArrayStr += ::rtl::OUString::valueOf( nDash ); } mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrStrokeDashArray, aDashArrayStr ); } ImplWritePolyPolygon( aPolyPoly, bLineOnly, sal_False ); } // ----------------------------------------------------------------------------- void SVGActionWriter::ImplWriteGradientEx( const PolyPolygon& rPolyPoly, const Gradient& rGradient, sal_uInt32 nWriteFlags, sal_Bool bApplyMapping ) { PolyPolygon aPolyPoly; if( bApplyMapping ) ImplMap( rPolyPoly, aPolyPoly ); else aPolyPoly = rPolyPoly; if( rGradient.GetStyle() == GRADIENT_LINEAR || rGradient.GetStyle() == GRADIENT_AXIAL || rGradient.GetStyle() == GRADIENT_RADIAL || rGradient.GetStyle() == GRADIENT_ELLIPTICAL ) { SVGShapeDescriptor aShapeDesc; aShapeDesc.maShapePolyPoly = aPolyPoly; aShapeDesc.mapShapeGradient.reset( new Gradient( rGradient ) ); ImplWriteShape( aShapeDesc, sal_False ); } else { GDIMetaFile aTmpMtf; mrExport.pushClip( aPolyPoly.getB2DPolyPolygon() ); mpVDev->AddGradientActions( rPolyPoly.GetBoundRect(), rGradient, aTmpMtf ); ++mnInnerMtfCount; ImplWriteActions( aTmpMtf, nWriteFlags, NULL ); --mnInnerMtfCount; mrExport.popClip(); } } // ----------------------------------------------------------------------------- void SVGActionWriter::ImplWriteText( const Point& rPos, const String& rText, const sal_Int32* pDXArray, long nWidth, sal_Bool bApplyMapping ) { sal_Int32 nLen = rText.Len(), i; Size aNormSize; ::std::auto_ptr< sal_Int32 > apTmpArray; ::std::auto_ptr< SvXMLElementExport > apTransform; sal_Int32* pDX; Point aPos; Point aBaseLinePos( rPos ); const FontMetric aMetric( mpVDev->GetFontMetric() ); const Font& rFont = mpVDev->GetFont(); if( rFont.GetAlign() == ALIGN_TOP ) aBaseLinePos.Y() += aMetric.GetAscent(); else if( rFont.GetAlign() == ALIGN_BOTTOM ) aBaseLinePos.Y() -= aMetric.GetDescent(); if( bApplyMapping ) ImplMap( rPos, aPos ); else aPos = rPos; // get text sizes if( pDXArray ) { aNormSize = Size( mpVDev->GetTextWidth( rText ), 0 ); pDX = const_cast< sal_Int32* >( pDXArray ); } else { apTmpArray.reset( new sal_Int32[ nLen ] ); aNormSize = Size( mpVDev->GetTextArray( rText, apTmpArray.get() ), 0 ); pDX = apTmpArray.get(); } // if text is rotated, set transform matrix at new g element if( rFont.GetOrientation() ) { Point aRot( aPos ); String aTransform; aTransform = String( ::rtl::OUString::createFromAscii( "translate" ) ); aTransform += '('; aTransform += String( ::rtl::OUString::valueOf( aRot.X() ) ); aTransform += ','; aTransform += String( ::rtl::OUString::valueOf( aRot.Y() ) ); aTransform += ')'; aTransform += String( ::rtl::OUString::createFromAscii( " rotate" ) ); aTransform += '('; aTransform += String( ::rtl::OUString::valueOf( rFont.GetOrientation() * -0.1 ) ); aTransform += ')'; aTransform += String( ::rtl::OUString::createFromAscii( " translate" ) ); aTransform += '('; aTransform += String( ::rtl::OUString::valueOf( -aRot.X() ) ); aTransform += ','; aTransform += String( ::rtl::OUString::valueOf( -aRot.Y() ) ); aTransform += ')'; mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrTransform, aTransform ); apTransform.reset( new SvXMLElementExport( mrExport, XML_NAMESPACE_NONE, aXMLElemG, sal_True, sal_True ) ); } if( nLen > 1 ) { ::com::sun::star::uno::Reference< ::com::sun::star::i18n::XBreakIterator > xBI( ::vcl::unohelper::CreateBreakIterator() ); const ::com::sun::star::lang::Locale& rLocale = Application::GetSettings().GetLocale(); sal_Int32 nCurPos = 0, nLastPos = 0, nX = aPos.X(); if ( mrExport.IsUseTSpans() ) { mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrX, ::rtl::OUString::valueOf( aPos.X() ) ); mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrY, ::rtl::OUString::valueOf( aPos.Y() ) ); SvXMLElementExport aElem( mrExport, XML_NAMESPACE_NONE, aXMLElemText, sal_True, sal_False ); { rtl::OUString aString; for( sal_Bool bCont = sal_True; bCont; ) { sal_Int32 nCount = 1; const ::rtl::OUString aSpace( ' ' ); nLastPos = nCurPos; nCurPos = xBI->nextCharacters( rText, nCurPos, rLocale, ::com::sun::star::i18n::CharacterIteratorMode::SKIPCELL, nCount, nCount ); nCount = nCurPos - nLastPos; bCont = ( nCurPos < rText.Len() ) && nCount; if( nCount ) { aString += rtl::OUString::valueOf( nX ); if( bCont ) { sal_Int32 nWidth = pDX[ nCurPos - 1 ]; if ( bApplyMapping ) nWidth = ImplMap( nWidth ); nX = aPos.X() + nWidth; aString += aSpace; } } } mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrX, aString ); SvXMLElementExport aElem( mrExport, XML_NAMESPACE_NONE, aXMLElemTSpan, sal_True, sal_False ); mrExport.GetDocHandler()->characters( rText ); } } else { aNormSize.Width() = pDX[ nLen - 2 ] + mpVDev->GetTextWidth( rText.GetChar( nLen - 1 ) ); if( nWidth && aNormSize.Width() && ( nWidth != aNormSize.Width() ) ) { const double fFactor = (double) nWidth / aNormSize.Width(); for( i = 0; i < ( nLen - 1 ); i++ ) pDX[ i ] = FRound( pDX[ i ] * fFactor ); } else { // write single glyphs at absolute text positions for( sal_Bool bCont = sal_True; bCont; ) { sal_Int32 nCount = 1; nLastPos = nCurPos; nCurPos = xBI->nextCharacters( rText, nCurPos, rLocale, ::com::sun::star::i18n::CharacterIteratorMode::SKIPCELL, nCount, nCount ); nCount = nCurPos - nLastPos; bCont = ( nCurPos < rText.Len() ) && nCount; if( nCount ) { const ::rtl::OUString aGlyph( rText.Copy( nLastPos, nCount ) ); mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrX, ::rtl::OUString::valueOf( nX ) ); mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrY, ::rtl::OUString::valueOf( aPos.Y() ) ); { SvXMLElementExport aElem( mrExport, XML_NAMESPACE_NONE, aXMLElemText, sal_True, sal_False ); mrExport.GetDocHandler()->characters( aGlyph ); } if( bCont ) { // #118796# do NOT access pDXArray, it may be zero (!) sal_Int32 nWidth = pDX[ nCurPos - 1 ]; if ( bApplyMapping ) nWidth = ImplMap( nWidth ); nX = aPos.X() + nWidth; } } } } } } else { mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrX, ::rtl::OUString::valueOf( aPos.X() ) ); mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrY, ::rtl::OUString::valueOf( aPos.Y() ) ); { SvXMLElementExport aElem( mrExport, XML_NAMESPACE_NONE, aXMLElemText, sal_True, sal_False ); mrExport.GetDocHandler()->characters( rText ); } } if( !mrExport.IsUseNativeTextDecoration() ) { if( rFont.GetStrikeout() != STRIKEOUT_NONE || rFont.GetUnderline() != UNDERLINE_NONE ) { Polygon aPoly( 4 ); const long nLineHeight = Max( (long) FRound( aMetric.GetLineHeight() * 0.05 ), (long) 1 ); if( rFont.GetStrikeout() ) { const long nYLinePos = aBaseLinePos.Y() - FRound( aMetric.GetAscent() * 0.26 ); aPoly[ 0 ].X() = aBaseLinePos.X(); aPoly[ 0 ].Y() = nYLinePos - ( nLineHeight >> 1 ); aPoly[ 1 ].X() = aBaseLinePos.X() + aNormSize.Width() - 1; aPoly[ 1 ].Y() = aPoly[ 0 ].Y(); aPoly[ 2 ].X() = aPoly[ 1 ].X(); aPoly[ 2 ].Y() = aPoly[ 0 ].Y() + nLineHeight - 1; aPoly[ 3 ].X() = aPoly[ 0 ].X(); aPoly[ 3 ].Y() = aPoly[ 2 ].Y(); ImplWritePolyPolygon( aPoly, sal_False ); } if( rFont.GetUnderline() ) { const long nYLinePos = aBaseLinePos.Y() + ( nLineHeight << 1 ); aPoly[ 0 ].X() = aBaseLinePos.X(); aPoly[ 0 ].Y() = nYLinePos - ( nLineHeight >> 1 ); aPoly[ 1 ].X() = aBaseLinePos.X() + aNormSize.Width() - 1; aPoly[ 1 ].Y() = aPoly[ 0 ].Y(); aPoly[ 2 ].X() = aPoly[ 1 ].X(); aPoly[ 2 ].Y() = aPoly[ 0 ].Y() + nLineHeight - 1; aPoly[ 3 ].X() = aPoly[ 0 ].X(); aPoly[ 3 ].Y() = aPoly[ 2 ].Y(); ImplWritePolyPolygon( aPoly, sal_False ); } } } } // ----------------------------------------------------------------------------- void SVGActionWriter::ImplWriteBmp( const BitmapEx& rBmpEx, const Point& rPt, const Size& rSz, const Point& rSrcPt, const Size& rSrcSz, sal_Bool bApplyMapping ) { if( !!rBmpEx ) { BitmapEx aBmpEx( rBmpEx ); Point aPoint = Point(); const Rectangle aBmpRect( aPoint, rBmpEx.GetSizePixel() ); const Rectangle aSrcRect( rSrcPt, rSrcSz ); if( aSrcRect != aBmpRect ) aBmpEx.Crop( aSrcRect ); if( !!aBmpEx ) { SvMemoryStream aOStm( 65535, 65535 ); if( GraphicConverter::Export( aOStm, rBmpEx, CVT_PNG ) == ERRCODE_NONE ) { Point aPt; Size aSz; // #119735# Do not copy the stream data to a ::rtl::OUString any longer, this is not needed and // (of course) throws many exceptions with the used RTL_TEXTENCODING_ASCII_US. Keeping that line // to show what I'm talking about // ::rtl::OUString aImageData( (sal_Char*) aOStm.GetData(), aOStm.Tell(), RTL_TEXTENCODING_ASCII_US ); const sal_Char* pImageData = (sal_Char*)aOStm.GetData(); const sal_uInt32 nImageDataLength = aOStm.Tell(); REF( NMSP_SAX::XExtendedDocumentHandler ) xExtDocHandler( mrExport.GetDocHandler(), NMSP_UNO::UNO_QUERY ); if( bApplyMapping ) { ImplMap( rPt, aPt ); ImplMap( rSz, aSz ); } else { aPt = rPt; aSz = rSz; } const Rectangle aRect( aPt, aSz ); if( mrExport.IsVisible( aRect ) && xExtDocHandler.is() ) { static const sal_uInt32 nPartLen = 64; const ::rtl::OUString aSpace( ' ' ); const ::rtl::OUString aLineFeed( ::rtl::OUString::valueOf( (sal_Unicode) 0x0a ) ); ::rtl::OUString aString; aString = aLineFeed; aString += B2UCONST( "<" ); aString += ::rtl::OUString::createFromAscii( aXMLElemImage ); aString += aSpace; aString += ::rtl::OUString::createFromAscii( aXMLAttrX ); aString += B2UCONST( "=\"" ); aString += ::rtl::OUString::valueOf( aPt.X() ); aString += B2UCONST( "\" " ); aString += ::rtl::OUString::createFromAscii( aXMLAttrY ); aString += B2UCONST( "=\"" ); aString += ::rtl::OUString::valueOf( aPt.Y() ); aString += B2UCONST( "\" " ); aString += ::rtl::OUString::createFromAscii( aXMLAttrWidth ); aString += B2UCONST( "=\"" ); aString += ::rtl::OUString::valueOf( aSz.Width() ); aString += B2UCONST( "\" " ); aString += ::rtl::OUString::createFromAscii( aXMLAttrHeight ); aString += B2UCONST( "=\"" ); aString += ::rtl::OUString::valueOf( aSz.Height() ); aString += B2UCONST( "\" " ); aString += ::rtl::OUString::createFromAscii( aXMLAttrXLinkHRef ); aString += B2UCONST( "=\"data:image/png;base64," ); xExtDocHandler->unknown( aString ); // #119735# const sal_uInt32 nQuadCount = nImageDataLength / 3; const sal_uInt32 nRest = nImageDataLength % 3; if( nQuadCount || nRest ) { sal_Int32 nBufLen = ( ( nQuadCount + ( nRest ? 1 : 0 ) ) << 2 ); const sal_Char* pSrc = pImageData; sal_Unicode* pBuffer = new sal_Unicode[ nBufLen * sizeof( sal_Unicode ) ]; sal_Unicode* pTmpDst = pBuffer; for( sal_uInt32 i = 0; i < nQuadCount; ++i ) { const sal_Int32 nA = *pSrc++; const sal_Int32 nB = *pSrc++; const sal_Int32 nC = *pSrc++; *pTmpDst++ = pBase64[ ( nA >> 2 ) & 0x3f ]; *pTmpDst++ = pBase64[ ( ( nA << 4 ) & 0x30 ) + ( ( nB >> 4 ) & 0xf ) ]; *pTmpDst++ = pBase64[ ( ( nB << 2 ) & 0x3c ) + ( ( nC >> 6 ) & 0x3 ) ]; *pTmpDst++ = pBase64[ nC & 0x3f ]; } if( nRest ) { const sal_Int32 nA = *pSrc++; *pTmpDst++ = pBase64[ ( nA >> 2 ) & 0x3f ]; if( 2 == nRest ) { const sal_Int32 nB = *pSrc; *pTmpDst++ = pBase64[ ( ( nA << 4 ) & 0x30 ) + ( ( nB >> 4 ) & 0xf ) ]; *pTmpDst++ = pBase64[ ( nB << 2 ) & 0x3c ]; } else { *pTmpDst++ = pBase64[ ( nA << 4 ) & 0x30 ]; *pTmpDst++ = '='; } *pTmpDst = '='; } for( sal_Int32 nCurPos = 0; nCurPos < nBufLen; nCurPos += nPartLen ) { const ::rtl::OUString aPart( pBuffer + nCurPos, ::std::min< sal_Int32 >( nPartLen, nBufLen - nCurPos ) ); xExtDocHandler->unknown( aLineFeed ); xExtDocHandler->unknown( aPart ); } delete[] pBuffer; } xExtDocHandler->unknown( B2UCONST( "\"/>" ) ); } } } } } // ----------------------------------------------------------------------------- void SVGActionWriter::ImplWriteActions( const GDIMetaFile& rMtf, sal_uInt32 nWriteFlags, const ::rtl::OUString* pElementId ) { // need a counter fo rthe actions written per shape to avoid double ID // generation sal_Int32 nEntryCount(0); if( mnInnerMtfCount ) nWriteFlags |= SVGWRITER_NO_SHAPE_COMMENTS; for( sal_uLong nCurAction = 0, nCount = rMtf.GetActionCount(); nCurAction < nCount; nCurAction++ ) { const MetaAction* pAction = rMtf.GetAction( nCurAction ); const sal_uInt16 nType = pAction->GetType(); switch( nType ) { case( META_PIXEL_ACTION ): { if( nWriteFlags & SVGWRITER_WRITE_FILL ) { const MetaPixelAction* pA = (const MetaPixelAction*) pAction; mpContext->AddPaintAttr( pA->GetColor(), pA->GetColor() ); ImplWriteLine( pA->GetPoint(), pA->GetPoint(), &pA->GetColor() ); } } break; case( META_POINT_ACTION ): { if( nWriteFlags & SVGWRITER_WRITE_FILL ) { const MetaPointAction* pA = (const MetaPointAction*) pAction; mpContext->AddPaintAttr( mpVDev->GetLineColor(), mpVDev->GetLineColor() ); ImplWriteLine( pA->GetPoint(), pA->GetPoint(), NULL ); } } break; case( META_LINE_ACTION ): { if( nWriteFlags & SVGWRITER_WRITE_FILL ) { const MetaLineAction* pA = (const MetaLineAction*) pAction; mpContext->AddPaintAttr( mpVDev->GetLineColor(), mpVDev->GetLineColor() ); ImplWriteLine( pA->GetStartPoint(), pA->GetEndPoint(), NULL ); } } break; case( META_RECT_ACTION ): { if( nWriteFlags & SVGWRITER_WRITE_FILL ) { mpContext->AddPaintAttr( mpVDev->GetLineColor(), mpVDev->GetFillColor() ); ImplWriteRect( ( (const MetaRectAction*) pAction )->GetRect(), 0, 0 ); } } break; case( META_ROUNDRECT_ACTION ): { if( nWriteFlags & SVGWRITER_WRITE_FILL ) { const MetaRoundRectAction* pA = (const MetaRoundRectAction*) pAction; mpContext->AddPaintAttr( mpVDev->GetLineColor(), mpVDev->GetFillColor() ); ImplWriteRect( pA->GetRect(), pA->GetHorzRound(), pA->GetVertRound() ); } } break; case( META_ELLIPSE_ACTION ): { if( nWriteFlags & SVGWRITER_WRITE_FILL ) { const MetaEllipseAction* pA = (const MetaEllipseAction*) pAction; const Rectangle& rRect = pA->GetRect(); mpContext->AddPaintAttr( mpVDev->GetLineColor(), mpVDev->GetFillColor() ); ImplWriteEllipse( rRect.Center(), rRect.GetWidth() >> 1, rRect.GetHeight() >> 1 ); } } break; case( META_ARC_ACTION ): case( META_PIE_ACTION ): case( META_CHORD_ACTION ): case( META_POLYGON_ACTION ): { if( nWriteFlags & SVGWRITER_WRITE_FILL ) { Polygon aPoly; switch( nType ) { case( META_ARC_ACTION ): { const MetaArcAction* pA = (const MetaArcAction*) pAction; aPoly = Polygon( pA->GetRect(), pA->GetStartPoint(), pA->GetEndPoint(), POLY_ARC ); } break; case( META_PIE_ACTION ): { const MetaPieAction* pA = (const MetaPieAction*) pAction; aPoly = Polygon( pA->GetRect(), pA->GetStartPoint(), pA->GetEndPoint(), POLY_PIE ); } break; case( META_CHORD_ACTION ): { const MetaChordAction* pA = (const MetaChordAction*) pAction; aPoly = Polygon( pA->GetRect(), pA->GetStartPoint(), pA->GetEndPoint(), POLY_CHORD ); } break; case( META_POLYGON_ACTION ): aPoly = ( (const MetaPolygonAction*) pAction )->GetPolygon(); break; } if( aPoly.GetSize() ) { mpContext->AddPaintAttr( mpVDev->GetLineColor(), mpVDev->GetFillColor() ); ImplWritePolyPolygon( aPoly, sal_False ); } } } break; case( META_POLYLINE_ACTION ): { if( nWriteFlags & SVGWRITER_WRITE_FILL ) { const MetaPolyLineAction* pA = (const MetaPolyLineAction*) pAction; const Polygon& rPoly = pA->GetPolygon(); if( rPoly.GetSize() ) { const LineInfo& rLineInfo = pA->GetLineInfo(); if(rLineInfo.GetWidth()) { sal_Int32 nStrokeWidth = ImplMap(rLineInfo.GetWidth()); mrExport.AddAttribute( XML_NAMESPACE_NONE, aXMLAttrStrokeWidth, ::rtl::OUString::valueOf( nStrokeWidth ) ); } mpContext->AddPaintAttr( mpVDev->GetLineColor(), Color( COL_TRANSPARENT ) ); ImplWritePolyPolygon( rPoly, sal_True ); } } } break; case( META_POLYPOLYGON_ACTION ): { if( nWriteFlags & SVGWRITER_WRITE_FILL ) { const MetaPolyPolygonAction* pA = (const MetaPolyPolygonAction*) pAction; const PolyPolygon& rPolyPoly = pA->GetPolyPolygon(); if( rPolyPoly.Count() ) { mpContext->AddPaintAttr( mpVDev->GetLineColor(), mpVDev->GetFillColor() ); ImplWritePolyPolygon( rPolyPoly, sal_False ); } } } break; case( META_GRADIENT_ACTION ): { if( nWriteFlags & SVGWRITER_WRITE_FILL ) { const MetaGradientAction* pA = (const MetaGradientAction*) pAction; const Polygon aRectPoly( pA->GetRect() ); const PolyPolygon aRectPolyPoly( aRectPoly ); ImplWriteGradientEx( aRectPolyPoly, pA->GetGradient(), nWriteFlags ); } } break; case( META_GRADIENTEX_ACTION ): { if( nWriteFlags & SVGWRITER_WRITE_FILL ) { const MetaGradientExAction* pA = (const MetaGradientExAction*) pAction; ImplWriteGradientEx( pA->GetPolyPolygon(), pA->GetGradient(), nWriteFlags ); } } break; case META_HATCH_ACTION: { if( nWriteFlags & SVGWRITER_WRITE_FILL ) { const MetaHatchAction* pA = (const MetaHatchAction*) pAction; GDIMetaFile aTmpMtf; mpVDev->AddHatchActions( pA->GetPolyPolygon(), pA->GetHatch(), aTmpMtf ); ++mnInnerMtfCount; ImplWriteActions( aTmpMtf, nWriteFlags, NULL ); --mnInnerMtfCount; } } break; case( META_TRANSPARENT_ACTION ): { if( nWriteFlags & SVGWRITER_WRITE_FILL ) { const MetaTransparentAction* pA = (const MetaTransparentAction*) pAction; const PolyPolygon& rPolyPoly = pA->GetPolyPolygon(); if( rPolyPoly.Count() ) { Color aNewLineColor( mpVDev->GetLineColor() ), aNewFillColor( mpVDev->GetFillColor() ); aNewLineColor.SetTransparency( sal::static_int_cast<sal_uInt8>( FRound( pA->GetTransparence() * 2.55 ) ) ); aNewFillColor.SetTransparency( sal::static_int_cast<sal_uInt8>( FRound( pA->GetTransparence() * 2.55 ) ) ); mpContext->AddPaintAttr( aNewLineColor, aNewFillColor ); ImplWritePolyPolygon( rPolyPoly, sal_False ); } } } break; case( META_FLOATTRANSPARENT_ACTION ): { if( nWriteFlags & SVGWRITER_WRITE_FILL ) { const MetaFloatTransparentAction* pA = (const MetaFloatTransparentAction*) pAction; GDIMetaFile aTmpMtf( pA->GetGDIMetaFile() ); Point aSrcPt( aTmpMtf.GetPrefMapMode().GetOrigin() ); const Size aSrcSize( aTmpMtf.GetPrefSize() ); const Point aDestPt( pA->GetPoint() ); const Size aDestSize( pA->GetSize() ); const double fScaleX = aSrcSize.Width() ? (double) aDestSize.Width() / aSrcSize.Width() : 1.0; const double fScaleY = aSrcSize.Height() ? (double) aDestSize.Height() / aSrcSize.Height() : 1.0; long nMoveX, nMoveY; if( fScaleX != 1.0 || fScaleY != 1.0 ) { aTmpMtf.Scale( fScaleX, fScaleY ); aSrcPt.X() = FRound( aSrcPt.X() * fScaleX ), aSrcPt.Y() = FRound( aSrcPt.Y() * fScaleY ); } nMoveX = aDestPt.X() - aSrcPt.X(), nMoveY = aDestPt.Y() - aSrcPt.Y(); if( nMoveX || nMoveY ) aTmpMtf.Move( nMoveX, nMoveY ); mpVDev->Push(); ++mnInnerMtfCount; ImplWriteActions( aTmpMtf, nWriteFlags, NULL ); --mnInnerMtfCount; mpVDev->Pop(); } } break; case( META_EPS_ACTION ): { if( nWriteFlags & SVGWRITER_WRITE_FILL ) { const MetaEPSAction* pA = (const MetaEPSAction*) pAction; const GDIMetaFile aGDIMetaFile( pA->GetSubstitute() ); sal_Bool bFound = sal_False; for( sal_uInt32 k = 0, nCount2 = aGDIMetaFile.GetActionCount(); ( k < nCount2 ) && !bFound; ++k ) { const MetaAction* pSubstAct = aGDIMetaFile.GetAction( k ); if( pSubstAct->GetType() == META_BMPSCALE_ACTION ) { bFound = sal_True; const MetaBmpScaleAction* pBmpScaleAction = (const MetaBmpScaleAction*) pSubstAct; ImplWriteBmp( pBmpScaleAction->GetBitmap(), pA->GetPoint(), pA->GetSize(), Point(), pBmpScaleAction->GetBitmap().GetSizePixel() ); } } } } break; case( META_COMMENT_ACTION ): { const MetaCommentAction* pA = (const MetaCommentAction*) pAction; String aSkipComment; if( ( pA->GetComment().CompareIgnoreCaseToAscii( "XGRAD_SEQ_BEGIN" ) == COMPARE_EQUAL ) && ( nWriteFlags & SVGWRITER_WRITE_FILL ) ) { const MetaGradientExAction* pGradAction = NULL; sal_Bool bDone = sal_False; while( !bDone && ( ++nCurAction < nCount ) ) { pAction = rMtf.GetAction( nCurAction ); if( pAction->GetType() == META_GRADIENTEX_ACTION ) pGradAction = (const MetaGradientExAction*) pAction; else if( ( pAction->GetType() == META_COMMENT_ACTION ) && ( ( (const MetaCommentAction*) pAction )->GetComment(). CompareIgnoreCaseToAscii( "XGRAD_SEQ_END" ) == COMPARE_EQUAL ) ) { bDone = sal_True; } } if( pGradAction ) ImplWriteGradientEx( pGradAction->GetPolyPolygon(), pGradAction->GetGradient(), nWriteFlags ); } else if( ( pA->GetComment().CompareIgnoreCaseToAscii( "XPATHFILL_SEQ_BEGIN" ) == COMPARE_EQUAL ) && ( nWriteFlags & SVGWRITER_WRITE_FILL ) && !( nWriteFlags & SVGWRITER_NO_SHAPE_COMMENTS ) && pA->GetDataSize() ) { // write open shape in every case if( mapCurShape.get() ) { ImplWriteShape( *mapCurShape ); mapCurShape.reset(); } SvMemoryStream aMemStm( (void*) pA->GetData(), pA->GetDataSize(), STREAM_READ ); SvtGraphicFill aFill; aMemStm >> aFill; sal_Bool bGradient = SvtGraphicFill::fillGradient == aFill.getFillType() && ( SvtGraphicFill::gradientLinear == aFill.getGradientType() || SvtGraphicFill::gradientRadial == aFill.getGradientType() ); sal_Bool bSkip = ( SvtGraphicFill::fillSolid == aFill.getFillType() || bGradient ); if( bSkip ) { PolyPolygon aShapePolyPoly; aFill.getPath( aShapePolyPoly ); if( aShapePolyPoly.Count() ) { mapCurShape.reset( new SVGShapeDescriptor ); if( pElementId ) { mapCurShape->maId = *pElementId + B2UCONST("_") + ::rtl::OUString::valueOf(nEntryCount++); } mapCurShape->maShapePolyPoly = aShapePolyPoly; mapCurShape->maShapeFillColor = aFill.getFillColor(); mapCurShape->maShapeFillColor.SetTransparency( (sal_uInt8) FRound( 255.0 * aFill.getTransparency() ) ); if( bGradient ) { // step through following actions until the first Gradient/GradientEx action is found while( !mapCurShape->mapShapeGradient.get() && bSkip && ( ++nCurAction < nCount ) ) { pAction = rMtf.GetAction( nCurAction ); if( ( pAction->GetType() == META_COMMENT_ACTION ) && ( ( (const MetaCommentAction*) pAction )->GetComment(). CompareIgnoreCaseToAscii( "XPATHFILL_SEQ_END" ) == COMPARE_EQUAL ) ) { bSkip = sal_False; } else if( pAction->GetType() == META_GRADIENTEX_ACTION ) { mapCurShape->mapShapeGradient.reset( new Gradient( static_cast< const MetaGradientExAction* >( pAction )->GetGradient() ) ); } else if( pAction->GetType() == META_GRADIENT_ACTION ) { mapCurShape->mapShapeGradient.reset( new Gradient( static_cast< const MetaGradientAction* >( pAction )->GetGradient() ) ); } } } } else bSkip = sal_False; } // skip rest of comment while( bSkip && ( ++nCurAction < nCount ) ) { pAction = rMtf.GetAction( nCurAction ); if( ( pAction->GetType() == META_COMMENT_ACTION ) && ( ( (const MetaCommentAction*) pAction )->GetComment(). CompareIgnoreCaseToAscii( "XPATHFILL_SEQ_END" ) == COMPARE_EQUAL ) ) { bSkip = sal_False; } } } else if( ( pA->GetComment().CompareIgnoreCaseToAscii( "XPATHSTROKE_SEQ_BEGIN" ) == COMPARE_EQUAL ) && ( nWriteFlags & SVGWRITER_WRITE_FILL ) && !( nWriteFlags & SVGWRITER_NO_SHAPE_COMMENTS ) && pA->GetDataSize() ) { SvMemoryStream aMemStm( (void*) pA->GetData(), pA->GetDataSize(), STREAM_READ ); SvtGraphicStroke aStroke; PolyPolygon aStartArrow, aEndArrow; aMemStm >> aStroke; aStroke.getStartArrow( aStartArrow ); aStroke.getEndArrow( aEndArrow ); // Currently no support for strokes with start/end arrow(s) // added that support Polygon aPoly; aStroke.getPath(aPoly); if(mapCurShape.get()) { if(1 != mapCurShape->maShapePolyPoly.Count() || !mapCurShape->maShapePolyPoly[0].IsEqual(aPoly)) { // this path action is not covering the same path than the already existing // fill polypolygon, so write out the fill polygon ImplWriteShape( *mapCurShape ); mapCurShape.reset(); } } if( !mapCurShape.get() ) { mapCurShape.reset( new SVGShapeDescriptor ); if( pElementId ) { mapCurShape->maId = *pElementId + B2UCONST("_") + ::rtl::OUString::valueOf(nEntryCount++); } mapCurShape->maShapePolyPoly = aPoly; } mapCurShape->maShapeLineColor = mpVDev->GetLineColor(); mapCurShape->maShapeLineColor.SetTransparency( (sal_uInt8) FRound( aStroke.getTransparency() * 255.0 ) ); mapCurShape->mnStrokeWidth = FRound( aStroke.getStrokeWidth() ); aStroke.getDashArray( mapCurShape->maDashArray ); // added support for LineJoin switch(aStroke.getJoinType()) { default: /* SvtGraphicStroke::joinMiter, SvtGraphicStroke::joinNone */ { mapCurShape->maLineJoin = basegfx::B2DLINEJOIN_MITER; break; } case SvtGraphicStroke::joinRound: { mapCurShape->maLineJoin = basegfx::B2DLINEJOIN_ROUND; break; } case SvtGraphicStroke::joinBevel: { mapCurShape->maLineJoin = basegfx::B2DLINEJOIN_BEVEL; break; } } // added support for LineCap switch(aStroke.getCapType()) { default: /* SvtGraphicStroke::capButt */ { mapCurShape->maLineCap = com::sun::star::drawing::LineCap_BUTT; break; } case SvtGraphicStroke::capRound: { mapCurShape->maLineCap = com::sun::star::drawing::LineCap_ROUND; break; } case SvtGraphicStroke::capSquare: { mapCurShape->maLineCap = com::sun::star::drawing::LineCap_SQUARE; break; } } if(mapCurShape.get() &&(aStartArrow.Count() || aEndArrow.Count())) { ImplWriteShape( *mapCurShape ); mapCurShape->maShapeFillColor = mapCurShape->maShapeLineColor; mapCurShape->maShapeLineColor = Color(COL_TRANSPARENT); mapCurShape->mnStrokeWidth = 0; mapCurShape->maDashArray.clear(); mapCurShape->maLineJoin = basegfx::B2DLINEJOIN_MITER; mapCurShape->maLineCap = com::sun::star::drawing::LineCap_BUTT; if(aStartArrow.Count()) { mapCurShape->maShapePolyPoly = aStartArrow; if( pElementId ) // #i124825# pElementId is optional, may be zero { mapCurShape->maId = *pElementId + B2UCONST("_") + ::rtl::OUString::valueOf(nEntryCount++); } ImplWriteShape( *mapCurShape ); } if(aEndArrow.Count()) { mapCurShape->maShapePolyPoly = aEndArrow; if( pElementId ) // #i124825# pElementId is optional, may be zero { mapCurShape->maId = *pElementId + B2UCONST("_") + ::rtl::OUString::valueOf(nEntryCount++); } ImplWriteShape( *mapCurShape ); } mapCurShape.reset(); } // write open shape in every case if( mapCurShape.get() ) { ImplWriteShape( *mapCurShape ); mapCurShape.reset(); } // skip rest of comment sal_Bool bSkip = true; while( bSkip && ( ++nCurAction < nCount ) ) { pAction = rMtf.GetAction( nCurAction ); if( ( pAction->GetType() == META_COMMENT_ACTION ) && ( ( (const MetaCommentAction*) pAction )->GetComment(). CompareIgnoreCaseToAscii( "XPATHSTROKE_SEQ_END" ) == COMPARE_EQUAL ) ) { bSkip = sal_False; } } } } break; case( META_BMP_ACTION ): { if( nWriteFlags & SVGWRITER_WRITE_FILL ) { const MetaBmpAction* pA = (const MetaBmpAction*) pAction; ImplWriteBmp( pA->GetBitmap(), pA->GetPoint(), mpVDev->PixelToLogic( pA->GetBitmap().GetSizePixel() ), Point(), pA->GetBitmap().GetSizePixel() ); } } break; case( META_BMPSCALE_ACTION ): { if( nWriteFlags & SVGWRITER_WRITE_FILL ) { const MetaBmpScaleAction* pA = (const MetaBmpScaleAction*) pAction; ImplWriteBmp( pA->GetBitmap(), pA->GetPoint(), pA->GetSize(), Point(), pA->GetBitmap().GetSizePixel() ); } } break; case( META_BMPSCALEPART_ACTION ): { if( nWriteFlags & SVGWRITER_WRITE_FILL ) { const MetaBmpScalePartAction* pA = (const MetaBmpScalePartAction*) pAction; ImplWriteBmp( pA->GetBitmap(), pA->GetDestPoint(), pA->GetDestSize(), pA->GetSrcPoint(), pA->GetSrcSize() ); } } break; case( META_BMPEX_ACTION ): { if( nWriteFlags & SVGWRITER_WRITE_FILL ) { const MetaBmpExAction* pA = (const MetaBmpExAction*) pAction; ImplWriteBmp( pA->GetBitmapEx(), pA->GetPoint(), mpVDev->PixelToLogic( pA->GetBitmapEx().GetSizePixel() ), Point(), pA->GetBitmapEx().GetSizePixel() ); } } break; case( META_BMPEXSCALE_ACTION ): { if( nWriteFlags & SVGWRITER_WRITE_FILL ) { const MetaBmpExScaleAction* pA = (const MetaBmpExScaleAction*) pAction; ImplWriteBmp( pA->GetBitmapEx(), pA->GetPoint(), pA->GetSize(), Point(), pA->GetBitmapEx().GetSizePixel() ); } } break; case( META_BMPEXSCALEPART_ACTION ): { if( nWriteFlags & SVGWRITER_WRITE_FILL ) { const MetaBmpExScalePartAction* pA = (const MetaBmpExScalePartAction*) pAction; ImplWriteBmp( pA->GetBitmapEx(), pA->GetDestPoint(), pA->GetDestSize(), pA->GetSrcPoint(), pA->GetSrcSize() ); } } break; case( META_TEXT_ACTION ): { if( nWriteFlags & SVGWRITER_WRITE_TEXT ) { const MetaTextAction* pA = (const MetaTextAction*) pAction; const String aText( pA->GetText(), pA->GetIndex(), pA->GetLen() ); if( aText.Len() ) { Font aFont( mpVDev->GetFont() ); Size aSz; ImplMap( Size( 0, aFont.GetHeight() ), aSz ); aFont.SetHeight( aSz.Height() ); mpContext->AddPaintAttr( COL_TRANSPARENT, mpVDev->GetTextColor() ); mpContext->SetFontAttr( aFont ); ImplWriteText( pA->GetPoint(), aText, NULL, 0 ); } } } break; case( META_TEXTRECT_ACTION ): { if( nWriteFlags & SVGWRITER_WRITE_TEXT ) { const MetaTextRectAction* pA = (const MetaTextRectAction*) pAction; if( pA->GetText().Len() ) { Font aFont( mpVDev->GetFont() ); Size aSz; ImplMap( Size( 0, aFont.GetHeight() ), aSz ); aFont.SetHeight( aSz.Height() ); mpContext->AddPaintAttr( COL_TRANSPARENT, mpVDev->GetTextColor() ); mpContext->SetFontAttr( aFont ); ImplWriteText( pA->GetRect().TopLeft(), pA->GetText(), NULL, 0 ); } } } break; case( META_TEXTARRAY_ACTION ): { if( nWriteFlags & SVGWRITER_WRITE_TEXT ) { const MetaTextArrayAction* pA = (const MetaTextArrayAction*) pAction; const String aText( pA->GetText(), pA->GetIndex(), pA->GetLen() ); if( aText.Len() ) { Font aFont( mpVDev->GetFont() ); Size aSz; ImplMap( Size( 0, aFont.GetHeight() ), aSz ); aFont.SetHeight( aSz.Height() ); mpContext->AddPaintAttr( COL_TRANSPARENT, mpVDev->GetTextColor() ); mpContext->SetFontAttr( aFont ); ImplWriteText( pA->GetPoint(), aText, pA->GetDXArray(), 0 ); } } } break; case( META_STRETCHTEXT_ACTION ): { if( nWriteFlags & SVGWRITER_WRITE_TEXT ) { const MetaStretchTextAction* pA = (const MetaStretchTextAction*) pAction; const String aText( pA->GetText(), pA->GetIndex(), pA->GetLen() ); if( aText.Len() ) { Font aFont( mpVDev->GetFont() ); Size aSz; ImplMap( Size( 0, aFont.GetHeight() ), aSz ); aFont.SetHeight( aSz.Height() ); mpContext->AddPaintAttr( COL_TRANSPARENT, mpVDev->GetTextColor() ); mpContext->SetFontAttr( aFont ); ImplWriteText( pA->GetPoint(), aText, NULL, pA->GetWidth() ); } } } break; case( META_CLIPREGION_ACTION ): case( META_ISECTRECTCLIPREGION_ACTION ): case( META_ISECTREGIONCLIPREGION_ACTION ): case( META_MOVECLIPREGION_ACTION ): { ( (MetaAction*) pAction )->Execute( mpVDev ); mbClipAttrChanged = sal_True; } break; case( META_REFPOINT_ACTION ): case( META_MAPMODE_ACTION ): case( META_LINECOLOR_ACTION ): case( META_FILLCOLOR_ACTION ): case( META_TEXTLINECOLOR_ACTION ): case( META_TEXTFILLCOLOR_ACTION ): case( META_TEXTCOLOR_ACTION ): case( META_TEXTALIGN_ACTION ): case( META_FONT_ACTION ): case( META_PUSH_ACTION ): case( META_POP_ACTION ): case( META_LAYOUTMODE_ACTION ): { ( (MetaAction*) pAction )->Execute( mpVDev ); } break; case( META_RASTEROP_ACTION ): case( META_MASK_ACTION ): case( META_MASKSCALE_ACTION ): case( META_MASKSCALEPART_ACTION ): case( META_WALLPAPER_ACTION ): case( META_TEXTLINE_ACTION ): { // !!! >>> we don't want to support these actions } break; default: DBG_ERROR( "SVGActionWriter::ImplWriteActions: unsupported MetaAction #" ); break; } } } // ----------------------------------------------------------------------------- void SVGActionWriter::WriteMetaFile( const Point& rPos100thmm, const Size& rSize100thmm, const GDIMetaFile& rMtf, sal_uInt32 nWriteFlags, const ::rtl::OUString* pElementId ) { MapMode aMapMode( rMtf.GetPrefMapMode() ); Size aPrefSize( rMtf.GetPrefSize() ); Fraction aFractionX( aMapMode.GetScaleX() ); Fraction aFractionY( aMapMode.GetScaleY() ); mpVDev->Push(); Size aSize( OutputDevice::LogicToLogic( rSize100thmm, MAP_100TH_MM, aMapMode ) ); aMapMode.SetScaleX( aFractionX *= Fraction( aSize.Width(), aPrefSize.Width() ) ); aMapMode.SetScaleY( aFractionY *= Fraction( aSize.Height(), aPrefSize.Height() ) ); Point aOffset( OutputDevice::LogicToLogic( rPos100thmm, MAP_100TH_MM, aMapMode ) ); aMapMode.SetOrigin( aOffset += aMapMode.GetOrigin() ); mpVDev->SetMapMode( aMapMode ); ImplAcquireContext(); mapCurShape.reset(); ImplWriteActions( rMtf, nWriteFlags, pElementId ); // draw open shape that doesn't have a border if( mapCurShape.get() ) { ImplWriteShape( *mapCurShape ); mapCurShape.reset(); } ImplReleaseContext(); mpVDev->Pop(); } // ------------- // - SVGWriter - // ------------- SVGWriter::SVGWriter( const REF( NMSP_LANG::XMultiServiceFactory )& rxMgr ) : mxFact( rxMgr ) { } // ----------------------------------------------------------------------------- SVGWriter::~SVGWriter() { } // ----------------------------------------------------------------------------- ANY SAL_CALL SVGWriter::queryInterface( const NMSP_UNO::Type & rType ) throw( NMSP_UNO::RuntimeException ) { const ANY aRet( NMSP_CPPU::queryInterface( rType, static_cast< NMSP_SVG::XSVGWriter* >( this ), static_cast< NMSP_LANG::XInitialization* >( this ) ) ); return( aRet.hasValue() ? aRet : OWeakObject::queryInterface( rType ) ); } // ----------------------------------------------------------------------------- void SAL_CALL SVGWriter::acquire() throw() { OWeakObject::acquire(); } // ----------------------------------------------------------------------------- void SAL_CALL SVGWriter::release() throw() { OWeakObject::release(); } // ----------------------------------------------------------------------------- void SAL_CALL SVGWriter::write( const REF( NMSP_SAX::XDocumentHandler )& rxDocHandler, const SEQ( sal_Int8 )& rMtfSeq ) throw( NMSP_UNO::RuntimeException ) { SvMemoryStream aMemStm( (char*) rMtfSeq.getConstArray(), rMtfSeq.getLength(), STREAM_READ ); GDIMetaFile aMtf; aMemStm.SetCompressMode( COMPRESSMODE_FULL ); aMemStm >> aMtf; const REF( NMSP_SAX::XDocumentHandler ) xDocumentHandler( rxDocHandler ); SVGExport* pWriter = new SVGExport( mxFact, xDocumentHandler, maFilterData ); pWriter->writeMtf( aMtf ); delete pWriter; } // ----------------------------------------------------------------------------- void SVGWriter::initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException) { if ( aArguments.getLength() == 1 ) { ::com::sun::star::uno::Any aArg = aArguments.getConstArray()[0]; aArg >>= maFilterData; } } // ----------------------------------------------------------------------------- #define SVG_WRITER_SERVICE_NAME "com.sun.star.svg.SVGWriter" #define SVG_WRITER_IMPLEMENTATION_NAME "com.sun.star.comp.Draw.SVGWriter" rtl::OUString SVGWriter_getImplementationName() throw (RuntimeException) { return rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM( SVG_WRITER_IMPLEMENTATION_NAME ) ); } // ----------------------------------------------------------------------------- Sequence< sal_Int8 > SAL_CALL SVGWriter_getImplementationId() throw(RuntimeException) { static const ::cppu::OImplementationId aId; return( aId.getImplementationId() ); } // ----------------------------------------------------------------------------- Sequence< rtl::OUString > SAL_CALL SVGWriter_getSupportedServiceNames() throw (RuntimeException) { Sequence< rtl::OUString > aRet( 1 ); aRet.getArray()[ 0 ] = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( SVG_WRITER_SERVICE_NAME ) ); return aRet; } // ----------------------------------------------------------------------------- Reference< XInterface > SAL_CALL SVGWriter_createInstance( const Reference< XMultiServiceFactory > & rSMgr ) throw( Exception ) { return( static_cast< cppu::OWeakObject* >( new SVGWriter( rSMgr ) ) ); }
39,256