code
stringlengths
4
1.01M
language
stringclasses
2 values
#!/usr/bin/python """Test of tree output using Firefox.""" from macaroon.playback import * import utils sequence = MacroSequence() sequence.append(PauseAction(3000)) sequence.append(KeyComboAction("<Alt>b")) sequence.append(KeyComboAction("Return")) sequence.append(KeyComboAction("Tab")) sequence.append(KeyComboAction("Tab")) sequence.append(KeyComboAction("Up")) sequence.append(KeyComboAction("Up")) sequence.append(KeyComboAction("Up")) sequence.append(KeyComboAction("Tab")) sequence.append(PauseAction(3000)) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("<Shift>Tab")) sequence.append(utils.AssertPresentationAction( "1. Shift Tab for tree", ["BRAILLE LINE: 'Firefox application Library frame All Bookmarks expanded TREE LEVEL 1'", " VISIBLE: 'All Bookmarks expanded TREE LEVE', cursor=1", "SPEECH OUTPUT: 'All Bookmarks.'", "SPEECH OUTPUT: 'expanded.'"])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("Down")) sequence.append(utils.AssertPresentationAction( "2. Down Arrow in tree", ["BRAILLE LINE: 'Firefox application Library frame Bookmarks Toolbar TREE LEVEL 2'", " VISIBLE: 'Bookmarks Toolbar TREE LEVEL 2', cursor=1", "SPEECH OUTPUT: 'Bookmarks Toolbar.'", "SPEECH OUTPUT: 'tree level 2'"])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("Down")) sequence.append(utils.AssertPresentationAction( "3. Down Arrow in tree", ["BRAILLE LINE: 'Firefox application Library frame Bookmarks Menu collapsed TREE LEVEL 2'", " VISIBLE: 'Bookmarks Menu collapsed TREE LE', cursor=1", "SPEECH OUTPUT: 'Bookmarks Menu.'", "SPEECH OUTPUT: 'collapsed.'"])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("KP_Enter")) sequence.append(utils.AssertPresentationAction( "4. Basic Where Am I", ["BRAILLE LINE: 'Firefox application Library frame Bookmarks Menu collapsed TREE LEVEL 2'", " VISIBLE: 'Bookmarks Menu collapsed TREE LE', cursor=1", "SPEECH OUTPUT: 'Bookmarks Menu tree item.'", "SPEECH OUTPUT: '2 of 3.'", "SPEECH OUTPUT: 'collapsed tree level 2'"])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("Right")) sequence.append(utils.AssertPresentationAction( "5. Right Arrow to expand folder", ["BRAILLE LINE: 'Firefox application Library frame Bookmarks Menu expanded TREE LEVEL 2'", " VISIBLE: 'Bookmarks Menu expanded TREE LEV', cursor=1", "SPEECH OUTPUT: 'expanded'"])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("KP_Enter")) sequence.append(utils.AssertPresentationAction( "6. Basic Where Am I", ["BRAILLE LINE: 'Firefox application Library frame Bookmarks Menu expanded TREE LEVEL 2'", " VISIBLE: 'Bookmarks Menu expanded TREE LEV', cursor=1", "SPEECH OUTPUT: 'Bookmarks Menu tree item.'", "SPEECH OUTPUT: '2 of 3.'", "SPEECH OUTPUT: 'expanded tree level 2'"])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("Down")) sequence.append(utils.AssertPresentationAction( "7. Down Arrow in tree", ["BRAILLE LINE: 'Firefox application Library frame GNOME TREE LEVEL 3'", " VISIBLE: 'GNOME TREE LEVEL 3', cursor=1", "SPEECH OUTPUT: 'GNOME.'", "SPEECH OUTPUT: 'tree level 3'"])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("KP_Enter")) sequence.append(utils.AssertPresentationAction( "8. Basic Where Am I", ["BRAILLE LINE: 'Firefox application Library frame GNOME TREE LEVEL 3'", " VISIBLE: 'GNOME TREE LEVEL 3', cursor=1", "SPEECH OUTPUT: 'GNOME tree item.'", "SPEECH OUTPUT: '1 of 2.'", "SPEECH OUTPUT: 'tree level 3'"])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("Up")) sequence.append(utils.AssertPresentationAction( "9. Up Arrow in tree", ["BRAILLE LINE: 'Firefox application Library frame Bookmarks Menu expanded TREE LEVEL 2'", " VISIBLE: 'Bookmarks Menu expanded TREE LEV', cursor=1", "SPEECH OUTPUT: 'Bookmarks Menu.'", "SPEECH OUTPUT: 'expanded.'", "SPEECH OUTPUT: 'tree level 2'"])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("Left")) sequence.append(utils.AssertPresentationAction( "10. Left Arrow to collapse folder", ["BRAILLE LINE: 'Firefox application Library frame Bookmarks Menu collapsed TREE LEVEL 2'", " VISIBLE: 'Bookmarks Menu collapsed TREE LE', cursor=1", "SPEECH OUTPUT: 'collapsed'"])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("Up")) sequence.append(utils.AssertPresentationAction( "11. Up Arrow in tree", ["BRAILLE LINE: 'Firefox application Library frame Bookmarks Toolbar TREE LEVEL 2'", " VISIBLE: 'Bookmarks Toolbar TREE LEVEL 2', cursor=1", "SPEECH OUTPUT: 'Bookmarks Toolbar.'"])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("Up")) sequence.append(utils.AssertPresentationAction( "12. Up Arrow in tree", ["BRAILLE LINE: 'Firefox application Library frame All Bookmarks expanded TREE LEVEL 1'", " VISIBLE: 'All Bookmarks expanded TREE LEVE', cursor=1", "SPEECH OUTPUT: 'All Bookmarks.'", "SPEECH OUTPUT: 'expanded.'", "SPEECH OUTPUT: 'tree level 1'"])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("Tab")) sequence.append(utils.AssertPresentationAction( "13. Tab back to tree table", ["BRAILLE LINE: 'Firefox application Library frame tree table Bookmarks Toolbar table row TREE LEVEL 1'", " VISIBLE: 'Bookmarks Toolbar table row TR', cursor=1", "SPEECH OUTPUT: 'Bookmarks Toolbar '"])) sequence.append(KeyComboAction("<Alt>F4")) sequence.append(utils.AssertionSummaryAction()) sequence.start()
Java
import { FutureResult } from '@ephox/katamari'; import { ResponseBodyDataTypes, RequestBody, ResponseBody } from './HttpData'; import { HttpError } from './HttpError'; export const enum HttpMethod { Get = 'get', Post = 'post', Delete = 'delete', Patch = 'patch', Put = 'put' } export type ProgressFunction = (loaded: number, total: number) => void; export type LoadedProgressFunction = (loaded: number) => void; export interface HttpRequest<T extends ResponseBodyDataTypes> { responseType: T; body: RequestBody; url: string; method: HttpMethod; query?: Record<string, string>; progress?: ProgressFunction; headers?: Record<string, string>; credentials?: boolean; } export interface HttpResponse<T extends ResponseBody> { headers: Record<string, string>; statusCode: number; body: T; } export type JwtToken = string; export type JwtTokenFactory = (fresh: boolean) => FutureResult<JwtToken, HttpError>; type Omit<T, K> = Pick<T, Exclude<keyof T, K>>; export type PostPutInit <T extends ResponseBodyDataTypes> = Omit<HttpRequest<T>, 'method'>; export type GetDelInit <T extends ResponseBodyDataTypes> = Omit<HttpRequest<T>, 'method' | 'body'>; export interface DownloadHttpRequest { url: string; progress?: LoadedProgressFunction; headers?: Record<string, string>; credentials?: boolean; }
Java
/* (c) Copyright 2001-2010 The world wide DirectFB Open Source Community (directfb.org) (c) Copyright 2000-2004 Convergence (integrated media) GmbH All rights reserved. Written by Denis Oliver Kropp <dok@directfb.org>, Andreas Hundt <andi@fischlustig.de>, Sven Neumann <neo@directfb.org>, Ville Syrjälä <syrjala@sci.fi> and Claudio Ciccani <klan@users.sf.net>. This library 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 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <config.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <directfb.h> #include <directfb_keynames.h> #include <direct/debug.h> #include <direct/list.h> #include <direct/memcpy.h> #include <direct/messages.h> #include <fusion/shmalloc.h> #include <fusion/reactor.h> #include <fusion/arena.h> #include <core/core.h> #include <core/coredefs.h> #include <core/coretypes.h> #include <core/core_parts.h> #include <core/gfxcard.h> #include <core/surface.h> #include <core/surface_buffer.h> #include <core/system.h> #include <core/layer_context.h> #include <core/layer_control.h> #include <core/layer_region.h> #include <core/layers.h> #include <core/input.h> #include <core/windows.h> #include <core/windows_internal.h> #include <direct/mem.h> #include <direct/memcpy.h> #include <direct/messages.h> #include <direct/modules.h> #include <direct/trace.h> #include <fusion/build.h> #include <misc/conf.h> #include <misc/util.h> #include <gfx/convert.h> #define CHECK_INTERVAL 20000 // Microseconds #define CHECK_NUMBER 200 D_DEBUG_DOMAIN( Core_Input, "Core/Input", "DirectFB Input Core" ); D_DEBUG_DOMAIN( Core_InputEvt, "Core/Input/Evt", "DirectFB Input Core Events & Dispatch" ); DEFINE_MODULE_DIRECTORY( dfb_input_modules, "inputdrivers", DFB_INPUT_DRIVER_ABI_VERSION ); /**********************************************************************************************************************/ typedef enum { CIDC_RELOAD_KEYMAP } CoreInputDeviceCommand; typedef struct { DirectLink link; int magic; DirectModuleEntry *module; const InputDriverFuncs *funcs; InputDriverInfo info; int nr_devices; } InputDriver; typedef struct { int min_keycode; int max_keycode; int num_entries; DFBInputDeviceKeymapEntry *entries; } InputDeviceKeymap; typedef struct { int magic; DFBInputDeviceID id; /* unique device id */ int num; InputDeviceInfo device_info; InputDeviceKeymap keymap; DFBInputDeviceModifierMask modifiers_l; DFBInputDeviceModifierMask modifiers_r; DFBInputDeviceLockState locks; DFBInputDeviceButtonMask buttons; DFBInputDeviceKeyIdentifier last_key; /* last key pressed */ DFBInputDeviceKeySymbol last_symbol; /* last symbol pressed */ bool first_press; /* first press of key */ FusionReactor *reactor; /* event dispatcher */ FusionSkirmish lock; FusionCall call; /* driver call via master */ unsigned int axis_num; DFBInputDeviceAxisInfo *axis_info; FusionRef ref; /* Ref between shared device & local device */ } InputDeviceShared; struct __DFB_CoreInputDevice { DirectLink link; int magic; InputDeviceShared *shared; InputDriver *driver; void *driver_data; CoreDFB *core; }; /**********************************************************************************************************************/ typedef struct { int magic; int num; InputDeviceShared *devices[MAX_INPUTDEVICES]; FusionReactor *reactor; /* For input hot-plug event */ } DFBInputCoreShared; struct __DFB_DFBInputCore { int magic; CoreDFB *core; DFBInputCoreShared *shared; DirectLink *drivers; DirectLink *devices; }; DFB_CORE_PART( input_core, InputCore ); /**********************************************************************************************************************/ typedef struct { DFBInputDeviceKeySymbol target; DFBInputDeviceKeySymbol result; } DeadKeyCombo; typedef struct { DFBInputDeviceKeySymbol deadkey; const DeadKeyCombo *combos; } DeadKeyMap; /* Data struct of input device hotplug event */ typedef struct { bool is_plugin; /* Hotplug in or not */ int dev_id; /* Input device ID*/ struct timeval stamp; /* Time stamp of event */ } InputDeviceHotplugEvent; /**********************************************************************************************************************/ static const DeadKeyCombo combos_grave[] = { { DIKS_SPACE, (unsigned char) '`' }, { DIKS_SMALL_A, (unsigned char) 'à' }, { DIKS_SMALL_E, (unsigned char) 'è' }, { DIKS_SMALL_I, (unsigned char) 'ì' }, { DIKS_SMALL_O, (unsigned char) 'ò' }, { DIKS_SMALL_U, (unsigned char) 'ù' }, { DIKS_CAPITAL_A, (unsigned char) 'À' }, { DIKS_CAPITAL_E, (unsigned char) 'È' }, { DIKS_CAPITAL_I, (unsigned char) 'Ì' }, { DIKS_CAPITAL_O, (unsigned char) 'Ò' }, { DIKS_CAPITAL_U, (unsigned char) 'Ù' }, { 0, 0 } }; static const DeadKeyCombo combos_acute[] = { { DIKS_SPACE, (unsigned char) '\'' }, { DIKS_SMALL_A, (unsigned char) 'á' }, { DIKS_SMALL_E, (unsigned char) 'é' }, { DIKS_SMALL_I, (unsigned char) 'í' }, { DIKS_SMALL_O, (unsigned char) 'ó' }, { DIKS_SMALL_U, (unsigned char) 'ú' }, { DIKS_SMALL_Y, (unsigned char) 'ý' }, { DIKS_CAPITAL_A, (unsigned char) 'Á' }, { DIKS_CAPITAL_E, (unsigned char) 'É' }, { DIKS_CAPITAL_I, (unsigned char) 'Í' }, { DIKS_CAPITAL_O, (unsigned char) 'Ó' }, { DIKS_CAPITAL_U, (unsigned char) 'Ú' }, { DIKS_CAPITAL_Y, (unsigned char) 'Ý' }, { 0, 0 } }; static const DeadKeyCombo combos_circumflex[] = { { DIKS_SPACE, (unsigned char) '^' }, { DIKS_SMALL_A, (unsigned char) 'â' }, { DIKS_SMALL_E, (unsigned char) 'ê' }, { DIKS_SMALL_I, (unsigned char) 'î' }, { DIKS_SMALL_O, (unsigned char) 'ô' }, { DIKS_SMALL_U, (unsigned char) 'û' }, { DIKS_CAPITAL_A, (unsigned char) 'Â' }, { DIKS_CAPITAL_E, (unsigned char) 'Ê' }, { DIKS_CAPITAL_I, (unsigned char) 'Î' }, { DIKS_CAPITAL_O, (unsigned char) 'Ô' }, { DIKS_CAPITAL_U, (unsigned char) 'Û' }, { 0, 0 } }; static const DeadKeyCombo combos_diaeresis[] = { { DIKS_SPACE, (unsigned char) '¨' }, { DIKS_SMALL_A, (unsigned char) 'ä' }, { DIKS_SMALL_E, (unsigned char) 'ë' }, { DIKS_SMALL_I, (unsigned char) 'ï' }, { DIKS_SMALL_O, (unsigned char) 'ö' }, { DIKS_SMALL_U, (unsigned char) 'ü' }, { DIKS_CAPITAL_A, (unsigned char) 'Ä' }, { DIKS_CAPITAL_E, (unsigned char) 'Ë' }, { DIKS_CAPITAL_I, (unsigned char) 'Ï' }, { DIKS_CAPITAL_O, (unsigned char) 'Ö' }, { DIKS_CAPITAL_U, (unsigned char) 'Ü' }, { 0, 0 } }; static const DeadKeyCombo combos_tilde[] = { { DIKS_SPACE, (unsigned char) '~' }, { DIKS_SMALL_A, (unsigned char) 'ã' }, { DIKS_SMALL_N, (unsigned char) 'ñ' }, { DIKS_SMALL_O, (unsigned char) 'õ' }, { DIKS_CAPITAL_A, (unsigned char) 'Ã' }, { DIKS_CAPITAL_N, (unsigned char) 'Ñ' }, { DIKS_CAPITAL_O, (unsigned char) 'Õ' }, { 0, 0 } }; static const DeadKeyMap deadkey_maps[] = { { DIKS_DEAD_GRAVE, combos_grave }, { DIKS_DEAD_ACUTE, combos_acute }, { DIKS_DEAD_CIRCUMFLEX, combos_circumflex }, { DIKS_DEAD_DIAERESIS, combos_diaeresis }, { DIKS_DEAD_TILDE, combos_tilde } }; /* define a lookup table to go from key IDs to names. * This is used to look up the names provided in a loaded key table */ /* this table is roughly 4Kb in size */ DirectFBKeySymbolNames(KeySymbolNames); DirectFBKeyIdentifierNames(KeyIdentifierNames); /**********************************************************************************************************************/ static void init_devices( CoreDFB *core ); static void allocate_device_keymap( CoreDFB *core, CoreInputDevice *device ); static DFBInputDeviceKeymapEntry *get_keymap_entry( CoreInputDevice *device, int code ); static DFBResult set_keymap_entry( CoreInputDevice *device, int code, DFBInputDeviceKeymapEntry *entry ); static DFBResult load_keymap( CoreInputDevice *device, char *filename ); static DFBInputDeviceKeySymbol lookup_keysymbol( char *symbolname ); static DFBInputDeviceKeyIdentifier lookup_keyidentifier( char *identifiername ); /**********************************************************************************************************************/ static bool lookup_from_table( CoreInputDevice *device, DFBInputEvent *event, DFBInputEventFlags lookup ); static void fixup_key_event ( CoreInputDevice *device, DFBInputEvent *event ); static void fixup_mouse_event( CoreInputDevice *device, DFBInputEvent *event ); static void flush_keys ( CoreInputDevice *device ); static bool core_input_filter( CoreInputDevice *device, DFBInputEvent *event ); /**********************************************************************************************************************/ static DFBInputDeviceKeyIdentifier symbol_to_id( DFBInputDeviceKeySymbol symbol ); static DFBInputDeviceKeySymbol id_to_symbol( DFBInputDeviceKeyIdentifier id, DFBInputDeviceModifierMask modifiers, DFBInputDeviceLockState locks ); /**********************************************************************************************************************/ static ReactionResult local_processing_hotplug( const void *msg_data, void *ctx ); /**********************************************************************************************************************/ static ReactionFunc dfb_input_globals[MAX_INPUT_GLOBALS+1] = { /* 0 */ _dfb_windowstack_inputdevice_listener, NULL }; DFBResult dfb_input_add_global( ReactionFunc func, int *ret_index ) { int i; D_DEBUG_AT( Core_Input, "%s( %p, %p )\n", __FUNCTION__, func, ret_index ); D_ASSERT( func != NULL ); D_ASSERT( ret_index != NULL ); for (i=0; i<MAX_INPUT_GLOBALS; i++) { if (!dfb_input_globals[i]) { dfb_input_globals[i] = func; D_DEBUG_AT( Core_Input, " -> index %d\n", i ); *ret_index = i; return DFB_OK; } } return DFB_LIMITEXCEEDED; } DFBResult dfb_input_set_global( ReactionFunc func, int index ) { D_DEBUG_AT( Core_Input, "%s( %p, %d )\n", __FUNCTION__, func, index ); D_ASSERT( func != NULL ); D_ASSERT( index >= 0 ); D_ASSERT( index < MAX_INPUT_GLOBALS ); D_ASSUME( dfb_input_globals[index] == NULL ); dfb_input_globals[index] = func; return DFB_OK; } /**********************************************************************************************************************/ static DFBInputCore *core_local; /* FIXME */ static DFBInputCoreShared *core_input; /* FIXME */ #if FUSION_BUILD_MULTI static Reaction local_processing_react; /* Local reaction to hot-plug event */ #endif static DFBResult dfb_input_core_initialize( CoreDFB *core, DFBInputCore *data, DFBInputCoreShared *shared ) { #if FUSION_BUILD_MULTI DFBResult result = DFB_OK; #endif D_DEBUG_AT( Core_Input, "dfb_input_core_initialize( %p, %p, %p )\n", core, data, shared ); D_ASSERT( data != NULL ); D_ASSERT( shared != NULL ); core_local = data; /* FIXME */ core_input = shared; /* FIXME */ data->core = core; data->shared = shared; direct_modules_explore_directory( &dfb_input_modules ); #if FUSION_BUILD_MULTI /* Create the reactor that responds input device hot-plug events. */ core_input->reactor = fusion_reactor_new( sizeof( InputDeviceHotplugEvent ), "Input Hotplug", dfb_core_world(core) ); if (!core_input->reactor) { D_ERROR( "DirectFB/Input: fusion_reactor_new() failed!\n" ); result = DFB_FAILURE; goto errorExit; } /* Attach local process function to the input hot-plug reactor. */ result = fusion_reactor_attach( core_input->reactor, local_processing_hotplug, (void*) core, &local_processing_react ); if (result) { D_ERROR( "DirectFB/Input: fusion_reactor_attach() failed!\n" ); goto errorExit; } #endif init_devices( core ); D_MAGIC_SET( data, DFBInputCore ); D_MAGIC_SET( shared, DFBInputCoreShared ); return DFB_OK; #if FUSION_BUILD_MULTI errorExit: /* Destroy the hot-plug reactor if it was created. */ if (core_input->reactor) fusion_reactor_destroy(core_input->reactor); return result; #endif } static DFBResult dfb_input_core_join( CoreDFB *core, DFBInputCore *data, DFBInputCoreShared *shared ) { int i; #if FUSION_BUILD_MULTI DFBResult result; #endif D_DEBUG_AT( Core_Input, "dfb_input_core_join( %p, %p, %p )\n", core, data, shared ); D_ASSERT( data != NULL ); D_MAGIC_ASSERT( shared, DFBInputCoreShared ); D_ASSERT( shared->reactor != NULL ); core_local = data; /* FIXME */ core_input = shared; /* FIXME */ data->core = core; data->shared = shared; #if FUSION_BUILD_MULTI /* Attach the local process function to the input hot-plug reactor. */ result = fusion_reactor_attach( core_input->reactor, local_processing_hotplug, (void*) core, &local_processing_react ); if (result) { D_ERROR( "DirectFB/Input: fusion_reactor_attach failed!\n" ); return result; } #endif for (i=0; i<core_input->num; i++) { CoreInputDevice *device; device = D_CALLOC( 1, sizeof(CoreInputDevice) ); if (!device) { D_OOM(); continue; } device->shared = core_input->devices[i]; #if FUSION_BUILD_MULTI /* Increase the reference counter. */ fusion_ref_up( &device->shared->ref, true ); #endif /* add it to the list */ direct_list_append( &data->devices, &device->link ); D_MAGIC_SET( device, CoreInputDevice ); } D_MAGIC_SET( data, DFBInputCore ); return DFB_OK; } static DFBResult dfb_input_core_shutdown( DFBInputCore *data, bool emergency ) { DFBInputCoreShared *shared; DirectLink *n; CoreInputDevice *device; FusionSHMPoolShared *pool = dfb_core_shmpool( data->core ); InputDriver *driver; D_DEBUG_AT( Core_Input, "dfb_input_core_shutdown( %p, %semergency )\n", data, emergency ? "" : "no " ); D_MAGIC_ASSERT( data, DFBInputCore ); D_MAGIC_ASSERT( data->shared, DFBInputCoreShared ); shared = data->shared; /* Stop each input provider's hot-plug thread that supports device hot-plugging. */ direct_list_foreach_safe (driver, n, core_local->drivers) { if (driver->funcs->GetCapability && driver->funcs->StopHotplug) { if (IDC_HOTPLUG & driver->funcs->GetCapability()) { D_DEBUG_AT( Core_Input, "Stopping hot-plug detection thread " "within %s\n ", driver->module->name ); if (driver->funcs->StopHotplug()) { D_ERROR( "DirectFB/Input: StopHotplug() failed with %s\n", driver->module->name ); } } } } #if FUSION_BUILD_MULTI fusion_reactor_detach( core_input->reactor, &local_processing_react ); fusion_reactor_destroy( core_input->reactor ); #endif direct_list_foreach_safe (device, n, data->devices) { InputDeviceShared *devshared; D_MAGIC_ASSERT( device, CoreInputDevice ); driver = device->driver; D_ASSERT( driver != NULL ); devshared = device->shared; D_ASSERT( devshared != NULL ); fusion_call_destroy( &devshared->call ); fusion_skirmish_destroy( &devshared->lock ); if (device->driver_data != NULL) { void *driver_data; D_ASSERT( driver->funcs != NULL ); D_ASSERT( driver->funcs->CloseDevice != NULL ); D_DEBUG_AT( Core_Input, " -> closing '%s' (%d) %d.%d (%s)\n", devshared->device_info.desc.name, devshared->num + 1, driver->info.version.major, driver->info.version.minor, driver->info.vendor ); driver_data = device->driver_data; device->driver_data = NULL; driver->funcs->CloseDevice( driver_data ); } if (!--driver->nr_devices) { direct_module_unref( driver->module ); D_FREE( driver ); } #if FUSION_BUILD_MULTI fusion_ref_destroy( &device->shared->ref ); #endif fusion_reactor_free( devshared->reactor ); if (devshared->keymap.entries) SHFREE( pool, devshared->keymap.entries ); if (devshared->axis_info) SHFREE( pool, devshared->axis_info ); SHFREE( pool, devshared ); D_MAGIC_CLEAR( device ); D_FREE( device ); } D_MAGIC_CLEAR( data ); D_MAGIC_CLEAR( shared ); return DFB_OK; } static DFBResult dfb_input_core_leave( DFBInputCore *data, bool emergency ) { DFBInputCoreShared *shared; DirectLink *n; CoreInputDevice *device; D_DEBUG_AT( Core_Input, "dfb_input_core_leave( %p, %semergency )\n", data, emergency ? "" : "no " ); D_MAGIC_ASSERT( data, DFBInputCore ); D_MAGIC_ASSERT( data->shared, DFBInputCoreShared ); shared = data->shared; #if FUSION_BUILD_MULTI fusion_reactor_detach( core_input->reactor, &local_processing_react ); #endif direct_list_foreach_safe (device, n, data->devices) { D_MAGIC_ASSERT( device, CoreInputDevice ); #if FUSION_BUILD_MULTI /* Decrease the ref between shared device and local device. */ fusion_ref_down( &device->shared->ref, true ); #endif D_FREE( device ); } D_MAGIC_CLEAR( data ); return DFB_OK; } static DFBResult dfb_input_core_suspend( DFBInputCore *data ) { DFBInputCoreShared *shared; CoreInputDevice *device; InputDriver *driver; D_DEBUG_AT( Core_Input, "dfb_input_core_suspend( %p )\n", data ); D_MAGIC_ASSERT( data, DFBInputCore ); D_MAGIC_ASSERT( data->shared, DFBInputCoreShared ); shared = data->shared; D_DEBUG_AT( Core_Input, " -> suspending...\n" ); /* Go through the drivers list and attempt to suspend all of the drivers that * support the Suspend function. */ direct_list_foreach (driver, core_local->drivers) { DFBResult ret; D_ASSERT( driver->funcs->Suspend != NULL ); ret = driver->funcs->Suspend(); if (ret != DFB_OK && ret != DFB_UNSUPPORTED) { D_DERROR( ret, "driver->Suspend failed during suspend (%s)\n", driver->info.name ); } } direct_list_foreach (device, data->devices) { InputDeviceShared *devshared; D_MAGIC_ASSERT( device, CoreInputDevice ); driver = device->driver; D_ASSERT( driver != NULL ); devshared = device->shared; D_ASSERT( devshared != NULL ); if (device->driver_data != NULL) { void *driver_data; D_ASSERT( driver->funcs != NULL ); D_ASSERT( driver->funcs->CloseDevice != NULL ); D_DEBUG_AT( Core_Input, " -> closing '%s' (%d) %d.%d (%s)\n", devshared->device_info.desc.name, devshared->num + 1, driver->info.version.major, driver->info.version.minor, driver->info.vendor ); driver_data = device->driver_data; device->driver_data = NULL; driver->funcs->CloseDevice( driver_data ); } flush_keys( device ); } D_DEBUG_AT( Core_Input, " -> suspended.\n" ); return DFB_OK; } static DFBResult dfb_input_core_resume( DFBInputCore *data ) { DFBInputCoreShared *shared; DFBResult ret; CoreInputDevice *device; InputDriver *driver; D_DEBUG_AT( Core_Input, "dfb_input_core_resume( %p )\n", data ); D_MAGIC_ASSERT( data, DFBInputCore ); D_MAGIC_ASSERT( data->shared, DFBInputCoreShared ); shared = data->shared; D_DEBUG_AT( Core_Input, " -> resuming...\n" ); direct_list_foreach (device, data->devices) { D_MAGIC_ASSERT( device, CoreInputDevice ); D_DEBUG_AT( Core_Input, " -> reopening '%s' (%d) %d.%d (%s)\n", device->shared->device_info.desc.name, device->shared->num + 1, device->driver->info.version.major, device->driver->info.version.minor, device->driver->info.vendor ); D_ASSERT( device->driver_data == NULL ); ret = device->driver->funcs->OpenDevice( device, device->shared->num, &device->shared->device_info, &device->driver_data ); if (ret) { D_DERROR( ret, "DirectFB/Input: Failed reopening device " "during resume (%s)!\n", device->shared->device_info.desc.name ); device->driver_data = NULL; } } /* Go through the drivers list and attempt to resume all of the drivers that * support the Resume function. */ direct_list_foreach (driver, core_local->drivers) { D_ASSERT( driver->funcs->Resume != NULL ); ret = driver->funcs->Resume(); if (ret != DFB_OK && ret != DFB_UNSUPPORTED) { D_DERROR( ret, "driver->Resume failed during resume (%s)\n", driver->info.name ); } } D_DEBUG_AT( Core_Input, " -> resumed.\n" ); return DFB_OK; } void dfb_input_enumerate_devices( InputDeviceCallback callback, void *ctx, DFBInputDeviceCapabilities caps ) { CoreInputDevice *device; D_ASSERT( core_input != NULL ); direct_list_foreach (device, core_local->devices) { DFBInputDeviceCapabilities dev_caps; D_MAGIC_ASSERT( device, CoreInputDevice ); D_ASSERT( device->shared != NULL ); dev_caps = device->shared->device_info.desc.caps; /* Always match if unclassified */ if (!dev_caps) dev_caps = DICAPS_ALL; if ((dev_caps & caps) && callback( device, ctx ) == DFENUM_CANCEL) break; } } DirectResult dfb_input_attach( CoreInputDevice *device, ReactionFunc func, void *ctx, Reaction *reaction ) { D_DEBUG_AT( Core_Input, "%s( %p, %p, %p, %p )\n", __FUNCTION__, device, func, ctx, reaction ); D_MAGIC_ASSERT( device, CoreInputDevice ); D_ASSERT( core_input != NULL ); D_ASSERT( device != NULL ); D_ASSERT( device->shared != NULL ); return fusion_reactor_attach( device->shared->reactor, func, ctx, reaction ); } DirectResult dfb_input_detach( CoreInputDevice *device, Reaction *reaction ) { D_DEBUG_AT( Core_Input, "%s( %p, %p )\n", __FUNCTION__, device, reaction ); D_MAGIC_ASSERT( device, CoreInputDevice ); D_ASSERT( core_input != NULL ); D_ASSERT( device != NULL ); D_ASSERT( device->shared != NULL ); return fusion_reactor_detach( device->shared->reactor, reaction ); } DirectResult dfb_input_attach_global( CoreInputDevice *device, int index, void *ctx, GlobalReaction *reaction ) { D_DEBUG_AT( Core_Input, "%s( %p, %d, %p, %p )\n", __FUNCTION__, device, index, ctx, reaction ); D_MAGIC_ASSERT( device, CoreInputDevice ); D_ASSERT( core_input != NULL ); D_ASSERT( device != NULL ); D_ASSERT( device->shared != NULL ); return fusion_reactor_attach_global( device->shared->reactor, index, ctx, reaction ); } DirectResult dfb_input_detach_global( CoreInputDevice *device, GlobalReaction *reaction ) { D_DEBUG_AT( Core_Input, "%s( %p, %p )\n", __FUNCTION__, device, reaction ); D_MAGIC_ASSERT( device, CoreInputDevice ); D_ASSERT( core_input != NULL ); D_ASSERT( device != NULL ); D_ASSERT( device->shared != NULL ); return fusion_reactor_detach_global( device->shared->reactor, reaction ); } const char * dfb_input_event_type_name( DFBInputEventType type ) { switch (type) { case DIET_UNKNOWN: return "UNKNOWN"; case DIET_KEYPRESS: return "KEYPRESS"; case DIET_KEYRELEASE: return "KEYRELEASE"; case DIET_BUTTONPRESS: return "BUTTONPRESS"; case DIET_BUTTONRELEASE: return "BUTTONRELEASE"; case DIET_AXISMOTION: return "AXISMOTION"; default: break; } return "<invalid>"; } void dfb_input_dispatch( CoreInputDevice *device, DFBInputEvent *event ) { D_DEBUG_AT( Core_Input, "%s( %p, %p )\n", __FUNCTION__, device, event ); D_MAGIC_ASSERT( device, CoreInputDevice ); D_ASSERT( core_input != NULL ); D_ASSERT( device != NULL ); D_ASSERT( event != NULL ); /* * When a USB device is hot-removed, it is possible that there are pending events * still being dispatched and the shared field becomes NULL. */ /* * 0. Sanity checks & debugging... */ if (!device->shared) { D_DEBUG_AT( Core_Input, " -> No shared data!\n" ); return; } D_ASSUME( device->shared->reactor != NULL ); if (!device->shared->reactor) { D_DEBUG_AT( Core_Input, " -> No reactor!\n" ); return; } D_DEBUG_AT( Core_InputEvt, " -> (%02x) %s%s%s\n", event->type, dfb_input_event_type_name( event->type ), (event->flags & DIEF_FOLLOW) ? " [FOLLOW]" : "", (event->flags & DIEF_REPEAT) ? " [REPEAT]" : "" ); #if D_DEBUG_ENABLED if (event->flags & DIEF_TIMESTAMP) D_DEBUG_AT( Core_InputEvt, " -> TIMESTAMP %lu.%06lu\n", event->timestamp.tv_sec, event->timestamp.tv_usec ); if (event->flags & DIEF_AXISABS) D_DEBUG_AT( Core_InputEvt, " -> AXISABS %d at %d\n", event->axis, event->axisabs ); if (event->flags & DIEF_AXISREL) D_DEBUG_AT( Core_InputEvt, " -> AXISREL %d by %d\n", event->axis, event->axisrel ); if (event->flags & DIEF_KEYCODE) D_DEBUG_AT( Core_InputEvt, " -> KEYCODE %d\n", event->key_code ); if (event->flags & DIEF_KEYID) D_DEBUG_AT( Core_InputEvt, " -> KEYID 0x%04x\n", event->key_id ); if (event->flags & DIEF_KEYSYMBOL) D_DEBUG_AT( Core_InputEvt, " -> KEYSYMBOL 0x%04x\n", event->key_symbol ); if (event->flags & DIEF_MODIFIERS) D_DEBUG_AT( Core_InputEvt, " -> MODIFIERS 0x%04x\n", event->modifiers ); if (event->flags & DIEF_LOCKS) D_DEBUG_AT( Core_InputEvt, " -> LOCKS 0x%04x\n", event->locks ); if (event->flags & DIEF_BUTTONS) D_DEBUG_AT( Core_InputEvt, " -> BUTTONS 0x%04x\n", event->buttons ); if (event->flags & DIEF_GLOBAL) D_DEBUG_AT( Core_InputEvt, " -> GLOBAL\n" ); #endif /* * 1. Fixup event... */ event->clazz = DFEC_INPUT; event->device_id = device->shared->id; if (!(event->flags & DIEF_TIMESTAMP)) { gettimeofday( &event->timestamp, NULL ); event->flags |= DIEF_TIMESTAMP; } switch (event->type) { case DIET_BUTTONPRESS: case DIET_BUTTONRELEASE: D_DEBUG_AT( Core_InputEvt, " -> BUTTON 0x%04x\n", event->button ); if (dfb_config->lefty) { if (event->button == DIBI_LEFT) event->button = DIBI_RIGHT; else if (event->button == DIBI_RIGHT) event->button = DIBI_LEFT; D_DEBUG_AT( Core_InputEvt, " -> lefty! => 0x%04x <=\n", event->button ); } /* fallthru */ case DIET_AXISMOTION: fixup_mouse_event( device, event ); break; case DIET_KEYPRESS: case DIET_KEYRELEASE: if (dfb_config->capslock_meta) { if (device->shared->keymap.num_entries && (event->flags & DIEF_KEYCODE)) lookup_from_table( device, event, (DIEF_KEYID | DIEF_KEYSYMBOL) & ~event->flags ); if (event->key_id == DIKI_CAPS_LOCK || event->key_symbol == DIKS_CAPS_LOCK) { event->flags |= DIEF_KEYID | DIEF_KEYSYMBOL; event->key_code = -1; event->key_id = DIKI_META_L; event->key_symbol = DIKS_META; } } fixup_key_event( device, event ); break; default: ; } #if D_DEBUG_ENABLED if (event->flags & DIEF_TIMESTAMP) D_DEBUG_AT( Core_InputEvt, " => TIMESTAMP %lu.%06lu\n", event->timestamp.tv_sec, event->timestamp.tv_usec ); if (event->flags & DIEF_AXISABS) D_DEBUG_AT( Core_InputEvt, " => AXISABS %d at %d\n", event->axis, event->axisabs ); if (event->flags & DIEF_AXISREL) D_DEBUG_AT( Core_InputEvt, " => AXISREL %d by %d\n", event->axis, event->axisrel ); if (event->flags & DIEF_KEYCODE) D_DEBUG_AT( Core_InputEvt, " => KEYCODE %d\n", event->key_code ); if (event->flags & DIEF_KEYID) D_DEBUG_AT( Core_InputEvt, " => KEYID 0x%04x\n", event->key_id ); if (event->flags & DIEF_KEYSYMBOL) D_DEBUG_AT( Core_InputEvt, " => KEYSYMBOL 0x%04x\n", event->key_symbol ); if (event->flags & DIEF_MODIFIERS) D_DEBUG_AT( Core_InputEvt, " => MODIFIERS 0x%04x\n", event->modifiers ); if (event->flags & DIEF_LOCKS) D_DEBUG_AT( Core_InputEvt, " => LOCKS 0x%04x\n", event->locks ); if (event->flags & DIEF_BUTTONS) D_DEBUG_AT( Core_InputEvt, " => BUTTONS 0x%04x\n", event->buttons ); if (event->flags & DIEF_GLOBAL) D_DEBUG_AT( Core_InputEvt, " => GLOBAL\n" ); #endif if (core_input_filter( device, event )) D_DEBUG_AT( Core_InputEvt, " ****>> FILTERED\n" ); else fusion_reactor_dispatch( device->shared->reactor, event, true, dfb_input_globals ); } DFBInputDeviceID dfb_input_device_id( const CoreInputDevice *device ) { D_MAGIC_ASSERT( device, CoreInputDevice ); D_ASSERT( core_input != NULL ); D_ASSERT( device != NULL ); D_ASSERT( device->shared != NULL ); return device->shared->id; } CoreInputDevice * dfb_input_device_at( DFBInputDeviceID id ) { CoreInputDevice *device; D_ASSERT( core_input != NULL ); direct_list_foreach (device, core_local->devices) { D_MAGIC_ASSERT( device, CoreInputDevice ); if (device->shared->id == id) return device; } return NULL; } /* Get an input device's capabilities. */ DFBInputDeviceCapabilities dfb_input_device_caps( const CoreInputDevice *device ) { D_MAGIC_ASSERT( device, CoreInputDevice ); D_ASSERT( core_input != NULL ); D_ASSERT( device != NULL ); D_ASSERT( device->shared != NULL ); return device->shared->device_info.desc.caps; } void dfb_input_device_description( const CoreInputDevice *device, DFBInputDeviceDescription *desc ) { D_MAGIC_ASSERT( device, CoreInputDevice ); D_ASSERT( core_input != NULL ); D_ASSERT( device != NULL ); D_ASSERT( device->shared != NULL ); *desc = device->shared->device_info.desc; } DFBResult dfb_input_device_get_keymap_entry( CoreInputDevice *device, int keycode, DFBInputDeviceKeymapEntry *entry ) { DFBInputDeviceKeymapEntry *keymap_entry; D_MAGIC_ASSERT( device, CoreInputDevice ); D_ASSERT( core_input != NULL ); D_ASSERT( device != NULL ); D_ASSERT( entry != NULL ); keymap_entry = get_keymap_entry( device, keycode ); if (!keymap_entry) return DFB_FAILURE; *entry = *keymap_entry; return DFB_OK; } DFBResult dfb_input_device_set_keymap_entry( CoreInputDevice *device, int keycode, DFBInputDeviceKeymapEntry *entry ) { D_MAGIC_ASSERT( device, CoreInputDevice ); D_ASSERT( core_input != NULL ); D_ASSERT( device != NULL ); D_ASSERT( entry != NULL ); return set_keymap_entry( device, keycode, entry ); } DFBResult dfb_input_device_load_keymap ( CoreInputDevice *device, char *filename ) { D_MAGIC_ASSERT( device, CoreInputDevice ); D_ASSERT( core_input != NULL ); D_ASSERT( device != NULL ); D_ASSERT( filename != NULL ); return load_keymap( device, filename ); } DFBResult dfb_input_device_reload_keymap( CoreInputDevice *device ) { int ret; InputDeviceShared *shared; D_MAGIC_ASSERT( device, CoreInputDevice ); shared = device->shared; D_ASSERT( shared != NULL ); D_INFO( "DirectFB/Input: Reloading keymap for '%s' [0x%02x]...\n", shared->device_info.desc.name, shared->id ); if (fusion_call_execute( &shared->call, FCEF_NONE, CIDC_RELOAD_KEYMAP, NULL, &ret )) return DFB_FUSION; return ret; } /** internal **/ static void input_add_device( CoreInputDevice *device ) { D_DEBUG_AT( Core_Input, "%s( %p )\n", __FUNCTION__, device ); D_MAGIC_ASSERT( device, CoreInputDevice ); D_ASSERT( core_input != NULL ); D_ASSERT( device != NULL ); D_ASSERT( device->shared != NULL ); if (core_input->num == MAX_INPUTDEVICES) { D_ERROR( "DirectFB/Input: Maximum number of devices reached!\n" ); return; } direct_list_append( &core_local->devices, &device->link ); core_input->devices[ core_input->num++ ] = device->shared; } static void allocate_device_keymap( CoreDFB *core, CoreInputDevice *device ) { int i; DFBInputDeviceKeymapEntry *entries; FusionSHMPoolShared *pool = dfb_core_shmpool( core ); InputDeviceShared *shared = device->shared; DFBInputDeviceDescription *desc = &shared->device_info.desc; int num_entries = desc->max_keycode - desc->min_keycode + 1; D_DEBUG_AT( Core_Input, "%s( %p, %p )\n", __FUNCTION__, core, device ); D_MAGIC_ASSERT( device, CoreInputDevice ); D_ASSERT( core_input != NULL ); entries = SHCALLOC( pool, num_entries, sizeof(DFBInputDeviceKeymapEntry) ); if (!entries) { D_OOSHM(); return; } /* write -1 indicating entry is not fetched yet from driver */ for (i=0; i<num_entries; i++) entries[i].code = -1; shared->keymap.min_keycode = desc->min_keycode; shared->keymap.max_keycode = desc->max_keycode; shared->keymap.num_entries = num_entries; shared->keymap.entries = entries; #if FUSION_BUILD_MULTI /* we need to fetch the whole map, otherwise a slave would try to */ for (i=desc->min_keycode; i<=desc->max_keycode; i++) get_keymap_entry( device, i ); #endif } static int make_id( DFBInputDeviceID prefered ) { CoreInputDevice *device; D_DEBUG_AT( Core_Input, "%s( 0x%02x )\n", __FUNCTION__, prefered ); D_ASSERT( core_input != NULL ); direct_list_foreach (device, core_local->devices) { D_MAGIC_ASSERT( device, CoreInputDevice ); if (device->shared->id == prefered) return make_id( (prefered < DIDID_ANY) ? DIDID_ANY : (prefered + 1) ); } return prefered; } static DFBResult reload_keymap( CoreInputDevice *device ) { int i; InputDeviceShared *shared; D_DEBUG_AT( Core_Input, "%s( %p )\n", __FUNCTION__, device ); D_MAGIC_ASSERT( device, CoreInputDevice ); shared = device->shared; D_ASSERT( shared != NULL ); if (shared->device_info.desc.min_keycode < 0 || shared->device_info.desc.max_keycode < 0) return DFB_UNSUPPORTED; /* write -1 indicating entry is not fetched yet from driver */ for (i=0; i<shared->keymap.num_entries; i++) shared->keymap.entries[i].code = -1; /* fetch the whole map */ for (i=shared->keymap.min_keycode; i<=shared->keymap.max_keycode; i++) get_keymap_entry( device, i ); D_INFO( "DirectFB/Input: Reloaded keymap for '%s' [0x%02x]\n", shared->device_info.desc.name, shared->id ); return DFB_OK; } static FusionCallHandlerResult input_device_call_handler( int caller, /* fusion id of the caller */ int call_arg, /* optional call parameter */ void *call_ptr, /* optional call parameter */ void *ctx, /* optional handler context */ unsigned int serial, int *ret_val ) { CoreInputDeviceCommand command = call_arg; CoreInputDevice *device = ctx; D_DEBUG_AT( Core_Input, "%s( %d, %d, %p, %p )\n", __FUNCTION__, caller, call_arg, call_ptr, ctx ); D_MAGIC_ASSERT( device, CoreInputDevice ); switch (command) { case CIDC_RELOAD_KEYMAP: *ret_val = reload_keymap( device ); break; default: D_BUG( "unknown Core Input Device Command '%d'", command ); *ret_val = DFB_BUG; } return FCHR_RETURN; } static DFBResult init_axes( CoreInputDevice *device ) { int i, num; DFBResult ret; InputDeviceShared *shared; const InputDriverFuncs *funcs; D_DEBUG_AT( Core_Input, "%s( %p )\n", __FUNCTION__, device ); D_MAGIC_ASSERT( device, CoreInputDevice ); D_ASSERT( device->driver != NULL ); funcs = device->driver->funcs; D_ASSERT( funcs != NULL ); shared = device->shared; D_ASSERT( shared != NULL ); if (shared->device_info.desc.max_axis < 0) return DFB_OK; num = shared->device_info.desc.max_axis + 1; shared->axis_info = SHCALLOC( dfb_core_shmpool(device->core), num, sizeof(DFBInputDeviceAxisInfo) ); if (!shared->axis_info) return D_OOSHM(); shared->axis_num = num; if (funcs->GetAxisInfo) { for (i=0; i<num; i++) { ret = funcs->GetAxisInfo( device, device->driver_data, i, &shared->axis_info[i] ); if (ret) D_DERROR( ret, "Core/Input: GetAxisInfo() failed for '%s' [%d] on axis %d!\n", shared->device_info.desc.name, shared->id, i ); } } return DFB_OK; } static void init_devices( CoreDFB *core ) { DirectLink *next; DirectModuleEntry *module; FusionSHMPoolShared *pool = dfb_core_shmpool( core ); D_DEBUG_AT( Core_Input, "%s( %p )\n", __FUNCTION__, core ); D_ASSERT( core_input != NULL ); direct_list_foreach_safe (module, next, dfb_input_modules.entries) { int n; InputDriver *driver; const InputDriverFuncs *funcs; InputDriverCapability driver_cap; DFBResult result; driver_cap = IDC_NONE; funcs = direct_module_ref( module ); if (!funcs) continue; driver = D_CALLOC( 1, sizeof(InputDriver) ); if (!driver) { D_OOM(); direct_module_unref( module ); continue; } D_ASSERT( funcs->GetDriverInfo != NULL ); funcs->GetDriverInfo( &driver->info ); D_DEBUG_AT( Core_Input, " -> probing '%s'...\n", driver->info.name ); driver->nr_devices = funcs->GetAvailable(); /* * If the input provider supports hot-plug, always load the module. */ if (!funcs->GetCapability) { D_DEBUG_AT(Core_Input, "InputDriverFuncs::GetCapability is NULL\n"); } else { driver_cap = funcs->GetCapability(); } if (!driver->nr_devices && !(driver_cap & IDC_HOTPLUG)) { direct_module_unref( module ); D_FREE( driver ); continue; } D_DEBUG_AT( Core_Input, " -> %d available device(s) provided by '%s'.\n", driver->nr_devices, driver->info.name ); driver->module = module; driver->funcs = funcs; direct_list_prepend( &core_local->drivers, &driver->link ); for (n=0; n<driver->nr_devices; n++) { char buf[128]; CoreInputDevice *device; InputDeviceInfo device_info; InputDeviceShared *shared; void *driver_data; device = D_CALLOC( 1, sizeof(CoreInputDevice) ); if (!device) { D_OOM(); continue; } shared = SHCALLOC( pool, 1, sizeof(InputDeviceShared) ); if (!shared) { D_OOSHM(); D_FREE( device ); continue; } device->core = core; memset( &device_info, 0, sizeof(InputDeviceInfo) ); device_info.desc.min_keycode = -1; device_info.desc.max_keycode = -1; D_MAGIC_SET( device, CoreInputDevice ); if (funcs->OpenDevice( device, n, &device_info, &driver_data )) { SHFREE( pool, shared ); D_MAGIC_CLEAR( device ); D_FREE( device ); continue; } D_DEBUG_AT( Core_Input, " -> opened '%s' (%d) %d.%d (%s)\n", device_info.desc.name, n + 1, driver->info.version.major, driver->info.version.minor, driver->info.vendor ); if (driver->nr_devices > 1) snprintf( buf, sizeof(buf), "%s (%d)", device_info.desc.name, n+1 ); else snprintf( buf, sizeof(buf), "%s", device_info.desc.name ); /* init skirmish */ fusion_skirmish_init( &shared->lock, buf, dfb_core_world(core) ); /* create reactor */ shared->reactor = fusion_reactor_new( sizeof(DFBInputEvent), buf, dfb_core_world(core) ); fusion_reactor_set_lock( shared->reactor, &shared->lock ); /* init call */ fusion_call_init( &shared->call, input_device_call_handler, device, dfb_core_world(core) ); /* initialize shared data */ shared->id = make_id(device_info.prefered_id); shared->num = n; shared->device_info = device_info; shared->last_key = DIKI_UNKNOWN; shared->first_press = true; /* initialize local data */ device->shared = shared; device->driver = driver; device->driver_data = driver_data; D_INFO( "DirectFB/Input: %s %d.%d (%s)\n", buf, driver->info.version.major, driver->info.version.minor, driver->info.vendor ); #if FUSION_BUILD_MULTI /* Initialize the ref between shared device and local device. */ snprintf( buf, sizeof(buf), "Ref of input device(%d)", shared->id ); fusion_ref_init( &shared->ref, buf, dfb_core_world(core) ); /* Increase reference counter. */ fusion_ref_up( &shared->ref, true ); #endif if (device_info.desc.min_keycode > device_info.desc.max_keycode) { D_BUG("min_keycode > max_keycode"); device_info.desc.min_keycode = -1; device_info.desc.max_keycode = -1; } else if (device_info.desc.min_keycode >= 0 && device_info.desc.max_keycode >= 0) allocate_device_keymap( core, device ); init_axes( device ); /* add it to the list */ input_add_device( device ); } /* * If the driver supports hot-plug, launch its hot-plug thread to respond to * hot-plug events. Failures in launching the hot-plug thread will only * result in no hot-plug feature being available. */ if (driver_cap == IDC_HOTPLUG) { result = funcs->LaunchHotplug(core, (void*) driver); /* On failure, the input provider can still be used without hot-plug. */ if (result) { D_INFO( "DirectFB/Input: Failed to enable hot-plug " "detection with %s\n ", driver->info.name); } else { D_INFO( "DirectFB/Input: Hot-plug detection enabled with %s \n", driver->info.name); } } } } /* * Create the DFB shared core input device, add the input device into the * local device list and shared dev array and broadcast the hot-plug in * message to all slaves. */ DFBResult dfb_input_create_device(int device_index, CoreDFB *core_in, void *driver_in) { char buf[128]; CoreInputDevice *device; InputDeviceInfo device_info; InputDeviceShared *shared; void *driver_data; InputDriver *driver = NULL; const InputDriverFuncs *funcs; FusionSHMPoolShared *pool; DFBResult result; D_DEBUG_AT(Core_Input, "Enter: %s()\n", __FUNCTION__); driver = (InputDriver *)driver_in; pool = dfb_core_shmpool(core_in); funcs = driver->funcs; if (!funcs) { D_ERROR("DirectFB/Input: driver->funcs is NULL\n"); goto errorExit; } device = D_CALLOC( 1, sizeof(CoreInputDevice) ); if (!device) { D_OOM(); goto errorExit; } shared = SHCALLOC( pool, 1, sizeof(InputDeviceShared) ); if (!shared) { D_OOM(); D_FREE( device ); goto errorExit; } device->core = core_in; memset( &device_info, 0, sizeof(InputDeviceInfo) ); device_info.desc.min_keycode = -1; device_info.desc.max_keycode = -1; D_MAGIC_SET( device, CoreInputDevice ); if (funcs->OpenDevice( device, device_index, &device_info, &driver_data )) { SHFREE( pool, shared ); D_MAGIC_CLEAR( device ); D_FREE( device ); D_DEBUG_AT( Core_Input, "DirectFB/Input: Cannot open device in %s, at %d in %s\n", __FUNCTION__, __LINE__, __FILE__); goto errorExit; } snprintf( buf, sizeof(buf), "%s (%d)", device_info.desc.name, device_index); /* init skirmish */ result = fusion_skirmish_init( &shared->lock, buf, dfb_core_world(device->core) ); if (result) { funcs->CloseDevice( driver_data ); SHFREE( pool, shared ); D_MAGIC_CLEAR( device ); D_FREE( device ); D_ERROR("DirectFB/Input: fusion_skirmish_init() failed! in %s, at %d in %s\n", __FUNCTION__, __LINE__, __FILE__); goto errorExit; } /* create reactor */ shared->reactor = fusion_reactor_new( sizeof(DFBInputEvent), buf, dfb_core_world(device->core) ); if (!shared->reactor) { funcs->CloseDevice( driver_data ); SHFREE( pool, shared ); D_MAGIC_CLEAR( device ); D_FREE( device ); fusion_skirmish_destroy(&shared->lock); D_ERROR("DirectFB/Input: fusion_reactor_new() failed! in %s, at %d in %s\n", __FUNCTION__, __LINE__, __FILE__); goto errorExit; } fusion_reactor_set_lock( shared->reactor, &shared->lock ); /* init call */ fusion_call_init( &shared->call, input_device_call_handler, device, dfb_core_world(device->core) ); /* initialize shared data */ shared->id = make_id(device_info.prefered_id); shared->num = device_index; shared->device_info = device_info; shared->last_key = DIKI_UNKNOWN; shared->first_press = true; /* initialize local data */ device->shared = shared; device->driver = driver; device->driver_data = driver_data; D_INFO( "DirectFB/Input: %s %d.%d (%s)\n", buf, driver->info.version.major, driver->info.version.minor, driver->info.vendor ); #if FUSION_BUILD_MULTI snprintf( buf, sizeof(buf), "Ref of input device(%d)", shared->id); fusion_ref_init( &shared->ref, buf, dfb_core_world(core_in)); fusion_ref_up( &shared->ref, true ); #endif if (device_info.desc.min_keycode > device_info.desc.max_keycode) { D_BUG("min_keycode > max_keycode"); device_info.desc.min_keycode = -1; device_info.desc.max_keycode = -1; } else if (device_info.desc.min_keycode >= 0 && device_info.desc.max_keycode >= 0) allocate_device_keymap( device->core, device ); /* add it into local device list and shared dev array */ D_DEBUG_AT(Core_Input, "In master, add a new device with dev_id=%d\n", shared->id); input_add_device( device ); driver->nr_devices++; D_DEBUG_AT(Core_Input, "Successfully added new input device with dev_id=%d in shared array\n", shared->id); InputDeviceHotplugEvent message; /* Setup the hot-plug in message. */ message.is_plugin = true; message.dev_id = shared->id; gettimeofday (&message.stamp, NULL); /* Send the hot-plug in message */ #if FUSION_BUILD_MULTI fusion_reactor_dispatch(core_input->reactor, &message, true, NULL); #else local_processing_hotplug((const void *) &message, (void*) core_in); #endif return DFB_OK; errorExit: return DFB_FAILURE; } /* * Tell whether the DFB input device handling of the system input device * indicated by device_index is already created. */ static CoreInputDevice * search_device_created(int device_index, void *driver_in) { DirectLink *n; CoreInputDevice *device; D_ASSERT(driver_in != NULL); direct_list_foreach_safe(device, n, core_local->devices) { if (device->driver != driver_in) continue; if (device->driver_data == NULL) { D_DEBUG_AT(Core_Input, "The device %d has been closed!\n", device->shared->id); return NULL; } if (device->driver->funcs->IsCreated && !device->driver->funcs->IsCreated(device_index, device->driver_data)) { return device; } } return NULL; } /* * Remove the DFB shared core input device handling of the system input device * indicated by device_index and broadcast the hot-plug out message to all slaves. */ DFBResult dfb_input_remove_device(int device_index, void *driver_in) { CoreInputDevice *device; InputDeviceShared *shared; FusionSHMPoolShared *pool; int i; int found = 0; int device_id; D_DEBUG_AT(Core_Input, "Enter: %s()\n", __FUNCTION__); D_ASSERT(driver_in !=NULL); device = search_device_created(device_index, driver_in); if (device == NULL) { D_DEBUG_AT(Core_Input, "DirectFB/input: Failed to find the device[%d] or the device is " "closed.\n", device_index); goto errorExit; } shared = device->shared; pool = dfb_core_shmpool( device->core ); device_id = shared->id; D_DEBUG_AT(Core_Input, "Find the device with dev_id=%d\n", device_id); device->driver->funcs->CloseDevice( device->driver_data ); device->driver->nr_devices--; InputDeviceHotplugEvent message; /* Setup the hot-plug out message */ message.is_plugin = false; message.dev_id = device_id; gettimeofday (&message.stamp, NULL); /* Send the hot-plug out message */ #if FUSION_BUILD_MULTI fusion_reactor_dispatch( core_input->reactor, &message, true, NULL); int loop = CHECK_NUMBER; while (--loop) { if (fusion_ref_zero_trylock( &device->shared->ref ) == DR_OK) { fusion_ref_unlock(&device->shared->ref); break; } usleep(CHECK_INTERVAL); } if (!loop) D_DEBUG_AT(Core_Input, "Shared device might be connected to by others\n"); fusion_ref_destroy(&device->shared->ref); #else local_processing_hotplug((const void*) &message, (void*) device->core); #endif /* Remove the device from shared array */ for (i = 0; i < core_input->num; i++) { if (!found && (core_input->devices[i]->id == shared->id)) found = 1; if (found) core_input->devices[i] = core_input->devices[(i + 1) % MAX_INPUTDEVICES]; } if (found) core_input->devices[core_input->num -1] = NULL; core_input->num--; fusion_call_destroy( &shared->call ); fusion_skirmish_destroy( &shared->lock ); fusion_reactor_free( shared->reactor ); if (shared->keymap.entries) SHFREE( pool, shared->keymap.entries ); SHFREE( pool, shared ); D_DEBUG_AT(Core_Input, "Successfully remove the device with dev_id=%d in shared array\n", device_id); return DFB_OK; errorExit: return DFB_FAILURE; } /* * Create local input device and add it into the local input devices list. */ static CoreInputDevice * add_device_into_local_list(int dev_id) { int i; D_DEBUG_AT(Core_Input, "Enter: %s()\n", __FUNCTION__); for (i = 0; i < core_input->num; i++) { if (core_input->devices[i]->id == dev_id) { CoreInputDevice *device; D_DEBUG_AT(Core_Input, "Find the device with dev_id=%d in shared array, and " "allocate local device\n", dev_id); device = D_CALLOC( 1, sizeof(CoreInputDevice) ); if (!device) { return NULL; } device->shared = core_input->devices[i]; #if FUSION_BUILD_MULTI /* Increase the reference counter. */ fusion_ref_up( &device->shared->ref, true ); #endif /* add it to the list */ direct_list_append( &core_local->devices, &device->link ); D_MAGIC_SET( device, CoreInputDevice ); return device; } } return NULL; } /* * Local input device function that handles hot-plug in/out messages. */ static ReactionResult local_processing_hotplug( const void *msg_data, void *ctx ) { const InputDeviceHotplugEvent *message = msg_data; CoreInputDevice *device = NULL; D_DEBUG_AT(Core_Input, "Enter: %s()\n", __FUNCTION__); D_DEBUG_AT(Core_Input, "<PID:%6d> hotplug-in:%d device_id=%d message!\n", getpid(), message->is_plugin, message->dev_id ); if (message->is_plugin) { device = dfb_input_device_at(message->dev_id); if (!device){ /* Update local device list according to shared devices array */ if (!(device = add_device_into_local_list(message->dev_id))) { D_ERROR("DirectFB/Input: update_local_devices_list() failed\n" ); goto errorExit; } } /* attach the device to event containers */ containers_attach_device( device ); /* attach the device to stack containers */ stack_containers_attach_device( device ); } else { device = dfb_input_device_at(message->dev_id); if (device) { direct_list_remove(&core_local->devices, &device->link); containers_detach_device(device); stack_containers_detach_device(device); #if FUSION_BUILD_MULTI /* Decrease reference counter. */ fusion_ref_down( &device->shared->ref, true ); #endif D_MAGIC_CLEAR( device ); D_FREE(device); } else D_ERROR("DirectFB/Input:Can't find the device to be removed!\n"); } return DFB_OK; errorExit: return DFB_FAILURE; } static DFBInputDeviceKeymapEntry * get_keymap_entry( CoreInputDevice *device, int code ) { InputDeviceKeymap *map; DFBInputDeviceKeymapEntry *entry; D_MAGIC_ASSERT( device, CoreInputDevice ); D_ASSERT( core_input != NULL ); D_ASSERT( device != NULL ); D_ASSERT( device->shared != NULL ); map = &device->shared->keymap; /* safety check */ if (code < map->min_keycode || code > map->max_keycode) return NULL; /* point to right array index */ entry = &map->entries[code - map->min_keycode]; /* need to initialize? */ if (entry->code != code) { DFBResult ret; InputDriver *driver = device->driver; if (!driver) { D_BUG("seem to be a slave with an empty keymap"); return NULL; } /* write keycode to entry */ entry->code = code; /* fetch entry from driver */ ret = driver->funcs->GetKeymapEntry( device, device->driver_data, entry ); if (ret) return NULL; /* drivers may leave this blank */ if (entry->identifier == DIKI_UNKNOWN) entry->identifier = symbol_to_id( entry->symbols[DIKSI_BASE] ); if (entry->symbols[DIKSI_BASE_SHIFT] == DIKS_NULL) entry->symbols[DIKSI_BASE_SHIFT] = entry->symbols[DIKSI_BASE]; if (entry->symbols[DIKSI_ALT] == DIKS_NULL) entry->symbols[DIKSI_ALT] = entry->symbols[DIKSI_BASE]; if (entry->symbols[DIKSI_ALT_SHIFT] == DIKS_NULL) entry->symbols[DIKSI_ALT_SHIFT] = entry->symbols[DIKSI_ALT]; } return entry; } /* replace a single keymap entry with the code-entry pair */ static DFBResult set_keymap_entry( CoreInputDevice *device, int code, DFBInputDeviceKeymapEntry *entry ) { InputDeviceKeymap *map; D_ASSERT( device->shared != NULL ); D_ASSERT( device->shared->keymap.entries != NULL ); map = &device->shared->keymap; /* sanity check */ if (code < map->min_keycode || code > map->max_keycode) return DFB_FAILURE; /* copy the entry to the map */ map->entries[code - map->min_keycode] = *entry; return DFB_OK; } /* replace the complete current keymap with a keymap from a file. * the minimum-maximum keycodes of the driver are to be respected. */ static DFBResult load_keymap( CoreInputDevice *device, char *filename ) { DFBResult ret = DFB_OK; InputDeviceKeymap *map = 0; FILE *file = 0; DFBInputDeviceLockState lockstate = 0; D_ASSERT( device->shared != NULL ); D_ASSERT( device->shared->keymap.entries != NULL ); map = &device->shared->keymap; /* open the file */ file = fopen( filename, "r" ); if( !file ) { return errno2result( errno ); } /* read the file, line by line, and consume the mentioned scancodes */ while(1) { int i; int dummy; char buffer[201]; int keycode; char diki[201]; char diks[4][201]; char *b; DFBInputDeviceKeymapEntry entry = { .code = 0 }; b = fgets( buffer, 200, file ); if( !b ) { if( feof(file) ) { fclose(file); return DFB_OK; } fclose(file); return errno2result(errno); } /* comment or empty line */ if( buffer[0]=='#' || strcmp(buffer,"\n")==0 ) continue; /* check for lock state change */ if( !strncmp(buffer,"capslock:",9) ) { lockstate |= DILS_CAPS; continue; } if( !strncmp(buffer,":capslock",9) ) { lockstate &= ~DILS_CAPS; continue; } if( !strncmp(buffer,"numlock:",8) ) { lockstate |= DILS_NUM; continue; } if( !strncmp(buffer,":numlock",8) ) { lockstate &= ~DILS_NUM; continue; } i = sscanf( buffer, " keycode %i = %s = %s %s %s %s %i\n", &keycode, diki, diks[0], diks[1], diks[2], diks[3], &dummy ); if( i < 3 || i > 6 ) { /* we want 1 to 4 key symbols */ D_INFO( "DirectFB/Input: skipped erroneous input line %s\n", buffer ); continue; } if( keycode > map->max_keycode || keycode < map->min_keycode ) { D_INFO( "DirectFB/Input: skipped keycode %d out of range\n", keycode ); continue; } entry.code = keycode; entry.locks = lockstate; entry.identifier = lookup_keyidentifier( diki ); switch( i ) { case 6: entry.symbols[3] = lookup_keysymbol( diks[3] ); case 5: entry.symbols[2] = lookup_keysymbol( diks[2] ); case 4: entry.symbols[1] = lookup_keysymbol( diks[1] ); case 3: entry.symbols[0] = lookup_keysymbol( diks[0] ); /* fall through */ } switch( i ) { case 3: entry.symbols[1] = entry.symbols[0]; case 4: entry.symbols[2] = entry.symbols[0]; case 5: entry.symbols[3] = entry.symbols[1]; /* fall through */ } ret = set_keymap_entry( device, keycode, &entry ); if( ret ) return ret; } } static DFBInputDeviceKeySymbol lookup_keysymbol( char *symbolname ) { int i; /* we want uppercase */ for( i=0; i<strlen(symbolname); i++ ) if( symbolname[i] >= 'a' && symbolname[i] <= 'z' ) symbolname[i] = symbolname[i] - 'a' + 'A'; for( i=0; i < sizeof (KeySymbolNames) / sizeof (KeySymbolNames[0]); i++ ) { if( strcmp( symbolname, KeySymbolNames[i].name ) == 0 ) return KeySymbolNames[i].symbol; } /* not found, maybe starting with 0x for raw conversion. * We are already at uppercase. */ if( symbolname[0]=='0' && symbolname[1]=='X' ) { int code=0; symbolname+=2; while(*symbolname) { if( *symbolname >= '0' && *symbolname <= '9' ) { code = code*16 + *symbolname - '0'; } else if( *symbolname >= 'A' && *symbolname <= 'F' ) { code = code*16 + *symbolname - 'A' + 10; } else { /* invalid character */ return DIKS_NULL; } symbolname++; } return code; } return DIKS_NULL; } static DFBInputDeviceKeyIdentifier lookup_keyidentifier( char *identifiername ) { int i; /* we want uppercase */ for( i=0; i<strlen(identifiername); i++ ) if( identifiername[i] >= 'a' && identifiername[i] <= 'z' ) identifiername[i] = identifiername[i] - 'a' + 'A'; for( i=0; i < sizeof (KeyIdentifierNames) / sizeof (KeyIdentifierNames[0]); i++ ) { if( strcmp( identifiername, KeyIdentifierNames[i].name ) == 0 ) return KeyIdentifierNames[i].identifier; } return DIKI_UNKNOWN; } static bool lookup_from_table( CoreInputDevice *device, DFBInputEvent *event, DFBInputEventFlags lookup ) { DFBInputDeviceKeymapEntry *entry; D_MAGIC_ASSERT( device, CoreInputDevice ); D_ASSERT( core_input != NULL ); D_ASSERT( device != NULL ); D_ASSERT( device->shared != NULL ); D_ASSERT( event != NULL ); /* fetch the entry from the keymap, possibly calling the driver */ entry = get_keymap_entry( device, event->key_code ); if (!entry) return false; /* lookup identifier */ if (lookup & DIEF_KEYID) event->key_id = entry->identifier; /* lookup symbol */ if (lookup & DIEF_KEYSYMBOL) { DFBInputDeviceKeymapSymbolIndex index = (event->modifiers & DIMM_ALTGR) ? DIKSI_ALT : DIKSI_BASE; if ((event->modifiers & DIMM_SHIFT) || (entry->locks & event->locks)) index++; /* don't modify modifiers */ if (DFB_KEY_TYPE( entry->symbols[DIKSI_BASE] ) == DIKT_MODIFIER) event->key_symbol = entry->symbols[DIKSI_BASE]; else event->key_symbol = entry->symbols[index]; } return true; } static int find_key_code_by_id( CoreInputDevice *device, DFBInputDeviceKeyIdentifier id ) { int i; InputDeviceKeymap *map; D_MAGIC_ASSERT( device, CoreInputDevice ); D_ASSERT( core_input != NULL ); D_ASSERT( device != NULL ); D_ASSERT( device->shared != NULL ); map = &device->shared->keymap; for (i=0; i<map->num_entries; i++) { DFBInputDeviceKeymapEntry *entry = &map->entries[i]; if (entry->identifier == id) return entry->code; } return -1; } static int find_key_code_by_symbol( CoreInputDevice *device, DFBInputDeviceKeySymbol symbol ) { int i; InputDeviceKeymap *map; D_MAGIC_ASSERT( device, CoreInputDevice ); D_ASSERT( core_input != NULL ); D_ASSERT( device != NULL ); D_ASSERT( device->shared != NULL ); map = &device->shared->keymap; for (i=0; i<map->num_entries; i++) { int n; DFBInputDeviceKeymapEntry *entry = &map->entries[i]; for (n=0; n<=DIKSI_LAST; n++) if (entry->symbols[n] == symbol) return entry->code; } return -1; } #define FIXUP_KEY_FIELDS (DIEF_MODIFIERS | DIEF_LOCKS | \ DIEF_KEYCODE | DIEF_KEYID | DIEF_KEYSYMBOL) /* * Fill partially missing values for key_code, key_id and key_symbol by * translating those that are set. Fix modifiers/locks before if not set. * * * There are five valid constellations that give reasonable values. * (not counting the constellation where everything is set) * * Device has no translation table * 1. key_id is set, key_symbol not * -> key_code defaults to -1, key_symbol from key_id (up-translation) * 2. key_symbol is set, key_id not * -> key_code defaults to -1, key_id from key_symbol (down-translation) * * Device has a translation table * 3. key_code is set * -> look up key_id and/or key_symbol (key_code being the index) * 4. key_id is set * -> look up key_code and possibly key_symbol (key_id being searched for) * 5. key_symbol is set * -> look up key_code and key_id (key_symbol being searched for) * * Fields remaining will be set to the default, e.g. key_code to -1. */ static void fixup_key_event( CoreInputDevice *device, DFBInputEvent *event ) { int i; DFBInputEventFlags valid = event->flags & FIXUP_KEY_FIELDS; DFBInputEventFlags missing = valid ^ FIXUP_KEY_FIELDS; InputDeviceShared *shared = device->shared; D_MAGIC_ASSERT( device, CoreInputDevice ); /* Add missing flags */ event->flags |= missing; /* * Use cached values for modifiers/locks if they are missing. */ if (missing & DIEF_MODIFIERS) event->modifiers = shared->modifiers_l | shared->modifiers_r; if (missing & DIEF_LOCKS) event->locks = shared->locks; /* * With translation table */ if (device->shared->keymap.num_entries) { if (valid & DIEF_KEYCODE) { lookup_from_table( device, event, missing ); missing &= ~(DIEF_KEYID | DIEF_KEYSYMBOL); } else if (valid & DIEF_KEYID) { event->key_code = find_key_code_by_id( device, event->key_id ); if (event->key_code != -1) { lookup_from_table( device, event, missing ); missing &= ~(DIEF_KEYCODE | DIEF_KEYSYMBOL); } else if (missing & DIEF_KEYSYMBOL) { event->key_symbol = id_to_symbol( event->key_id, event->modifiers, event->locks ); missing &= ~DIEF_KEYSYMBOL; } } else if (valid & DIEF_KEYSYMBOL) { event->key_code = find_key_code_by_symbol( device, event->key_symbol ); if (event->key_code != -1) { lookup_from_table( device, event, missing ); missing &= ~(DIEF_KEYCODE | DIEF_KEYID); } else { event->key_id = symbol_to_id( event->key_symbol ); missing &= ~DIEF_KEYSYMBOL; } } } else { /* * Without translation table */ if (valid & DIEF_KEYID) { if (missing & DIEF_KEYSYMBOL) { event->key_symbol = id_to_symbol( event->key_id, event->modifiers, event->locks ); missing &= ~DIEF_KEYSYMBOL; } } else if (valid & DIEF_KEYSYMBOL) { event->key_id = symbol_to_id( event->key_symbol ); missing &= ~DIEF_KEYID; } } /* * Clear remaining fields. */ if (missing & DIEF_KEYCODE) event->key_code = -1; if (missing & DIEF_KEYID) event->key_id = DIKI_UNKNOWN; if (missing & DIEF_KEYSYMBOL) event->key_symbol = DIKS_NULL; /* * Update cached values for modifiers. */ if (DFB_KEY_TYPE(event->key_symbol) == DIKT_MODIFIER) { if (event->type == DIET_KEYPRESS) { switch (event->key_id) { case DIKI_SHIFT_L: shared->modifiers_l |= DIMM_SHIFT; break; case DIKI_SHIFT_R: shared->modifiers_r |= DIMM_SHIFT; break; case DIKI_CONTROL_L: shared->modifiers_l |= DIMM_CONTROL; break; case DIKI_CONTROL_R: shared->modifiers_r |= DIMM_CONTROL; break; case DIKI_ALT_L: shared->modifiers_l |= DIMM_ALT; break; case DIKI_ALT_R: shared->modifiers_r |= (event->key_symbol == DIKS_ALTGR) ? DIMM_ALTGR : DIMM_ALT; break; case DIKI_META_L: shared->modifiers_l |= DIMM_META; break; case DIKI_META_R: shared->modifiers_r |= DIMM_META; break; case DIKI_SUPER_L: shared->modifiers_l |= DIMM_SUPER; break; case DIKI_SUPER_R: shared->modifiers_r |= DIMM_SUPER; break; case DIKI_HYPER_L: shared->modifiers_l |= DIMM_HYPER; break; case DIKI_HYPER_R: shared->modifiers_r |= DIMM_HYPER; break; default: ; } } else { switch (event->key_id) { case DIKI_SHIFT_L: shared->modifiers_l &= ~DIMM_SHIFT; break; case DIKI_SHIFT_R: shared->modifiers_r &= ~DIMM_SHIFT; break; case DIKI_CONTROL_L: shared->modifiers_l &= ~DIMM_CONTROL; break; case DIKI_CONTROL_R: shared->modifiers_r &= ~DIMM_CONTROL; break; case DIKI_ALT_L: shared->modifiers_l &= ~DIMM_ALT; break; case DIKI_ALT_R: shared->modifiers_r &= (event->key_symbol == DIKS_ALTGR) ? ~DIMM_ALTGR : ~DIMM_ALT; break; case DIKI_META_L: shared->modifiers_l &= ~DIMM_META; break; case DIKI_META_R: shared->modifiers_r &= ~DIMM_META; break; case DIKI_SUPER_L: shared->modifiers_l &= ~DIMM_SUPER; break; case DIKI_SUPER_R: shared->modifiers_r &= ~DIMM_SUPER; break; case DIKI_HYPER_L: shared->modifiers_l &= ~DIMM_HYPER; break; case DIKI_HYPER_R: shared->modifiers_r &= ~DIMM_HYPER; break; default: ; } } /* write back to event */ if (missing & DIEF_MODIFIERS) event->modifiers = shared->modifiers_l | shared->modifiers_r; } /* * Update cached values for locks. */ if (event->type == DIET_KEYPRESS) { /* When we receive a new key press, toggle lock flags */ if (shared->first_press || shared->last_key != event->key_id) { switch (event->key_id) { case DIKI_CAPS_LOCK: shared->locks ^= DILS_CAPS; break; case DIKI_NUM_LOCK: shared->locks ^= DILS_NUM; break; case DIKI_SCROLL_LOCK: shared->locks ^= DILS_SCROLL; break; default: ; } } /* write back to event */ if (missing & DIEF_LOCKS) event->locks = shared->locks; /* store last pressed key */ shared->last_key = event->key_id; shared->first_press = false; } else if (event->type == DIET_KEYRELEASE) { shared->first_press = true; } /* Handle dead keys. */ if (DFB_KEY_TYPE(shared->last_symbol) == DIKT_DEAD) { for (i=0; i<D_ARRAY_SIZE(deadkey_maps); i++) { const DeadKeyMap *map = &deadkey_maps[i]; if (map->deadkey == shared->last_symbol) { for (i=0; map->combos[i].target; i++) { if (map->combos[i].target == event->key_symbol) { event->key_symbol = map->combos[i].result; break; } } break; } } if (event->type == DIET_KEYRELEASE && DFB_KEY_TYPE(event->key_symbol) != DIKT_MODIFIER) shared->last_symbol = event->key_symbol; } else shared->last_symbol = event->key_symbol; } static void fixup_mouse_event( CoreInputDevice *device, DFBInputEvent *event ) { InputDeviceShared *shared = device->shared; D_MAGIC_ASSERT( device, CoreInputDevice ); if (event->flags & DIEF_BUTTONS) { shared->buttons = event->buttons; } else { switch (event->type) { case DIET_BUTTONPRESS: shared->buttons |= (1 << event->button); break; case DIET_BUTTONRELEASE: shared->buttons &= ~(1 << event->button); break; default: ; } /* Add missing flag */ event->flags |= DIEF_BUTTONS; event->buttons = shared->buttons; } switch (event->type) { case DIET_AXISMOTION: if ((event->flags & DIEF_AXISABS) && event->axis >= 0 && event->axis < shared->axis_num) { if (!(event->flags & DIEF_MIN) && (shared->axis_info[event->axis].flags & DIAIF_ABS_MIN)) { event->min = shared->axis_info[event->axis].abs_min; event->flags |= DIEF_MIN; } if (!(event->flags & DIEF_MAX) && (shared->axis_info[event->axis].flags & DIAIF_ABS_MAX)) { event->max = shared->axis_info[event->axis].abs_max; event->flags |= DIEF_MAX; } } break; default: break; } } static DFBInputDeviceKeyIdentifier symbol_to_id( DFBInputDeviceKeySymbol symbol ) { if (symbol >= 'a' && symbol <= 'z') return DIKI_A + symbol - 'a'; if (symbol >= 'A' && symbol <= 'Z') return DIKI_A + symbol - 'A'; if (symbol >= '0' && symbol <= '9') return DIKI_0 + symbol - '0'; if (symbol >= DIKS_F1 && symbol <= DIKS_F12) return DIKI_F1 + symbol - DIKS_F1; switch (symbol) { case DIKS_ESCAPE: return DIKI_ESCAPE; case DIKS_CURSOR_LEFT: return DIKI_LEFT; case DIKS_CURSOR_RIGHT: return DIKI_RIGHT; case DIKS_CURSOR_UP: return DIKI_UP; case DIKS_CURSOR_DOWN: return DIKI_DOWN; case DIKS_ALTGR: return DIKI_ALT_R; case DIKS_CONTROL: return DIKI_CONTROL_L; case DIKS_SHIFT: return DIKI_SHIFT_L; case DIKS_ALT: return DIKI_ALT_L; case DIKS_META: return DIKI_META_L; case DIKS_SUPER: return DIKI_SUPER_L; case DIKS_HYPER: return DIKI_HYPER_L; case DIKS_TAB: return DIKI_TAB; case DIKS_ENTER: return DIKI_ENTER; case DIKS_SPACE: return DIKI_SPACE; case DIKS_BACKSPACE: return DIKI_BACKSPACE; case DIKS_INSERT: return DIKI_INSERT; case DIKS_DELETE: return DIKI_DELETE; case DIKS_HOME: return DIKI_HOME; case DIKS_END: return DIKI_END; case DIKS_PAGE_UP: return DIKI_PAGE_UP; case DIKS_PAGE_DOWN: return DIKI_PAGE_DOWN; case DIKS_CAPS_LOCK: return DIKI_CAPS_LOCK; case DIKS_NUM_LOCK: return DIKI_NUM_LOCK; case DIKS_SCROLL_LOCK: return DIKI_SCROLL_LOCK; case DIKS_PRINT: return DIKI_PRINT; case DIKS_PAUSE: return DIKI_PAUSE; case DIKS_BACKSLASH: return DIKI_BACKSLASH; case DIKS_PERIOD: return DIKI_PERIOD; case DIKS_COMMA: return DIKI_COMMA; default: ; } return DIKI_UNKNOWN; } static DFBInputDeviceKeySymbol id_to_symbol( DFBInputDeviceKeyIdentifier id, DFBInputDeviceModifierMask modifiers, DFBInputDeviceLockState locks ) { bool shift = (modifiers & DIMM_SHIFT) || (locks & DILS_CAPS); if (id >= DIKI_A && id <= DIKI_Z) return (shift ? DIKS_CAPITAL_A : DIKS_SMALL_A) + id - DIKI_A; if (id >= DIKI_0 && id <= DIKI_9) return DIKS_0 + id - DIKI_0; if (id >= DIKI_KP_0 && id <= DIKI_KP_9) return DIKS_0 + id - DIKI_KP_0; if (id >= DIKI_F1 && id <= DIKI_F12) return DIKS_F1 + id - DIKI_F1; switch (id) { case DIKI_ESCAPE: return DIKS_ESCAPE; case DIKI_LEFT: return DIKS_CURSOR_LEFT; case DIKI_RIGHT: return DIKS_CURSOR_RIGHT; case DIKI_UP: return DIKS_CURSOR_UP; case DIKI_DOWN: return DIKS_CURSOR_DOWN; case DIKI_CONTROL_L: case DIKI_CONTROL_R: return DIKS_CONTROL; case DIKI_SHIFT_L: case DIKI_SHIFT_R: return DIKS_SHIFT; case DIKI_ALT_L: case DIKI_ALT_R: return DIKS_ALT; case DIKI_META_L: case DIKI_META_R: return DIKS_META; case DIKI_SUPER_L: case DIKI_SUPER_R: return DIKS_SUPER; case DIKI_HYPER_L: case DIKI_HYPER_R: return DIKS_HYPER; case DIKI_TAB: return DIKS_TAB; case DIKI_ENTER: return DIKS_ENTER; case DIKI_SPACE: return DIKS_SPACE; case DIKI_BACKSPACE: return DIKS_BACKSPACE; case DIKI_INSERT: return DIKS_INSERT; case DIKI_DELETE: return DIKS_DELETE; case DIKI_HOME: return DIKS_HOME; case DIKI_END: return DIKS_END; case DIKI_PAGE_UP: return DIKS_PAGE_UP; case DIKI_PAGE_DOWN: return DIKS_PAGE_DOWN; case DIKI_CAPS_LOCK: return DIKS_CAPS_LOCK; case DIKI_NUM_LOCK: return DIKS_NUM_LOCK; case DIKI_SCROLL_LOCK: return DIKS_SCROLL_LOCK; case DIKI_PRINT: return DIKS_PRINT; case DIKI_PAUSE: return DIKS_PAUSE; case DIKI_KP_DIV: return DIKS_SLASH; case DIKI_KP_MULT: return DIKS_ASTERISK; case DIKI_KP_MINUS: return DIKS_MINUS_SIGN; case DIKI_KP_PLUS: return DIKS_PLUS_SIGN; case DIKI_KP_ENTER: return DIKS_ENTER; case DIKI_KP_SPACE: return DIKS_SPACE; case DIKI_KP_TAB: return DIKS_TAB; case DIKI_KP_EQUAL: return DIKS_EQUALS_SIGN; case DIKI_KP_DECIMAL: return DIKS_PERIOD; case DIKI_KP_SEPARATOR: return DIKS_COMMA; case DIKI_BACKSLASH: return DIKS_BACKSLASH; case DIKI_EQUALS_SIGN: return DIKS_EQUALS_SIGN; case DIKI_LESS_SIGN: return DIKS_LESS_THAN_SIGN; case DIKI_MINUS_SIGN: return DIKS_MINUS_SIGN; case DIKI_PERIOD: return DIKS_PERIOD; case DIKI_QUOTE_LEFT: case DIKI_QUOTE_RIGHT: return DIKS_QUOTATION; case DIKI_SEMICOLON: return DIKS_SEMICOLON; case DIKI_SLASH: return DIKS_SLASH; default: ; } return DIKS_NULL; } static void release_key( CoreInputDevice *device, DFBInputDeviceKeyIdentifier id ) { DFBInputEvent evt; D_MAGIC_ASSERT( device, CoreInputDevice ); evt.type = DIET_KEYRELEASE; if (DFB_KEY_TYPE(id) == DIKT_IDENTIFIER) { evt.flags = DIEF_KEYID; evt.key_id = id; } else { evt.flags = DIEF_KEYSYMBOL; evt.key_symbol = id; } dfb_input_dispatch( device, &evt ); } static void flush_keys( CoreInputDevice *device ) { D_MAGIC_ASSERT( device, CoreInputDevice ); if (device->shared->modifiers_l) { if (device->shared->modifiers_l & DIMM_ALT) release_key( device, DIKI_ALT_L ); if (device->shared->modifiers_l & DIMM_CONTROL) release_key( device, DIKI_CONTROL_L ); if (device->shared->modifiers_l & DIMM_HYPER) release_key( device, DIKI_HYPER_L ); if (device->shared->modifiers_l & DIMM_META) release_key( device, DIKI_META_L ); if (device->shared->modifiers_l & DIMM_SHIFT) release_key( device, DIKI_SHIFT_L ); if (device->shared->modifiers_l & DIMM_SUPER) release_key( device, DIKI_SUPER_L ); } if (device->shared->modifiers_r) { if (device->shared->modifiers_r & DIMM_ALTGR) release_key( device, DIKS_ALTGR ); if (device->shared->modifiers_r & DIMM_ALT) release_key( device, DIKI_ALT_R ); if (device->shared->modifiers_r & DIMM_CONTROL) release_key( device, DIKI_CONTROL_R ); if (device->shared->modifiers_r & DIMM_HYPER) release_key( device, DIKI_HYPER_R ); if (device->shared->modifiers_r & DIMM_META) release_key( device, DIKI_META_R ); if (device->shared->modifiers_r & DIMM_SHIFT) release_key( device, DIKI_SHIFT_R ); if (device->shared->modifiers_r & DIMM_SUPER) release_key( device, DIKI_SUPER_R ); } } static void dump_primary_layer_surface( CoreDFB *core ) { CoreLayer *layer = dfb_layer_at( DLID_PRIMARY ); CoreLayerContext *context; /* Get the currently active context. */ if (dfb_layer_get_active_context( layer, &context ) == DFB_OK) { CoreLayerRegion *region; /* Get the first region. */ if (dfb_layer_context_get_primary_region( context, false, &region ) == DFB_OK) { CoreSurface *surface; /* Lock the region to avoid tearing due to concurrent updates. */ dfb_layer_region_lock( region ); /* Get the surface of the region. */ if (dfb_layer_region_get_surface( region, &surface ) == DFB_OK) { /* Dump the surface contents. */ dfb_surface_dump_buffer( surface, CSBR_FRONT, dfb_config->screenshot_dir, "dfb" ); /* Release the surface. */ dfb_surface_unref( surface ); } /* Unlock the region. */ dfb_layer_region_unlock( region ); /* Release the region. */ dfb_layer_region_unref( region ); } /* Release the context. */ dfb_layer_context_unref( context ); } } static bool core_input_filter( CoreInputDevice *device, DFBInputEvent *event ) { D_MAGIC_ASSERT( device, CoreInputDevice ); if (dfb_system_input_filter( device, event )) return true; if (event->type == DIET_KEYPRESS) { switch (event->key_symbol) { case DIKS_PRINT: if (!event->modifiers && dfb_config->screenshot_dir) { dump_primary_layer_surface( device->core ); return true; } break; case DIKS_BACKSPACE: if (event->modifiers == DIMM_META) direct_trace_print_stacks(); break; case DIKS_ESCAPE: if (event->modifiers == DIMM_META) { #if FUSION_BUILD_MULTI DFBResult ret; CoreLayer *layer = dfb_layer_at( DLID_PRIMARY ); CoreLayerContext *context; /* Get primary (shared) context. */ ret = dfb_layer_get_primary_context( layer, false, &context ); if (ret) return false; /* Activate the context. */ dfb_layer_activate_context( layer, context ); /* Release the context. */ dfb_layer_context_unref( context ); #else kill( 0, SIGINT ); #endif return true; } break; default: break; } } return false; }
Java
/** * Copyright (C) 2010 Orbeon, Inc. * * This program is free software; you can redistribute it and/or modify it under the terms of the * GNU Lesser General Public License as published by the Free Software Foundation; either version * 2.1 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * The full text of the license is available at http://www.gnu.org/copyleft/lesser.html */ package org.orbeon.oxf.xforms.analysis.model import org.dom4j.{Document, Element, QName} import org.orbeon.oxf.common.{ValidationException, Version} import org.orbeon.oxf.http.Credentials import org.orbeon.oxf.processor.ProcessorImpl import org.orbeon.oxf.util.ScalaUtils.{CodePointsOps, stringOptionToSet} import org.orbeon.oxf.util.{Logging, NetUtils, XPath} import org.orbeon.oxf.xforms.XFormsConstants._ import org.orbeon.oxf.xforms.analysis.controls.ComponentControl import org.orbeon.oxf.xforms.analysis.{ElementAnalysis, SimpleElementAnalysis, StaticStateContext} import org.orbeon.oxf.xforms.model.InstanceDataOps import org.orbeon.oxf.xforms.xbl.Scope import org.orbeon.oxf.xml.dom4j.{Dom4jUtils, ExtendedLocationData} import org.orbeon.oxf.xml.{Dom4j, TransformerUtils} import org.orbeon.saxon.dom4j.{DocumentWrapper, TypedDocumentWrapper} import org.orbeon.saxon.om.DocumentInfo import scala.collection.JavaConverters._ /** * Static analysis of an XForms instance. */ class Instance( staticStateContext : StaticStateContext, element : Element, parent : Option[ElementAnalysis], preceding : Option[ElementAnalysis], scope : Scope ) extends SimpleElementAnalysis( staticStateContext, element, parent, preceding, scope ) with InstanceMetadata with Logging { def partExposeXPathTypes = part.isExposeXPathTypes override def extendedLocationData = new ExtendedLocationData( locationData, Some("processing XForms instance"), List("id" → staticId), Option(element) ) // Get constant inline content from AbstractBinding if possible, otherwise extract from element. // Doing so allows for sharing of constant instances globally, among uses of an AbstractBinding and among multiple // instances of a given form. This is useful in particular for component i18n resource instances. def inlineContent = { // An instance within xf:implementation has a ComponentControl grandparent def componentForConstantInstances = if (readonly && useInlineContent) parent.get.parent collect { case component: ComponentControl ⇒ component } else None componentForConstantInstances map { component ⇒ val modelIndex = ElementAnalysis.precedingSiblingIterator(parent.get) count (_.localName == "model") val instanceIndex = ElementAnalysis.precedingSiblingIterator(this) count (_.localName == "instance") debug("getting readonly inline instance from abstract binding", Seq( "model id" → parent.get.staticId, "instance id" → staticId, "scope id" → component.binding.innerScope.scopeId, "binding name" → component.binding.abstractBinding.debugBindingName, "model index" → modelIndex.toString, "instance index" → instanceIndex.toString)) // Delegate to AbstractBinding component.binding.abstractBinding.constantInstances((modelIndex, instanceIndex)) } getOrElse extractInlineContent } } // Used to gather instance metadata from AbstractBinding class ThrowawayInstance(val element: Element) extends InstanceMetadata { def extendedLocationData = ElementAnalysis.createLocationData(element) def partExposeXPathTypes = false def inlineContent = extractInlineContent } // Separate trait that can also be used by AbstractBinding to extract instance metadata trait InstanceMetadata { def element: Element def partExposeXPathTypes: Boolean def extendedLocationData: ExtendedLocationData import ElementAnalysis._ import Instance._ val readonly = element.attributeValue(XXFORMS_READONLY_ATTRIBUTE_QNAME) == "true" val cache = Version.instance.isPEFeatureEnabled(element.attributeValue(XXFORMS_CACHE_QNAME) == "true", "cached XForms instance") val timeToLive = Instance.timeToLiveOrDefault(element) val handleXInclude = false // lazy because depends on property, which depends on top-level model being set in XFormsStaticStateImpl! lazy val exposeXPathTypes = Option(element.attributeValue(XXFORMS_EXPOSE_XPATH_TYPES_QNAME)) map (_ == "true") getOrElse ! readonly && partExposeXPathTypes val (indexIds, indexClasses) = { val tokens = attSet(element, XXFORMS_INDEX_QNAME) (tokens("id"), tokens("class")) } private val validation = element.attributeValue(XXFORMS_VALIDATION_QNAME) def isLaxValidation = (validation eq null) || validation == "lax" def isStrictValidation = validation == "strict" def isSchemaValidation = isLaxValidation || isStrictValidation val credentialsOrNull = { // NOTE: AVTs not supported because XPath expressions in those could access instances that haven't been loaded def username = element.attributeValue(XXFORMS_USERNAME_QNAME) def password = element.attributeValue(XXFORMS_PASSWORD_QNAME) def preemptiveAuth = element.attributeValue(XXFORMS_PREEMPTIVE_AUTHENTICATION_QNAME) def domain = element.attributeValue(XXFORMS_DOMAIN_QNAME) Option(username) map (Credentials(_, password, preemptiveAuth, domain)) orNull } val excludeResultPrefixes = stringOptionToSet(Option(element.attributeValue(XXFORMS_EXCLUDE_RESULT_PREFIXES))) // Inline root element if any private val root = Dom4j.elements(element) headOption private def hasInlineContent = root.isDefined // Create inline instance document if any def inlineContent: DocumentInfo // Extract the inline content into a new document (mutable or not) protected def extractInlineContent = extractDocument(root.get, excludeResultPrefixes, readonly, exposeXPathTypes, removeInstanceData = false) // Don't allow more than one child element if (Dom4j.elements(element).size > 1) throw new ValidationException("xf:instance must contain at most one child element", extendedLocationData) private def getAttributeEncode(qName: QName) = Option(element.attributeValue(qName)) map (att ⇒ NetUtils.encodeHRRI(att.trimAllToEmpty, true)) private def src = getAttributeEncode(SRC_QNAME) private def resource = getAttributeEncode(RESOURCE_QNAME) // @src always wins, @resource always loses val useInlineContent = src.isEmpty && hasInlineContent val useExternalContent = src.isDefined || ! hasInlineContent && resource.isDefined val (instanceSource, dependencyURL) = (if (useInlineContent) None else src orElse resource) match { case someSource @ Some(source) if ProcessorImpl.isProcessorOutputScheme(source) ⇒ someSource → None // input:* doesn't add a URL dependency, but is handled by the pipeline engine case someSource @ Some(_) ⇒ someSource → someSource case _ ⇒ None → None } // Don't allow a blank src attribute if (useExternalContent && instanceSource.contains("")) throw new ValidationException("xf:instance must not specify a blank URL", extendedLocationData) } object Instance { def timeToLiveOrDefault(element: Element) = { val timeToLiveValue = element.attributeValue(XXFORMS_TIME_TO_LIVE_QNAME) Option(timeToLiveValue) map (_.toLong) getOrElse -1L } // Extract the document starting at the given root element // This always creates a copy of the original sub-tree // // @readonly if true, the document returned is a compact TinyTree, otherwise a DocumentWrapper // @exposeXPathTypes if true, use a TypedDocumentWrapper def extractDocument( element : Element, excludeResultPrefixes : Set[String], readonly : Boolean, exposeXPathTypes : Boolean, removeInstanceData : Boolean ): DocumentInfo = { require(! (readonly && exposeXPathTypes)) // we can't expose types on readonly instances at the moment // Extract a document and adjust namespaces if requested // NOTE: Should implement exactly as per XSLT 2.0 // NOTE: Should implement namespace fixup, the code below can break serialization def extractDocument = excludeResultPrefixes match { case prefixes if prefixes("#all") ⇒ // Special #all Dom4jUtils.createDocumentCopyElement(element) case prefixes if prefixes.nonEmpty ⇒ // List of prefixes Dom4jUtils.createDocumentCopyParentNamespaces(element, prefixes.asJava) case _ ⇒ // No exclusion Dom4jUtils.createDocumentCopyParentNamespaces(element) } if (readonly) TransformerUtils.dom4jToTinyTree(XPath.GlobalConfiguration, extractDocument, false) else wrapDocument( if (removeInstanceData) InstanceDataOps.removeRecursively(extractDocument) else extractDocument, exposeXPathTypes ) } def wrapDocument(document: Document, exposeXPathTypes: Boolean): DocumentWrapper = if (exposeXPathTypes) new TypedDocumentWrapper( Dom4jUtils.normalizeTextNodes(document).asInstanceOf[Document], null, XPath.GlobalConfiguration ) else new DocumentWrapper( Dom4jUtils.normalizeTextNodes(document).asInstanceOf[Document], null, XPath.GlobalConfiguration ) }
Java
#ifndef EPubCaseElement_h #define EPubCaseElement_h #include "epubElement.h" namespace WebCore { class EPubCaseElement : public epubElement { public: static PassRefPtr<EPubCaseElement> create(const QualifiedName&, Document*); void finishParsingChildren(); private: EPubCaseElement(const QualifiedName&, Document*); }; } // namespace WebCore #endif // EPubCaseElement_h
Java
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtQuick module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qquickrectangle_p.h" #include "qquickrectangle_p_p.h" #include <QtQuick/private/qsgcontext_p.h> #include <private/qsgadaptationlayer_p.h> #include <QtGui/qpixmapcache.h> #include <QtCore/qstringbuilder.h> #include <QtCore/qmath.h> #include <QtCore/qmetaobject.h> QT_BEGIN_NAMESPACE // XXX todo - should we change rectangle to draw entirely within its width/height? /*! \internal \class QQuickPen \brief For specifying a pen used for drawing rectangle borders on a QQuickView By default, the pen is invalid and nothing is drawn. You must either set a color (then the default width is 1) or a width (then the default color is black). A width of 1 indicates is a single-pixel line on the border of the item being painted. Example: \qml Rectangle { border.width: 2 border.color: "red" } \endqml */ QQuickPen::QQuickPen(QObject *parent) : QObject(parent) , m_width(1) , m_color("#000000") , m_aligned(true) , m_valid(false) { } qreal QQuickPen::width() const { return m_width; } void QQuickPen::setWidth(qreal w) { if (m_width == w && m_valid) return; m_width = w; m_valid = m_color.alpha() && (qRound(m_width) >= 1 || (!m_aligned && m_width > 0)); emit penChanged(); } QColor QQuickPen::color() const { return m_color; } void QQuickPen::setColor(const QColor &c) { m_color = c; m_valid = m_color.alpha() && (qRound(m_width) >= 1 || (!m_aligned && m_width > 0)); emit penChanged(); } bool QQuickPen::pixelAligned() const { return m_aligned; } void QQuickPen::setPixelAligned(bool aligned) { if (aligned == m_aligned) return; m_aligned = aligned; m_valid = m_color.alpha() && (qRound(m_width) >= 1 || (!m_aligned && m_width > 0)); emit penChanged(); } bool QQuickPen::isValid() const { return m_valid; } /*! \qmltype GradientStop \instantiates QQuickGradientStop \inqmlmodule QtQuick \ingroup qtquick-visual-utility \brief Defines the color at a position in a Gradient \sa Gradient */ /*! \qmlproperty real QtQuick::GradientStop::position \qmlproperty color QtQuick::GradientStop::color The position and color properties describe the color used at a given position in a gradient, as represented by a gradient stop. The default position is 0.0; the default color is black. \sa Gradient */ QQuickGradientStop::QQuickGradientStop(QObject *parent) : QObject(parent) { } qreal QQuickGradientStop::position() const { return m_position; } void QQuickGradientStop::setPosition(qreal position) { m_position = position; updateGradient(); } QColor QQuickGradientStop::color() const { return m_color; } void QQuickGradientStop::setColor(const QColor &color) { m_color = color; updateGradient(); } void QQuickGradientStop::updateGradient() { if (QQuickGradient *grad = qobject_cast<QQuickGradient*>(parent())) grad->doUpdate(); } /*! \qmltype Gradient \instantiates QQuickGradient \inqmlmodule QtQuick \ingroup qtquick-visual-utility \brief Defines a gradient fill A gradient is defined by two or more colors, which will be blended seamlessly. The colors are specified as a set of GradientStop child items, each of which defines a position on the gradient from 0.0 to 1.0 and a color. The position of each GradientStop is defined by setting its \l{GradientStop::}{position} property; its color is defined using its \l{GradientStop::}{color} property. A gradient without any gradient stops is rendered as a solid white fill. Note that this item is not a visual representation of a gradient. To display a gradient, use a visual item (like \l Rectangle) which supports the use of gradients. \section1 Example Usage \div {class="float-right"} \inlineimage qml-gradient.png \enddiv The following example declares a \l Rectangle item with a gradient starting with red, blending to yellow at one third of the height of the rectangle, and ending with green: \snippet qml/gradient.qml code \clearfloat \section1 Performance and Limitations Calculating gradients can be computationally expensive compared to the use of solid color fills or images. Consider using gradients for static items in a user interface. In Qt 5.0, only vertical, linear gradients can be applied to items. If you need to apply different orientations of gradients, a combination of rotation and clipping will need to be applied to the relevant items. This can introduce additional performance requirements for your application. The use of animations involving gradient stops may not give the desired result. An alternative way to animate gradients is to use pre-generated images or SVG drawings containing gradients. \sa GradientStop */ /*! \qmlproperty list<GradientStop> QtQuick::Gradient::stops \default This property holds the gradient stops describing the gradient. By default, this property contains an empty list. To set the gradient stops, define them as children of the Gradient. */ QQuickGradient::QQuickGradient(QObject *parent) : QObject(parent) { } QQuickGradient::~QQuickGradient() { } QQmlListProperty<QQuickGradientStop> QQuickGradient::stops() { return QQmlListProperty<QQuickGradientStop>(this, m_stops); } QGradientStops QQuickGradient::gradientStops() const { QGradientStops stops; for (int i = 0; i < m_stops.size(); ++i){ int j = 0; while (j < stops.size() && stops.at(j).first < m_stops[i]->position()) j++; stops.insert(j, QGradientStop(m_stops.at(i)->position(), m_stops.at(i)->color())); } return stops; } void QQuickGradient::doUpdate() { emit updated(); } int QQuickRectanglePrivate::doUpdateSlotIdx = -1; /*! \qmltype Rectangle \instantiates QQuickRectangle \inqmlmodule QtQuick \inherits Item \ingroup qtquick-visual \brief Paints a filled rectangle with an optional border Rectangle items are used to fill areas with solid color or gradients, and/or to provide a rectangular border. \section1 Appearance Each Rectangle item is painted using either a solid fill color, specified using the \l color property, or a gradient, defined using a Gradient type and set using the \l gradient property. If both a color and a gradient are specified, the gradient is used. You can add an optional border to a rectangle with its own color and thickness by setting the \l border.color and \l border.width properties. Set the color to "transparent" to paint a border without a fill color. You can also create rounded rectangles using the \l radius property. Since this introduces curved edges to the corners of a rectangle, it may be appropriate to set the \l Item::antialiasing property to improve its appearance. \section1 Example Usage \div {class="float-right"} \inlineimage declarative-rect.png \enddiv The following example shows the effects of some of the common properties on a Rectangle item, which in this case is used to create a square: \snippet qml/rectangle/rectangle.qml document \clearfloat \section1 Performance Using the \l Item::antialiasing property improves the appearance of a rounded rectangle at the cost of rendering performance. You should consider unsetting this property for rectangles in motion, and only set it when they are stationary. \sa Image */ QQuickRectangle::QQuickRectangle(QQuickItem *parent) : QQuickItem(*(new QQuickRectanglePrivate), parent) { setFlag(ItemHasContents); } void QQuickRectangle::doUpdate() { update(); } /*! \qmlproperty bool QtQuick::Rectangle::antialiasing Used to decide if the Rectangle should use antialiasing or not. \l {Antialiasing} provides information on the performance implications of this property. The default is true for Rectangles with a radius, and false otherwise. */ /*! \qmlpropertygroup QtQuick::Rectangle::border \qmlproperty int QtQuick::Rectangle::border.width \qmlproperty color QtQuick::Rectangle::border.color The width and color used to draw the border of the rectangle. A width of 1 creates a thin line. For no line, use a width of 0 or a transparent color. \note The width of the rectangle's border does not affect the geometry of the rectangle itself or its position relative to other items if anchors are used. The border is rendered within the rectangle's boundaries. */ QQuickPen *QQuickRectangle::border() { Q_D(QQuickRectangle); return d->getPen(); } /*! \qmlproperty Gradient QtQuick::Rectangle::gradient The gradient to use to fill the rectangle. This property allows for the construction of simple vertical gradients. Other gradients may by formed by adding rotation to the rectangle. \div {class="float-left"} \inlineimage declarative-rect_gradient.png \enddiv \snippet qml/rectangle/rectangle-gradient.qml rectangles \clearfloat If both a gradient and a color are specified, the gradient will be used. \sa Gradient, color */ QQuickGradient *QQuickRectangle::gradient() const { Q_D(const QQuickRectangle); return d->gradient; } void QQuickRectangle::setGradient(QQuickGradient *gradient) { Q_D(QQuickRectangle); if (d->gradient == gradient) return; static int updatedSignalIdx = -1; if (updatedSignalIdx < 0) updatedSignalIdx = QMetaMethod::fromSignal(&QQuickGradient::updated).methodIndex(); if (d->doUpdateSlotIdx < 0) d->doUpdateSlotIdx = QQuickRectangle::staticMetaObject.indexOfSlot("doUpdate()"); if (d->gradient) QMetaObject::disconnect(d->gradient, updatedSignalIdx, this, d->doUpdateSlotIdx); d->gradient = gradient; if (d->gradient) QMetaObject::connect(d->gradient, updatedSignalIdx, this, d->doUpdateSlotIdx); update(); } void QQuickRectangle::resetGradient() { setGradient(0); } /*! \qmlproperty real QtQuick::Rectangle::radius This property holds the corner radius used to draw a rounded rectangle. If radius is non-zero, the rectangle will be painted as a rounded rectangle, otherwise it will be painted as a normal rectangle. The same radius is used by all 4 corners; there is currently no way to specify different radii for different corners. */ qreal QQuickRectangle::radius() const { Q_D(const QQuickRectangle); return d->radius; } void QQuickRectangle::setRadius(qreal radius) { Q_D(QQuickRectangle); if (d->radius == radius) return; d->radius = radius; d->setImplicitAntialiasing(radius != 0.0); update(); emit radiusChanged(); } /*! \qmlproperty color QtQuick::Rectangle::color This property holds the color used to fill the rectangle. The default color is white. \div {class="float-right"} \inlineimage rect-color.png \enddiv The following example shows rectangles with colors specified using hexadecimal and named color notation: \snippet qml/rectangle/rectangle-colors.qml rectangles \clearfloat If both a gradient and a color are specified, the gradient will be used. \sa gradient */ QColor QQuickRectangle::color() const { Q_D(const QQuickRectangle); return d->color; } void QQuickRectangle::setColor(const QColor &c) { Q_D(QQuickRectangle); if (d->color == c) return; d->color = c; update(); emit colorChanged(); } QSGNode *QQuickRectangle::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *data) { Q_UNUSED(data); Q_D(QQuickRectangle); if (width() <= 0 || height() <= 0 || (d->color.alpha() == 0 && (!d->pen || d->pen->width() == 0 || d->pen->color().alpha() == 0))) { delete oldNode; return 0; } QSGRectangleNode *rectangle = static_cast<QSGRectangleNode *>(oldNode); if (!rectangle) rectangle = d->sceneGraphContext()->createRectangleNode(); rectangle->setRect(QRectF(0, 0, width(), height())); rectangle->setColor(d->color); if (d->pen && d->pen->isValid()) { rectangle->setPenColor(d->pen->color()); rectangle->setPenWidth(d->pen->width()); rectangle->setAligned(d->pen->pixelAligned()); } else { rectangle->setPenWidth(0); } rectangle->setRadius(d->radius); rectangle->setAntialiasing(antialiasing()); QGradientStops stops; if (d->gradient) { stops = d->gradient->gradientStops(); } rectangle->setGradientStops(stops); rectangle->update(); return rectangle; } QT_END_NAMESPACE
Java
/* * JBoss, Home of Professional Open Source. * Copyright 2014, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.management.cli; import java.io.File; import java.net.URL; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import org.jboss.as.test.shared.TestSuiteEnvironment; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import org.junit.Test; import org.w3c.dom.Document; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; /** * * @author Dominik Pospisil <dpospisi@redhat.com> */ public class JBossCliXmlValidationTestCase { @Test public void validateJBossCliXmlTestCase() throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder parser = factory.newDocumentBuilder(); final String jbossDist = TestSuiteEnvironment.getSystemProperty("jboss.dist"); Document document = parser.parse(new File(jbossDist, "bin/jboss-cli.xml")); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); schemaFactory.setErrorHandler(new ErrorHandlerImpl()); //schemaFactory.setResourceResolver(new XMLResourceResolver()); Schema schema = schemaFactory.newSchema(resourceToURL("schema/wildfly-cli_3_4.xsd")); Validator validator = schema.newValidator(); validator.validate(new DOMSource(document)); } protected static final class ErrorHandlerImpl implements ErrorHandler { @Override public void error(SAXParseException e) throws SAXException { fail(formatMessage(e)); } @Override public void fatalError(SAXParseException e) throws SAXException { fail(formatMessage(e)); } @Override public void warning(SAXParseException e) throws SAXException { System.out.println(formatMessage(e)); } private String formatMessage(SAXParseException e) { StringBuffer sb = new StringBuffer(); sb.append(e.getLineNumber()).append(':').append(e.getColumnNumber()); if (e.getPublicId() != null) sb.append(" publicId='").append(e.getPublicId()).append('\''); if (e.getSystemId() != null) sb.append(" systemId='").append(e.getSystemId()).append('\''); sb.append(' ').append(e.getLocalizedMessage()); sb.append(" a possible cause may be that a subsystem is not using the most up to date schema."); return sb.toString(); } } private URL resourceToURL(final String name) { final ClassLoader classLoader = getClass().getClassLoader(); final URL resource = classLoader.getResource(name); assertNotNull("Can't locate resource " + name + " on " + classLoader, resource); return resource; } }
Java
/* baskcground color */ .member-menu-top .profile-image, .member-menu-logged ul, .flatBoard .login-wrap, .m-element .notice-list li .notice-text, .m-imagenews .info span.category, .swiper-active-switch, .m-ranking .rank-num {background-color: #7371b4;} /* @mCol */ .btDark, .flatMember .btSubmit, .flatBoard .btSubmit, .login-body .btLogin, .lang-list {background-color: #32323f} /* @sCol */ header.main, .main-logo, .login-wrap, .member-header-wrap, .main-image-wrap, .main-normal-image {background: -webkit-gradient(linear, left top, right top, from(#d17ca6), to(#7371b4)); background: -webkit-linear-gradient(left, #7371b4, #d17ca6);} .sc header.main{ background-image: url('../images/bgScan_top.png'), -webkit-gradient(linear, left top, right top, from(#d17ca6), to(#7371b4)); background-image: url('../images/bgScan_top.png'), -webkit-linear-gradient(left, #7371b4, #d17ca6); background-size: auto; } .sc .login-wrap, .sc .member-header-wrap, .sc .main-normal-image, .sc .main-logo{ background-image: url('../images/bgScan.png'), -webkit-gradient(linear, left top, right top, from(#d17ca6), to(#7371b4)); background-image: url('../images/bgScan.png'), -webkit-linear-gradient(left, #7371b4, #d17ca6); background-size: auto; } .sc2 header.main{ background-image: url('../images/bgScan2_top.png'), -webkit-gradient(linear, left top, right top, from(#d17ca6), to(#7371b4)); background-image: url('../images/bgScan2_top.png'), -webkit-linear-gradient(left, #7371b4, #d17ca6); background-size: auto; } .sc2 .login-wrap, .sc2 .member-header-wrap, .sc2 .main-normal-image, .sc2 .main-logo{ background-image: url('../images/bgScan2.png'), -webkit-gradient(linear, left top, right top, from(#d17ca6), to(#7371b4)); background-image: url('../images/bgScan2.png'), -webkit-linear-gradient(left, #7371b4, #d17ca6); background-size: auto; } .m-element nav ul, .m-element section h3, .member-header ul {background: -webkit-gradient(linear, left top, right top, from(#a76385), to(#5e5890)); background: -webkit-linear-gradient(left, #5e5890, #a76385);} .read-control li:not(.comment-num) a, .read-control li:not(.comment-num) button {background-color: #d17ca6;}/* g right */ .global-search .btClose, .read-control .num2 span {background-color: #a76385}/* g right d */ .member-menu-top, .m-imagenews .info span.name {background-color: #6a63a2}/* g left */ .main-search button {background-color: #000; opacity: 0.4;} /* border color */ .member-menu-top a.btLogin {border-right: 1px solid #5f5990;} /* @mCol_line */ .member-menu-logged li {border-bottom: 1px solid #6a68a5;} /* @mCol_line */ input[type="text"]:focus, input[type="email"]:focus, input[type="url"]:focus, input[type="file"]:focus, input[type="password"]:focus, textarea:focus {border: 1px solid #7371b4;} /* @mCol */ .lang-list:after {border-color: #32323f transparent} /* @sCol */ .member-header .profile-image {box-shadow: 0px 0px 0px 1px rgba(0,0,0,0.2);} .searchinput2 {box-shadow: 0px 0px 0px 8px rgba(0,0,0,0.4);} .gnb li ul li a.selected {border-left: 5px solid #7371b4;} /* font color */ .flatMember em, .read-control li.comment-num .num, .write-form em, .gnb li ul li ul li.selected {color: #7371b4 !important;} /* @mCol */ .category-list em {color: #d17ca6;}/* g right */ header.main h1, .global-search .btClose, .member-menu-top a, .member-menu-top .name, .flatMember .btSubmit, .flatBoard .btSubmit, .read-control .num2 span, .m-element .notice-list li .notice-text, .member-top-title, .top-title {color: #FFF;} /* @mCol_l */ .member-menu-logged li a, .social-login h2, .main-search button {color: #FFF;} /* @mCol_l2 */ .m-list-reply {color: #344d62;} /* @sCol_l3 */ .login-body .btLogin, .btDark, .lang-list li button {color: #c7d0dd;} /* @sCol_l */ .m-element nav a, .member-header .member-menu li a {color: #FFF; opacity: 0.4;} /* @sCol_l2 */ .m-element nav li.active a, .m-element section h3 span, .member-header .member-menu li a.active {color: #FFF; opacity: 0.8;} /* etc */ .login-body, .signup-body, .find-body, .flatBoard .origin-body, .flatBoard .message-body {box-shadow: 0 0 10px rgba(0,0,0,0.2); -moz-box-shadow: 0 0 10px rgba(0,0,0,0.2); -webkit-box-shadow: 0 0 10px rgba(0,0,0,0.2);} /* pad color */ @media screen and (min-width: 768px){ .leftCol .m-element nav ul, .leftCol .m-element section h3 {background: -webkit-gradient(linear, left top, right top, from(#825f8a), to(#5e5890)); background: -webkit-linear-gradient(left, #5e5890, #825f8a);} .rightCol .m-element nav ul, .rightCol .m-element section h3 {background: -webkit-gradient(linear, left top, right top, from(#a76385), to(#825f8a)); background: -webkit-linear-gradient(left, #825f8a, #a76385);} } /* phone color */ @media screen and (max-width: 767px){ /* board comment */ .comment-control li span {background-color: #8e8cc0; border-bottom: 1px solid #7371b4;} /* mCol_l2 */ .comment-control li span.im {background-color: #7371b4; border-bottom: 1px solid #6a68a5;} /* @mCol_line */ }
Java
// The libMesh Finite Element Library. // Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Local includes #include "quadrature_clough.h" #include "quadrature_gauss.h" namespace libMesh { void QClough::init_2D(const ElemType _type, unsigned int p) { #if LIBMESH_DIM > 1 QGauss gauss_rule(2, _order); gauss_rule.init(TRI6, p); //----------------------------------------------------------------------- // 2D quadrature rules switch (_type) { //--------------------------------------------- // Triangle quadrature rules case TRI3: case TRI6: { std::vector<Point> &gausspoints = gauss_rule.get_points(); std::vector<Real> &gaussweights = gauss_rule.get_weights(); unsigned int numgausspts = gausspoints.size(); _points.resize(numgausspts*3); _weights.resize(numgausspts*3); for (unsigned int i = 0; i != numgausspts; ++i) { _points[3*i](0) = gausspoints[i](0) + gausspoints[i](1) / 3.; _points[3*i](1) = gausspoints[i](1) / 3.; _points[3*i+1](0) = gausspoints[i](1) / 3.; _points[3*i+1](1) = gausspoints[i](0) + gausspoints[i](1) / 3.; _points[3*i+2](0) = 1./3. + gausspoints[i](0) * 2./3. - gausspoints[i](1) / 3.; _points[3*i+2](1) = 1./3. - gausspoints[i](0) / 3. + gausspoints[i](1) * 2./3.; _weights[3*i] = gaussweights[i] / 3.; _weights[3*i+1] = _weights[3*i]; _weights[3*i+2] = _weights[3*i]; } return; } //--------------------------------------------- // Unsupported type default: { libMesh::err << "Element type not supported!:" << _type << std::endl; libmesh_error(); } } libmesh_error(); return; #endif } } // namespace libMesh
Java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ /** * */ package org.hibernate.spatial.testing.dialects.h2geodb; import org.hibernate.spatial.testing.AbstractExpectationsFactory; import org.hibernate.spatial.testing.NativeSQLStatement; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.Point; import org.geolatte.geom.ByteBuffer; import org.geolatte.geom.codec.Wkb; import org.geolatte.geom.jts.JTS; /** * A Factory class that generates expected {@link org.hibernate.spatial.testing.NativeSQLStatement}s for GeoDB * version < 0.4. These versions don't support storage of the SRID value with * the geometry. * * @author Jan Boonen, Geodan IT b.v. */ @Deprecated //Class no longer used. Remove. public class GeoDBNoSRIDExpectationsFactory extends AbstractExpectationsFactory { public GeoDBNoSRIDExpectationsFactory(GeoDBDataSourceUtils dataSourceUtils) { super( dataSourceUtils ); } @Override protected NativeSQLStatement createNativeAsBinaryStatement() { return createNativeSQLStatement( "select id, ST_AsEWKB(geom) from GEOMTEST" ); } @Override protected NativeSQLStatement createNativeAsTextStatement() { return createNativeSQLStatement( "select id, ST_AsText(geom) from GEOMTEST" ); } @Override protected NativeSQLStatement createNativeBoundaryStatement() { throw new UnsupportedOperationException( "Method ST_Bounday() is not implemented in the current version of GeoDB." ); } @Override protected NativeSQLStatement createNativeBufferStatement(Double distance) { return createNativeSQLStatement( "select t.id, ST_Buffer(t.geom,?) from GEOMTEST t where ST_SRID(t.geom) = 4326", new Object[] { distance } ); } @Override protected NativeSQLStatement createNativeContainsStatement(Geometry geom) { return createNativeSQLStatementAllWKTParams( "select t.id, ST_Contains(t.geom, ST_GeomFromText(?, 4326)) from GEOMTEST t where ST_Contains(t.geom, ST_GeomFromText(?, 4326)) = 1", geom.toText() ); } @Override protected NativeSQLStatement createNativeConvexHullStatement(Geometry geom) { throw new UnsupportedOperationException( "Method ST_ConvexHull() is not implemented in the current version of GeoDB." ); } @Override protected NativeSQLStatement createNativeCrossesStatement(Geometry geom) { return createNativeSQLStatementAllWKTParams( "select t.id, ST_Crosses(t.geom, ST_GeomFromText(?, 4326)) from GEOMTEST t where ST_Crosses(t.geom, ST_GeomFromText(?, 4326)) = 1", geom.toText() ); } @Override protected NativeSQLStatement createNativeDifferenceStatement(Geometry geom) { throw new UnsupportedOperationException( "Method ST_Difference() is not implemented in the current version of GeoDB." ); } @Override protected NativeSQLStatement createNativeDimensionSQL() { throw new UnsupportedOperationException( "Method ST_Dimension() is not implemented in the current version of GeoDB." ); } @Override protected NativeSQLStatement createNativeDisjointStatement(Geometry geom) { return createNativeSQLStatementAllWKTParams( "select t.id, ST_Disjoint(t.geom, ST_GeomFromText(?, 4326)) from GEOMTEST t where ST_Disjoint(t.geom, ST_GeomFromText(?, 4326)) = 1", geom.toText() ); } @Override protected NativeSQLStatement createNativeTransformStatement(int epsg) { throw new UnsupportedOperationException(); } @Override protected NativeSQLStatement createNativeHavingSRIDStatement(int srid) { return createNativeSQLStatement( "select t.id, (st_srid(t.geom) = " + srid + ") from GeomTest t where ST_SRID(t.geom) = " + srid ); } @Override protected NativeSQLStatement createNativeDistanceStatement(Geometry geom) { return createNativeSQLStatementAllWKTParams( "select t.id, st_distance(t.geom, ST_GeomFromText(?, 4326)) from GeomTest t where ST_SRID(t.geom) = 4326", geom.toText() ); } @Override protected NativeSQLStatement createNativeEnvelopeStatement() { return createNativeSQLStatement( "select id, ST_Envelope(geom) from GEOMTEST" ); } @Override protected NativeSQLStatement createNativeEqualsStatement(Geometry geom) { return createNativeSQLStatementAllWKTParams( "select t.id, ST_Equals(t.geom, ST_GeomFromText(?, 4326)) from GEOMTEST t where ST_Equals(t.geom, ST_GeomFromText(?, 4326)) = 1", geom.toText() ); } @Override protected NativeSQLStatement createNativeFilterStatement(Geometry geom) { throw new UnsupportedOperationException( "Method ST_MBRIntersects() is not implemented in the current version of GeoDB." ); } @Override protected NativeSQLStatement createNativeGeomUnionStatement(Geometry geom) { throw new UnsupportedOperationException( "Method ST_GeomUnion() is not implemented in the current version of GeoDB." ); } @Override protected NativeSQLStatement createNativeGeometryTypeStatement() { return createNativeSQLStatement( "select id, GeometryType(geom) from GEOMTEST" ); } @Override protected NativeSQLStatement createNativeIntersectionStatement(Geometry geom) { throw new UnsupportedOperationException( "Method ST_Intersection() is not implemented in the current version of GeoDB." ); } @Override protected NativeSQLStatement createNativeIntersectsStatement(Geometry geom) { return createNativeSQLStatementAllWKTParams( "select t.id, ST_Intersects(t.geom, ST_GeomFromText(?, 4326)) from GEOMTEST t where ST_Intersects(t.geom, ST_GeomFromText(?, 4326)) = 1", geom.toText() ); } @Override protected NativeSQLStatement createNativeIsEmptyStatement() { return createNativeSQLStatement( "select id, ST_IsEmpty(geom) from GEOMTEST" ); } @Override protected NativeSQLStatement createNativeIsNotEmptyStatement() { return createNativeSQLStatement( "select id, not ST_IsEmpty(geom) from GEOMTEST" ); } @Override protected NativeSQLStatement createNativeIsSimpleStatement() { return createNativeSQLStatement( "select id, ST_IsSimple(geom) from GEOMTEST" ); } @Override protected NativeSQLStatement createNativeOverlapsStatement(Geometry geom) { return createNativeSQLStatementAllWKTParams( "select t.id, ST_Overlaps(t.geom, ST_GeomFromText(?, 4326)) from GEOMTEST t where ST_Overlaps(t.geom, ST_GeomFromText(?, 4326)) = 1", geom.toText() ); } @Override protected NativeSQLStatement createNativeRelateStatement(Geometry geom, String matrix) { throw new UnsupportedOperationException( "Method ST_Relate() is not implemented in the current version of GeoDB." ); } @Override protected NativeSQLStatement createNativeDwithinStatement(Point geom, double distance) { String sql = "select t.id, st_dwithin(t.geom, ST_GeomFromText(?, 4326), " + distance + " ) from GeomTest t where st_dwithin(t.geom, ST_GeomFromText(?, 4326), " + distance + ") = 'true' and ST_SRID(t.geom) = 4326"; return createNativeSQLStatementAllWKTParams( sql, geom.toText() ); } /* * (non-Javadoc) * * @seeorg.hibernatespatial.test.AbstractExpectationsFactory# * createNativeSridStatement() */ @Override protected NativeSQLStatement createNativeSridStatement() { return createNativeSQLStatement( "select id, ST_SRID(geom) from GEOMTEST" ); } @Override protected NativeSQLStatement createNativeSymDifferenceStatement( Geometry geom) { throw new UnsupportedOperationException( "Method ST_SymDifference() is not implemented in the current version of GeoDB." ); } @Override protected NativeSQLStatement createNativeTouchesStatement(Geometry geom) { return createNativeSQLStatementAllWKTParams( "select t.id, ST_Touches(t.geom, ST_GeomFromText(?, 4326)) from GEOMTEST t where ST_Touches(t.geom, ST_GeomFromText(?, 4326)) = 1", geom.toText() ); } @Override protected NativeSQLStatement createNativeWithinStatement( Geometry testPolygon) { return createNativeSQLStatementAllWKTParams( "select t.id, ST_Within(t.geom, ST_GeomFromText(?, 4326)) from GEOMTEST t where ST_Within(t.geom, ST_GeomFromText(?, 4326)) = 1 and ST_SRID(t.geom) = 4326", testPolygon.toText() ); } @Override protected Geometry decode(Object o) { return JTS.to( Wkb.fromWkb( ByteBuffer.from( (byte[]) o ) ) ); } }
Java
/* $Id: glade-databox.c 4 2008-06-22 09:19:11Z rbock $ */ /* -*- Mode: C; c-basic-offset: 4 -*- * libglade - a library for building interfaces from XML files at runtime * Copyright (C) 1998-2001 James Henstridge <james@daa.com.au> * Copyright 2001 Ximian, Inc. * * glade-databox.c: support for canvas widgets in libglade. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * * Authors: * Jacob Berkman <jacob@ximian.com> * James Henstridge <james@daa.com.au> * * Modified for gtkdatabox by (based on gnome-canvas glade interface): * H. Nieuwenhuis <vzzbx@xs4all.nl> */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <string.h> #include <glade/glade-init.h> #include <glade/glade-build.h> #include <gtkdatabox.h> #include <gtkdatabox_ruler.h> /* this macro puts a version check function into the module */ GLADE_MODULE_CHECK_INIT void glade_module_register_widgets (void) { glade_require ("gtk"); glade_register_widget (GTK_TYPE_DATABOX, glade_standard_build_widget, NULL, NULL); glade_register_widget (GTK_DATABOX_TYPE_RULER, glade_standard_build_widget, NULL, NULL); glade_provide ("databox"); }
Java
// in all regexp "\" must be replaced by "\\" var datas= { "default": { // the name of this definition group. It's posisble to have different rules inside the same definition file "REGEXP": { "before_word": "[^a-zA-Z0-9_]|^" // \\s|\\.| ,"possible_words_letters": "[a-zA-Z0-9_]+" ,"letter_after_word_must_match": "[^a-zA-Z0-9_]|$" ,"prefix_separator": "\\.|->" } ,"CASE_SENSITIVE": true ,"MAX_TEXT_LENGTH": 100 // the length of the text being analyzed before the cursor position ,"KEYWORDS": [ // [ // 0 : the keyword the user is typing // 1 : the string inserted in code ("{_@_}" being the new position of the cursor) // 2 : the needed prefix // 3 : the text the appear in the suggestion box (if empty, the string to insert will be displayed ['Array', 'Array()', '', 'alert( String message )'] ,['alert', 'alert({_@_})', '', 'alert(message)'] ,['ascrollTo', 'scrollTo({_@_})', '', 'scrollTo(x,y)'] ,['alert', 'alert({_@_},bouh);', '', 'alert(message, message2)'] ,['aclose', 'close({_@_})', '', 'alert(message)'] ,['aconfirm', 'confirm({_@_})', '', 'alert(message)'] ,['aonfocus', 'onfocus', '', ''] ,['aonerror', 'onerror', '', 'blabla'] ,['aonerror', 'onerror', '', ''] ,['window', '', '', ''] ,['location', 'location', 'window', ''] ,['document', 'document', 'window', ''] ,['href', 'href', 'location', ''] ] } }; // the second identifier must be the same as the one of the syntax coloring definition file EditArea_autocompletion._load_auto_complete_file( datas, "php" );
Java
/* Test driver for thbrk */ #define MAXLINELENGTH 1000 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <thai/thbrk.h> /* run with "-i" argument to get the interactive version otherwise it will run the self test and exit */ int main (int argc, char* argv[]) { thchar_t str[MAXLINELENGTH]; thchar_t out[MAXLINELENGTH*6+1]; int pos[MAXLINELENGTH]; int outputLength; int numCut, i; int interactive = 0; ThBrk *brk; if (argc >= 2) { if (0 == strcmp (argv[1], "-i")) interactive = 1; } brk = th_brk_new (NULL); if (!brk) { printf ("Unable to create word breaker!\n"); exit (-1); } if (interactive) { while (!feof (stdin)) { printf ("Please enter thai words/sentences: "); if (!fgets ((char *)str, MAXLINELENGTH-1, stdin)) { numCut = th_brk_find_breaks (brk, str, pos, MAXLINELENGTH); printf ("Total %d cut points.", numCut); if (numCut > 0) { printf ("Cut points list: %d", pos[0]); for (i = 1; i < numCut; i++) { printf(", %d", pos[i]); } } printf("\n"); outputLength = th_brk_insert_breaks (brk, str, out, sizeof out, "<WBR>"); printf ("Output string length is %d\n", outputLength-1); /* the penultimate is \n */ printf ("Output string is %s", out); printf("***********************************************************************\n"); } } } else { strcpy ((char *)str, "ÊÇÑÊ´Õ¤ÃѺ ¡Í.ÃÁ¹. ¹Õèà»ç¹¡Ò÷´ÊͺµÑÇàͧ"); printf ("Testing with string: %s\n", str); numCut = th_brk_find_breaks (brk, str, pos, MAXLINELENGTH); printf ("Total %d cut points.", numCut); if (numCut != 7) { printf("Error! should be 7.. test th_brk_find_breaks() failed...\n"); exit (-1); } printf("Cut points list: %d", pos[0]); for (i = 1; i < numCut; i++) { printf(", %d", pos[i]); } printf("\n"); outputLength = th_brk_insert_breaks (brk, str, out, sizeof out, "<WBR>"); printf ("Output string is %s\n", out); printf ("Output string length is %d\n", outputLength); if (outputLength != 75) { printf ("Error! should be 75.. test th_brk_insert_breaks() failed...\n"); exit (-1); } printf ("*** End of thbrk self test ******\n"); } th_brk_delete (brk); return 0; }
Java
# This file is part of the GOsa framework. # # http://gosa-project.org # # Copyright: # (C) 2016 GONICUS GmbH, Germany, http://www.gonicus.de # # See the LICENSE file in the project's top-level directory for details. import pkg_resources from gosa.common.components import PluginRegistry from gosa.common.utils import N_ from gosa.common.error import GosaErrorHandler as C # Register the errors handled by us C.register_codes(dict( BACKEND_NOT_FOUND=N_("Backend '%(topic)s' not found"), )) class ObjectBackendRegistry(object): instance = None backends = {} uuidAttr = "entryUUID" __index = None def __init__(self): # Load available backends for entry in pkg_resources.iter_entry_points("gosa.object.backend"): clazz = entry.load() ObjectBackendRegistry.backends[clazz.__name__] = clazz() def dn2uuid(self, backend, dn, from_db_only=False): uuid = ObjectBackendRegistry.backends[backend].dn2uuid(dn) if uuid is None and from_db_only is True: # fallback to db if self.__index is None: self.__index = PluginRegistry.getInstance("ObjectIndex") res = self.__index.search({'dn': dn}, {'uuid': 1}) if len(res) == 1: uuid = res[0]['_uuid'] return uuid def uuid2dn(self, backend, uuid, from_db_only=False): dn = ObjectBackendRegistry.backends[backend].uuid2dn(uuid) if dn is None and from_db_only is True: # fallback to db if self.__index is None: self.__index = PluginRegistry.getInstance("ObjectIndex") res = self.__index.search({'uuid': uuid}, {'dn': 1}) if len(res) == 1: dn = res[0]['dn'] return dn def get_timestamps(self, backend, dn): return ObjectBackendRegistry.backends[backend].get_timestamps(dn) @staticmethod def getInstance(): if not ObjectBackendRegistry.instance: ObjectBackendRegistry.instance = ObjectBackendRegistry() return ObjectBackendRegistry.instance @staticmethod def getBackend(name): if not name in ObjectBackendRegistry.backends: raise ValueError(C.make_error("BACKEND_NOT_FOUND", name)) return ObjectBackendRegistry.backends[name]
Java
/* * Created on 17-dic-2005 * * TODO To change the template for this generated file go to Window - * Preferences - Java - Code Style - Code Templates */ package org.herac.tuxguitar.gui.actions.transport; import org.eclipse.swt.events.TypedEvent; import org.herac.tuxguitar.gui.TuxGuitar; import org.herac.tuxguitar.gui.actions.Action; /** * @author julian * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class TransportStopAction extends Action { public static final String NAME = "action.transport.stop"; public TransportStopAction() { super(NAME, AUTO_LOCK | AUTO_UNLOCK | AUTO_UPDATE | KEY_BINDING_AVAILABLE); } protected int execute(TypedEvent e) { TuxGuitar.instance().getTransport().stop(); return 0; } }
Java
<?php // Only one consumer per queue is allowed. // Set $queue name to test exclusiveness include(__DIR__ . '/config.php'); use PhpAmqpLib\Connection\AMQPStreamConnection; $exchange = 'fanout_exclusive_example_exchange'; $queue = ''; // if empty let RabbitMQ create a queue name // set a queue name and run multiple instances // to test exclusiveness $consumerTag = 'consumer' . getmypid(); $connection = new AMQPStreamConnection(HOST, PORT, USER, PASS, VHOST); $channel = $connection->channel(); /* name: $queue // should be unique in fanout exchange. Let RabbitMQ create // a queue name for us passive: false // don't check if a queue with the same name exists durable: false // the queue will not survive server restarts exclusive: true // the queue can not be accessed by other channels auto_delete: true //the queue will be deleted once the channel is closed. */ list($queueName, ,) = $channel->queue_declare($queue, false, false, true, true); /* name: $exchange type: direct passive: false // don't check if a exchange with the same name exists durable: false // the exchange will not survive server restarts auto_delete: true //the exchange will be deleted once the channel is closed. */ $channel->exchange_declare($exchange, 'fanout', false, false, true); $channel->queue_bind($queueName, $exchange); /** * @param \PhpAmqpLib\Message\AMQPMessage $message */ function process_message($message) { echo "\n--------\n"; echo $message->body; echo "\n--------\n"; $message->delivery_info['channel']->basic_ack($message->delivery_info['delivery_tag']); // Send a message with the string "quit" to cancel the consumer. if ($message->body === 'quit') { $message->delivery_info['channel']->basic_cancel($message->delivery_info['consumer_tag']); } } /* queue: Queue from where to get the messages consumer_tag: Consumer identifier no_local: Don't receive messages published by this consumer. no_ack: Tells the server if the consumer will acknowledge the messages. exclusive: Request exclusive consumer access, meaning only this consumer can access the queue nowait: don't wait for a server response. In case of error the server will raise a channel exception callback: A PHP Callback */ $channel->basic_consume($queueName, $consumerTag, false, false, true, false, 'process_message'); /** * @param \PhpAmqpLib\Channel\AMQPChannel $channel * @param \PhpAmqpLib\Connection\AbstractConnection $connection */ function shutdown($channel, $connection) { $channel->close(); $connection->close(); } register_shutdown_function('shutdown', $channel, $connection); // Loop as long as the channel has callbacks registered while (count($channel->callbacks)) { $channel->wait(); }
Java
// <copyright file="AcmlLinearAlgebraProvider.float.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // // Copyright (c) 2009-2011 Math.NET // // 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. // </copyright> namespace MathNet.Numerics.Algorithms.LinearAlgebra.Acml { using System; using System.Security; using Properties; /// <summary> /// AMD Core Math Library (ACML) linear algebra provider. /// </summary> public partial class AcmlLinearAlgebraProvider { /// <summary> /// Computes the dot product of x and y. /// </summary> /// <param name="x">The vector x.</param> /// <param name="y">The vector y.</param> /// <returns>The dot product of x and y.</returns> /// <remarks>This is equivalent to the DOT BLAS routine.</remarks> [SecuritySafeCritical] public override float DotProduct(float[] x, float[] y) { if (y == null) { throw new ArgumentNullException("y"); } if (x == null) { throw new ArgumentNullException("x"); } if (x.Length != y.Length) { throw new ArgumentException(Resources.ArgumentArraysSameLength); } return SafeNativeMethods.s_dot_product(x.Length, x, y); } /// <summary> /// Adds a scaled vector to another: <c>result = y + alpha*x</c>. /// </summary> /// <param name="y">The vector to update.</param> /// <param name="alpha">The value to scale <paramref name="x"/> by.</param> /// <param name="x">The vector to add to <paramref name="y"/>.</param> /// <param name="result">The result of the addition.</param> /// <remarks>This is similar to the AXPY BLAS routine.</remarks> [SecuritySafeCritical] public override void AddVectorToScaledVector(float[] y, float alpha, float[] x, float[] result) { if (y == null) { throw new ArgumentNullException("y"); } if (x == null) { throw new ArgumentNullException("x"); } if (y.Length != x.Length) { throw new ArgumentException(Resources.ArgumentVectorsSameLength); } if (!ReferenceEquals(y, result)) { Array.Copy(y, 0, result, 0, y.Length); } if (alpha == 0.0f) { return; } SafeNativeMethods.s_axpy(y.Length, alpha, x, result); } /// <summary> /// Scales an array. Can be used to scale a vector and a matrix. /// </summary> /// <param name="alpha">The scalar.</param> /// <param name="x">The values to scale.</param> /// <param name="result">This result of the scaling.</param> /// <remarks>This is similar to the SCAL BLAS routine.</remarks> [SecuritySafeCritical] public override void ScaleArray(float alpha, float[] x, float[] result) { if (x == null) { throw new ArgumentNullException("x"); } if (!ReferenceEquals(x, result)) { Array.Copy(x, 0, result, 0, x.Length); } if (alpha == 1.0f) { return; } SafeNativeMethods.s_scale(x.Length, alpha, result); } /// <summary> /// Multiples two matrices. <c>result = x * y</c> /// </summary> /// <param name="x">The x matrix.</param> /// <param name="rowsX">The number of rows in the x matrix.</param> /// <param name="columnsX">The number of columns in the x matrix.</param> /// <param name="y">The y matrix.</param> /// <param name="rowsY">The number of rows in the y matrix.</param> /// <param name="columnsY">The number of columns in the y matrix.</param> /// <param name="result">Where to store the result of the multiplication.</param> /// <remarks>This is a simplified version of the BLAS GEMM routine with alpha /// set to 1.0f and beta set to 0.0f, and x and y are not transposed.</remarks> public override void MatrixMultiply(float[] x, int rowsX, int columnsX, float[] y, int rowsY, int columnsY, float[] result) { MatrixMultiplyWithUpdate(Transpose.DontTranspose, Transpose.DontTranspose, 1.0f, x, rowsX, columnsX, y, rowsY, columnsY, 0.0f, result); } /// <summary> /// Multiplies two matrices and updates another with the result. <c>c = alpha*op(a)*op(b) + beta*c</c> /// </summary> /// <param name="transposeA">How to transpose the <paramref name="a"/> matrix.</param> /// <param name="transposeB">How to transpose the <paramref name="b"/> matrix.</param> /// <param name="alpha">The value to scale <paramref name="a"/> matrix.</param> /// <param name="a">The a matrix.</param> /// <param name="rowsA">The number of rows in the <paramref name="a"/> matrix.</param> /// <param name="columnsA">The number of columns in the <paramref name="a"/> matrix.</param> /// <param name="b">The b matrix</param> /// <param name="rowsB">The number of rows in the <paramref name="b"/> matrix.</param> /// <param name="columnsB">The number of columns in the <paramref name="b"/> matrix.</param> /// <param name="beta">The value to scale the <paramref name="c"/> matrix.</param> /// <param name="c">The c matrix.</param> [SecuritySafeCritical] public override void MatrixMultiplyWithUpdate(Transpose transposeA, Transpose transposeB, float alpha, float[] a, int rowsA, int columnsA, float[] b, int rowsB, int columnsB, float beta, float[] c) { if (a == null) { throw new ArgumentNullException("a"); } if (b == null) { throw new ArgumentNullException("b"); } if (c == null) { throw new ArgumentNullException("c"); } var m = transposeA == Transpose.DontTranspose ? rowsA : columnsA; var n = transposeB == Transpose.DontTranspose ? columnsB : rowsB; var k = transposeA == Transpose.DontTranspose ? columnsA : rowsA; var l = transposeB == Transpose.DontTranspose ? rowsB : columnsB; if (c.Length != m * n) { throw new ArgumentException(Resources.ArgumentMatrixDimensions); } if (k != l) { throw new ArgumentException(Resources.ArgumentMatrixDimensions); } SafeNativeMethods.s_matrix_multiply(transposeA, transposeB, m, n, k, alpha, a, b, beta, c); } /// <summary> /// Computes the LUP factorization of A. P*A = L*U. /// </summary> /// <param name="data">An <paramref name="order"/> by <paramref name="order"/> matrix. The matrix is overwritten with the /// the LU factorization on exit. The lower triangular factor L is stored in under the diagonal of <paramref name="data"/> (the diagonal is always 1.0f /// for the L factor). The upper triangular factor U is stored on and above the diagonal of <paramref name="data"/>.</param> /// <param name="order">The order of the square matrix <paramref name="data"/>.</param> /// <param name="ipiv">On exit, it contains the pivot indices. The size of the array must be <paramref name="order"/>.</param> /// <remarks>This is equivalent to the GETRF LAPACK routine.</remarks> [SecuritySafeCritical] public override void LUFactor(float[] data, int order, int[] ipiv) { if (data == null) { throw new ArgumentNullException("data"); } if (ipiv == null) { throw new ArgumentNullException("ipiv"); } if (data.Length != order * order) { throw new ArgumentException(Resources.ArgumentArraysSameLength, "data"); } if (ipiv.Length != order) { throw new ArgumentException(Resources.ArgumentArraysSameLength, "ipiv"); } SafeNativeMethods.s_lu_factor(order, data, ipiv); } /// <summary> /// Computes the inverse of matrix using LU factorization. /// </summary> /// <param name="a">The N by N matrix to invert. Contains the inverse On exit.</param> /// <param name="order">The order of the square matrix <paramref name="a"/>.</param> /// <remarks>This is equivalent to the GETRF and GETRI LAPACK routines.</remarks> [SecuritySafeCritical] public override void LUInverse(float[] a, int order) { if (a == null) { throw new ArgumentNullException("a"); } if (a.Length != order * order) { throw new ArgumentException(Resources.ArgumentArraysSameLength, "a"); } var work = new float[order]; SafeNativeMethods.s_lu_inverse(order, a, work, work.Length); } /// <summary> /// Computes the inverse of a previously factored matrix. /// </summary> /// <param name="a">The LU factored N by N matrix. Contains the inverse On exit.</param> /// <param name="order">The order of the square matrix <paramref name="a"/>.</param> /// <param name="ipiv">The pivot indices of <paramref name="a"/>.</param> /// <remarks>This is equivalent to the GETRI LAPACK routine.</remarks> [SecuritySafeCritical] public override void LUInverseFactored(float[] a, int order, int[] ipiv) { if (a == null) { throw new ArgumentNullException("a"); } if (ipiv == null) { throw new ArgumentNullException("ipiv"); } if (a.Length != order * order) { throw new ArgumentException(Resources.ArgumentArraysSameLength, "a"); } if (ipiv.Length != order) { throw new ArgumentException(Resources.ArgumentArraysSameLength, "ipiv"); } var work = new float[order]; SafeNativeMethods.s_lu_inverse_factored(order, a, ipiv, work, order); } /// <summary> /// Computes the inverse of matrix using LU factorization. /// </summary> /// <param name="a">The N by N matrix to invert. Contains the inverse On exit.</param> /// <param name="order">The order of the square matrix <paramref name="a"/>.</param> /// <param name="work">The work array. The array must have a length of at least N, /// but should be N*blocksize. The blocksize is machine dependent. On exit, work[0] contains the optimal /// work size value.</param> /// <remarks>This is equivalent to the GETRF and GETRI LAPACK routines.</remarks> [SecuritySafeCritical] public override void LUInverse(float[] a, int order, float[] work) { if (a == null) { throw new ArgumentNullException("a"); } if (a.Length != order * order) { throw new ArgumentException(Resources.ArgumentArraysSameLength, "a"); } if (work == null) { throw new ArgumentNullException("work"); } if (work.Length < order) { throw new ArgumentException(Resources.WorkArrayTooSmall, "work"); } SafeNativeMethods.s_lu_inverse(order, a, work, work.Length); } /// <summary> /// Computes the inverse of a previously factored matrix. /// </summary> /// <param name="a">The LU factored N by N matrix. Contains the inverse On exit.</param> /// <param name="order">The order of the square matrix <paramref name="a"/>.</param> /// <param name="ipiv">The pivot indices of <paramref name="a"/>.</param> /// <param name="work">The work array. The array must have a length of at least N, /// but should be N*blocksize. The blocksize is machine dependent. On exit, work[0] contains the optimal /// work size value.</param> /// <remarks>This is equivalent to the GETRI LAPACK routine.</remarks> [SecuritySafeCritical] public override void LUInverseFactored(float[] a, int order, int[] ipiv, float[] work) { if (a == null) { throw new ArgumentNullException("a"); } if (ipiv == null) { throw new ArgumentNullException("ipiv"); } if (a.Length != order * order) { throw new ArgumentException(Resources.ArgumentArraysSameLength, "a"); } if (ipiv.Length != order) { throw new ArgumentException(Resources.ArgumentArraysSameLength, "ipiv"); } if (work == null) { throw new ArgumentNullException("work"); } if (work.Length < order) { throw new ArgumentException(Resources.WorkArrayTooSmall, "work"); } SafeNativeMethods.s_lu_inverse_factored(order, a, ipiv, work, order); } /// <summary> /// Solves A*X=B for X using LU factorization. /// </summary> /// <param name="columnsOfB">The number of columns of B.</param> /// <param name="a">The square matrix A.</param> /// <param name="order">The order of the square matrix <paramref name="a"/>.</param> /// <param name="b">On entry the B matrix; on exit the X matrix.</param> /// <remarks>This is equivalent to the GETRF and GETRS LAPACK routines.</remarks> [SecuritySafeCritical] public override void LUSolve(int columnsOfB, float[] a, int order, float[] b) { if (a == null) { throw new ArgumentNullException("a"); } if (a.Length != order * order) { throw new ArgumentException(Resources.ArgumentArraysSameLength, "a"); } if (b.Length != columnsOfB * order) { throw new ArgumentException(Resources.ArgumentArraysSameLength, "b"); } if (ReferenceEquals(a, b)) { throw new ArgumentException(Resources.ArgumentReferenceDifferent); } SafeNativeMethods.s_lu_solve(order, columnsOfB, a, b); } /// <summary> /// Solves A*X=B for X using a previously factored A matrix. /// </summary> /// <param name="columnsOfB">The number of columns of B.</param> /// <param name="a">The factored A matrix.</param> /// <param name="order">The order of the square matrix <paramref name="a"/>.</param> /// <param name="ipiv">The pivot indices of <paramref name="a"/>.</param> /// <param name="b">On entry the B matrix; on exit the X matrix.</param> /// <remarks>This is equivalent to the GETRS LAPACK routine.</remarks> [SecuritySafeCritical] public override void LUSolveFactored(int columnsOfB, float[] a, int order, int[] ipiv, float[] b) { if (a == null) { throw new ArgumentNullException("a"); } if (ipiv == null) { throw new ArgumentNullException("ipiv"); } if (a.Length != order * order) { throw new ArgumentException(Resources.ArgumentArraysSameLength, "a"); } if (ipiv.Length != order) { throw new ArgumentException(Resources.ArgumentArraysSameLength, "ipiv"); } if (b.Length != columnsOfB * order) { throw new ArgumentException(Resources.ArgumentArraysSameLength, "b"); } if (ReferenceEquals(a, b)) { throw new ArgumentException(Resources.ArgumentReferenceDifferent); } SafeNativeMethods.s_lu_solve_factored(order, columnsOfB, a, ipiv, b); } /// <summary> /// Computes the Cholesky factorization of A. /// </summary> /// <param name="a">On entry, a square, positive definite matrix. On exit, the matrix is overwritten with the /// the Cholesky factorization.</param> /// <param name="order">The number of rows or columns in the matrix.</param> /// <remarks>This is equivalent to the POTRF LAPACK routine.</remarks> [SecuritySafeCritical] public override void CholeskyFactor(float[] a, int order) { if (a == null) { throw new ArgumentNullException("a"); } if (order < 1) { throw new ArgumentException(Resources.ArgumentMustBePositive, "order"); } if (a.Length != order * order) { throw new ArgumentException(Resources.ArgumentArraysSameLength, "a"); } var info = SafeNativeMethods.s_cholesky_factor(order, a); if (info > 0) { throw new ArgumentException(Resources.ArgumentMatrixPositiveDefinite); } } /// <summary> /// Solves A*X=B for X using Cholesky factorization. /// </summary> /// <param name="a">The square, positive definite matrix A.</param> /// <param name="orderA">The number of rows and columns in A.</param> /// <param name="b">On entry the B matrix; on exit the X matrix.</param> /// <param name="columnsB">The number of columns in the B matrix.</param> /// <remarks>This is equivalent to the POTRF add POTRS LAPACK routines. /// </remarks> [SecuritySafeCritical] public override void CholeskySolve(float[] a, int orderA, float[] b, int columnsB) { if (a == null) { throw new ArgumentNullException("a"); } if (b == null) { throw new ArgumentNullException("b"); } if (b.Length != orderA * columnsB) { throw new ArgumentException(Resources.ArgumentArraysSameLength, "b"); } if (ReferenceEquals(a, b)) { throw new ArgumentException(Resources.ArgumentReferenceDifferent); } SafeNativeMethods.s_cholesky_solve(orderA, columnsB, a, b); } /// <summary> /// Solves A*X=B for X using a previously factored A matrix. /// </summary> /// <param name="a">The square, positive definite matrix A.</param> /// <param name="orderA">The number of rows and columns in A.</param> /// <param name="b">On entry the B matrix; on exit the X matrix.</param> /// <param name="columnsB">The number of columns in the B matrix.</param> /// <remarks>This is equivalent to the POTRS LAPACK routine.</remarks> [SecuritySafeCritical] public override void CholeskySolveFactored(float[] a, int orderA, float[] b, int columnsB) { if (a == null) { throw new ArgumentNullException("a"); } if (b == null) { throw new ArgumentNullException("b"); } if (b.Length != orderA * columnsB) { throw new ArgumentException(Resources.ArgumentArraysSameLength, "b"); } if (ReferenceEquals(a, b)) { throw new ArgumentException(Resources.ArgumentReferenceDifferent); } SafeNativeMethods.s_cholesky_solve_factored(orderA, columnsB, a, b); } /// <summary> /// Computes the QR factorization of A. /// </summary> /// <param name="r">On entry, it is the M by N A matrix to factor. On exit, /// it is overwritten with the R matrix of the QR factorization. </param> /// <param name="rowsR">The number of rows in the A matrix.</param> /// <param name="columnsR">The number of columns in the A matrix.</param> /// <param name="q">On exit, A M by M matrix that holds the Q matrix of the /// QR factorization.</param> /// <param name="tau">A min(m,n) vector. On exit, contains additional information /// to be used by the QR solve routine.</param> /// <remarks>This is similar to the GEQRF and ORGQR LAPACK routines.</remarks> [SecuritySafeCritical] public override void QRFactor(float[] r, int rowsR, int columnsR, float[] q, float[] tau) { if (r == null) { throw new ArgumentNullException("r"); } if (q == null) { throw new ArgumentNullException("q"); } if (r.Length != rowsR * columnsR) { throw new ArgumentException(string.Format(Resources.ArgumentArrayWrongLength, "rowsR * columnsR"), "r"); } if (tau.Length < Math.Min(rowsR, columnsR)) { throw new ArgumentException(string.Format(Resources.ArrayTooSmall, "min(m,n)"), "tau"); } if (q.Length != rowsR * rowsR) { throw new ArgumentException(string.Format(Resources.ArgumentArrayWrongLength, "rowsR * rowsR"), "q"); } var work = new float[columnsR * Control.BlockSize]; SafeNativeMethods.s_qr_factor(rowsR, columnsR, r, tau, q, work, work.Length); } /// <summary> /// Computes the QR factorization of A. /// </summary> /// <param name="r">On entry, it is the M by N A matrix to factor. On exit, /// it is overwritten with the R matrix of the QR factorization. </param> /// <param name="rowsR">The number of rows in the A matrix.</param> /// <param name="columnsR">The number of columns in the A matrix.</param> /// <param name="q">On exit, A M by M matrix that holds the Q matrix of the /// QR factorization.</param> /// <param name="tau">A min(m,n) vector. On exit, contains additional information /// to be used by the QR solve routine.</param> /// <param name="work">The work array. The array must have a length of at least N, /// but should be N*blocksize. The blocksize is machine dependent. On exit, work[0] contains the optimal /// work size value.</param> /// <remarks>This is similar to the GEQRF and ORGQR LAPACK routines.</remarks> [SecuritySafeCritical] public override void QRFactor(float[] r, int rowsR, int columnsR, float[] q, float[] tau, float[] work) { if (r == null) { throw new ArgumentNullException("r"); } if (q == null) { throw new ArgumentNullException("q"); } if (work == null) { throw new ArgumentNullException("work"); } if (r.Length != rowsR * columnsR) { throw new ArgumentException(string.Format(Resources.ArgumentArrayWrongLength, "rowsR * columnsR"), "r"); } if (tau.Length < Math.Min(rowsR, columnsR)) { throw new ArgumentException(string.Format(Resources.ArrayTooSmall, "min(m,n)"), "tau"); } if (q.Length != rowsR * rowsR) { throw new ArgumentException(string.Format(Resources.ArgumentArrayWrongLength, "rowsR * rowsR"), "q"); } if (work.Length < columnsR * Control.BlockSize) { work[0] = columnsR * Control.BlockSize; throw new ArgumentException(Resources.WorkArrayTooSmall, "work"); } SafeNativeMethods.s_qr_factor(rowsR, columnsR, r, tau, q, work, work.Length); } /// <summary> /// Solves A*X=B for X using QR factorization of A. /// </summary> /// <param name="a">The A matrix.</param> /// <param name="rows">The number of rows in the A matrix.</param> /// <param name="columns">The number of columns in the A matrix.</param> /// <param name="b">The B matrix.</param> /// <param name="columnsB">The number of columns of B.</param> /// <param name="x">On exit, the solution matrix.</param> /// <remarks>Rows must be greater or equal to columns.</remarks> public override void QRSolve(float[] a, int rows, int columns, float[] b, int columnsB, float[] x) { if (a == null) { throw new ArgumentNullException("a"); } if (b == null) { throw new ArgumentNullException("b"); } if (x == null) { throw new ArgumentNullException("x"); } if (a.Length != rows * columns) { throw new ArgumentException(Resources.ArgumentArraysSameLength, "a"); } if (b.Length != rows * columnsB) { throw new ArgumentException(Resources.ArgumentArraysSameLength, "b"); } if (x.Length != columns * columnsB) { throw new ArgumentException(Resources.ArgumentArraysSameLength, "x"); } if (rows < columns) { throw new ArgumentException(Resources.RowsLessThanColumns); } var work = new float[columns * Control.BlockSize]; QRSolve(a, rows, columns, b, columnsB, x, work); } /// <summary> /// Solves A*X=B for X using QR factorization of A. /// </summary> /// <param name="a">The A matrix.</param> /// <param name="rows">The number of rows in the A matrix.</param> /// <param name="columns">The number of columns in the A matrix.</param> /// <param name="b">The B matrix.</param> /// <param name="columnsB">The number of columns of B.</param> /// <param name="x">On exit, the solution matrix.</param> /// <param name="work">The work array. The array must have a length of at least N, /// but should be N*blocksize. The blocksize is machine dependent. On exit, work[0] contains the optimal /// work size value.</param> /// <remarks>Rows must be greater or equal to columns.</remarks> public override void QRSolve(float[] a, int rows, int columns, float[] b, int columnsB, float[] x, float[] work) { if (a == null) { throw new ArgumentNullException("a"); } if (b == null) { throw new ArgumentNullException("b"); } if (x == null) { throw new ArgumentNullException("x"); } if (work == null) { throw new ArgumentNullException("work"); } if (a.Length != rows * columns) { throw new ArgumentException(Resources.ArgumentArraysSameLength, "a"); } if (b.Length != rows * columnsB) { throw new ArgumentException(Resources.ArgumentArraysSameLength, "b"); } if (x.Length != columns * columnsB) { throw new ArgumentException(Resources.ArgumentArraysSameLength, "x"); } if (rows < columns) { throw new ArgumentException(Resources.RowsLessThanColumns); } if (work.Length < 1) { work[0] = rows * Control.BlockSize; throw new ArgumentException(Resources.WorkArrayTooSmall, "work"); } SafeNativeMethods.s_qr_solve(rows, columns, columnsB, a, b, x, work, work.Length); } /// <summary> /// Solves A*X=B for X using a previously QR factored matrix. /// </summary> /// <param name="q">The Q matrix obtained by calling <see cref="QRFactor(float[],int,int,float[],float[])"/>.</param> /// <param name="r">The R matrix obtained by calling <see cref="QRFactor(float[],int,int,float[],float[])"/>. </param> /// <param name="rowsR">The number of rows in the A matrix.</param> /// <param name="columnsR">The number of columns in the A matrix.</param> /// <param name="tau">Contains additional information on Q. Only used for the native solver /// and can be <c>null</c> for the managed provider.</param> /// <param name="b">The B matrix.</param> /// <param name="columnsB">The number of columns of B.</param> /// <param name="x">On exit, the solution matrix.</param> /// <remarks>Rows must be greater or equal to columns.</remarks> [SecuritySafeCritical] public override void QRSolveFactored(float[] q, float[] r, int rowsR, int columnsR, float[] tau, float[] b, int columnsB, float[] x) { if (r == null) { throw new ArgumentNullException("r"); } if (q == null) { throw new ArgumentNullException("q"); } if (b == null) { throw new ArgumentNullException("q"); } if (x == null) { throw new ArgumentNullException("q"); } if (r.Length != rowsR * columnsR) { throw new ArgumentException(Resources.ArgumentArraysSameLength, "r"); } if (q.Length != rowsR * rowsR) { throw new ArgumentException(Resources.ArgumentArraysSameLength, "q"); } if (b.Length != rowsR * columnsB) { throw new ArgumentException(Resources.ArgumentArraysSameLength, "b"); } if (x.Length != columnsR * columnsB) { throw new ArgumentException(Resources.ArgumentArraysSameLength, "x"); } if (rowsR < columnsR) { throw new ArgumentException(Resources.RowsLessThanColumns); } var work = new float[columnsR * Control.BlockSize]; QRSolveFactored(q, r, rowsR, columnsR, tau, b, columnsB, x, work); } /// <summary> /// Solves A*X=B for X using a previously QR factored matrix. /// </summary> /// <param name="q">The Q matrix obtained by QR factor. This is only used for the managed provider and can be /// <c>null</c> for the native provider. The native provider uses the Q portion stored in the R matrix.</param> /// <param name="r">The R matrix obtained by calling <see cref="QRFactor(float[],int,int,float[],float[])"/>. </param> /// <param name="rowsR">The number of rows in the A matrix.</param> /// <param name="columnsR">The number of columns in the A matrix.</param> /// <param name="tau">Contains additional information on Q. Only used for the native solver /// and can be <c>null</c> for the managed provider.</param> /// <param name="b">On entry the B matrix; on exit the X matrix.</param> /// <param name="columnsB">The number of columns of B.</param> /// <param name="x">On exit, the solution matrix.</param> /// <param name="work">The work array - only used in the native provider. The array must have a length of at least N, /// but should be N*blocksize. The blocksize is machine dependent. On exit, work[0] contains the optimal /// work size value.</param> /// <remarks>Rows must be greater or equal to columns.</remarks> public override void QRSolveFactored(float[] q, float[] r, int rowsR, int columnsR, float[] tau, float[] b, int columnsB, float[] x, float[] work) { if (r == null) { throw new ArgumentNullException("r"); } if (q == null) { throw new ArgumentNullException("q"); } if (b == null) { throw new ArgumentNullException("q"); } if (x == null) { throw new ArgumentNullException("q"); } if (work == null) { throw new ArgumentNullException("work"); } if (r.Length != rowsR * columnsR) { throw new ArgumentException(Resources.ArgumentArraysSameLength, "r"); } if (q.Length != rowsR * rowsR) { throw new ArgumentException(Resources.ArgumentArraysSameLength, "q"); } if (b.Length != rowsR * columnsB) { throw new ArgumentException(Resources.ArgumentArraysSameLength, "b"); } if (x.Length != columnsR * columnsB) { throw new ArgumentException(Resources.ArgumentArraysSameLength, "x"); } if (rowsR < columnsR) { throw new ArgumentException(Resources.RowsLessThanColumns); } if (work.Length < 1) { work[0] = rowsR * Control.BlockSize; throw new ArgumentException(Resources.WorkArrayTooSmall, "work"); } SafeNativeMethods.s_qr_solve_factored(rowsR, columnsR, columnsB, r, b, tau, x, work, work.Length); } /// <summary> /// Computes the singular value decomposition of A. /// </summary> /// <param name="computeVectors">Compute the singular U and VT vectors or not.</param> /// <param name="a">On entry, the M by N matrix to decompose. On exit, A may be overwritten.</param> /// <param name="rowsA">The number of rows in the A matrix.</param> /// <param name="columnsA">The number of columns in the A matrix.</param> /// <param name="s">The singular values of A in ascending value.</param> /// <param name="u">If <paramref name="computeVectors"/> is <c>true</c>, on exit U contains the left /// singular vectors.</param> /// <param name="vt">If <paramref name="computeVectors"/> is <c>true</c>, on exit VT contains the transposed /// right singular vectors.</param> /// <remarks>This is equivalent to the GESVD LAPACK routine.</remarks> [SecuritySafeCritical] public override void SingularValueDecomposition(bool computeVectors, float[] a, int rowsA, int columnsA, float[] s, float[] u, float[] vt) { if (a == null) { throw new ArgumentNullException("a"); } if (s == null) { throw new ArgumentNullException("s"); } if (u == null) { throw new ArgumentNullException("u"); } if (vt == null) { throw new ArgumentNullException("vt"); } if (u.Length != rowsA * rowsA) { throw new ArgumentException(Resources.ArgumentArraysSameLength, "u"); } if (vt.Length != columnsA * columnsA) { throw new ArgumentException(Resources.ArgumentArraysSameLength, "vt"); } if (s.Length != Math.Min(rowsA, columnsA)) { throw new ArgumentException(Resources.ArgumentArraysSameLength, "s"); } var work = new float[Math.Max(((3 * Math.Min(rowsA, columnsA)) + Math.Max(rowsA, columnsA)), 5 * Math.Min(rowsA, columnsA))]; SingularValueDecomposition(computeVectors, a, rowsA, columnsA, s, u, vt, work); } /// <summary> /// Solves A*X=B for X using the singular value decomposition of A. /// </summary> /// <param name="a">On entry, the M by N matrix to decompose.</param> /// <param name="rowsA">The number of rows in the A matrix.</param> /// <param name="columnsA">The number of columns in the A matrix.</param> /// <param name="b">The B matrix.</param> /// <param name="columnsB">The number of columns of B.</param> /// <param name="x">On exit, the solution matrix.</param> public override void SvdSolve(float[] a, int rowsA, int columnsA, float[] b, int columnsB, float[] x) { if (a == null) { throw new ArgumentNullException("a"); } if (b == null) { throw new ArgumentNullException("b"); } if (x == null) { throw new ArgumentNullException("x"); } if (b.Length != rowsA * columnsB) { throw new ArgumentException(Resources.ArgumentArraysSameLength, "b"); } if (x.Length != columnsA * columnsB) { throw new ArgumentException(Resources.ArgumentArraysSameLength, "b"); } var work = new float[Math.Max(((3 * Math.Min(rowsA, columnsA)) + Math.Max(rowsA, columnsA)), 5 * Math.Min(rowsA, columnsA))]; var s = new float[Math.Min(rowsA, columnsA)]; var u = new float[rowsA * rowsA]; var vt = new float[columnsA * columnsA]; var clone = new float[a.Length]; a.Copy(clone); SingularValueDecomposition(true, clone, rowsA, columnsA, s, u, vt, work); SvdSolveFactored(rowsA, columnsA, s, u, vt, b, columnsB, x); } /// <summary> /// Computes the singular value decomposition of A. /// </summary> /// <param name="computeVectors">Compute the singular U and VT vectors or not.</param> /// <param name="a">On entry, the M by N matrix to decompose. On exit, A may be overwritten.</param> /// <param name="rowsA">The number of rows in the A matrix.</param> /// <param name="columnsA">The number of columns in the A matrix.</param> /// <param name="s">The singular values of A in ascending value.</param> /// <param name="u">If <paramref name="computeVectors"/> is <c>true</c>, on exit U contains the left /// singular vectors.</param> /// <param name="vt">If <paramref name="computeVectors"/> is <c>true</c>, on exit VT contains the transposed /// right singular vectors.</param> /// <param name="work">The work array. For real matrices, the work array should be at least /// Max(3*Min(M, N) + Max(M, N), 5*Min(M,N)). For complex matrices, 2*Min(M, N) + Max(M, N). /// On exit, work[0] contains the optimal work size value.</param> /// <remarks>This is equivalent to the GESVD LAPACK routine.</remarks> [SecuritySafeCritical] public override void SingularValueDecomposition(bool computeVectors, float[] a, int rowsA, int columnsA, float[] s, float[] u, float[] vt, float[] work) { if (a == null) { throw new ArgumentNullException("a"); } if (s == null) { throw new ArgumentNullException("s"); } if (u == null) { throw new ArgumentNullException("u"); } if (vt == null) { throw new ArgumentNullException("vt"); } if (work == null) { throw new ArgumentNullException("work"); } if (u.Length != rowsA * rowsA) { throw new ArgumentException(Resources.ArgumentArraysSameLength, "u"); } if (vt.Length != columnsA * columnsA) { throw new ArgumentException(Resources.ArgumentArraysSameLength, "vt"); } if (s.Length != Math.Min(rowsA, columnsA)) { throw new ArgumentException(Resources.ArgumentArraysSameLength, "s"); } if (work.Length == 0) { throw new ArgumentException(Resources.ArgumentSingleDimensionArray, "work"); } if (work.Length < Math.Max(((3 * Math.Min(rowsA, columnsA)) + Math.Max(rowsA, columnsA)), 5 * Math.Min(rowsA, columnsA))) { work[0] = Math.Max((3 * Math.Min(rowsA, columnsA)) + Math.Max(rowsA, columnsA), 5 * Math.Min(rowsA, columnsA)); throw new ArgumentException(Resources.WorkArrayTooSmall, "work"); } SafeNativeMethods.s_svd_factor(computeVectors, rowsA, columnsA, a, s, u, vt, work, work.Length); } } }
Java
import java.io.IOException; import jade.core.AID; import java.util.ArrayList; import java.util.Scanner; import jade.core.Agent; public class DutchModel { public static void main(String[] args) throws IOException { String option=""; ArrayList<BiderAgent> bidders= new ArrayList<BiderAgent>(); System.out.println("Welcome to Fish Dutch Auction!"); System.out.println("Press 1 to sell a product."); System.out.println("Press 2 to Bid for a product."); Scanner scan= new Scanner(System.in); option= scan.nextLine(); System.out.println(option); if(option.equals("1")) { } else if(option.equals("2")) { Loader bidderxml = new Loader("Bidders.xml"); bidders=bidderxml.loadXmlBidders(); Product p1= new Product("gg",1,"g1",null); AuctioneerAgent Ag = new AuctioneerAgent(10,1,1200); SellerAgent s1= new SellerAgent (p1); AID sel = s1.getSellerAid(); Ag.setSellerAid(sel); Ag.setup(); s1.setup(); } else { System.out.println("Wrong input... Time Out!"); } } }
Java
<!-- MOOSE Object Documentation Stub: Remove this when content is added. --> #VolumePostprocessor !devel /XFEM/VolumePostprocessor float=right width=auto margin=20px padding=20px background-color=#F8F8F8 !description /XFEM/VolumePostprocessor !parameters /XFEM/VolumePostprocessor !inputfiles /XFEM/VolumePostprocessor !childobjects /XFEM/VolumePostprocessor
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_40) on Wed Feb 10 11:30:58 CST 2016 --> <title>Uses of Class org.hibernate.engine.FetchStrategy (Hibernate JavaDocs)</title> <meta name="date" content="2016-02-10"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.hibernate.engine.FetchStrategy (Hibernate JavaDocs)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/hibernate/engine/class-use/FetchStrategy.html" target="_top">Frames</a></li> <li><a href="FetchStrategy.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.hibernate.engine.FetchStrategy" class="title">Uses of Class<br>org.hibernate.engine.FetchStrategy</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.hibernate.loader.plan.build.internal">org.hibernate.loader.plan.build.internal</a></td> <td class="colLast"> <div class="block">Contains the internal implementations used for building a metamodel-driven LoadPlan.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#org.hibernate.loader.plan.build.internal.returns">org.hibernate.loader.plan.build.internal.returns</a></td> <td class="colLast"> <div class="block">Contains the internal implementations of the building blocks that make up a metamodel-driven LoadPlan.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="#org.hibernate.loader.plan.build.internal.spaces">org.hibernate.loader.plan.build.internal.spaces</a></td> <td class="colLast"> <div class="block">Contains the internal implementations of query spaces in a metamodel-driven LoadPlan.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#org.hibernate.loader.plan.build.spi">org.hibernate.loader.plan.build.spi</a></td> <td class="colLast"> <div class="block">Defines the SPI for building a metamodel-driven LoadPlan</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="#org.hibernate.loader.plan.spi">org.hibernate.loader.plan.spi</a></td> <td class="colLast"> <div class="block">Defines the SPI for the building blocks that make up a LoadPlan.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#org.hibernate.persister.walking.internal">org.hibernate.persister.walking.internal</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><a href="#org.hibernate.persister.walking.spi">org.hibernate.persister.walking.spi</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#org.hibernate.tuple.component">org.hibernate.tuple.component</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><a href="#org.hibernate.tuple.entity">org.hibernate.tuple.entity</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.hibernate.loader.plan.build.internal"> <!-- --> </a> <h3>Uses of <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a> in <a href="../../../../org/hibernate/loader/plan/build/internal/package-summary.html">org.hibernate.loader.plan.build.internal</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing fields, and an explanation"> <caption><span>Fields in <a href="../../../../org/hibernate/loader/plan/build/internal/package-summary.html">org.hibernate.loader.plan.build.internal</a> declared as <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>protected static <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a></code></td> <td class="colLast"><span class="typeNameLabel">AbstractEntityGraphVisitationStrategy.</span><code><span class="memberNameLink"><a href="../../../../org/hibernate/loader/plan/build/internal/AbstractEntityGraphVisitationStrategy.html#DEFAULT_EAGER">DEFAULT_EAGER</a></span></code> <div class="block">The JPA 2.1 SPEC's Entity Graph only defines _WHEN_ to load an attribute, it doesn't define _HOW_ to load it So I'm here just making an assumption that when it is EAGER, then we use JOIN, and when it is LAZY, then we use SELECT.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>protected static <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a></code></td> <td class="colLast"><span class="typeNameLabel">AbstractEntityGraphVisitationStrategy.</span><code><span class="memberNameLink"><a href="../../../../org/hibernate/loader/plan/build/internal/AbstractEntityGraphVisitationStrategy.html#DEFAULT_LAZY">DEFAULT_LAZY</a></span></code>&nbsp;</td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../org/hibernate/loader/plan/build/internal/package-summary.html">org.hibernate.loader.plan.build.internal</a> that return <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>protected <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a></code></td> <td class="colLast"><span class="typeNameLabel">FetchStyleLoadPlanBuildingAssociationVisitationStrategy.</span><code><span class="memberNameLink"><a href="../../../../org/hibernate/loader/plan/build/internal/FetchStyleLoadPlanBuildingAssociationVisitationStrategy.html#adjustJoinFetchIfNeeded-org.hibernate.persister.walking.spi.AssociationAttributeDefinition-org.hibernate.engine.FetchStrategy-">adjustJoinFetchIfNeeded</a></span>(<a href="../../../../org/hibernate/persister/walking/spi/AssociationAttributeDefinition.html" title="interface in org.hibernate.persister.walking.spi">AssociationAttributeDefinition</a>&nbsp;attributeDefinition, <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a>&nbsp;fetchStrategy)</code> <div class="block">If required by this strategy, returns a different <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine"><code>FetchStrategy</code></a> from what is specified for the given association attribute.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>protected <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a></code></td> <td class="colLast"><span class="typeNameLabel">AbstractEntityGraphVisitationStrategy.</span><code><span class="memberNameLink"><a href="../../../../org/hibernate/loader/plan/build/internal/AbstractEntityGraphVisitationStrategy.html#adjustJoinFetchIfNeeded-org.hibernate.persister.walking.spi.AssociationAttributeDefinition-org.hibernate.engine.FetchStrategy-">adjustJoinFetchIfNeeded</a></span>(<a href="../../../../org/hibernate/persister/walking/spi/AssociationAttributeDefinition.html" title="interface in org.hibernate.persister.walking.spi">AssociationAttributeDefinition</a>&nbsp;attributeDefinition, <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a>&nbsp;fetchStrategy)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>protected <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a></code></td> <td class="colLast"><span class="typeNameLabel">FetchStyleLoadPlanBuildingAssociationVisitationStrategy.</span><code><span class="memberNameLink"><a href="../../../../org/hibernate/loader/plan/build/internal/FetchStyleLoadPlanBuildingAssociationVisitationStrategy.html#determineFetchStrategy-org.hibernate.persister.walking.spi.AssociationAttributeDefinition-">determineFetchStrategy</a></span>(<a href="../../../../org/hibernate/persister/walking/spi/AssociationAttributeDefinition.html" title="interface in org.hibernate.persister.walking.spi">AssociationAttributeDefinition</a>&nbsp;attributeDefinition)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>protected <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a></code></td> <td class="colLast"><span class="typeNameLabel">AbstractEntityGraphVisitationStrategy.</span><code><span class="memberNameLink"><a href="../../../../org/hibernate/loader/plan/build/internal/AbstractEntityGraphVisitationStrategy.html#determineFetchStrategy-org.hibernate.persister.walking.spi.AssociationAttributeDefinition-">determineFetchStrategy</a></span>(<a href="../../../../org/hibernate/persister/walking/spi/AssociationAttributeDefinition.html" title="interface in org.hibernate.persister.walking.spi">AssociationAttributeDefinition</a>&nbsp;attributeDefinition)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>protected <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a></code></td> <td class="colLast"><span class="typeNameLabel">CascadeStyleLoadPlanBuildingAssociationVisitationStrategy.</span><code><span class="memberNameLink"><a href="../../../../org/hibernate/loader/plan/build/internal/CascadeStyleLoadPlanBuildingAssociationVisitationStrategy.html#determineFetchStrategy-org.hibernate.persister.walking.spi.AssociationAttributeDefinition-">determineFetchStrategy</a></span>(<a href="../../../../org/hibernate/persister/walking/spi/AssociationAttributeDefinition.html" title="interface in org.hibernate.persister.walking.spi">AssociationAttributeDefinition</a>&nbsp;attributeDefinition)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>protected abstract <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a></code></td> <td class="colLast"><span class="typeNameLabel">AbstractLoadPlanBuildingAssociationVisitationStrategy.</span><code><span class="memberNameLink"><a href="../../../../org/hibernate/loader/plan/build/internal/AbstractLoadPlanBuildingAssociationVisitationStrategy.html#determineFetchStrategy-org.hibernate.persister.walking.spi.AssociationAttributeDefinition-">determineFetchStrategy</a></span>(<a href="../../../../org/hibernate/persister/walking/spi/AssociationAttributeDefinition.html" title="interface in org.hibernate.persister.walking.spi">AssociationAttributeDefinition</a>&nbsp;attributeDefinition)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>protected <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a></code></td> <td class="colLast"><span class="typeNameLabel">FetchGraphLoadPlanBuildingStrategy.</span><code><span class="memberNameLink"><a href="../../../../org/hibernate/loader/plan/build/internal/FetchGraphLoadPlanBuildingStrategy.html#resolveImplicitFetchStrategyFromEntityGraph-org.hibernate.persister.walking.spi.AssociationAttributeDefinition-">resolveImplicitFetchStrategyFromEntityGraph</a></span>(<a href="../../../../org/hibernate/persister/walking/spi/AssociationAttributeDefinition.html" title="interface in org.hibernate.persister.walking.spi">AssociationAttributeDefinition</a>&nbsp;attributeDefinition)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>protected abstract <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a></code></td> <td class="colLast"><span class="typeNameLabel">AbstractEntityGraphVisitationStrategy.</span><code><span class="memberNameLink"><a href="../../../../org/hibernate/loader/plan/build/internal/AbstractEntityGraphVisitationStrategy.html#resolveImplicitFetchStrategyFromEntityGraph-org.hibernate.persister.walking.spi.AssociationAttributeDefinition-">resolveImplicitFetchStrategyFromEntityGraph</a></span>(<a href="../../../../org/hibernate/persister/walking/spi/AssociationAttributeDefinition.html" title="interface in org.hibernate.persister.walking.spi">AssociationAttributeDefinition</a>&nbsp;attributeDefinition)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>protected <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a></code></td> <td class="colLast"><span class="typeNameLabel">LoadGraphLoadPlanBuildingStrategy.</span><code><span class="memberNameLink"><a href="../../../../org/hibernate/loader/plan/build/internal/LoadGraphLoadPlanBuildingStrategy.html#resolveImplicitFetchStrategyFromEntityGraph-org.hibernate.persister.walking.spi.AssociationAttributeDefinition-">resolveImplicitFetchStrategyFromEntityGraph</a></span>(<a href="../../../../org/hibernate/persister/walking/spi/AssociationAttributeDefinition.html" title="interface in org.hibernate.persister.walking.spi">AssociationAttributeDefinition</a>&nbsp;attributeDefinition)</code>&nbsp;</td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../org/hibernate/loader/plan/build/internal/package-summary.html">org.hibernate.loader.plan.build.internal</a> with parameters of type <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>protected <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a></code></td> <td class="colLast"><span class="typeNameLabel">FetchStyleLoadPlanBuildingAssociationVisitationStrategy.</span><code><span class="memberNameLink"><a href="../../../../org/hibernate/loader/plan/build/internal/FetchStyleLoadPlanBuildingAssociationVisitationStrategy.html#adjustJoinFetchIfNeeded-org.hibernate.persister.walking.spi.AssociationAttributeDefinition-org.hibernate.engine.FetchStrategy-">adjustJoinFetchIfNeeded</a></span>(<a href="../../../../org/hibernate/persister/walking/spi/AssociationAttributeDefinition.html" title="interface in org.hibernate.persister.walking.spi">AssociationAttributeDefinition</a>&nbsp;attributeDefinition, <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a>&nbsp;fetchStrategy)</code> <div class="block">If required by this strategy, returns a different <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine"><code>FetchStrategy</code></a> from what is specified for the given association attribute.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>protected <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a></code></td> <td class="colLast"><span class="typeNameLabel">AbstractEntityGraphVisitationStrategy.</span><code><span class="memberNameLink"><a href="../../../../org/hibernate/loader/plan/build/internal/AbstractEntityGraphVisitationStrategy.html#adjustJoinFetchIfNeeded-org.hibernate.persister.walking.spi.AssociationAttributeDefinition-org.hibernate.engine.FetchStrategy-">adjustJoinFetchIfNeeded</a></span>(<a href="../../../../org/hibernate/persister/walking/spi/AssociationAttributeDefinition.html" title="interface in org.hibernate.persister.walking.spi">AssociationAttributeDefinition</a>&nbsp;attributeDefinition, <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a>&nbsp;fetchStrategy)</code>&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.hibernate.loader.plan.build.internal.returns"> <!-- --> </a> <h3>Uses of <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a> in <a href="../../../../org/hibernate/loader/plan/build/internal/returns/package-summary.html">org.hibernate.loader.plan.build.internal.returns</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing fields, and an explanation"> <caption><span>Fields in <a href="../../../../org/hibernate/loader/plan/build/internal/returns/package-summary.html">org.hibernate.loader.plan.build.internal.returns</a> declared as <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>protected static <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a></code></td> <td class="colLast"><span class="typeNameLabel">AbstractCompositeFetch.</span><code><span class="memberNameLink"><a href="../../../../org/hibernate/loader/plan/build/internal/returns/AbstractCompositeFetch.html#FETCH_STRATEGY">FETCH_STRATEGY</a></span></code>&nbsp;</td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../org/hibernate/loader/plan/build/internal/returns/package-summary.html">org.hibernate.loader.plan.build.internal.returns</a> that return <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a></code></td> <td class="colLast"><span class="typeNameLabel">AbstractCompositeFetch.</span><code><span class="memberNameLink"><a href="../../../../org/hibernate/loader/plan/build/internal/returns/AbstractCompositeFetch.html#getFetchStrategy--">getFetchStrategy</a></span>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a></code></td> <td class="colLast"><span class="typeNameLabel">CollectionAttributeFetchImpl.</span><code><span class="memberNameLink"><a href="../../../../org/hibernate/loader/plan/build/internal/returns/CollectionAttributeFetchImpl.html#getFetchStrategy--">getFetchStrategy</a></span>()</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a></code></td> <td class="colLast"><span class="typeNameLabel">AnyAttributeFetchImpl.</span><code><span class="memberNameLink"><a href="../../../../org/hibernate/loader/plan/build/internal/returns/AnyAttributeFetchImpl.html#getFetchStrategy--">getFetchStrategy</a></span>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a></code></td> <td class="colLast"><span class="typeNameLabel">EntityAttributeFetchImpl.</span><code><span class="memberNameLink"><a href="../../../../org/hibernate/loader/plan/build/internal/returns/EntityAttributeFetchImpl.html#getFetchStrategy--">getFetchStrategy</a></span>()</code>&nbsp;</td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../org/hibernate/loader/plan/build/internal/returns/package-summary.html">org.hibernate.loader.plan.build.internal.returns</a> with parameters of type <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../org/hibernate/loader/plan/spi/AnyAttributeFetch.html" title="interface in org.hibernate.loader.plan.spi">AnyAttributeFetch</a></code></td> <td class="colLast"><span class="typeNameLabel">AbstractExpandingFetchSource.</span><code><span class="memberNameLink"><a href="../../../../org/hibernate/loader/plan/build/internal/returns/AbstractExpandingFetchSource.html#buildAnyAttributeFetch-org.hibernate.persister.walking.spi.AssociationAttributeDefinition-org.hibernate.engine.FetchStrategy-">buildAnyAttributeFetch</a></span>(<a href="../../../../org/hibernate/persister/walking/spi/AssociationAttributeDefinition.html" title="interface in org.hibernate.persister.walking.spi">AssociationAttributeDefinition</a>&nbsp;attributeDefinition, <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a>&nbsp;fetchStrategy)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../org/hibernate/loader/plan/spi/BidirectionalEntityReference.html" title="interface in org.hibernate.loader.plan.spi">BidirectionalEntityReference</a></code></td> <td class="colLast"><span class="typeNameLabel">AbstractExpandingFetchSource.</span><code><span class="memberNameLink"><a href="../../../../org/hibernate/loader/plan/build/internal/returns/AbstractExpandingFetchSource.html#buildBidirectionalEntityReference-org.hibernate.persister.walking.spi.AssociationAttributeDefinition-org.hibernate.engine.FetchStrategy-org.hibernate.loader.plan.spi.EntityReference-">buildBidirectionalEntityReference</a></span>(<a href="../../../../org/hibernate/persister/walking/spi/AssociationAttributeDefinition.html" title="interface in org.hibernate.persister.walking.spi">AssociationAttributeDefinition</a>&nbsp;attributeDefinition, <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a>&nbsp;fetchStrategy, <a href="../../../../org/hibernate/loader/plan/spi/EntityReference.html" title="interface in org.hibernate.loader.plan.spi">EntityReference</a>&nbsp;targetEntityReference)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../org/hibernate/loader/plan/spi/CollectionAttributeFetch.html" title="interface in org.hibernate.loader.plan.spi">CollectionAttributeFetch</a></code></td> <td class="colLast"><span class="typeNameLabel">AbstractCompositeReference.</span><code><span class="memberNameLink"><a href="../../../../org/hibernate/loader/plan/build/internal/returns/AbstractCompositeReference.html#buildCollectionAttributeFetch-org.hibernate.persister.walking.spi.AssociationAttributeDefinition-org.hibernate.engine.FetchStrategy-">buildCollectionAttributeFetch</a></span>(<a href="../../../../org/hibernate/persister/walking/spi/AssociationAttributeDefinition.html" title="interface in org.hibernate.persister.walking.spi">AssociationAttributeDefinition</a>&nbsp;attributeDefinition, <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a>&nbsp;fetchStrategy)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../org/hibernate/loader/plan/spi/CollectionAttributeFetch.html" title="interface in org.hibernate.loader.plan.spi">CollectionAttributeFetch</a></code></td> <td class="colLast"><span class="typeNameLabel">AbstractExpandingFetchSource.</span><code><span class="memberNameLink"><a href="../../../../org/hibernate/loader/plan/build/internal/returns/AbstractExpandingFetchSource.html#buildCollectionAttributeFetch-org.hibernate.persister.walking.spi.AssociationAttributeDefinition-org.hibernate.engine.FetchStrategy-">buildCollectionAttributeFetch</a></span>(<a href="../../../../org/hibernate/persister/walking/spi/AssociationAttributeDefinition.html" title="interface in org.hibernate.persister.walking.spi">AssociationAttributeDefinition</a>&nbsp;attributeDefinition, <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a>&nbsp;fetchStrategy)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../org/hibernate/loader/plan/spi/EntityFetch.html" title="interface in org.hibernate.loader.plan.spi">EntityFetch</a></code></td> <td class="colLast"><span class="typeNameLabel">AbstractExpandingFetchSource.</span><code><span class="memberNameLink"><a href="../../../../org/hibernate/loader/plan/build/internal/returns/AbstractExpandingFetchSource.html#buildEntityAttributeFetch-org.hibernate.persister.walking.spi.AssociationAttributeDefinition-org.hibernate.engine.FetchStrategy-">buildEntityAttributeFetch</a></span>(<a href="../../../../org/hibernate/persister/walking/spi/AssociationAttributeDefinition.html" title="interface in org.hibernate.persister.walking.spi">AssociationAttributeDefinition</a>&nbsp;attributeDefinition, <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a>&nbsp;fetchStrategy)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><span class="typeNameLabel">EntityReturnImpl.</span><code><span class="memberNameLink"><a href="../../../../org/hibernate/loader/plan/build/internal/returns/EntityReturnImpl.html#validateFetchPlan-org.hibernate.engine.FetchStrategy-org.hibernate.persister.walking.spi.AttributeDefinition-">validateFetchPlan</a></span>(<a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a>&nbsp;fetchStrategy, <a href="../../../../org/hibernate/persister/walking/spi/AttributeDefinition.html" title="interface in org.hibernate.persister.walking.spi">AttributeDefinition</a>&nbsp;attributeDefinition)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><span class="typeNameLabel">AbstractCompositeReference.</span><code><span class="memberNameLink"><a href="../../../../org/hibernate/loader/plan/build/internal/returns/AbstractCompositeReference.html#validateFetchPlan-org.hibernate.engine.FetchStrategy-org.hibernate.persister.walking.spi.AttributeDefinition-">validateFetchPlan</a></span>(<a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a>&nbsp;fetchStrategy, <a href="../../../../org/hibernate/persister/walking/spi/AttributeDefinition.html" title="interface in org.hibernate.persister.walking.spi">AttributeDefinition</a>&nbsp;attributeDefinition)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><span class="typeNameLabel">CollectionFetchableElementEntityGraph.</span><code><span class="memberNameLink"><a href="../../../../org/hibernate/loader/plan/build/internal/returns/CollectionFetchableElementEntityGraph.html#validateFetchPlan-org.hibernate.engine.FetchStrategy-org.hibernate.persister.walking.spi.AttributeDefinition-">validateFetchPlan</a></span>(<a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a>&nbsp;fetchStrategy, <a href="../../../../org/hibernate/persister/walking/spi/AttributeDefinition.html" title="interface in org.hibernate.persister.walking.spi">AttributeDefinition</a>&nbsp;attributeDefinition)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><span class="typeNameLabel">CollectionFetchableIndexEntityGraph.</span><code><span class="memberNameLink"><a href="../../../../org/hibernate/loader/plan/build/internal/returns/CollectionFetchableIndexEntityGraph.html#validateFetchPlan-org.hibernate.engine.FetchStrategy-org.hibernate.persister.walking.spi.AttributeDefinition-">validateFetchPlan</a></span>(<a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a>&nbsp;fetchStrategy, <a href="../../../../org/hibernate/persister/walking/spi/AttributeDefinition.html" title="interface in org.hibernate.persister.walking.spi">AttributeDefinition</a>&nbsp;attributeDefinition)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><span class="typeNameLabel">EntityAttributeFetchImpl.</span><code><span class="memberNameLink"><a href="../../../../org/hibernate/loader/plan/build/internal/returns/EntityAttributeFetchImpl.html#validateFetchPlan-org.hibernate.engine.FetchStrategy-org.hibernate.persister.walking.spi.AttributeDefinition-">validateFetchPlan</a></span>(<a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a>&nbsp;fetchStrategy, <a href="../../../../org/hibernate/persister/walking/spi/AttributeDefinition.html" title="interface in org.hibernate.persister.walking.spi">AttributeDefinition</a>&nbsp;attributeDefinition)</code>&nbsp;</td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing constructors, and an explanation"> <caption><span>Constructors in <a href="../../../../org/hibernate/loader/plan/build/internal/returns/package-summary.html">org.hibernate.loader.plan.build.internal.returns</a> with parameters of type <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/hibernate/loader/plan/build/internal/returns/AnyAttributeFetchImpl.html#AnyAttributeFetchImpl-org.hibernate.loader.plan.spi.FetchSource-org.hibernate.persister.walking.spi.AssociationAttributeDefinition-org.hibernate.engine.FetchStrategy-">AnyAttributeFetchImpl</a></span>(<a href="../../../../org/hibernate/loader/plan/spi/FetchSource.html" title="interface in org.hibernate.loader.plan.spi">FetchSource</a>&nbsp;fetchSource, <a href="../../../../org/hibernate/persister/walking/spi/AssociationAttributeDefinition.html" title="interface in org.hibernate.persister.walking.spi">AssociationAttributeDefinition</a>&nbsp;fetchedAttribute, <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a>&nbsp;fetchStrategy)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/hibernate/loader/plan/build/internal/returns/CollectionAttributeFetchImpl.html#CollectionAttributeFetchImpl-org.hibernate.loader.plan.build.spi.ExpandingFetchSource-org.hibernate.persister.walking.spi.AssociationAttributeDefinition-org.hibernate.engine.FetchStrategy-org.hibernate.loader.plan.build.spi.ExpandingCollectionQuerySpace-">CollectionAttributeFetchImpl</a></span>(<a href="../../../../org/hibernate/loader/plan/build/spi/ExpandingFetchSource.html" title="interface in org.hibernate.loader.plan.build.spi">ExpandingFetchSource</a>&nbsp;fetchSource, <a href="../../../../org/hibernate/persister/walking/spi/AssociationAttributeDefinition.html" title="interface in org.hibernate.persister.walking.spi">AssociationAttributeDefinition</a>&nbsp;fetchedAttribute, <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a>&nbsp;fetchStrategy, <a href="../../../../org/hibernate/loader/plan/build/spi/ExpandingCollectionQuerySpace.html" title="interface in org.hibernate.loader.plan.build.spi">ExpandingCollectionQuerySpace</a>&nbsp;collectionQuerySpace)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/hibernate/loader/plan/build/internal/returns/EntityAttributeFetchImpl.html#EntityAttributeFetchImpl-org.hibernate.loader.plan.build.spi.ExpandingFetchSource-org.hibernate.persister.walking.spi.AssociationAttributeDefinition-org.hibernate.engine.FetchStrategy-org.hibernate.loader.plan.build.spi.ExpandingEntityQuerySpace-">EntityAttributeFetchImpl</a></span>(<a href="../../../../org/hibernate/loader/plan/build/spi/ExpandingFetchSource.html" title="interface in org.hibernate.loader.plan.build.spi">ExpandingFetchSource</a>&nbsp;fetchSource, <a href="../../../../org/hibernate/persister/walking/spi/AssociationAttributeDefinition.html" title="interface in org.hibernate.persister.walking.spi">AssociationAttributeDefinition</a>&nbsp;fetchedAttribute, <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a>&nbsp;fetchStrategy, <a href="../../../../org/hibernate/loader/plan/build/spi/ExpandingEntityQuerySpace.html" title="interface in org.hibernate.loader.plan.build.spi">ExpandingEntityQuerySpace</a>&nbsp;entityQuerySpace)</code>&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.hibernate.loader.plan.build.internal.spaces"> <!-- --> </a> <h3>Uses of <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a> in <a href="../../../../org/hibernate/loader/plan/build/internal/spaces/package-summary.html">org.hibernate.loader.plan.build.internal.spaces</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../org/hibernate/loader/plan/build/internal/spaces/package-summary.html">org.hibernate.loader.plan.build.internal.spaces</a> with parameters of type <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../org/hibernate/loader/plan/build/spi/ExpandingCollectionQuerySpace.html" title="interface in org.hibernate.loader.plan.build.spi">ExpandingCollectionQuerySpace</a></code></td> <td class="colLast"><span class="typeNameLabel">QuerySpaceHelper.</span><code><span class="memberNameLink"><a href="../../../../org/hibernate/loader/plan/build/internal/spaces/QuerySpaceHelper.html#makeCollectionQuerySpace-org.hibernate.loader.plan.build.spi.ExpandingQuerySpace-org.hibernate.persister.walking.spi.AssociationAttributeDefinition-java.lang.String-org.hibernate.engine.FetchStrategy-">makeCollectionQuerySpace</a></span>(<a href="../../../../org/hibernate/loader/plan/build/spi/ExpandingQuerySpace.html" title="interface in org.hibernate.loader.plan.build.spi">ExpandingQuerySpace</a>&nbsp;lhsQuerySpace, <a href="../../../../org/hibernate/persister/walking/spi/AssociationAttributeDefinition.html" title="interface in org.hibernate.persister.walking.spi">AssociationAttributeDefinition</a>&nbsp;attributeDefinition, <a href="http://download.oracle.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;querySpaceUid, <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a>&nbsp;fetchStrategy)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../org/hibernate/loader/plan/build/spi/ExpandingEntityQuerySpace.html" title="interface in org.hibernate.loader.plan.build.spi">ExpandingEntityQuerySpace</a></code></td> <td class="colLast"><span class="typeNameLabel">QuerySpaceHelper.</span><code><span class="memberNameLink"><a href="../../../../org/hibernate/loader/plan/build/internal/spaces/QuerySpaceHelper.html#makeEntityQuerySpace-org.hibernate.loader.plan.build.spi.ExpandingQuerySpace-org.hibernate.persister.walking.spi.AssociationAttributeDefinition-java.lang.String-org.hibernate.engine.FetchStrategy-">makeEntityQuerySpace</a></span>(<a href="../../../../org/hibernate/loader/plan/build/spi/ExpandingQuerySpace.html" title="interface in org.hibernate.loader.plan.build.spi">ExpandingQuerySpace</a>&nbsp;lhsQuerySpace, <a href="../../../../org/hibernate/persister/walking/spi/AssociationAttributeDefinition.html" title="interface in org.hibernate.persister.walking.spi">AssociationAttributeDefinition</a>&nbsp;attribute, <a href="http://download.oracle.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;querySpaceUid, <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a>&nbsp;fetchStrategy)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><span class="typeNameLabel">QuerySpaceHelper.</span><code><span class="memberNameLink"><a href="../../../../org/hibernate/loader/plan/build/internal/spaces/QuerySpaceHelper.html#shouldIncludeJoin-org.hibernate.engine.FetchStrategy-">shouldIncludeJoin</a></span>(<a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a>&nbsp;fetchStrategy)</code>&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.hibernate.loader.plan.build.spi"> <!-- --> </a> <h3>Uses of <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a> in <a href="../../../../org/hibernate/loader/plan/build/spi/package-summary.html">org.hibernate.loader.plan.build.spi</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../org/hibernate/loader/plan/build/spi/package-summary.html">org.hibernate.loader.plan.build.spi</a> with parameters of type <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../org/hibernate/loader/plan/spi/AnyAttributeFetch.html" title="interface in org.hibernate.loader.plan.spi">AnyAttributeFetch</a></code></td> <td class="colLast"><span class="typeNameLabel">ExpandingFetchSource.</span><code><span class="memberNameLink"><a href="../../../../org/hibernate/loader/plan/build/spi/ExpandingFetchSource.html#buildAnyAttributeFetch-org.hibernate.persister.walking.spi.AssociationAttributeDefinition-org.hibernate.engine.FetchStrategy-">buildAnyAttributeFetch</a></span>(<a href="../../../../org/hibernate/persister/walking/spi/AssociationAttributeDefinition.html" title="interface in org.hibernate.persister.walking.spi">AssociationAttributeDefinition</a>&nbsp;attributeDefinition, <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a>&nbsp;fetchStrategy)</code> <div class="block">Builds a fetch for an "any" attribute.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../org/hibernate/loader/plan/spi/BidirectionalEntityReference.html" title="interface in org.hibernate.loader.plan.spi">BidirectionalEntityReference</a></code></td> <td class="colLast"><span class="typeNameLabel">ExpandingFetchSource.</span><code><span class="memberNameLink"><a href="../../../../org/hibernate/loader/plan/build/spi/ExpandingFetchSource.html#buildBidirectionalEntityReference-org.hibernate.persister.walking.spi.AssociationAttributeDefinition-org.hibernate.engine.FetchStrategy-org.hibernate.loader.plan.spi.EntityReference-">buildBidirectionalEntityReference</a></span>(<a href="../../../../org/hibernate/persister/walking/spi/AssociationAttributeDefinition.html" title="interface in org.hibernate.persister.walking.spi">AssociationAttributeDefinition</a>&nbsp;attributeDefinition, <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a>&nbsp;fetchStrategy, <a href="../../../../org/hibernate/loader/plan/spi/EntityReference.html" title="interface in org.hibernate.loader.plan.spi">EntityReference</a>&nbsp;targetEntityReference)</code> <div class="block">Builds a bidirectional entity reference for an entity attribute.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../org/hibernate/loader/plan/spi/CollectionAttributeFetch.html" title="interface in org.hibernate.loader.plan.spi">CollectionAttributeFetch</a></code></td> <td class="colLast"><span class="typeNameLabel">ExpandingFetchSource.</span><code><span class="memberNameLink"><a href="../../../../org/hibernate/loader/plan/build/spi/ExpandingFetchSource.html#buildCollectionAttributeFetch-org.hibernate.persister.walking.spi.AssociationAttributeDefinition-org.hibernate.engine.FetchStrategy-">buildCollectionAttributeFetch</a></span>(<a href="../../../../org/hibernate/persister/walking/spi/AssociationAttributeDefinition.html" title="interface in org.hibernate.persister.walking.spi">AssociationAttributeDefinition</a>&nbsp;attributeDefinition, <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a>&nbsp;fetchStrategy)</code> <div class="block">Builds a fetch for a collection attribute.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../org/hibernate/loader/plan/spi/EntityFetch.html" title="interface in org.hibernate.loader.plan.spi">EntityFetch</a></code></td> <td class="colLast"><span class="typeNameLabel">ExpandingFetchSource.</span><code><span class="memberNameLink"><a href="../../../../org/hibernate/loader/plan/build/spi/ExpandingFetchSource.html#buildEntityAttributeFetch-org.hibernate.persister.walking.spi.AssociationAttributeDefinition-org.hibernate.engine.FetchStrategy-">buildEntityAttributeFetch</a></span>(<a href="../../../../org/hibernate/persister/walking/spi/AssociationAttributeDefinition.html" title="interface in org.hibernate.persister.walking.spi">AssociationAttributeDefinition</a>&nbsp;attributeDefinition, <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a>&nbsp;fetchStrategy)</code> <div class="block">Builds a fetch for an entity attribute.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><span class="typeNameLabel">ExpandingFetchSource.</span><code><span class="memberNameLink"><a href="../../../../org/hibernate/loader/plan/build/spi/ExpandingFetchSource.html#validateFetchPlan-org.hibernate.engine.FetchStrategy-org.hibernate.persister.walking.spi.AttributeDefinition-">validateFetchPlan</a></span>(<a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a>&nbsp;fetchStrategy, <a href="../../../../org/hibernate/persister/walking/spi/AttributeDefinition.html" title="interface in org.hibernate.persister.walking.spi">AttributeDefinition</a>&nbsp;attributeDefinition)</code> <div class="block">Is the asserted plan valid from this owner to a fetch?</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.hibernate.loader.plan.spi"> <!-- --> </a> <h3>Uses of <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a> in <a href="../../../../org/hibernate/loader/plan/spi/package-summary.html">org.hibernate.loader.plan.spi</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../org/hibernate/loader/plan/spi/package-summary.html">org.hibernate.loader.plan.spi</a> that return <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a></code></td> <td class="colLast"><span class="typeNameLabel">Fetch.</span><code><span class="memberNameLink"><a href="../../../../org/hibernate/loader/plan/spi/Fetch.html#getFetchStrategy--">getFetchStrategy</a></span>()</code> <div class="block">Gets the fetch strategy for this fetch.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.hibernate.persister.walking.internal"> <!-- --> </a> <h3>Uses of <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a> in <a href="../../../../org/hibernate/persister/walking/internal/package-summary.html">org.hibernate.persister.walking.internal</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../org/hibernate/persister/walking/internal/package-summary.html">org.hibernate.persister.walking.internal</a> with parameters of type <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>static boolean</code></td> <td class="colLast"><span class="typeNameLabel">FetchStrategyHelper.</span><code><span class="memberNameLink"><a href="../../../../org/hibernate/persister/walking/internal/FetchStrategyHelper.html#isJoinFetched-org.hibernate.engine.FetchStrategy-">isJoinFetched</a></span>(<a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a>&nbsp;fetchStrategy)</code>&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.hibernate.persister.walking.spi"> <!-- --> </a> <h3>Uses of <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a> in <a href="../../../../org/hibernate/persister/walking/spi/package-summary.html">org.hibernate.persister.walking.spi</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../org/hibernate/persister/walking/spi/package-summary.html">org.hibernate.persister.walking.spi</a> that return <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a></code></td> <td class="colLast"><span class="typeNameLabel">AssociationAttributeDefinition.</span><code><span class="memberNameLink"><a href="../../../../org/hibernate/persister/walking/spi/AssociationAttributeDefinition.html#determineFetchPlan-org.hibernate.engine.spi.LoadQueryInfluencers-org.hibernate.loader.PropertyPath-">determineFetchPlan</a></span>(<a href="../../../../org/hibernate/engine/spi/LoadQueryInfluencers.html" title="class in org.hibernate.engine.spi">LoadQueryInfluencers</a>&nbsp;loadQueryInfluencers, <a href="../../../../org/hibernate/loader/PropertyPath.html" title="class in org.hibernate.loader">PropertyPath</a>&nbsp;propertyPath)</code>&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.hibernate.tuple.component"> <!-- --> </a> <h3>Uses of <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a> in <a href="../../../../org/hibernate/tuple/component/package-summary.html">org.hibernate.tuple.component</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../org/hibernate/tuple/component/package-summary.html">org.hibernate.tuple.component</a> that return <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a></code></td> <td class="colLast"><span class="typeNameLabel">CompositeBasedAssociationAttribute.</span><code><span class="memberNameLink"><a href="../../../../org/hibernate/tuple/component/CompositeBasedAssociationAttribute.html#determineFetchPlan-org.hibernate.engine.spi.LoadQueryInfluencers-org.hibernate.loader.PropertyPath-">determineFetchPlan</a></span>(<a href="../../../../org/hibernate/engine/spi/LoadQueryInfluencers.html" title="class in org.hibernate.engine.spi">LoadQueryInfluencers</a>&nbsp;loadQueryInfluencers, <a href="../../../../org/hibernate/loader/PropertyPath.html" title="class in org.hibernate.loader">PropertyPath</a>&nbsp;propertyPath)</code>&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.hibernate.tuple.entity"> <!-- --> </a> <h3>Uses of <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a> in <a href="../../../../org/hibernate/tuple/entity/package-summary.html">org.hibernate.tuple.entity</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../org/hibernate/tuple/entity/package-summary.html">org.hibernate.tuple.entity</a> that return <a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">FetchStrategy</a></code></td> <td class="colLast"><span class="typeNameLabel">EntityBasedAssociationAttribute.</span><code><span class="memberNameLink"><a href="../../../../org/hibernate/tuple/entity/EntityBasedAssociationAttribute.html#determineFetchPlan-org.hibernate.engine.spi.LoadQueryInfluencers-org.hibernate.loader.PropertyPath-">determineFetchPlan</a></span>(<a href="../../../../org/hibernate/engine/spi/LoadQueryInfluencers.html" title="class in org.hibernate.engine.spi">LoadQueryInfluencers</a>&nbsp;loadQueryInfluencers, <a href="../../../../org/hibernate/loader/PropertyPath.html" title="class in org.hibernate.loader">PropertyPath</a>&nbsp;propertyPath)</code>&nbsp;</td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../org/hibernate/engine/FetchStrategy.html" title="class in org.hibernate.engine">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/hibernate/engine/class-use/FetchStrategy.html" target="_top">Frames</a></li> <li><a href="FetchStrategy.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &copy; 2001-2016 <a href="http://redhat.com">Red Hat, Inc.</a> All Rights Reserved.</small></p> </body> </html>
Java
DESTDIR = "/" LENS_DEST = "$(DESTDIR)/usr/share/augeas/lenses" LENS_TEST_DEST = "$(LENS_DEST)/tests" install: install -d -m0755 $(LENS_DEST) install -d -m0755 $(LENS_TEST_DEST) install -m0644 gitolite.aug $(LENS_DEST) install -m0644 tests/test_gitolite.aug $(LENS_TEST_DEST) test: augparse -I . tests/test_gitolite.aug
Java
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en_US" lang="en_US"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <!-- qstyleoption.cpp --> <title>Qt 4.8: QStyleOptionComboBox Class Reference</title> <link rel="stylesheet" type="text/css" href="style/offline.css" /> </head> <body> <div class="header" id="qtdocheader"> <div class="content"> <a href="index.html" class="qtref"><span>Qt Reference Documentation</span></a> </div> <div class="breadcrumb toolblock"> <ul> <li class="first"><a href="index.html">Home</a></li> <!-- Breadcrumbs go here --> <li><a href="modules.html">Modules</a></li> <li><a href="qtgui.html">QtGui</a></li> <li>QStyleOptionComboBox</li> </ul> </div> </div> <div class="content mainContent"> <div class="toc"> <h3><a name="toc">Contents</a></h3> <ul> <li class="level1"><a href="#public-types">Public Types</a></li> <li class="level1"><a href="#public-functions">Public Functions</a></li> <li class="level1"><a href="#public-variables">Public Variables</a></li> <li class="level1"><a href="#details">Detailed Description</a></li> </ul> </div> <h1 class="title">QStyleOptionComboBox Class Reference</h1> <!-- $$$QStyleOptionComboBox-brief --> <p>The QStyleOptionComboBox class is used to describe the parameter for drawing a combobox. <a href="#details">More...</a></p> <!-- @@@QStyleOptionComboBox --> <pre class="cpp"> <span class="preprocessor">#include &lt;QStyleOptionComboBox&gt;</span></pre><p><b>Inherits: </b><a href="qstyleoptioncomplex.html">QStyleOptionComplex</a>.</p> <p><b>Inherited by: </b></p> <ul> <li><a href="qstyleoptioncombobox-members.html">List of all members, including inherited members</a></li> </ul> <a name="public-types"></a> <h2>Public Types</h2> <table class="alignedsummary"> <tr><td class="memItemLeft rightAlign topAlign"> enum </td><td class="memItemRight bottomAlign"><b><a href="qstyleoptioncombobox.html#StyleOptionType-enum">StyleOptionType</a></b> { Type }</td></tr> <tr><td class="memItemLeft rightAlign topAlign"> enum </td><td class="memItemRight bottomAlign"><b><a href="qstyleoptioncombobox.html#StyleOptionVersion-enum">StyleOptionVersion</a></b> { Version }</td></tr> </table> <a name="public-functions"></a> <h2>Public Functions</h2> <table class="alignedsummary"> <tr><td class="memItemLeft rightAlign topAlign"> </td><td class="memItemRight bottomAlign"><b><a href="qstyleoptioncombobox.html#QStyleOptionComboBox">QStyleOptionComboBox</a></b> ()</td></tr> <tr><td class="memItemLeft rightAlign topAlign"> </td><td class="memItemRight bottomAlign"><b><a href="qstyleoptioncombobox.html#QStyleOptionComboBox-2">QStyleOptionComboBox</a></b> ( const QStyleOptionComboBox &amp; <i>other</i> )</td></tr> </table> <ul> <li class="fn">2 public functions inherited from <a href="qstyleoption.html#public-functions">QStyleOption</a></li> </ul> <a name="public-variables"></a> <h2>Public Variables</h2> <table class="alignedsummary"> <tr><td class="memItemLeft rightAlign topAlign"> QIcon </td><td class="memItemRight bottomAlign"><b><a href="qstyleoptioncombobox.html#currentIcon-var">currentIcon</a></b></td></tr> <tr><td class="memItemLeft rightAlign topAlign"> QString </td><td class="memItemRight bottomAlign"><b><a href="qstyleoptioncombobox.html#currentText-var">currentText</a></b></td></tr> <tr><td class="memItemLeft rightAlign topAlign"> bool </td><td class="memItemRight bottomAlign"><b><a href="qstyleoptioncombobox.html#editable-var">editable</a></b></td></tr> <tr><td class="memItemLeft rightAlign topAlign"> bool </td><td class="memItemRight bottomAlign"><b><a href="qstyleoptioncombobox.html#frame-var">frame</a></b></td></tr> <tr><td class="memItemLeft rightAlign topAlign"> QSize </td><td class="memItemRight bottomAlign"><b><a href="qstyleoptioncombobox.html#iconSize-var">iconSize</a></b></td></tr> <tr><td class="memItemLeft rightAlign topAlign"> QRect </td><td class="memItemRight bottomAlign"><b><a href="qstyleoptioncombobox.html#popupRect-var">popupRect</a></b></td></tr> </table> <ul> <li class="fn">2 public variables inherited from <a href="qstyleoptioncomplex.html#public-variables">QStyleOptionComplex</a></li> <li class="fn">7 public variables inherited from <a href="qstyleoption.html#public-variables">QStyleOption</a></li> </ul> <a name="details"></a> <!-- $$$QStyleOptionComboBox-description --> <div class="descr"> <h2>Detailed Description</h2> <p>The QStyleOptionComboBox class is used to describe the parameter for drawing a combobox.</p> <p><a href="qstyleoptionbutton.html">QStyleOptionButton</a> contains all the information that <a href="qstyle.html">QStyle</a> functions need to draw <a href="qcombobox.html">QComboBox</a>.</p> <p>For performance reasons, the access to the member variables is direct (i.e&#x2e;, using the <tt>.</tt> or <tt>-&gt;</tt> operator). This low-level feel makes the structures straightforward to use and emphasizes that these are simply parameters used by the style functions.</p> <p>For an example demonstrating how style options can be used, see the <a href="widgets-styles.html">Styles</a> example.</p> </div> <p><b>See also </b><a href="qstyleoption.html">QStyleOption</a>, <a href="qstyleoptioncomplex.html">QStyleOptionComplex</a>, and <a href="qcombobox.html">QComboBox</a>.</p> <!-- @@@QStyleOptionComboBox --> <div class="types"> <h2>Member Type Documentation</h2> <!-- $$$StyleOptionType$$$Type --> <h3 class="fn"><a name="StyleOptionType-enum"></a>enum QStyleOptionComboBox::<span class="name">StyleOptionType</span></h3> <p>This enum is used to hold information about the type of the style option, and is defined for each <a href="qstyleoption.html">QStyleOption</a> subclass.</p> <table class="valuelist"><tr valign="top" class="odd"><th class="tblConst">Constant</th><th class="tblval">Value</th><th class="tbldscr">Description</th></tr> <tr><td class="topAlign"><tt>QStyleOptionComboBox::Type</tt></td><td class="topAlign"><tt>SO_ComboBox</tt></td><td class="topAlign">The type of style option provided (<a href="qstyleoption.html#OptionType-enum">SO_ComboBox</a> for this class).</td></tr> </table> <p>The type is used internally by <a href="qstyleoption.html">QStyleOption</a>, its subclasses, and <a href="qstyleoption.html#qstyleoption_cast">qstyleoption_cast</a>() to determine the type of style option. In general you do not need to worry about this unless you want to create your own <a href="qstyleoption.html">QStyleOption</a> subclass and your own styles.</p> <p><b>See also </b><a href="qstyleoptioncombobox.html#StyleOptionVersion-enum">StyleOptionVersion</a>.</p> <!-- @@@StyleOptionType --> <!-- $$$StyleOptionVersion$$$Version --> <h3 class="fn"><a name="StyleOptionVersion-enum"></a>enum QStyleOptionComboBox::<span class="name">StyleOptionVersion</span></h3> <p>This enum is used to hold information about the version of the style option, and is defined for each <a href="qstyleoption.html">QStyleOption</a> subclass.</p> <table class="valuelist"><tr valign="top" class="odd"><th class="tblConst">Constant</th><th class="tblval">Value</th><th class="tbldscr">Description</th></tr> <tr><td class="topAlign"><tt>QStyleOptionComboBox::Version</tt></td><td class="topAlign"><tt>1</tt></td><td class="topAlign">1</td></tr> </table> <p>The version is used by <a href="qstyleoption.html">QStyleOption</a> subclasses to implement extensions without breaking compatibility. If you use <a href="qstyleoption.html#qstyleoption_cast">qstyleoption_cast</a>(), you normally do not need to check it.</p> <p><b>See also </b><a href="qstyleoptioncombobox.html#StyleOptionType-enum">StyleOptionType</a>.</p> <!-- @@@StyleOptionVersion --> </div> <div class="func"> <h2>Member Function Documentation</h2> <!-- $$$QStyleOptionComboBox[overload1]$$$QStyleOptionComboBox --> <h3 class="fn"><a name="QStyleOptionComboBox"></a>QStyleOptionComboBox::<span class="name">QStyleOptionComboBox</span> ()</h3> <p>Creates a <a href="qstyleoptioncombobox.html">QStyleOptionComboBox</a>, initializing the members variables to their default values.</p> <!-- @@@QStyleOptionComboBox --> <!-- $$$QStyleOptionComboBox$$$QStyleOptionComboBoxconstQStyleOptionComboBox& --> <h3 class="fn"><a name="QStyleOptionComboBox-2"></a>QStyleOptionComboBox::<span class="name">QStyleOptionComboBox</span> ( const <span class="type">QStyleOptionComboBox</span> &amp; <i>other</i> )</h3> <p>Constructs a copy of the <i>other</i> style option.</p> <!-- @@@QStyleOptionComboBox --> </div> <div class="vars"> <h2>Member Variable Documentation</h2> <!-- $$$currentIcon --> <h3 class="fn"><a name="currentIcon-var"></a><span class="type"><a href="qicon.html">QIcon</a></span> QStyleOptionComboBox::<span class="name">currentIcon</span></h3> <p>This variable holds the icon for the current item of the combo box.</p> <p>The default value is an empty icon, i.e&#x2e; an icon with neither a pixmap nor a filename.</p> <!-- @@@currentIcon --> <!-- $$$currentText --> <h3 class="fn"><a name="currentText-var"></a><span class="type"><a href="qstring.html">QString</a></span> QStyleOptionComboBox::<span class="name">currentText</span></h3> <p>This variable holds the text for the current item of the combo box.</p> <p>The default value is an empty string.</p> <!-- @@@currentText --> <!-- $$$editable --> <h3 class="fn"><a name="editable-var"></a><span class="type">bool</span> QStyleOptionComboBox::<span class="name">editable</span></h3> <p>This variable holds whether or not the combobox is editable or not.</p> <p>the default value is false</p> <p><b>See also </b><a href="qcombobox.html#editable-prop">QComboBox::isEditable</a>().</p> <!-- @@@editable --> <!-- $$$frame --> <h3 class="fn"><a name="frame-var"></a><span class="type">bool</span> QStyleOptionComboBox::<span class="name">frame</span></h3> <p>This variable holds whether the combo box has a frame.</p> <p>The default value is true.</p> <!-- @@@frame --> <!-- $$$iconSize --> <h3 class="fn"><a name="iconSize-var"></a><span class="type"><a href="qsize.html">QSize</a></span> QStyleOptionComboBox::<span class="name">iconSize</span></h3> <p>This variable holds the icon size for the current item of the combo box.</p> <p>The default value is <a href="qsize.html">QSize</a>(-1, -1), i.e&#x2e; an invalid size.</p> <!-- @@@iconSize --> <!-- $$$popupRect --> <h3 class="fn"><a name="popupRect-var"></a><span class="type"><a href="qrect.html">QRect</a></span> QStyleOptionComboBox::<span class="name">popupRect</span></h3> <p>This variable holds the popup rectangle for the combobox.</p> <p>The default value is a null rectangle, i.e&#x2e; a rectangle with both the width and the height set to 0.</p> <p>This variable is currently unused. You can safely ignore it.</p> <p><b>See also </b><a href="qstyle.html#SubControl-enum">QStyle::SC_ComboBoxListBoxPopup</a>.</p> <!-- @@@popupRect --> </div> <div class="ft"> <span></span> </div> </div> <div class="footer"> <p> <acronym title="Copyright">&copy;</acronym> 2008-2011 Nokia Corporation and/or its subsidiaries. Nokia, Qt and their respective logos are trademarks of Nokia Corporation in Finland and/or other countries worldwide.</p> <p> All other trademarks are property of their respective owners. <a title="Privacy Policy" href="http://qt.nokia.com/about/privacy-policy">Privacy Policy</a></p> <br /> <p> Licensees holding valid Qt Commercial licenses may use this document in accordance with the Qt Commercial License Agreement provided with the Software or, alternatively, in accordance with the terms contained in a written agreement between you and Nokia.</p> <p> Alternatively, this document may be used under the terms of the <a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation License version 1.3</a> as published by the Free Software Foundation.</p> </div> </body> </html>
Java
/* * Copyright (C) 2010 Herve Quiroz * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.trancecode.collection; import com.google.common.base.Preconditions; import com.google.common.base.Predicates; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet.Builder; import com.google.common.collect.Iterables; import java.util.Set; /** * Utility methods related to {@link Set}. * * @author Herve Quiroz */ public final class TcSets { public static <T> ImmutableSet<T> immutableSet(final Iterable<T> set, final T element) { Preconditions.checkNotNull(set); Preconditions.checkNotNull(element); if (set instanceof Set && ((Set<?>) set).contains(element)) { return ImmutableSet.copyOf(set); } final Builder<T> builder = ImmutableSet.builder(); return builder.addAll(set).add(element).build(); } public static <T> ImmutableSet<T> immutableSet(final Set<T> set1, final Set<T> set2) { Preconditions.checkNotNull(set1); Preconditions.checkNotNull(set2); if (set1.isEmpty()) { return ImmutableSet.copyOf(set2); } if (set2.isEmpty()) { return ImmutableSet.copyOf(set1); } final Builder<T> builder = ImmutableSet.builder(); return builder.addAll(set1).addAll(set2).build(); } public static <T> ImmutableSet<T> immutableSetWithout(final Iterable<T> elements, final T element) { Preconditions.checkNotNull(elements); Preconditions.checkNotNull(element); if (elements instanceof Set && !((Set<?>) elements).contains(element)) { return ImmutableSet.copyOf(elements); } return ImmutableSet.copyOf(Iterables.filter(elements, Predicates.not(Predicates.equalTo(element)))); } private TcSets() { // No instantiation } }
Java
// The libMesh Finite Element Library. // Copyright (C) 2002-2016 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #ifndef LIBMESH_SYSTEM_H #define LIBMESH_SYSTEM_H // Local Includes #include "libmesh/auto_ptr.h" #include "libmesh/elem_range.h" #include "libmesh/enum_norm_type.h" #include "libmesh/enum_xdr_mode.h" #include "libmesh/enum_subset_solve_mode.h" #include "libmesh/enum_parallel_type.h" #include "libmesh/fem_function_base.h" #include "libmesh/libmesh_common.h" #include "libmesh/parallel_object.h" #include "libmesh/qoi_set.h" #include "libmesh/reference_counted_object.h" #include "libmesh/tensor_value.h" // For point_hessian #include "libmesh/variable.h" // C++ includes #include <cstddef> #include <set> #include <vector> namespace libMesh { // Forward Declarations class System; class EquationSystems; class MeshBase; class Xdr; class DofMap; template <typename Output> class FunctionBase; class Parameters; class ParameterVector; class Point; class SensitivityData; template <typename T> class NumericVector; template <typename T> class VectorValue; typedef VectorValue<Number> NumberVectorValue; typedef NumberVectorValue Gradient; class SystemSubset; class FEType; class SystemNorm; /** * This is the base class for classes which contain * information related to any physical process that might be simulated. * Such information may range from the actual solution values to * algorithmic flags that may be used to control the numerical methods * employed. In general, use an \p EqnSystems<T_sys> object to handle * one or more of the children of this class. * Note that templating \p EqnSystems relaxes the use of virtual members. * * \author Benjamin S. Kirk * \date 2003-2004 */ class System : public ReferenceCountedObject<System>, public ParallelObject { public: /** * Constructor. Optionally initializes required * data structures. */ System (EquationSystems & es, const std::string & name, const unsigned int number); /** * Abstract base class to be used for sysem initialization. * A user class derived from this class may be used to * intialize the system values by attaching an object * with the method \p attach_init_object. */ class Initialization { public: /** * Destructor. Virtual because we will have virtual functions. */ virtual ~Initialization () {} /** * Initialization function. This function will be called * to initialize the system values upon creation and must * be provided by the user in a derived class. */ virtual void initialize () = 0; }; /** * Abstract base class to be used for sysem assembly. * A user class derived from this class may be used to * assemble the system by attaching an object * with the method \p attach_assemble_object. */ class Assembly { public: /** * Destructor. Virtual because we will have virtual functions. */ virtual ~Assembly () {} /** * Assembly function. This function will be called * to assemble the system prior to a solve and must * be provided by the user in a derived class. */ virtual void assemble () = 0; }; /** * Abstract base class to be used for sysem constraints. * A user class derived from this class may be used to * constrain the system by attaching an object * with the method \p attach_constraint_object. */ class Constraint { public: /** * Destructor. Virtual because we will have virtual functions. */ virtual ~Constraint () {} /** * Constraint function. This function will be called * to constrain the system prior to a solve and must * be provided by the user in a derived class. */ virtual void constrain () = 0; }; /** * Abstract base class to be used for quantities of interest. * A user class derived from this class may be used to * compute quantities of interest by attaching an object * with the method \p attach_QOI_object. */ class QOI { public: /** * Destructor. Virtual because we will have virtual functions. */ virtual ~QOI () {} /** * Quantitiy of interest function. This function will be called * to compute quantities of interest and must be provided by the * user in a derived class. */ virtual void qoi (const QoISet & qoi_indices) = 0; }; /** * Abstract base class to be used for derivatives of quantities * of interest. A user class derived from this class may be used * to compute quantities of interest by attaching an object * with the method \p attach_QOI_derivative_object. */ class QOIDerivative { public: /** * Destructor. Virtual because we will have virtual functions. */ virtual ~QOIDerivative () {} /** * Quantitiy of interest derivative function. This function will * be called to compute derivatived of quantities of interest and * must be provided by the user in a derived class. */ virtual void qoi_derivative (const QoISet & qoi_indices, bool include_liftfunc, bool apply_constraints) = 0; }; /** * Destructor. */ virtual ~System (); /** * The type of system. */ typedef System sys_type; /** * @returns a clever pointer to the system. */ sys_type & system () { return *this; } /** * Clear all the data structures associated with * the system. */ virtual void clear (); /** * Initializes degrees of freedom on the current mesh. * Sets the */ void init (); /** * Reinitializes degrees of freedom and other * required data on the current mesh. Note that the matrix * is not initialized at this time since it may not be required * for all applications. @e Should be overloaded in derived classes. */ virtual void reinit (); /** * Reinitializes the constraints for this system. */ virtual void reinit_constraints (); /** * Returns true iff this system has been initialized. */ bool is_initialized(); /** * Update the local values to reflect the solution * on neighboring processors. */ virtual void update (); /** * Prepares \p matrix and \p _dof_map for matrix assembly. * Does not actually assemble anything. For matrix assembly, * use the \p assemble() in derived classes. * @e Should be overloaded in derived classes. */ virtual void assemble (); /** * Calls user qoi function. * @e Can be overloaded in derived classes. */ virtual void assemble_qoi (const QoISet & qoi_indices = QoISet()); /** * Calls user qoi derivative function. * @e Can be overloaded in derived classes. */ virtual void assemble_qoi_derivative (const QoISet & qoi_indices = QoISet(), bool include_liftfunc = true, bool apply_constraints = true); /** * Calls residual parameter derivative function. * * Library subclasses use finite differences by default. * * This should assemble the sensitivity rhs vectors to hold * -(partial R / partial p_i), making them ready to solve * the forward sensitivity equation. * * This method is only implemented in some derived classes. */ virtual void assemble_residual_derivatives (const ParameterVector & parameters); /** * After calling this method, any solve will be restricted to the * given subdomain. To disable this mode, call this method with \p * subset being a \p NULL pointer. */ virtual void restrict_solve_to (const SystemSubset * subset, const SubsetSolveMode subset_solve_mode=SUBSET_ZERO); /** * Solves the system. Should be overloaded in derived systems. */ virtual void solve () {} /** * Solves the sensitivity system, for the provided parameters. * Must be overloaded in derived systems. * * Returns a pair with the total number of linear iterations * performed and the (sum of the) final residual norms * * This method is only implemented in some derived classes. */ virtual std::pair<unsigned int, Real> sensitivity_solve (const ParameterVector & parameters); /** * Assembles & solves the linear system(s) (dR/du)*u_w = sum(w_p*-dR/dp), for * those parameters p contained within \p parameters weighted by the * values w_p found within \p weights. * * Returns a pair with the total number of linear iterations * performed and the (sum of the) final residual norms * * This method is only implemented in some derived classes. */ virtual std::pair<unsigned int, Real> weighted_sensitivity_solve (const ParameterVector & parameters, const ParameterVector & weights); /** * Solves the adjoint system, for the specified qoi indices, or for * every qoi if \p qoi_indices is NULL. Must be overloaded in * derived systems. * * Returns a pair with the total number of linear iterations * performed and the (sum of the) final residual norms * * This method is only implemented in some derived classes. */ virtual std::pair<unsigned int, Real> adjoint_solve (const QoISet & qoi_indices = QoISet()); /** * Assembles & solves the linear system(s) * (dR/du)^T*z_w = sum(w_p*(d^2q/dudp - d^2R/dudp*z)), for those * parameters p contained within \p parameters, weighted by the * values w_p found within \p weights. * * Assumes that adjoint_solve has already calculated z for each qoi * in \p qoi_indices. * * Returns a pair with the total number of linear iterations * performed and the (sum of the) final residual norms * * This method is only implemented in some derived classes. */ virtual std::pair<unsigned int, Real> weighted_sensitivity_adjoint_solve (const ParameterVector & parameters, const ParameterVector & weights, const QoISet & qoi_indices = QoISet()); /** * Accessor for the adjoint_already_solved boolean */ bool is_adjoint_already_solved() const { return adjoint_already_solved;} /** * Setter for the adjoint_already_solved boolean */ void set_adjoint_already_solved(bool setting) { adjoint_already_solved = setting;} /** * Solves for the derivative of each of the system's quantities of * interest q in \p qoi[qoi_indices] with respect to each parameter * in \p parameters, placing the result for qoi \p i and parameter * \p j into \p sensitivities[i][j]. * * Note that parameters is a const vector, not a vector-of-const; * parameter values in this vector need to be mutable for finite * differencing to work. * * Automatically chooses the forward method for problems with more * quantities of interest than parameters, or the adjoint method * otherwise. * * This method is only usable in derived classes which overload * an implementation. */ virtual void qoi_parameter_sensitivity (const QoISet & qoi_indices, const ParameterVector & parameters, SensitivityData & sensitivities); /** * Solves for parameter sensitivities using the adjoint method. * * This method is only implemented in some derived classes. */ virtual void adjoint_qoi_parameter_sensitivity (const QoISet & qoi_indices, const ParameterVector & parameters, SensitivityData & sensitivities); /** * Solves for parameter sensitivities using the forward method. * * This method is only implemented in some derived classes. */ virtual void forward_qoi_parameter_sensitivity (const QoISet & qoi_indices, const ParameterVector & parameters, SensitivityData & sensitivities); /** * For each of the system's quantities of interest q in * \p qoi[qoi_indices], and for a vector of parameters p, the * parameter sensitivity Hessian H_ij is defined as * H_ij = (d^2 q)/(d p_i d p_j) * This Hessian is the output of this method, where for each q_i, * H_jk is stored in \p hessian.second_derivative(i,j,k). * * This method is only implemented in some derived classes. */ virtual void qoi_parameter_hessian(const QoISet & qoi_indices, const ParameterVector & parameters, SensitivityData & hessian); /** * For each of the system's quantities of interest q in * \p qoi[qoi_indices], and for a vector of parameters p, the * parameter sensitivity Hessian H_ij is defined as * H_ij = (d^2 q)/(d p_i d p_j) * The Hessian-vector product, for a vector v_k in parameter space, is * S_j = H_jk v_k * This product is the output of this method, where for each q_i, * S_j is stored in \p sensitivities[i][j]. * * This method is only implemented in some derived classes. */ virtual void qoi_parameter_hessian_vector_product(const QoISet & qoi_indices, const ParameterVector & parameters, const ParameterVector & vector, SensitivityData & product); /** * @returns \p true when the other system contains * identical data, up to the given threshold. Outputs * some diagnostic info when \p verbose is set. */ virtual bool compare (const System & other_system, const Real threshold, const bool verbose) const; /** * @returns the system name. */ const std::string & name () const; /** * @returns the type of system, helpful in identifying * which system type to use when reading equation system * data from file. Should be overloaded in derived classes. */ virtual std::string system_type () const { return "Basic"; } /** * Projects arbitrary functions onto the current solution. * The function value \p f and its gradient \p g are * user-provided cloneable functors. * A gradient \p g is only required/used for projecting onto finite * element spaces with continuous derivatives. * If non-default \p Parameters are to be used, they can be provided * in the \p parameters argument. */ void project_solution (FunctionBase<Number> * f, FunctionBase<Gradient> * g = NULL) const; /** * Projects arbitrary functions onto the current solution. * The function value \p f and its gradient \p g are * user-provided cloneable functors. * A gradient \p g is only required/used for projecting onto finite * element spaces with continuous derivatives. * If non-default \p Parameters are to be used, they can be provided * in the \p parameters argument. */ void project_solution (FEMFunctionBase<Number> * f, FEMFunctionBase<Gradient> * g = NULL) const; /** * Projects arbitrary functions onto the current solution. * The function value \p fptr and its gradient \p gptr are * represented by function pointers. * A gradient \p gptr is only required/used for projecting onto * finite element spaces with continuous derivatives. */ void project_solution (Number fptr(const Point & p, const Parameters & parameters, const std::string & sys_name, const std::string & unknown_name), Gradient gptr(const Point & p, const Parameters & parameters, const std::string & sys_name, const std::string & unknown_name), const Parameters & parameters) const; /** * Projects arbitrary functions onto a vector of degree of freedom * values for the current system. * The function value \p f and its gradient \p g are * user-provided cloneable functors. * A gradient \p g is only required/used for projecting onto finite * element spaces with continuous derivatives. * If non-default \p Parameters are to be used, they can be provided * in the \p parameters argument. * * Constrain the new vector using the requested adjoint rather than * primal constraints if is_adjoint is non-negative. */ void project_vector (NumericVector<Number> & new_vector, FunctionBase<Number> * f, FunctionBase<Gradient> * g = NULL, int is_adjoint = -1) const; /** * Projects arbitrary functions onto a vector of degree of freedom * values for the current system. * The function value \p f and its gradient \p g are * user-provided cloneable functors. * A gradient \p g is only required/used for projecting onto finite * element spaces with continuous derivatives. * If non-default \p Parameters are to be used, they can be provided * in the \p parameters argument. * * Constrain the new vector using the requested adjoint rather than * primal constraints if is_adjoint is non-negative. */ void project_vector (NumericVector<Number> & new_vector, FEMFunctionBase<Number> * f, FEMFunctionBase<Gradient> * g = NULL, int is_adjoint = -1) const; /** * Projects arbitrary functions onto a vector of degree of freedom * values for the current system. * The function value \p fptr and its gradient \p gptr are * represented by function pointers. * A gradient \p gptr is only required/used for projecting onto * finite element spaces with continuous derivatives. * * Constrain the new vector using the requested adjoint rather than * primal constraints if is_adjoint is non-negative. */ void project_vector (Number fptr(const Point & p, const Parameters & parameters, const std::string & sys_name, const std::string & unknown_name), Gradient gptr(const Point & p, const Parameters & parameters, const std::string & sys_name, const std::string & unknown_name), const Parameters & parameters, NumericVector<Number> & new_vector, int is_adjoint = -1) const; /** * Projects arbitrary boundary functions onto a vector of degree of * freedom values for the current system. * Only degrees of freedom which affect the function's trace on a * boundary in the set \p b are affected. * Only degrees of freedom associated with the variables listed in * the vector \p variables are projected. * The function value \p f and its gradient \p g are * user-provided cloneable functors. * A gradient \p g is only required/used for projecting onto finite * element spaces with continuous derivatives. * If non-default \p Parameters are to be used, they can be provided * in the \p parameters argument. */ void boundary_project_solution (const std::set<boundary_id_type> & b, const std::vector<unsigned int> & variables, FunctionBase<Number> * f, FunctionBase<Gradient> * g = NULL); /** * Projects arbitrary boundary functions onto a vector of degree of * freedom values for the current system. * Only degrees of freedom which affect the function's trace on a * boundary in the set \p b are affected. * Only degrees of freedom associated with the variables listed in * the vector \p variables are projected. * The function value \p fptr and its gradient \p gptr are * represented by function pointers. * A gradient \p gptr is only required/used for projecting onto * finite element spaces with continuous derivatives. */ void boundary_project_solution (const std::set<boundary_id_type> & b, const std::vector<unsigned int> & variables, Number fptr(const Point & p, const Parameters & parameters, const std::string & sys_name, const std::string & unknown_name), Gradient gptr(const Point & p, const Parameters & parameters, const std::string & sys_name, const std::string & unknown_name), const Parameters & parameters); /** * Projects arbitrary boundary functions onto a vector of degree of * freedom values for the current system. * Only degrees of freedom which affect the function's trace on a * boundary in the set \p b are affected. * Only degrees of freedom associated with the variables listed in * the vector \p variables are projected. * The function value \p f and its gradient \p g are * user-provided cloneable functors. * A gradient \p g is only required/used for projecting onto finite * element spaces with continuous derivatives. * If non-default \p Parameters are to be used, they can be provided * in the \p parameters argument. * * Constrain the new vector using the requested adjoint rather than * primal constraints if is_adjoint is non-negative. */ void boundary_project_vector (const std::set<boundary_id_type> & b, const std::vector<unsigned int> & variables, NumericVector<Number> & new_vector, FunctionBase<Number> * f, FunctionBase<Gradient> * g = NULL, int is_adjoint = -1) const; /** * Projects arbitrary boundary functions onto a vector of degree of * freedom values for the current system. * Only degrees of freedom which affect the function's trace on a * boundary in the set \p b are affected. * Only degrees of freedom associated with the variables listed in * the vector \p variables are projected. * The function value \p fptr and its gradient \p gptr are * represented by function pointers. * A gradient \p gptr is only required/used for projecting onto * finite element spaces with continuous derivatives. * * Constrain the new vector using the requested adjoint rather than * primal constraints if is_adjoint is non-negative. */ void boundary_project_vector (const std::set<boundary_id_type> & b, const std::vector<unsigned int> & variables, Number fptr(const Point & p, const Parameters & parameters, const std::string & sys_name, const std::string & unknown_name), Gradient gptr(const Point & p, const Parameters & parameters, const std::string & sys_name, const std::string & unknown_name), const Parameters & parameters, NumericVector<Number> & new_vector, int is_adjoint = -1) const; /** * @returns the system number. */ unsigned int number () const; /** * Fill the input vector \p global_soln so that it contains * the global solution on all processors. * Requires communication with all other processors. */ void update_global_solution (std::vector<Number> & global_soln) const; /** * Fill the input vector \p global_soln so that it contains * the global solution on processor \p dest_proc. * Requires communication with all other processors. */ void update_global_solution (std::vector<Number> & global_soln, const processor_id_type dest_proc) const; /** * @returns a constant reference to this systems's \p _mesh. */ const MeshBase & get_mesh() const; /** * @returns a reference to this systems's \p _mesh. */ MeshBase & get_mesh(); /** * @returns a constant reference to this system's \p _dof_map. */ const DofMap & get_dof_map() const; /** * @returns a writeable reference to this system's \p _dof_map. */ DofMap & get_dof_map(); /** * @returns a constant reference to this system's parent EquationSystems object. */ const EquationSystems & get_equation_systems() const { return _equation_systems; } /** * @returns a reference to this system's parent EquationSystems object. */ EquationSystems & get_equation_systems() { return _equation_systems; } /** * @returns \p true if the system is active, \p false otherwise. * An active system will be solved. */ bool active () const; /** * Activates the system. Only active systems are solved. */ void activate (); /** * Deactivates the system. Only active systems are solved. */ void deactivate (); /** * Sets the system to be "basic only": i.e. advanced system * components such as ImplicitSystem matrices may not be * initialized. This is useful for efficiency in certain utility * programs that never use System::solve(). This method must be * called after the System or derived class is created but before it * is initialized; e.g. from within EquationSystems::read() */ void set_basic_system_only (); /** * Vector iterator typedefs. */ typedef std::map<std::string, NumericVector<Number> *>::iterator vectors_iterator; typedef std::map<std::string, NumericVector<Number> *>::const_iterator const_vectors_iterator; /** * Beginning of vectors container */ vectors_iterator vectors_begin (); /** * Beginning of vectors container */ const_vectors_iterator vectors_begin () const; /** * End of vectors container */ vectors_iterator vectors_end (); /** * End of vectors container */ const_vectors_iterator vectors_end () const; /** * Adds the additional vector \p vec_name to this system. All the * additional vectors are similarly distributed, like the \p * solution, and inititialized to zero. * * By default vectors added by add_vector are projected to changed grids by * reinit(). To zero them instead (more efficient), pass "false" as the * second argument */ NumericVector<Number> & add_vector (const std::string & vec_name, const bool projections=true, const ParallelType type = PARALLEL); /** * Removes the additional vector \p vec_name from this system */ void remove_vector(const std::string & vec_name); /** * Tells the System whether or not to project the solution vector onto new * grids when the system is reinitialized. The solution will be projected * unless project_solution_on_reinit() = false is called. */ bool & project_solution_on_reinit (void) { return _solution_projection; } /** * @returns \p true if this \p System has a vector associated with the * given name, \p false otherwise. */ bool have_vector (const std::string & vec_name) const; /** * @returns a const pointer to the vector if this \p System has a * vector associated with the given name, \p NULL otherwise. */ const NumericVector<Number> * request_vector (const std::string & vec_name) const; /** * @returns a pointer to the vector if this \p System has a * vector associated with the given name, \p NULL otherwise. */ NumericVector<Number> * request_vector (const std::string & vec_name); /** * @returns a const pointer to this system's @e additional vector * number \p vec_num (where the vectors are counted starting with * 0), or returns \p NULL if the system has no such vector. */ const NumericVector<Number> * request_vector (const unsigned int vec_num) const; /** * @returns a writeable pointer to this system's @e additional * vector number \p vec_num (where the vectors are counted starting * with 0), or returns \p NULL if the system has no such vector. */ NumericVector<Number> * request_vector (const unsigned int vec_num); /** * @returns a const reference to this system's @e additional vector * named \p vec_name. Access is only granted when the vector is already * properly initialized. */ const NumericVector<Number> & get_vector (const std::string & vec_name) const; /** * @returns a writeable reference to this system's @e additional vector * named \p vec_name. Access is only granted when the vector is already * properly initialized. */ NumericVector<Number> & get_vector (const std::string & vec_name); /** * @returns a const reference to this system's @e additional vector * number \p vec_num (where the vectors are counted starting with * 0). */ const NumericVector<Number> & get_vector (const unsigned int vec_num) const; /** * @returns a writeable reference to this system's @e additional * vector number \p vec_num (where the vectors are counted starting * with 0). */ NumericVector<Number> & get_vector (const unsigned int vec_num); /** * @returns the name of this system's @e additional vector number \p * vec_num (where the vectors are counted starting with 0). */ const std::string & vector_name (const unsigned int vec_num) const; /** * @returns the name of a system vector, given a reference to that vector */ const std::string & vector_name (const NumericVector<Number> & vec_reference) const; /** * Allows one to set the QoI index controlling whether the vector * identified by vec_name represents a solution from the adjoint * (qoi_num >= 0) or primal (qoi_num == -1) space. This becomes * significant if those spaces have differing heterogeneous * Dirichlet constraints. * * qoi_num == -2 can be used to indicate a vector which should not * be affected by constraints during projection operations. */ void set_vector_as_adjoint (const std::string & vec_name, int qoi_num); /** * @returns the int describing whether the vector identified by * vec_name represents a solution from an adjoint (non-negative) or * the primal (-1) space. */ int vector_is_adjoint (const std::string & vec_name) const; /** * Allows one to set the boolean controlling whether the vector * identified by vec_name should be "preserved": projected to new * meshes, saved, etc. */ void set_vector_preservation (const std::string & vec_name, bool preserve); /** * @returns the boolean describing whether the vector identified by * vec_name should be "preserved": projected to new meshes, saved, * etc. */ bool vector_preservation (const std::string & vec_name) const; /** * @returns a reference to one of the system's adjoint solution * vectors, by default the one corresponding to the first qoi. * Creates the vector if it doesn't already exist. */ NumericVector<Number> & add_adjoint_solution(unsigned int i=0); /** * @returns a reference to one of the system's adjoint solution * vectors, by default the one corresponding to the first qoi. */ NumericVector<Number> & get_adjoint_solution(unsigned int i=0); /** * @returns a reference to one of the system's adjoint solution * vectors, by default the one corresponding to the first qoi. */ const NumericVector<Number> & get_adjoint_solution(unsigned int i=0) const; /** * @returns a reference to one of the system's solution sensitivity * vectors, by default the one corresponding to the first parameter. * Creates the vector if it doesn't already exist. */ NumericVector<Number> & add_sensitivity_solution(unsigned int i=0); /** * @returns a reference to one of the system's solution sensitivity * vectors, by default the one corresponding to the first parameter. */ NumericVector<Number> & get_sensitivity_solution(unsigned int i=0); /** * @returns a reference to one of the system's solution sensitivity * vectors, by default the one corresponding to the first parameter. */ const NumericVector<Number> & get_sensitivity_solution(unsigned int i=0) const; /** * @returns a reference to one of the system's weighted sensitivity * adjoint solution vectors, by default the one corresponding to the * first qoi. * Creates the vector if it doesn't already exist. */ NumericVector<Number> & add_weighted_sensitivity_adjoint_solution(unsigned int i=0); /** * @returns a reference to one of the system's weighted sensitivity * adjoint solution vectors, by default the one corresponding to the * first qoi. */ NumericVector<Number> & get_weighted_sensitivity_adjoint_solution(unsigned int i=0); /** * @returns a reference to one of the system's weighted sensitivity * adjoint solution vectors, by default the one corresponding to the * first qoi. */ const NumericVector<Number> & get_weighted_sensitivity_adjoint_solution(unsigned int i=0) const; /** * @returns a reference to the solution of the last weighted * sensitivity solve * Creates the vector if it doesn't already exist. */ NumericVector<Number> & add_weighted_sensitivity_solution(); /** * @returns a reference to the solution of the last weighted * sensitivity solve */ NumericVector<Number> & get_weighted_sensitivity_solution(); /** * @returns a reference to the solution of the last weighted * sensitivity solve */ const NumericVector<Number> & get_weighted_sensitivity_solution() const; /** * @returns a reference to one of the system's adjoint rhs * vectors, by default the one corresponding to the first qoi. * Creates the vector if it doesn't already exist. */ NumericVector<Number> & add_adjoint_rhs(unsigned int i=0); /** * @returns a reference to one of the system's adjoint rhs * vectors, by default the one corresponding to the first qoi. * This what the user's QoI derivative code should assemble * when setting up an adjoint problem */ NumericVector<Number> & get_adjoint_rhs(unsigned int i=0); /** * @returns a reference to one of the system's adjoint rhs * vectors, by default the one corresponding to the first qoi. */ const NumericVector<Number> & get_adjoint_rhs(unsigned int i=0) const; /** * @returns a reference to one of the system's sensitivity rhs * vectors, by default the one corresponding to the first parameter. * Creates the vector if it doesn't already exist. */ NumericVector<Number> & add_sensitivity_rhs(unsigned int i=0); /** * @returns a reference to one of the system's sensitivity rhs * vectors, by default the one corresponding to the first parameter. * By default these vectors are built by the library, using finite * differences, when \p assemble_residual_derivatives() is called. * * When assembled, this vector should hold * -(partial R / partial p_i) */ NumericVector<Number> & get_sensitivity_rhs(unsigned int i=0); /** * @returns a reference to one of the system's sensitivity rhs * vectors, by default the one corresponding to the first parameter. */ const NumericVector<Number> & get_sensitivity_rhs(unsigned int i=0) const; /** * @returns the number of vectors (in addition to the solution) * handled by this system * This is the size of the \p _vectors map */ unsigned int n_vectors () const; /** * @returns the number of matrices * handled by this system. * * This will return 0 by default but can be overriden. */ virtual unsigned int n_matrices () const; /** * @returns the number of variables in the system */ unsigned int n_vars() const; /** * @returns the number of \p VariableGroup variable groups in the system */ unsigned int n_variable_groups() const; /** * @returns the total number of scalar components in the system's * variables. This will equal \p n_vars() in the case of all * scalar-valued variables. */ unsigned int n_components() const; /** * @returns the number of degrees of freedom in the system */ dof_id_type n_dofs() const; /** * Returns the number of active degrees of freedom * for this System. */ dof_id_type n_active_dofs() const; /** * @returns the total number of constrained degrees of freedom * in the system. */ dof_id_type n_constrained_dofs() const; /** * @returns the number of constrained degrees of freedom * on this processor. */ dof_id_type n_local_constrained_dofs() const; /** * @returns the number of degrees of freedom local * to this processor */ dof_id_type n_local_dofs() const; /** * Adds the variable \p var to the list of variables * for this system. Returns the index number for the new variable. */ unsigned int add_variable (const std::string & var, const FEType & type, const std::set<subdomain_id_type> * const active_subdomains = NULL); /** * Adds the variable \p var to the list of variables * for this system. Same as before, but assumes \p LAGRANGE * as default value for \p FEType.family. */ unsigned int add_variable (const std::string & var, const Order order = FIRST, const FEFamily = LAGRANGE, const std::set<subdomain_id_type> * const active_subdomains = NULL); /** * Adds the variable \p var to the list of variables * for this system. Returns the index number for the new variable. */ unsigned int add_variables (const std::vector<std::string> & vars, const FEType & type, const std::set<subdomain_id_type> * const active_subdomains = NULL); /** * Adds the variable \p var to the list of variables * for this system. Same as before, but assumes \p LAGRANGE * as default value for \p FEType.family. */ unsigned int add_variables (const std::vector<std::string> & vars, const Order order = FIRST, const FEFamily = LAGRANGE, const std::set<subdomain_id_type> * const active_subdomains = NULL); /** * Return a constant reference to \p Variable \p var. */ const Variable & variable (unsigned int var) const; /** * Return a constant reference to \p VariableGroup \p vg. */ const VariableGroup & variable_group (unsigned int vg) const; /** * @returns true if a variable named \p var exists in this System */ bool has_variable(const std::string & var) const; /** * @returns the name of variable \p i. */ const std::string & variable_name(const unsigned int i) const; /** * @returns the variable number assoicated with * the user-specified variable named \p var. */ unsigned short int variable_number (const std::string & var) const; /** * Fills \p all_variable_numbers with all the variable numbers for the * variables that have been added to this system. */ void get_all_variable_numbers(std::vector<unsigned int> & all_variable_numbers) const; /** * @returns an index, starting from 0 for the first component of the * first variable, and incrementing for each component of each * (potentially vector-valued) variable in the system in order. * For systems with only scalar-valued variables, this will be the * same as \p variable_number(var) * * Irony: currently our only non-scalar-valued variable type is * SCALAR. */ unsigned int variable_scalar_number (const std::string & var, unsigned int component) const; /** * @returns an index, starting from 0 for the first component of the * first variable, and incrementing for each component of each * (potentially vector-valued) variable in the system in order. * For systems with only scalar-valued variables, this will be the * same as \p var_num * * Irony: currently our only non-scalar-valued variable type is * SCALAR. */ unsigned int variable_scalar_number (unsigned int var_num, unsigned int component) const; /** * @returns the finite element type variable number \p i. */ const FEType & variable_type (const unsigned int i) const; /** * @returns the finite element type for variable \p var. */ const FEType & variable_type (const std::string & var) const; /** * @returns \p true when \p VariableGroup structures should be * automatically identified, \p false otherwise. */ bool identify_variable_groups () const; /** * Toggle automatic \p VariableGroup identification. */ void identify_variable_groups (const bool); /** * @returns a norm of variable \p var in the vector \p v, in the specified * norm (e.g. L2, L_INF, H1) */ Real calculate_norm(const NumericVector<Number> & v, unsigned int var, FEMNormType norm_type, std::set<unsigned int> * skip_dimensions=NULL) const; /** * @returns a norm of the vector \p v, using \p component_norm and \p * component_scale to choose and weight the norms of each variable. */ Real calculate_norm(const NumericVector<Number> & v, const SystemNorm & norm, std::set<unsigned int> * skip_dimensions=NULL) const; /** * Reads the basic data header for this System. */ void read_header (Xdr & io, const std::string & version, const bool read_header=true, const bool read_additional_data=true, const bool read_legacy_format=false); /** * Reads additional data, namely vectors, for this System. */ void read_legacy_data (Xdr & io, const bool read_additional_data=true); /** * Reads additional data, namely vectors, for this System. * This method may safely be called on a distributed-memory mesh. */ template <typename ValType> void read_serialized_data (Xdr & io, const bool read_additional_data=true); /** * Non-templated version for backward compatibility. * * Reads additional data, namely vectors, for this System. * This method may safely be called on a distributed-memory mesh. */ void read_serialized_data (Xdr & io, const bool read_additional_data=true) { read_serialized_data<Number>(io, read_additional_data); } /** * Read a number of identically distributed vectors. This method * allows for optimization for the multiple vector case by only communicating * the metadata once. */ template <typename InValType> std::size_t read_serialized_vectors (Xdr & io, const std::vector<NumericVector<Number> *> & vectors) const; /** * Non-templated version for backward compatibility. * * Read a number of identically distributed vectors. This method * allows for optimization for the multiple vector case by only communicating * the metadata once. */ std::size_t read_serialized_vectors (Xdr & io, const std::vector<NumericVector<Number> *> & vectors) const { return read_serialized_vectors<Number>(io, vectors); } /** * Reads additional data, namely vectors, for this System. * This method may safely be called on a distributed-memory mesh. * This method will read an individual file for each processor in the simulation * where the local solution components for that processor are stored. */ template <typename InValType> void read_parallel_data (Xdr & io, const bool read_additional_data); /** * Non-templated version for backward compatibility. * * Reads additional data, namely vectors, for this System. * This method may safely be called on a distributed-memory mesh. * This method will read an individual file for each processor in the simulation * where the local solution components for that processor are stored. */ void read_parallel_data (Xdr & io, const bool read_additional_data) { read_parallel_data<Number>(io, read_additional_data); } /** * Writes the basic data header for this System. */ void write_header (Xdr & io, const std::string & version, const bool write_additional_data) const; /** * Writes additional data, namely vectors, for this System. * This method may safely be called on a distributed-memory mesh. */ void write_serialized_data (Xdr & io, const bool write_additional_data = true) const; /** * Serialize & write a number of identically distributed vectors. This method * allows for optimization for the multiple vector case by only communicating * the metadata once. */ std::size_t write_serialized_vectors (Xdr & io, const std::vector<const NumericVector<Number> *> & vectors) const; /** * Writes additional data, namely vectors, for this System. * This method may safely be called on a distributed-memory mesh. * This method will create an individual file for each processor in the simulation * where the local solution components for that processor will be stored. */ void write_parallel_data (Xdr & io, const bool write_additional_data) const; /** * @returns a string containing information about the * system. */ std::string get_info () const; /** * Register a user function to use in initializing the system. */ void attach_init_function (void fptr(EquationSystems & es, const std::string & name)); /** * Register a user class to use to initialize the system. * Note this is exclusive with the \p attach_init_function. */ void attach_init_object (Initialization & init); /** * Register a user function to use in assembling the system * matrix and RHS. */ void attach_assemble_function (void fptr(EquationSystems & es, const std::string & name)); /** * Register a user object to use in assembling the system * matrix and RHS. */ void attach_assemble_object (Assembly & assemble); /** * Register a user function for imposing constraints. */ void attach_constraint_function (void fptr(EquationSystems & es, const std::string & name)); /** * Register a user object for imposing constraints. */ void attach_constraint_object (Constraint & constrain); /** * Register a user function for evaluating the quantities of interest, * whose values should be placed in \p System::qoi */ void attach_QOI_function (void fptr(EquationSystems & es, const std::string & name, const QoISet & qoi_indices)); /** * Register a user object for evaluating the quantities of interest, * whose values should be placed in \p System::qoi */ void attach_QOI_object (QOI & qoi); /** * Register a user function for evaluating derivatives of a quantity * of interest with respect to test functions, whose values should * be placed in \p System::rhs */ void attach_QOI_derivative (void fptr(EquationSystems & es, const std::string & name, const QoISet & qoi_indices, bool include_liftfunc, bool apply_constraints)); /** * Register a user object for evaluating derivatives of a quantity * of interest with respect to test functions, whose values should * be placed in \p System::rhs */ void attach_QOI_derivative_object (QOIDerivative & qoi_derivative); /** * Calls user's attached initialization function, or is overloaded by * the user in derived classes. */ virtual void user_initialization (); /** * Calls user's attached assembly function, or is overloaded by * the user in derived classes. */ virtual void user_assembly (); /** * Calls user's attached constraint function, or is overloaded by * the user in derived classes. */ virtual void user_constrain (); /** * Calls user's attached quantity of interest function, or is * overloaded by the user in derived classes. */ virtual void user_QOI (const QoISet & qoi_indices); /** * Calls user's attached quantity of interest derivative function, * or is overloaded by the user in derived classes. */ virtual void user_QOI_derivative (const QoISet & qoi_indices = QoISet(), bool include_liftfunc = true, bool apply_constraints = true); /** * Re-update the local values when the mesh has changed. * This method takes the data updated by \p update() and * makes it up-to-date on the current mesh. */ virtual void re_update (); /** * Restrict vectors after the mesh has coarsened */ virtual void restrict_vectors (); /** * Prolong vectors after the mesh has refined */ virtual void prolong_vectors (); /** * Flag which tells the system to whether or not to * call the user assembly function during each call to solve(). * By default, every call to solve() begins with a call to the * user assemble, so this flag is true. (For explicit systems, * "solving" the system occurs during the assembly step, so this * flag is always true for explicit systems.) * * You will only want to set this to false if you need direct * control over when the system is assembled, and are willing to * track the state of its assembly yourself. An example of such a * case is an implicit system with multiple right hand sides. In * this instance, a single assembly would likely be followed with * multiple calls to solve. * * The frequency system and Newmark system have their own versions * of this flag, called _finished_assemble, which might be able to * be replaced with this more general concept. */ bool assemble_before_solve; /** * Avoids use of any cached data that might affect any solve result. Should * be overloaded in derived systems. */ virtual void disable_cache (); /** * A boolean to be set to true by systems using elem_fixed_solution, * for optional use by e.g. stabilized methods. * False by default. * * Note for FEMSystem users: * Warning: if this variable is set to true, it must be before init_data() is * called. */ bool use_fixed_solution; /** * A member int that can be employed to indicate increased or * reduced quadrature order. * * Note for FEMSystem users: * By default, when calling the user-defined residual functions, the * FEMSystem will first set up an appropriate * FEType::default_quadrature_rule() object for performing the integration. * This rule will integrate elements of order up to 2*p+1 exactly (where p is * the sum of the base FEType and local p refinement levels), but if * additional (or reduced) quadrature accuracy is desired then this * extra_quadrature_order (default 0) will be added. */ int extra_quadrature_order; //-------------------------------------------------- // The solution and solution access members /** * @returns the current solution for the specified global * DOF. */ Number current_solution (const dof_id_type global_dof_number) const; /** * Data structure to hold solution values. */ UniquePtr<NumericVector<Number> > solution; /** * All the values I need to compute my contribution * to the simulation at hand. Think of this as the * current solution with any ghost values needed from * other processors. This vector is necessarily larger * than the \p solution vector in the case of a parallel * simulation. The \p update() member is used to synchronize * the contents of the \p solution and \p current_local_solution * vectors. */ UniquePtr<NumericVector<Number> > current_local_solution; /** * For time-dependent problems, this is the time t at the beginning of * the current timestep. * * Note for DifferentiableSystem users: * do *not* access this time during an assembly! * Use the DiffContext::time value instead to get correct * results. */ Real time; /** * Values of the quantities of interest. This vector needs * to be both resized and filled by the user before any quantity of * interest assembly is done and before any sensitivities are * calculated. */ std::vector<Number> qoi; /** * Returns the value of the solution variable \p var at the physical * point \p p in the mesh, without knowing a priori which element * contains \p p. * * Note that this function uses \p MeshBase::sub_point_locator(); users * may or may not want to call \p MeshBase::clear_point_locator() * afterward. Also, point_locator() is expensive (N log N for * initial construction, log N for evaluations). Avoid using this * function in any context where you are already looping over * elements. * * Because the element containing \p p may lie on any processor, * this function is parallel-only. * * By default this method expects the point to reside inside the domain * and will abort if no element can be found which contains \p p. The * optional parameter \p insist_on_success can be set to false to allow * the method to return 0 when the point is not located. */ Number point_value(unsigned int var, const Point & p, const bool insist_on_success = true) const; /** * Returns the value of the solution variable \p var at the physical * point \p p contained in local Elem \p e * * This version of point_value can be run in serial, but assumes \p e is in * the local mesh partition. */ Number point_value(unsigned int var, const Point & p, const Elem & e) const; /** * Returns the gradient of the solution variable \p var at the physical * point \p p in the mesh, similarly to point_value. */ Gradient point_gradient(unsigned int var, const Point & p, const bool insist_on_success = true) const; /** * Returns the gradient of the solution variable \p var at the physical * point \p p in local Elem \p e in the mesh, similarly to point_value. */ Gradient point_gradient(unsigned int var, const Point & p, const Elem & e) const; /** * Returns the second derivative tensor of the solution variable \p var * at the physical point \p p in the mesh, similarly to point_value. */ Tensor point_hessian(unsigned int var, const Point & p, const bool insist_on_success = true) const; /** * Returns the second derivative tensor of the solution variable \p var * at the physical point \p p in local Elem \p e in the mesh, similarly to * point_value. */ Tensor point_hessian(unsigned int var, const Point & p, const Elem & e) const; /** * Fills the std::set with the degrees of freedom on the local * processor corresponding the the variable number passed in. */ void local_dof_indices (const unsigned int var, std::set<dof_id_type> & var_indices) const; /** * Zeroes all dofs in \p v that correspond to variable number \p * var_num. */ void zero_variable (NumericVector<Number> & v, unsigned int var_num) const; /** * Returns a writeable reference to a boolean that determines if this system * can be written to file or not. If set to \p true, then * \p EquationSystems::write will ignore this system. */ bool & hide_output() { return _hide_output; } protected: /** * Initializes the data for the system. Note that this is called * before any user-supplied intitialization function so that all * required storage will be available. */ virtual void init_data (); /** * Projects the vector defined on the old mesh onto the * new mesh. * * Constrain the new vector using the requested adjoint rather than * primal constraints if is_adjoint is non-negative. */ void project_vector (NumericVector<Number> &, int is_adjoint = -1) const; /** * Projects the vector defined on the old mesh onto the * new mesh. The original vector is unchanged and the new vector * is passed through the second argument. * * Constrain the new vector using the requested adjoint rather than * primal constraints if is_adjoint is non-negative. */ void project_vector (const NumericVector<Number> &, NumericVector<Number> &, int is_adjoint = -1) const; private: /** * This isn't a copyable object, so let's make sure nobody tries. * * We won't even bother implementing this; we'll just make sure that * the compiler doesn't implement a default. */ System (const System &); /** * This isn't a copyable object, so let's make sure nobody tries. * * We won't even bother implementing this; we'll just make sure that * the compiler doesn't implement a default. */ System & operator=(const System &); /** * Finds the discrete norm for the entries in the vector * corresponding to Dofs associated with var. */ Real discrete_var_norm (const NumericVector<Number> & v, unsigned int var, FEMNormType norm_type) const; /** * Reads an input vector from the stream \p io and assigns * the values to a set of \p DofObjects. This method uses * blocked input and is safe to call on a distributed memory-mesh. * Unless otherwise specified, all variables are read. */ template <typename iterator_type, typename InValType> std::size_t read_serialized_blocked_dof_objects (const dof_id_type n_objects, const iterator_type begin, const iterator_type end, const InValType dummy, Xdr & io, const std::vector<NumericVector<Number> *> & vecs, const unsigned int var_to_read=libMesh::invalid_uint) const; /** * Reads the SCALAR dofs from the stream \p io and assigns the values * to the appropriate entries of \p vec. * * Returns the number of dofs read. */ unsigned int read_SCALAR_dofs (const unsigned int var, Xdr & io, NumericVector<Number> & vec) const; /** * Reads a vector for this System. * This method may safely be called on a distributed-memory mesh. * * Returns the length of the vector read. */ template <typename InValType> numeric_index_type read_serialized_vector (Xdr & io, NumericVector<Number> & vec); /** * Non-templated version for backward compatibility. * * Reads a vector for this System. * This method may safely be called on a distributed-memory mesh. * * Returns the length of the vector read. */ numeric_index_type read_serialized_vector (Xdr & io, NumericVector<Number> & vec) { return read_serialized_vector<Number>(io, vec); } /** * Writes an output vector to the stream \p io for a set of \p DofObjects. * This method uses blocked output and is safe to call on a distributed memory-mesh. * * Returns the number of values written */ template <typename iterator_type> std::size_t write_serialized_blocked_dof_objects (const std::vector<const NumericVector<Number> *> & vecs, const dof_id_type n_objects, const iterator_type begin, const iterator_type end, Xdr & io, const unsigned int var_to_write=libMesh::invalid_uint) const; /** * Writes the SCALAR dofs associated with var to the stream \p io. * * Returns the number of values written. */ unsigned int write_SCALAR_dofs (const NumericVector<Number> & vec, const unsigned int var, Xdr & io) const; /** * Writes a vector for this System. * This method may safely be called on a distributed-memory mesh. * * Returns the number of values written. */ dof_id_type write_serialized_vector (Xdr & io, const NumericVector<Number> & vec) const; /** * Function that initializes the system. */ void (* _init_system_function) (EquationSystems & es, const std::string & name); /** * Object that initializes the system. */ Initialization * _init_system_object; /** * Function that assembles the system. */ void (* _assemble_system_function) (EquationSystems & es, const std::string & name); /** * Object that assembles the system. */ Assembly * _assemble_system_object; /** * Function to impose constraints. */ void (* _constrain_system_function) (EquationSystems & es, const std::string & name); /** * Object that constrains the system. */ Constraint * _constrain_system_object; /** * Function to evaluate quantity of interest */ void (* _qoi_evaluate_function) (EquationSystems & es, const std::string & name, const QoISet & qoi_indices); /** * Object to compute quantities of interest. */ QOI * _qoi_evaluate_object; /** * Function to evaluate quantity of interest derivative */ void (* _qoi_evaluate_derivative_function) (EquationSystems & es, const std::string & name, const QoISet & qoi_indices, bool include_liftfunc, bool apply_constraints); /** * Object to compute derivatives of quantities of interest. */ QOIDerivative * _qoi_evaluate_derivative_object; /** * Data structure describing the relationship between * nodes, variables, etc... and degrees of freedom. */ UniquePtr<DofMap> _dof_map; /** * Constant reference to the \p EquationSystems object * used for the simulation. */ EquationSystems & _equation_systems; /** * Constant reference to the \p mesh data structure used * for the simulation. */ MeshBase & _mesh; /** * A name associated with this system. */ const std::string _sys_name; /** * The number associated with this system */ const unsigned int _sys_number; /** * The \p Variable in this \p System. */ std::vector<Variable> _variables; /** * The \p VariableGroup in this \p System. */ std::vector<VariableGroup> _variable_groups; /** * The variable numbers corresponding to user-specified * names, useful for name-based lookups. */ std::map<std::string, unsigned short int> _variable_numbers; /** * Flag stating if the system is active or not. */ bool _active; /** * Some systems need an arbitrary number of vectors. * This map allows names to be associated with arbitrary * vectors. All the vectors in this map will be distributed * in the same way as the solution vector. */ std::map<std::string, NumericVector<Number> * > _vectors; /** * Holds true if a vector by that name should be projected * onto a changed grid, false if it should be zeroed. */ std::map<std::string, bool> _vector_projections; /** * Holds non-negative if a vector by that name should be projected * using adjoint constraints/BCs, -1 if primal */ std::map<std::string, int> _vector_is_adjoint; /** * Holds the type of a vector */ std::map<std::string, ParallelType> _vector_types; /** * Holds true if the solution vector should be projected * onto a changed grid, false if it should be zeroed. * This is true by default. */ bool _solution_projection; /** * Holds true if the components of more advanced system types (e.g. * system matrices) should not be initialized. */ bool _basic_system_only; /** * \p true when additional vectors and variables do not require * immediate initialization, \p false otherwise. */ bool _is_initialized; /** * \p true when \p VariableGroup structures should be automatically * identified, \p false otherwise. Defaults to \p true. */ bool _identify_variable_groups; /** * This flag is used only when *reading* in a system from file. * Based on the system header, it keeps track of whether or not * additional vectors were actually written for this file. */ bool _additional_data_written; /** * This vector is used only when *reading* in a system from file. * Based on the system header, it keeps track of any index remapping * between variable names in the data file and variable names in the * already-constructed system. I.e. if we have a system with * variables "A1", "A2", "B1", and "B2", but we read in a data file with * only "A1" and "B1" defined, then we don't want to try and read in * A2 or B2, and we don't want to assign A1 and B1 values to * different dof indices. */ std::vector<unsigned int> _written_var_indices; /** * Has the adjoint problem already been solved? If the user sets * \p adjoint_already_solved to \p true, we won't waste time solving * it again. */ bool adjoint_already_solved; /** * Are we allowed to write this system to file? If \p _hide_output is * \p true, then \p EquationSystems::write will ignore this system. */ bool _hide_output; }; // ------------------------------------------------------------ // System inline methods inline const std::string & System::name() const { return _sys_name; } inline unsigned int System::number() const { return _sys_number; } inline const MeshBase & System::get_mesh() const { return _mesh; } inline MeshBase & System::get_mesh() { return _mesh; } inline const DofMap & System::get_dof_map() const { return *_dof_map; } inline DofMap & System::get_dof_map() { return *_dof_map; } inline bool System::active() const { return _active; } inline void System::activate () { _active = true; } inline void System::deactivate () { _active = false; } inline bool System::is_initialized () { return _is_initialized; } inline void System::set_basic_system_only () { _basic_system_only = true; } inline unsigned int System::n_vars() const { return cast_int<unsigned int>(_variables.size()); } inline unsigned int System::n_variable_groups() const { return cast_int<unsigned int>(_variable_groups.size()); } inline unsigned int System::n_components() const { if (_variables.empty()) return 0; const Variable & last = _variables.back(); return last.first_scalar_number() + last.n_components(); } inline const Variable & System::variable (const unsigned int i) const { libmesh_assert_less (i, _variables.size()); return _variables[i]; } inline const VariableGroup & System::variable_group (const unsigned int vg) const { libmesh_assert_less (vg, _variable_groups.size()); return _variable_groups[vg]; } inline const std::string & System::variable_name (const unsigned int i) const { libmesh_assert_less (i, _variables.size()); return _variables[i].name(); } inline unsigned int System::variable_scalar_number (const std::string & var, unsigned int component) const { return variable_scalar_number(this->variable_number(var), component); } inline unsigned int System::variable_scalar_number (unsigned int var_num, unsigned int component) const { return _variables[var_num].first_scalar_number() + component; } inline const FEType & System::variable_type (const unsigned int i) const { libmesh_assert_less (i, _variables.size()); return _variables[i].type(); } inline const FEType & System::variable_type (const std::string & var) const { return _variables[this->variable_number(var)].type(); } inline bool System::identify_variable_groups () const { return _identify_variable_groups; } inline void System::identify_variable_groups (const bool ivg) { _identify_variable_groups = ivg; } inline dof_id_type System::n_active_dofs() const { return this->n_dofs() - this->n_constrained_dofs(); } inline bool System::have_vector (const std::string & vec_name) const { return (_vectors.count(vec_name)); } inline unsigned int System::n_vectors () const { return cast_int<unsigned int>(_vectors.size()); } inline unsigned int System::n_matrices () const { return 0; } inline System::vectors_iterator System::vectors_begin () { return _vectors.begin(); } inline System::const_vectors_iterator System::vectors_begin () const { return _vectors.begin(); } inline System::vectors_iterator System::vectors_end () { return _vectors.end(); } inline System::const_vectors_iterator System::vectors_end () const { return _vectors.end(); } inline void System::assemble_residual_derivatives (const ParameterVector &) { libmesh_not_implemented(); } inline void System::disable_cache () { assemble_before_solve = true; } inline std::pair<unsigned int, Real> System::sensitivity_solve (const ParameterVector &) { libmesh_not_implemented(); } inline std::pair<unsigned int, Real> System::weighted_sensitivity_solve (const ParameterVector &, const ParameterVector &) { libmesh_not_implemented(); } inline std::pair<unsigned int, Real> System::adjoint_solve (const QoISet &) { libmesh_not_implemented(); } inline std::pair<unsigned int, Real> System::weighted_sensitivity_adjoint_solve (const ParameterVector &, const ParameterVector &, const QoISet &) { libmesh_not_implemented(); } inline void System::adjoint_qoi_parameter_sensitivity (const QoISet &, const ParameterVector &, SensitivityData &) { libmesh_not_implemented(); } inline void System::forward_qoi_parameter_sensitivity (const QoISet &, const ParameterVector &, SensitivityData &) { libmesh_not_implemented(); } inline void System::qoi_parameter_hessian(const QoISet &, const ParameterVector &, SensitivityData &) { libmesh_not_implemented(); } inline void System::qoi_parameter_hessian_vector_product(const QoISet &, const ParameterVector &, const ParameterVector &, SensitivityData &) { libmesh_not_implemented(); } } // namespace libMesh #endif // LIBMESH_SYSTEM_H
Java
/** * @file llviewerdisplayname.cpp * @brief Wrapper for display name functionality * * $LicenseInfo:firstyear=2010&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * This library 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; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "llviewerdisplayname.h" // viewer includes #include "llagent.h" #include "llviewerregion.h" #include "llvoavatar.h" // library includes #include "llavatarnamecache.h" #include "llhttpclient.h" #include "llhttpnode.h" #include "llnotificationsutil.h" #include "llui.h" // getLanguage() #include "fsradar.h" #include "lggcontactsets.h" #include "llviewercontrol.h" namespace LLViewerDisplayName { // Fired when viewer receives server response to display name change set_name_signal_t sSetDisplayNameSignal; // Fired when there is a change in the agent's name name_changed_signal_t sNameChangedSignal; void addNameChangedCallback(const name_changed_signal_t::slot_type& cb) { sNameChangedSignal.connect(cb); } void doNothing() { } } class LLSetDisplayNameResponder : public LLHTTPClient::Responder { public: // only care about errors /*virtual*/ void errorWithContent(U32 status, const std::string& reason, const LLSD& content) { LL_WARNS() << "LLSetDisplayNameResponder error [status:" << status << "]: " << content << LL_ENDL; LLViewerDisplayName::sSetDisplayNameSignal(false, "", LLSD()); LLViewerDisplayName::sSetDisplayNameSignal.disconnect_all_slots(); } }; void LLViewerDisplayName::set(const std::string& display_name, const set_name_slot_t& slot) { // TODO: simple validation here LLViewerRegion* region = gAgent.getRegion(); llassert(region); std::string cap_url = region->getCapability("SetDisplayName"); if (cap_url.empty()) { // this server does not support display names, report error slot(false, "unsupported", LLSD()); return; } // People API can return localized error messages. Indicate our // language preference via header. LLSD headers; headers["Accept-Language"] = LLUI::getLanguage(); // People API requires both the old and new value to change a variable. // Our display name will be in cache before the viewer's UI is available // to request a change, so we can use direct lookup without callback. LLAvatarName av_name; if (!LLAvatarNameCache::get( gAgent.getID(), &av_name)) { slot(false, "name unavailable", LLSD()); return; } // People API expects array of [ "old value", "new value" ] LLSD change_array = LLSD::emptyArray(); change_array.append(av_name.getDisplayName()); change_array.append(display_name); LL_INFOS() << "Set name POST to " << cap_url << LL_ENDL; // Record our caller for when the server sends back a reply sSetDisplayNameSignal.connect(slot); // POST the requested change. The sim will not send a response back to // this request directly, rather it will send a separate message after it // communicates with the back-end. LLSD body; body["display_name"] = change_array; LLHTTPClient::post(cap_url, body, new LLSetDisplayNameResponder, headers); } class LLSetDisplayNameReply : public LLHTTPNode { LOG_CLASS(LLSetDisplayNameReply); public: /*virtual*/ void post( LLHTTPNode::ResponsePtr response, const LLSD& context, const LLSD& input) const { LLSD body = input["body"]; S32 status = body["status"].asInteger(); bool success = (status == 200); std::string reason = body["reason"].asString(); LLSD content = body["content"]; LL_INFOS() << "status " << status << " reason " << reason << LL_ENDL; // If viewer's concept of display name is out-of-date, the set request // will fail with 409 Conflict. If that happens, fetch up-to-date // name information. if (status == 409) { LLUUID agent_id = gAgent.getID(); // Flush stale data LLAvatarNameCache::erase( agent_id ); // Queue request for new data: nothing to do on callback though... // Note: no need to disconnect the callback as it never gets out of scope LLAvatarNameCache::get(agent_id, boost::bind(&LLViewerDisplayName::doNothing)); // Kill name tag, as it is wrong LLVOAvatar::invalidateNameTag( agent_id ); } // inform caller of result LLViewerDisplayName::sSetDisplayNameSignal(success, reason, content); LLViewerDisplayName::sSetDisplayNameSignal.disconnect_all_slots(); } }; class LLDisplayNameUpdate : public LLHTTPNode { /*virtual*/ void post( LLHTTPNode::ResponsePtr response, const LLSD& context, const LLSD& input) const { LLSD body = input["body"]; LLUUID agent_id = body["agent_id"]; std::string old_display_name = body["old_display_name"]; // By convention this record is called "agent" in the People API LLSD name_data = body["agent"]; // Inject the new name data into cache LLAvatarName av_name; av_name.fromLLSD( name_data ); LL_INFOS() << "name-update now " << LLDate::now() << " next_update " << LLDate(av_name.mNextUpdate) << LL_ENDL; // Name expiration time may be provided in headers, or we may use a // default value // *TODO: get actual headers out of ResponsePtr //LLSD headers = response->mHeaders; LLSD headers; av_name.mExpires = LLAvatarNameCache::nameExpirationFromHeaders(headers); LLAvatarNameCache::insert(agent_id, av_name); // force name tag to update LLVOAvatar::invalidateNameTag(agent_id); LLSD args; args["OLD_NAME"] = old_display_name; args["SLID"] = av_name.getUserName(); args["NEW_NAME"] = av_name.getDisplayName(); if (LGGContactSets::getInstance()->hasPseudonym(agent_id)) { LLSD payload; payload["agent_id"] = agent_id; LLNotificationsUtil::add("DisplayNameUpdateRemoveAlias", args, payload, boost::bind(&LGGContactSets::callbackAliasReset, LGGContactSets::getInstance(), _1, _2)); } else { // <FS:Ansariel> Optional hiding of display name update notification if (gSavedSettings.getBOOL("FSShowDisplayNameUpdateNotification")) { LLNotificationsUtil::add("DisplayNameUpdate", args); } // </FS:Ansariel> Optional hiding of display name update notification } if (agent_id == gAgent.getID()) { LLViewerDisplayName::sNameChangedSignal(); } // <FS:Ansariel> Update name in radar else { FSRadar* radar = FSRadar::getInstance(); if (radar) { radar->updateName(agent_id); } } // </FS:Ansariel> } }; LLHTTPRegistration<LLSetDisplayNameReply> gHTTPRegistrationMessageSetDisplayNameReply( "/message/SetDisplayNameReply"); LLHTTPRegistration<LLDisplayNameUpdate> gHTTPRegistrationMessageDisplayNameUpdate( "/message/DisplayNameUpdate");
Java
//////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2013 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import java.io.File; import org.junit.Test; /** * Test fixture for the UnnecessaryParenthesesCheck. * * @author Eric K. Roe */ public class UnnecessaryParenthesesCheckTest extends BaseCheckTestSupport { private static final String TEST_FILE = "coding" + File.separator + "InputUnnecessaryParentheses.java"; @Test public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(UnnecessaryParenthesesCheck.class); final String[] expected = { "4:22: Unnecessary parentheses around assignment right-hand side.", "4:29: Unnecessary parentheses around expression.", "4:31: Unnecessary parentheses around identifier 'i'.", "4:46: Unnecessary parentheses around assignment right-hand side.", "5:15: Unnecessary parentheses around assignment right-hand side.", "6:14: Unnecessary parentheses around identifier 'x'.", "6:17: Unnecessary parentheses around assignment right-hand side.", "7:15: Unnecessary parentheses around assignment right-hand side.", "8:14: Unnecessary parentheses around identifier 'x'.", "8:17: Unnecessary parentheses around assignment right-hand side.", "11:22: Unnecessary parentheses around assignment right-hand side.", "11:30: Unnecessary parentheses around identifier 'i'.", "11:46: Unnecessary parentheses around assignment right-hand side.", "15:17: Unnecessary parentheses around literal '0'.", "25:11: Unnecessary parentheses around assignment right-hand side.", "29:11: Unnecessary parentheses around assignment right-hand side.", "31:11: Unnecessary parentheses around assignment right-hand side.", "33:11: Unnecessary parentheses around assignment right-hand side.", "34:16: Unnecessary parentheses around identifier 'a'.", "35:14: Unnecessary parentheses around identifier 'a'.", "35:20: Unnecessary parentheses around identifier 'b'.", "35:26: Unnecessary parentheses around literal '600'.", "35:40: Unnecessary parentheses around literal '12.5f'.", "35:56: Unnecessary parentheses around identifier 'arg2'.", "36:14: Unnecessary parentheses around string \"this\".", "36:25: Unnecessary parentheses around string \"that\".", "37:11: Unnecessary parentheses around assignment right-hand side.", "37:14: Unnecessary parentheses around string \"this is a really, really...\".", "39:16: Unnecessary parentheses around return value.", "43:21: Unnecessary parentheses around literal '1'.", "43:26: Unnecessary parentheses around literal '13.5'.", "44:22: Unnecessary parentheses around literal 'true'.", "45:17: Unnecessary parentheses around identifier 'b'.", "49:17: Unnecessary parentheses around assignment right-hand side.", "51:11: Unnecessary parentheses around assignment right-hand side.", "53:16: Unnecessary parentheses around return value.", "63:13: Unnecessary parentheses around expression.", "67:16: Unnecessary parentheses around expression.", "72:19: Unnecessary parentheses around expression.", "73:23: Unnecessary parentheses around literal '4000'.", "78:19: Unnecessary parentheses around assignment right-hand side.", "80:11: Unnecessary parentheses around assignment right-hand side.", "80:16: Unnecessary parentheses around literal '3'.", "81:27: Unnecessary parentheses around assignment right-hand side.", }; verify(checkConfig, getPath(TEST_FILE), expected); } @Test public void test15Extensions() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(UnnecessaryParenthesesCheck.class); final String[] expected = {}; verify(checkConfig, getPath("Input15Extensions.java"), expected); } }
Java
/* -*-c++-*- $Id: Version,v 1.2 2004/04/20 12:26:04 andersb Exp $ */ /** * OsgHaptics - OpenSceneGraph Haptic Library * Copyright (C) 2006 VRlab, Umeå University * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ #include <osgHaptics/HapticRenderLeaf.h> #include <osgHaptics/RenderTriangleOperator.h> #include <osgHaptics/HapticRenderBin.h> #include <osgHaptics/Shape.h> #include <osgUtil/StateGraph> #include <osg/Geometry> #include <osg/TriangleFunctor> using namespace osgHaptics; void HapticRenderLeaf::render(osg::RenderInfo& renderInfo,osgUtil::RenderLeaf* previous) { // don't draw this leaf if the abort rendering flag has been set. if (renderInfo.getState()->getAbortRendering()) { //cout << "early abort"<<endl; return; } if (previous) { // apply matrices if required. renderInfo.getState()->applyProjectionMatrix(_projection.get()); renderInfo.getState()->applyModelViewMatrix(_modelview.get()); // apply state if required. osgUtil::StateGraph* prev_rg = previous->_parent; osgUtil::StateGraph* prev_rg_parent = prev_rg->_parent; osgUtil::StateGraph* rg = _parent; if (prev_rg_parent!=rg->_parent) { osgUtil::StateGraph::moveStateGraph(*renderInfo.getState(),prev_rg_parent,rg->_parent); // send state changes and matrix changes to OpenGL. renderInfo.getState()->apply(rg->_stateset.get()); } else if (rg!=prev_rg) { // send state changes and matrix changes to OpenGL. renderInfo.getState()->apply(rg->_stateset.get()); } const osgHaptics::Shape *shape = m_renderbin->getShape(renderInfo); //--by SophiaSoo/CUHK: for two arms // Does this shape contain the device currently rendered? if (!shape || !shape->containCurrentDevice()) { return; } bool render_shape=false; render_shape = !m_renderbin->hasBeenDrawn(renderInfo); // If we have a shape, // and the device is reporting, Dont render haptic shape, // then bail out and skip the rendering of this HapticRenderLeaf if (shape && !shape->getHapticDevice()->getEnableShapeRender()) return; if (shape && render_shape) { //shape = static_cast<const osgHaptics::Shape*> (sa); shape->preDraw(); } #ifdef OSGUTIL_RENDERBACKEND_USE_REF_PTR osg::Geometry* geom = dynamic_cast<osg::Geometry *>(_drawable.get()); #else osg::Geometry* geom = dynamic_cast<osg::Geometry *>(_drawable); #endif if (geom) { RenderTriangleOperator op; geom->accept(op); } else // draw the drawable { _drawable->draw(renderInfo); } if (shape && render_shape) { shape->postDraw(); } } else { std::cerr << "!!!!!!!!!!!!!!!!!!!!!!!!!!!" << std::endl; // apply matrices if required. renderInfo.getState()->applyProjectionMatrix(_projection.get()); renderInfo.getState()->applyModelViewMatrix(_modelview.get()); // apply state if required. osgUtil::StateGraph::moveStateGraph(*renderInfo.getState(),NULL,_parent->_parent); #ifdef OSGUTIL_RENDERBACKEND_USE_REF_PTR renderInfo.getState()->apply(_parent->_stateset.get()); #else renderInfo.getState()->apply(_parent->_stateset); #endif // draw the drawable _drawable->draw(renderInfo); } }
Java
/***************************************************************** JADE - Java Agent DEvelopment Framework is a framework to develop multi-agent systems in compliance with the FIPA specifications. Copyright (C) 2000 CSELT S.p.A. GNU Lesser General Public License This library 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, version 2.1 of the License. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *****************************************************************/ package jade.core; //#APIDOC_EXCLUDE_FILE import jade.util.leap.Serializable; import jade.security.JADEPrincipal; import jade.security.Credentials; /** The <code>NodeDescriptor</code> class serves as a meta-level description of a kernel-level service. Instances of this class contain a <code>Node</code> object, along with its name and properties, and are used in service management operations, as well as in agent-level introspection of platform-level entities. @author Giovanni Rimassa - FRAMeTech s.r.l. @see Node */ public class NodeDescriptor implements Serializable { /** Builds a new node descriptor, describing the given node with the given name and properties. @param nn The name of the described node. @param node The described <code>Node</code> object. */ public NodeDescriptor(Node node) { myName = node.getName(); myNode = node; } /** Builds a node descriptor for a node hosting an agent container. @param cid The container ID for the hosted container. @param node The described <code>Node</code> object. @param principal The principal of the node owner. @param credentials The credentials of the node owner. */ public NodeDescriptor(ContainerID cid, Node node) { myName = cid.getName(); myNode = node; myContainer = cid; } /** Builds an uninitialized node descriptor. @see NodeDescriptor#setName(String sn) @see NodeDescriptor#setNode(Node node) */ public NodeDescriptor() { } /** Change the name (if any) of the described node. @param nn The name to assign to the described node. */ public void setName(String nn) { myName = nn; } /** Retrieve the name (if any) of the described node. @return The name of the described node, or <code>null</code> if no name was set. */ public String getName() { return myName; } /** Change the described node (if any). @param node The <code>Node</code> object that is to be described by this node descriptor. */ public void setNode(Node node) { myNode = node; } /** Retrieve the described node. @return The <code>Node</code> object described by this node descriptor, or <code>null</code> if no node was set. */ public Node getNode() { return myNode; } /** Retrieve the ID of the container (if any) hosted by the described node. @return The <code>ContainerID</code> of the hosted container, or <code>null</code> if no such container was set. */ public ContainerID getContainer() { return myContainer; } public void setParentNode(Node n) { parentNode = n; } public Node getParentNode() { return parentNode; } /** Set the username of the owner of the described node */ public void setUsername(String username) { this.username = username; } /** Retrieve the username of the owner of the described node */ public String getUsername() { return username; } /** Set the password of the owner of the described node */ public void setPassword(byte[] password) { this.password = password; } /** Retrieve the password of the owner of the described node */ public byte[] getPassword() { return password; } /** Set the principal of the described node */ public void setPrincipal(JADEPrincipal principal) { myPrincipal = principal; } /** Retrieve the principal of the described node */ public JADEPrincipal getPrincipal() { return myPrincipal; } /** Set the principal of the owner of this node */ public void setOwnerPrincipal(JADEPrincipal principal) { ownerPrincipal = principal; } /** Retrieve the principal of the owner of this node (if any) @return The principal of the owner of this node, or <code>null</code> if no principal was set. */ public JADEPrincipal getOwnerPrincipal() { return ownerPrincipal; } /** Set the credentials of the owner of this node */ public void setOwnerCredentials(Credentials credentials) { ownerCredentials = credentials; } /** Retrieve the credentials of the owner of this node (if any) @return The credentials of the owner of this node, or <code>null</code> if no credentials were set. */ public Credentials getOwnerCredentials() { return ownerCredentials; } private String myName; private Node myNode; private Node parentNode; private ContainerID myContainer; private String username; private byte[] password; private JADEPrincipal myPrincipal; private JADEPrincipal ownerPrincipal; private Credentials ownerCredentials; }
Java
/*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998-2007 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <gadget/gadgetConfig.h> #include <boost/concept_check.hpp> #include <vpr/Util/Debug.h> #include <vpr/IO/ObjectWriter.h> #include <vpr/IO/ObjectReader.h> #include <gadget/Type/Command.h> namespace gadget { const CommandData Command::getCommandData(int devNum) { SampleBuffer_t::buffer_t& stable_buffer = mCommandSamples.stableBuffer(); if ( (!stable_buffer.empty()) && (stable_buffer.back().size() > (unsigned)devNum) ) // If Have entry && devNum in range { return stable_buffer.back()[devNum]; } else // No data or request out of range, return default value { if ( stable_buffer.empty() ) { vprDEBUG(vprDBG_ALL, vprDBG_WARNING_LVL) << "WARNING: [gadget::Command::getCommandData()] " << "Stable buffer is empty. If this is not the first " << "read, then this is a problem.\n" << vprDEBUG_FLUSH; } else { vprDEBUG(vprDBG_ALL, vprDBG_CONFIG_LVL) << "WARNING: [gadget::Command::getCommandData()] " << "Requested devNum (" << devNum << ") is not in the range available. " << "This is probably a configuration error.\n" << vprDEBUG_FLUSH; } return mDefaultValue; } } void Command::writeObject(vpr::ObjectWriter* writer) { writer->beginTag(Command::getInputTypeName()); SampleBuffer_t::buffer_t& stable_buffer = mCommandSamples.stableBuffer(); writer->beginAttribute(gadget::tokens::DataTypeAttrib); // Write out the data type so that we can assert if reading in wrong // place. writer->writeUint16(MSG_DATA_COMMAND); writer->endAttribute(); writer->beginAttribute(gadget::tokens::SampleBufferLenAttrib); // Write the # of vectors in the stable buffer. writer->writeUint16(stable_buffer.size()); writer->endAttribute(); if ( !stable_buffer.empty() ) { mCommandSamples.lock(); for ( unsigned j = 0; j < stable_buffer.size(); ++j ) // For each vector in the stable buffer { writer->beginTag(gadget::tokens::BufferSampleTag); writer->beginAttribute(gadget::tokens::BufferSampleLenAttrib); writer->writeUint16(stable_buffer[j].size()); // Write the # of CommandDatas in the vector writer->endAttribute(); for ( unsigned i = 0; i < stable_buffer[j].size(); ++i ) // For each CommandData in the vector { writer->beginTag(gadget::tokens::DigitalValue); writer->beginAttribute(gadget::tokens::TimeStamp); writer->writeUint64(stable_buffer[j][i].getTime().usec()); // Write Time Stamp vpr::Uint64 writer->endAttribute(); writer->writeUint32((vpr::Uint32)stable_buffer[j][i].getDigital()); // Write Command Data(int) writer->endTag(); } writer->endTag(); } mCommandSamples.unlock(); } writer->endTag(); } void Command::readObject(vpr::ObjectReader* reader) { vprASSERT(reader->attribExists("rim.timestamp.delta")); vpr::Uint64 delta = reader->getAttrib<vpr::Uint64>("rim.timestamp.delta"); // ASSERT if this data is really not Command Data reader->beginTag(Command::getInputTypeName()); reader->beginAttribute(gadget::tokens::DataTypeAttrib); vpr::Uint16 temp = reader->readUint16(); reader->endAttribute(); // XXX: Should there be error checking for the case when vprASSERT() // is compiled out? -PH 8/21/2003 vprASSERT(temp==MSG_DATA_COMMAND && "[Remote Input Manager]Not Command Data"); boost::ignore_unused_variable_warning(temp); std::vector<CommandData> dataSample; unsigned numCommandDatas; vpr::Uint32 value; vpr::Uint64 timeStamp; CommandData temp_command_data; reader->beginAttribute(gadget::tokens::SampleBufferLenAttrib); unsigned numVectors = reader->readUint16(); reader->endAttribute(); mCommandSamples.lock(); for ( unsigned i = 0; i < numVectors; ++i ) { reader->beginTag(gadget::tokens::BufferSampleTag); reader->beginAttribute(gadget::tokens::BufferSampleLenAttrib); numCommandDatas = reader->readUint16(); reader->endAttribute(); dataSample.clear(); for ( unsigned j = 0; j < numCommandDatas; ++j ) { reader->beginTag(gadget::tokens::DigitalValue); reader->beginAttribute(gadget::tokens::TimeStamp); timeStamp = reader->readUint64(); // read Time Stamp vpr::Uint64 reader->endAttribute(); value = reader->readUint32(); // read Command Data(int) reader->endTag(); temp_command_data.setDigital(value); temp_command_data.setTime(vpr::Interval(timeStamp + delta,vpr::Interval::Usec)); dataSample.push_back(temp_command_data); } mCommandSamples.addSample(dataSample); reader->endTag(); } mCommandSamples.unlock(); mCommandSamples.swapBuffers(); reader->endTag(); } } // End of gadget namespace
Java
/** * OpenAL cross platform audio library * Copyright (C) 1999-2007 by authors. * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * Or go to http://www.gnu.org/copyleft/lgpl.html */ #include "config.h" #include <math.h> #include <stdlib.h> #include <stdio.h> #include <memory.h> #include <ctype.h> #include <signal.h> #include "alMain.h" #include "alSource.h" #include "AL/al.h" #include "AL/alc.h" #include "alThunk.h" #include "alSource.h" #include "alBuffer.h" #include "alAuxEffectSlot.h" #include "alError.h" #include "bs2b.h" #include "alu.h" /************************************************ * Backends ************************************************/ #define EmptyFuncs { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL } static struct BackendInfo BackendList[] = { #ifdef HAVE_PULSEAUDIO { "pulse", alc_pulse_init, alc_pulse_deinit, alc_pulse_probe, EmptyFuncs }, #endif #ifdef HAVE_ALSA { "alsa", alc_alsa_init, alc_alsa_deinit, alc_alsa_probe, EmptyFuncs }, #endif #ifdef HAVE_COREAUDIO { "core", alc_ca_init, alc_ca_deinit, alc_ca_probe, EmptyFuncs }, #endif #ifdef HAVE_OSS { "oss", alc_oss_init, alc_oss_deinit, alc_oss_probe, EmptyFuncs }, #endif #ifdef HAVE_SOLARIS { "solaris", alc_solaris_init, alc_solaris_deinit, alc_solaris_probe, EmptyFuncs }, #endif #ifdef HAVE_SNDIO { "sndio", alc_sndio_init, alc_sndio_deinit, alc_sndio_probe, EmptyFuncs }, #endif #ifdef HAVE_MMDEVAPI { "mmdevapi", alcMMDevApiInit, alcMMDevApiDeinit, alcMMDevApiProbe, EmptyFuncs }, #endif #ifdef HAVE_DSOUND { "dsound", alcDSoundInit, alcDSoundDeinit, alcDSoundProbe, EmptyFuncs }, #endif #ifdef HAVE_WINMM { "winmm", alcWinMMInit, alcWinMMDeinit, alcWinMMProbe, EmptyFuncs }, #endif #ifdef HAVE_PORTAUDIO { "port", alc_pa_init, alc_pa_deinit, alc_pa_probe, EmptyFuncs }, #endif #ifdef HAVE_OPENSL { "opensl", alc_opensl_init, alc_opensl_deinit, alc_opensl_probe, EmptyFuncs }, #endif { "null", alc_null_init, alc_null_deinit, alc_null_probe, EmptyFuncs }, #ifdef HAVE_WAVE { "wave", alc_wave_init, alc_wave_deinit, alc_wave_probe, EmptyFuncs }, #endif { NULL, NULL, NULL, NULL, EmptyFuncs } }; static struct BackendInfo BackendLoopback = { "loopback", alc_loopback_init, alc_loopback_deinit, alc_loopback_probe, EmptyFuncs }; #undef EmptyFuncs static struct BackendInfo PlaybackBackend; static struct BackendInfo CaptureBackend; /************************************************ * Functions, enums, and errors ************************************************/ typedef struct ALCfunction { const ALCchar *funcName; ALCvoid *address; } ALCfunction; typedef struct ALCenums { const ALCchar *enumName; ALCenum value; } ALCenums; #define DECL(x) { #x, (ALCvoid*)(x) } static const ALCfunction alcFunctions[] = { DECL(alcCreateContext), DECL(alcMakeContextCurrent), DECL(alcProcessContext), DECL(alcSuspendContext), DECL(alcDestroyContext), DECL(alcGetCurrentContext), DECL(alcGetContextsDevice), DECL(alcOpenDevice), DECL(alcCloseDevice), DECL(alcGetError), DECL(alcIsExtensionPresent), DECL(alcGetProcAddress), DECL(alcGetEnumValue), DECL(alcGetString), DECL(alcGetIntegerv), DECL(alcCaptureOpenDevice), DECL(alcCaptureCloseDevice), DECL(alcCaptureStart), DECL(alcCaptureStop), DECL(alcCaptureSamples), DECL(alcSetThreadContext), DECL(alcGetThreadContext), DECL(alcLoopbackOpenDeviceSOFT), DECL(alcIsRenderFormatSupportedSOFT), DECL(alcRenderSamplesSOFT), DECL(alEnable), DECL(alDisable), DECL(alIsEnabled), DECL(alGetString), DECL(alGetBooleanv), DECL(alGetIntegerv), DECL(alGetFloatv), DECL(alGetDoublev), DECL(alGetBoolean), DECL(alGetInteger), DECL(alGetFloat), DECL(alGetDouble), DECL(alGetError), DECL(alIsExtensionPresent), DECL(alGetProcAddress), DECL(alGetEnumValue), DECL(alListenerf), DECL(alListener3f), DECL(alListenerfv), DECL(alListeneri), DECL(alListener3i), DECL(alListeneriv), DECL(alGetListenerf), DECL(alGetListener3f), DECL(alGetListenerfv), DECL(alGetListeneri), DECL(alGetListener3i), DECL(alGetListeneriv), DECL(alGenSources), DECL(alDeleteSources), DECL(alIsSource), DECL(alSourcef), DECL(alSource3f), DECL(alSourcefv), DECL(alSourcei), DECL(alSource3i), DECL(alSourceiv), DECL(alGetSourcef), DECL(alGetSource3f), DECL(alGetSourcefv), DECL(alGetSourcei), DECL(alGetSource3i), DECL(alGetSourceiv), DECL(alSourcePlayv), DECL(alSourceStopv), DECL(alSourceRewindv), DECL(alSourcePausev), DECL(alSourcePlay), DECL(alSourceStop), DECL(alSourceRewind), DECL(alSourcePause), DECL(alSourceQueueBuffers), DECL(alSourceUnqueueBuffers), DECL(alGenBuffers), DECL(alDeleteBuffers), DECL(alIsBuffer), DECL(alBufferData), DECL(alBufferf), DECL(alBuffer3f), DECL(alBufferfv), DECL(alBufferi), DECL(alBuffer3i), DECL(alBufferiv), DECL(alGetBufferf), DECL(alGetBuffer3f), DECL(alGetBufferfv), DECL(alGetBufferi), DECL(alGetBuffer3i), DECL(alGetBufferiv), DECL(alDopplerFactor), DECL(alDopplerVelocity), DECL(alSpeedOfSound), DECL(alDistanceModel), DECL(alGenFilters), DECL(alDeleteFilters), DECL(alIsFilter), DECL(alFilteri), DECL(alFilteriv), DECL(alFilterf), DECL(alFilterfv), DECL(alGetFilteri), DECL(alGetFilteriv), DECL(alGetFilterf), DECL(alGetFilterfv), DECL(alGenEffects), DECL(alDeleteEffects), DECL(alIsEffect), DECL(alEffecti), DECL(alEffectiv), DECL(alEffectf), DECL(alEffectfv), DECL(alGetEffecti), DECL(alGetEffectiv), DECL(alGetEffectf), DECL(alGetEffectfv), DECL(alGenAuxiliaryEffectSlots), DECL(alDeleteAuxiliaryEffectSlots), DECL(alIsAuxiliaryEffectSlot), DECL(alAuxiliaryEffectSloti), DECL(alAuxiliaryEffectSlotiv), DECL(alAuxiliaryEffectSlotf), DECL(alAuxiliaryEffectSlotfv), DECL(alGetAuxiliaryEffectSloti), DECL(alGetAuxiliaryEffectSlotiv), DECL(alGetAuxiliaryEffectSlotf), DECL(alGetAuxiliaryEffectSlotfv), DECL(alBufferSubDataSOFT), DECL(alBufferSamplesSOFT), DECL(alBufferSubSamplesSOFT), DECL(alGetBufferSamplesSOFT), DECL(alIsBufferFormatSupportedSOFT), DECL(alDeferUpdatesSOFT), DECL(alProcessUpdatesSOFT), DECL(alGetSourcedSOFT), DECL(alGetSource3dSOFT), DECL(alGetSourcedvSOFT), DECL(alGetSourcei64SOFT), DECL(alGetSource3i64SOFT), DECL(alGetSourcei64vSOFT), { NULL, NULL } }; #undef DECL #define DECL(x) { #x, (x) } static const ALCenums enumeration[] = { DECL(ALC_INVALID), DECL(ALC_FALSE), DECL(ALC_TRUE), DECL(ALC_MAJOR_VERSION), DECL(ALC_MINOR_VERSION), DECL(ALC_ATTRIBUTES_SIZE), DECL(ALC_ALL_ATTRIBUTES), DECL(ALC_DEFAULT_DEVICE_SPECIFIER), DECL(ALC_DEVICE_SPECIFIER), DECL(ALC_ALL_DEVICES_SPECIFIER), DECL(ALC_DEFAULT_ALL_DEVICES_SPECIFIER), DECL(ALC_EXTENSIONS), DECL(ALC_FREQUENCY), DECL(ALC_REFRESH), DECL(ALC_SYNC), DECL(ALC_MONO_SOURCES), DECL(ALC_STEREO_SOURCES), DECL(ALC_CAPTURE_DEVICE_SPECIFIER), DECL(ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER), DECL(ALC_CAPTURE_SAMPLES), DECL(ALC_CONNECTED), DECL(ALC_EFX_MAJOR_VERSION), DECL(ALC_EFX_MINOR_VERSION), DECL(ALC_MAX_AUXILIARY_SENDS), DECL(ALC_FORMAT_CHANNELS_SOFT), DECL(ALC_FORMAT_TYPE_SOFT), DECL(ALC_MONO_SOFT), DECL(ALC_STEREO_SOFT), DECL(ALC_QUAD_SOFT), DECL(ALC_5POINT1_SOFT), DECL(ALC_6POINT1_SOFT), DECL(ALC_7POINT1_SOFT), DECL(ALC_BYTE_SOFT), DECL(ALC_UNSIGNED_BYTE_SOFT), DECL(ALC_SHORT_SOFT), DECL(ALC_UNSIGNED_SHORT_SOFT), DECL(ALC_INT_SOFT), DECL(ALC_UNSIGNED_INT_SOFT), DECL(ALC_FLOAT_SOFT), DECL(ALC_NO_ERROR), DECL(ALC_INVALID_DEVICE), DECL(ALC_INVALID_CONTEXT), DECL(ALC_INVALID_ENUM), DECL(ALC_INVALID_VALUE), DECL(ALC_OUT_OF_MEMORY), DECL(AL_INVALID), DECL(AL_NONE), DECL(AL_FALSE), DECL(AL_TRUE), DECL(AL_SOURCE_RELATIVE), DECL(AL_CONE_INNER_ANGLE), DECL(AL_CONE_OUTER_ANGLE), DECL(AL_PITCH), DECL(AL_POSITION), DECL(AL_DIRECTION), DECL(AL_VELOCITY), DECL(AL_LOOPING), DECL(AL_BUFFER), DECL(AL_GAIN), DECL(AL_MIN_GAIN), DECL(AL_MAX_GAIN), DECL(AL_ORIENTATION), DECL(AL_REFERENCE_DISTANCE), DECL(AL_ROLLOFF_FACTOR), DECL(AL_CONE_OUTER_GAIN), DECL(AL_MAX_DISTANCE), DECL(AL_SEC_OFFSET), DECL(AL_SAMPLE_OFFSET), DECL(AL_SAMPLE_RW_OFFSETS_SOFT), DECL(AL_BYTE_OFFSET), DECL(AL_BYTE_RW_OFFSETS_SOFT), DECL(AL_SOURCE_TYPE), DECL(AL_STATIC), DECL(AL_STREAMING), DECL(AL_UNDETERMINED), DECL(AL_METERS_PER_UNIT), DECL(AL_DIRECT_CHANNELS_SOFT), DECL(AL_DIRECT_FILTER), DECL(AL_AUXILIARY_SEND_FILTER), DECL(AL_AIR_ABSORPTION_FACTOR), DECL(AL_ROOM_ROLLOFF_FACTOR), DECL(AL_CONE_OUTER_GAINHF), DECL(AL_DIRECT_FILTER_GAINHF_AUTO), DECL(AL_AUXILIARY_SEND_FILTER_GAIN_AUTO), DECL(AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO), DECL(AL_SOURCE_STATE), DECL(AL_INITIAL), DECL(AL_PLAYING), DECL(AL_PAUSED), DECL(AL_STOPPED), DECL(AL_BUFFERS_QUEUED), DECL(AL_BUFFERS_PROCESSED), DECL(AL_FORMAT_MONO8), DECL(AL_FORMAT_MONO16), DECL(AL_FORMAT_MONO_FLOAT32), DECL(AL_FORMAT_MONO_DOUBLE_EXT), DECL(AL_FORMAT_STEREO8), DECL(AL_FORMAT_STEREO16), DECL(AL_FORMAT_STEREO_FLOAT32), DECL(AL_FORMAT_STEREO_DOUBLE_EXT), DECL(AL_FORMAT_MONO_IMA4), DECL(AL_FORMAT_STEREO_IMA4), DECL(AL_FORMAT_QUAD8_LOKI), DECL(AL_FORMAT_QUAD16_LOKI), DECL(AL_FORMAT_QUAD8), DECL(AL_FORMAT_QUAD16), DECL(AL_FORMAT_QUAD32), DECL(AL_FORMAT_51CHN8), DECL(AL_FORMAT_51CHN16), DECL(AL_FORMAT_51CHN32), DECL(AL_FORMAT_61CHN8), DECL(AL_FORMAT_61CHN16), DECL(AL_FORMAT_61CHN32), DECL(AL_FORMAT_71CHN8), DECL(AL_FORMAT_71CHN16), DECL(AL_FORMAT_71CHN32), DECL(AL_FORMAT_REAR8), DECL(AL_FORMAT_REAR16), DECL(AL_FORMAT_REAR32), DECL(AL_FORMAT_MONO_MULAW), DECL(AL_FORMAT_MONO_MULAW_EXT), DECL(AL_FORMAT_STEREO_MULAW), DECL(AL_FORMAT_STEREO_MULAW_EXT), DECL(AL_FORMAT_QUAD_MULAW), DECL(AL_FORMAT_51CHN_MULAW), DECL(AL_FORMAT_61CHN_MULAW), DECL(AL_FORMAT_71CHN_MULAW), DECL(AL_FORMAT_REAR_MULAW), DECL(AL_FORMAT_MONO_ALAW_EXT), DECL(AL_FORMAT_STEREO_ALAW_EXT), DECL(AL_MONO8_SOFT), DECL(AL_MONO16_SOFT), DECL(AL_MONO32F_SOFT), DECL(AL_STEREO8_SOFT), DECL(AL_STEREO16_SOFT), DECL(AL_STEREO32F_SOFT), DECL(AL_QUAD8_SOFT), DECL(AL_QUAD16_SOFT), DECL(AL_QUAD32F_SOFT), DECL(AL_REAR8_SOFT), DECL(AL_REAR16_SOFT), DECL(AL_REAR32F_SOFT), DECL(AL_5POINT1_8_SOFT), DECL(AL_5POINT1_16_SOFT), DECL(AL_5POINT1_32F_SOFT), DECL(AL_6POINT1_8_SOFT), DECL(AL_6POINT1_16_SOFT), DECL(AL_6POINT1_32F_SOFT), DECL(AL_7POINT1_8_SOFT), DECL(AL_7POINT1_16_SOFT), DECL(AL_7POINT1_32F_SOFT), DECL(AL_MONO_SOFT), DECL(AL_STEREO_SOFT), DECL(AL_QUAD_SOFT), DECL(AL_REAR_SOFT), DECL(AL_5POINT1_SOFT), DECL(AL_6POINT1_SOFT), DECL(AL_7POINT1_SOFT), DECL(AL_BYTE_SOFT), DECL(AL_UNSIGNED_BYTE_SOFT), DECL(AL_SHORT_SOFT), DECL(AL_UNSIGNED_SHORT_SOFT), DECL(AL_INT_SOFT), DECL(AL_UNSIGNED_INT_SOFT), DECL(AL_FLOAT_SOFT), DECL(AL_DOUBLE_SOFT), DECL(AL_BYTE3_SOFT), DECL(AL_UNSIGNED_BYTE3_SOFT), DECL(AL_FREQUENCY), DECL(AL_BITS), DECL(AL_CHANNELS), DECL(AL_SIZE), DECL(AL_INTERNAL_FORMAT_SOFT), DECL(AL_BYTE_LENGTH_SOFT), DECL(AL_SAMPLE_LENGTH_SOFT), DECL(AL_SEC_LENGTH_SOFT), DECL(AL_UNUSED), DECL(AL_PENDING), DECL(AL_PROCESSED), DECL(AL_NO_ERROR), DECL(AL_INVALID_NAME), DECL(AL_INVALID_ENUM), DECL(AL_INVALID_VALUE), DECL(AL_INVALID_OPERATION), DECL(AL_OUT_OF_MEMORY), DECL(AL_VENDOR), DECL(AL_VERSION), DECL(AL_RENDERER), DECL(AL_EXTENSIONS), DECL(AL_DOPPLER_FACTOR), DECL(AL_DOPPLER_VELOCITY), DECL(AL_DISTANCE_MODEL), DECL(AL_SPEED_OF_SOUND), DECL(AL_SOURCE_DISTANCE_MODEL), DECL(AL_DEFERRED_UPDATES_SOFT), DECL(AL_INVERSE_DISTANCE), DECL(AL_INVERSE_DISTANCE_CLAMPED), DECL(AL_LINEAR_DISTANCE), DECL(AL_LINEAR_DISTANCE_CLAMPED), DECL(AL_EXPONENT_DISTANCE), DECL(AL_EXPONENT_DISTANCE_CLAMPED), DECL(AL_FILTER_TYPE), DECL(AL_FILTER_NULL), DECL(AL_FILTER_LOWPASS), #if 0 DECL(AL_FILTER_HIGHPASS), DECL(AL_FILTER_BANDPASS), #endif DECL(AL_LOWPASS_GAIN), DECL(AL_LOWPASS_GAINHF), DECL(AL_EFFECT_TYPE), DECL(AL_EFFECT_NULL), DECL(AL_EFFECT_REVERB), DECL(AL_EFFECT_EAXREVERB), #if 0 DECL(AL_EFFECT_CHORUS), DECL(AL_EFFECT_DISTORTION), #endif DECL(AL_EFFECT_ECHO), #if 0 DECL(AL_EFFECT_FLANGER), DECL(AL_EFFECT_FREQUENCY_SHIFTER), DECL(AL_EFFECT_VOCAL_MORPHER), DECL(AL_EFFECT_PITCH_SHIFTER), #endif DECL(AL_EFFECT_RING_MODULATOR), #if 0 DECL(AL_EFFECT_AUTOWAH), DECL(AL_EFFECT_COMPRESSOR), DECL(AL_EFFECT_EQUALIZER), #endif DECL(AL_EFFECT_DEDICATED_LOW_FREQUENCY_EFFECT), DECL(AL_EFFECT_DEDICATED_DIALOGUE), DECL(AL_EAXREVERB_DENSITY), DECL(AL_EAXREVERB_DIFFUSION), DECL(AL_EAXREVERB_GAIN), DECL(AL_EAXREVERB_GAINHF), DECL(AL_EAXREVERB_GAINLF), DECL(AL_EAXREVERB_DECAY_TIME), DECL(AL_EAXREVERB_DECAY_HFRATIO), DECL(AL_EAXREVERB_DECAY_LFRATIO), DECL(AL_EAXREVERB_REFLECTIONS_GAIN), DECL(AL_EAXREVERB_REFLECTIONS_DELAY), DECL(AL_EAXREVERB_REFLECTIONS_PAN), DECL(AL_EAXREVERB_LATE_REVERB_GAIN), DECL(AL_EAXREVERB_LATE_REVERB_DELAY), DECL(AL_EAXREVERB_LATE_REVERB_PAN), DECL(AL_EAXREVERB_ECHO_TIME), DECL(AL_EAXREVERB_ECHO_DEPTH), DECL(AL_EAXREVERB_MODULATION_TIME), DECL(AL_EAXREVERB_MODULATION_DEPTH), DECL(AL_EAXREVERB_AIR_ABSORPTION_GAINHF), DECL(AL_EAXREVERB_HFREFERENCE), DECL(AL_EAXREVERB_LFREFERENCE), DECL(AL_EAXREVERB_ROOM_ROLLOFF_FACTOR), DECL(AL_EAXREVERB_DECAY_HFLIMIT), DECL(AL_REVERB_DENSITY), DECL(AL_REVERB_DIFFUSION), DECL(AL_REVERB_GAIN), DECL(AL_REVERB_GAINHF), DECL(AL_REVERB_DECAY_TIME), DECL(AL_REVERB_DECAY_HFRATIO), DECL(AL_REVERB_REFLECTIONS_GAIN), DECL(AL_REVERB_REFLECTIONS_DELAY), DECL(AL_REVERB_LATE_REVERB_GAIN), DECL(AL_REVERB_LATE_REVERB_DELAY), DECL(AL_REVERB_AIR_ABSORPTION_GAINHF), DECL(AL_REVERB_ROOM_ROLLOFF_FACTOR), DECL(AL_REVERB_DECAY_HFLIMIT), DECL(AL_ECHO_DELAY), DECL(AL_ECHO_LRDELAY), DECL(AL_ECHO_DAMPING), DECL(AL_ECHO_FEEDBACK), DECL(AL_ECHO_SPREAD), DECL(AL_RING_MODULATOR_FREQUENCY), DECL(AL_RING_MODULATOR_HIGHPASS_CUTOFF), DECL(AL_RING_MODULATOR_WAVEFORM), DECL(AL_DEDICATED_GAIN), { NULL, (ALCenum)0 } }; #undef DECL static const ALCchar alcNoError[] = "No Error"; static const ALCchar alcErrInvalidDevice[] = "Invalid Device"; static const ALCchar alcErrInvalidContext[] = "Invalid Context"; static const ALCchar alcErrInvalidEnum[] = "Invalid Enum"; static const ALCchar alcErrInvalidValue[] = "Invalid Value"; static const ALCchar alcErrOutOfMemory[] = "Out of Memory"; /************************************************ * Global variables ************************************************/ /* Enumerated device names */ static const ALCchar alcDefaultName[] = "OpenAL Soft\0"; static ALCchar *alcAllDevicesList; static ALCchar *alcCaptureDeviceList; /* Sizes only include the first ending null character, not the second */ static size_t alcAllDevicesListSize; static size_t alcCaptureDeviceListSize; /* Default is always the first in the list */ static ALCchar *alcDefaultAllDevicesSpecifier; static ALCchar *alcCaptureDefaultDeviceSpecifier; /* Default context extensions */ static const ALchar alExtList[] = "AL_EXT_ALAW AL_EXT_DOUBLE AL_EXT_EXPONENT_DISTANCE AL_EXT_FLOAT32 " "AL_EXT_IMA4 AL_EXT_LINEAR_DISTANCE AL_EXT_MCFORMATS AL_EXT_MULAW " "AL_EXT_MULAW_MCFORMATS AL_EXT_OFFSET AL_EXT_source_distance_model " "AL_LOKI_quadriphonic AL_SOFT_buffer_samples AL_SOFT_buffer_sub_data " "AL_SOFTX_deferred_updates AL_SOFT_direct_channels AL_SOFT_loop_points"; static volatile ALCenum LastNullDeviceError = ALC_NO_ERROR; /* Thread-local current context */ static pthread_key_t LocalContext; /* Process-wide current context */ static ALCcontext *volatile GlobalContext = NULL; /* Mixing thread piority level */ ALint RTPrioLevel; FILE *LogFile; #ifdef _DEBUG enum LogLevel LogLevel = LogWarning; #else enum LogLevel LogLevel = LogError; #endif /* Flag to trap ALC device errors */ static ALCboolean TrapALCError = ALC_FALSE; /* One-time configuration init control */ static pthread_once_t alc_config_once = PTHREAD_ONCE_INIT; /* Default effect that applies to sources that don't have an effect on send 0 */ static ALeffect DefaultEffect; /************************************************ * ALC information ************************************************/ static const ALCchar alcNoDeviceExtList[] = "ALC_ENUMERATE_ALL_EXT ALC_ENUMERATION_EXT ALC_EXT_CAPTURE " "ALC_EXT_thread_local_context ALC_SOFT_loopback"; static const ALCchar alcExtensionList[] = "ALC_ENUMERATE_ALL_EXT ALC_ENUMERATION_EXT ALC_EXT_CAPTURE " "ALC_EXT_DEDICATED ALC_EXT_disconnect ALC_EXT_EFX " "ALC_EXT_thread_local_context ALC_SOFT_loopback"; static const ALCint alcMajorVersion = 1; static const ALCint alcMinorVersion = 1; static const ALCint alcEFXMajorVersion = 1; static const ALCint alcEFXMinorVersion = 0; /************************************************ * Device lists ************************************************/ static ALCdevice *volatile DeviceList = NULL; static CRITICAL_SECTION ListLock; static void LockLists(void) { EnterCriticalSection(&ListLock); } static void UnlockLists(void) { LeaveCriticalSection(&ListLock); } /************************************************ * Library initialization ************************************************/ #if defined(_WIN32) static void alc_init(void); static void alc_deinit(void); static void alc_deinit_safe(void); UIntMap TlsDestructor; #ifndef AL_LIBTYPE_STATIC BOOL APIENTRY DllMain(HINSTANCE hModule,DWORD ul_reason_for_call,LPVOID lpReserved) { ALsizei i; // Perform actions based on the reason for calling. switch(ul_reason_for_call) { case DLL_PROCESS_ATTACH: /* Pin the DLL so we won't get unloaded until the process terminates */ GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_PIN | GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (WCHAR*)hModule, &hModule); InitUIntMap(&TlsDestructor, ~0); alc_init(); break; case DLL_THREAD_DETACH: LockUIntMapRead(&TlsDestructor); for(i = 0;i < TlsDestructor.size;i++) { void *ptr = pthread_getspecific(TlsDestructor.array[i].key); void (*callback)(void*) = (void(*)(void*))TlsDestructor.array[i].value; if(ptr && callback) callback(ptr); } UnlockUIntMapRead(&TlsDestructor); break; case DLL_PROCESS_DETACH: if(!lpReserved) alc_deinit(); else alc_deinit_safe(); ResetUIntMap(&TlsDestructor); break; } return TRUE; } #elif defined(_MSC_VER) #pragma section(".CRT$XCU",read) static void alc_constructor(void); static void alc_destructor(void); __declspec(allocate(".CRT$XCU")) void (__cdecl* alc_constructor_)(void) = alc_constructor; static void alc_constructor(void) { atexit(alc_destructor); alc_init(); } static void alc_destructor(void) { alc_deinit(); } #elif defined(HAVE_GCC_DESTRUCTOR) static void alc_init(void) __attribute__((constructor)); static void alc_deinit(void) __attribute__((destructor)); #else #error "No static initialization available on this platform!" #endif #elif defined(HAVE_GCC_DESTRUCTOR) static void alc_init(void) __attribute__((constructor)); static void alc_deinit(void) __attribute__((destructor)); #else #error "No global initialization available on this platform!" #endif static void ReleaseThreadCtx(void *ptr); static void alc_init(void) { const char *str; LogFile = stderr; str = getenv("__ALSOFT_HALF_ANGLE_CONES"); if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1)) ConeScale *= 0.5f; str = getenv("__ALSOFT_REVERSE_Z"); if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1)) ZScale *= -1.0f; pthread_key_create(&LocalContext, ReleaseThreadCtx); InitializeCriticalSection(&ListLock); ThunkInit(); } static void alc_initconfig(void) { const char *devs, *str; ALuint capfilter; float valf; int i, n; str = getenv("ALSOFT_LOGLEVEL"); if(str) { long lvl = strtol(str, NULL, 0); if(lvl >= NoLog && lvl <= LogRef) LogLevel = lvl; } str = getenv("ALSOFT_LOGFILE"); if(str && str[0]) { FILE *logfile = fopen(str, "wat"); if(logfile) LogFile = logfile; else ERR("Failed to open log file '%s'\n", str); } ReadALConfig(); capfilter = 0; #ifdef HAVE_SSE capfilter |= CPU_CAP_SSE; #endif #ifdef HAVE_NEON capfilter |= CPU_CAP_NEON; #endif if(ConfigValueStr(NULL, "disable-cpu-exts", &str)) { if(strcasecmp(str, "all") == 0) capfilter = 0; else { size_t len; const char *next = str; i = 0; do { str = next; next = strchr(str, ','); while(isspace(str[0])) str++; if(!str[0] || str[0] == ',') continue; len = (next ? ((size_t)(next-str)) : strlen(str)); if(strncasecmp(str, "sse", len) == 0) capfilter &= ~CPU_CAP_SSE; else if(strncasecmp(str, "neon", len) == 0) capfilter &= ~CPU_CAP_NEON; else WARN("Invalid CPU extension \"%s\"\n", str); } while(next++); } } FillCPUCaps(capfilter); #ifdef _WIN32 RTPrioLevel = 1; #else RTPrioLevel = 0; #endif ConfigValueInt(NULL, "rt-prio", &RTPrioLevel); if(ConfigValueStr(NULL, "resampler", &str)) { if(strcasecmp(str, "point") == 0 || strcasecmp(str, "none") == 0) DefaultResampler = PointResampler; else if(strcasecmp(str, "linear") == 0) DefaultResampler = LinearResampler; else if(strcasecmp(str, "cubic") == 0) DefaultResampler = CubicResampler; else { char *end; n = strtol(str, &end, 0); if(*end == '\0' && (n == PointResampler || n == LinearResampler || n == CubicResampler)) DefaultResampler = n; else WARN("Invalid resampler: %s\n", str); } } str = getenv("ALSOFT_TRAP_ERROR"); if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1)) { TrapALError = AL_TRUE; TrapALCError = AL_TRUE; } else { str = getenv("ALSOFT_TRAP_AL_ERROR"); if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1)) TrapALError = AL_TRUE; TrapALError = GetConfigValueBool(NULL, "trap-al-error", TrapALError); str = getenv("ALSOFT_TRAP_ALC_ERROR"); if(str && (strcasecmp(str, "true") == 0 || strtol(str, NULL, 0) == 1)) TrapALCError = ALC_TRUE; TrapALCError = GetConfigValueBool(NULL, "trap-alc-error", TrapALCError); } if(ConfigValueFloat("reverb", "boost", &valf)) ReverbBoost *= powf(10.0f, valf / 20.0f); EmulateEAXReverb = GetConfigValueBool("reverb", "emulate-eax", AL_FALSE); if(((devs=getenv("ALSOFT_DRIVERS")) && devs[0]) || ConfigValueStr(NULL, "drivers", &devs)) { int n; size_t len; const char *next = devs; int endlist, delitem; i = 0; do { devs = next; next = strchr(devs, ','); delitem = (devs[0] == '-'); if(devs[0] == '-') devs++; if(!devs[0] || devs[0] == ',') { endlist = 0; continue; } endlist = 1; len = (next ? ((size_t)(next-devs)) : strlen(devs)); for(n = i;BackendList[n].Init;n++) { if(len == strlen(BackendList[n].name) && strncmp(BackendList[n].name, devs, len) == 0) { if(delitem) { do { BackendList[n] = BackendList[n+1]; ++n; } while(BackendList[n].Init); } else { struct BackendInfo Bkp = BackendList[n]; while(n > i) { BackendList[n] = BackendList[n-1]; --n; } BackendList[n] = Bkp; i++; } break; } } } while(next++); if(endlist) { BackendList[i].name = NULL; BackendList[i].Init = NULL; BackendList[i].Deinit = NULL; BackendList[i].Probe = NULL; } } for(i = 0;BackendList[i].Init && (!PlaybackBackend.name || !CaptureBackend.name);i++) { if(!BackendList[i].Init(&BackendList[i].Funcs)) { WARN("Failed to initialize backend \"%s\"\n", BackendList[i].name); continue; } TRACE("Initialized backend \"%s\"\n", BackendList[i].name); if(BackendList[i].Funcs.OpenPlayback && !PlaybackBackend.name) { PlaybackBackend = BackendList[i]; TRACE("Added \"%s\" for playback\n", PlaybackBackend.name); } if(BackendList[i].Funcs.OpenCapture && !CaptureBackend.name) { CaptureBackend = BackendList[i]; TRACE("Added \"%s\" for capture\n", CaptureBackend.name); } } BackendLoopback.Init(&BackendLoopback.Funcs); if(ConfigValueStr(NULL, "excludefx", &str)) { size_t len; const char *next = str; do { str = next; next = strchr(str, ','); if(!str[0] || next == str) continue; len = (next ? ((size_t)(next-str)) : strlen(str)); for(n = 0;EffectList[n].name;n++) { if(len == strlen(EffectList[n].name) && strncmp(EffectList[n].name, str, len) == 0) DisabledEffects[EffectList[n].type] = AL_TRUE; } } while(next++); } InitEffect(&DefaultEffect); str = getenv("ALSOFT_DEFAULT_REVERB"); if((str && str[0]) || ConfigValueStr(NULL, "default-reverb", &str)) LoadReverbPreset(str, &DefaultEffect); } #define DO_INITCONFIG() pthread_once(&alc_config_once, alc_initconfig) /************************************************ * Library deinitialization ************************************************/ static void alc_cleanup(void) { ALCdevice *dev; free(alcAllDevicesList); alcAllDevicesList = NULL; alcAllDevicesListSize = 0; free(alcCaptureDeviceList); alcCaptureDeviceList = NULL; alcCaptureDeviceListSize = 0; free(alcDefaultAllDevicesSpecifier); alcDefaultAllDevicesSpecifier = NULL; free(alcCaptureDefaultDeviceSpecifier); alcCaptureDefaultDeviceSpecifier = NULL; if((dev=ExchangePtr((XchgPtr*)&DeviceList, NULL)) != NULL) { ALCuint num = 0; do { num++; } while((dev=dev->next) != NULL); ERR("%u device%s not closed\n", num, (num>1)?"s":""); } } static void alc_deinit_safe(void) { alc_cleanup(); FreeHrtfs(); FreeALConfig(); ThunkExit(); DeleteCriticalSection(&ListLock); pthread_key_delete(LocalContext); if(LogFile != stderr) fclose(LogFile); LogFile = NULL; } static void alc_deinit(void) { int i; alc_cleanup(); memset(&PlaybackBackend, 0, sizeof(PlaybackBackend)); memset(&CaptureBackend, 0, sizeof(CaptureBackend)); for(i = 0;BackendList[i].Deinit;i++) BackendList[i].Deinit(); BackendLoopback.Deinit(); alc_deinit_safe(); } /************************************************ * Device enumeration ************************************************/ static void ProbeList(ALCchar **list, size_t *listsize, enum DevProbe type) { DO_INITCONFIG(); LockLists(); free(*list); *list = NULL; *listsize = 0; if(type == ALL_DEVICE_PROBE && PlaybackBackend.Probe) PlaybackBackend.Probe(type); else if(type == CAPTURE_DEVICE_PROBE && CaptureBackend.Probe) CaptureBackend.Probe(type); UnlockLists(); } static void ProbeAllDevicesList(void) { ProbeList(&alcAllDevicesList, &alcAllDevicesListSize, ALL_DEVICE_PROBE); } static void ProbeCaptureDeviceList(void) { ProbeList(&alcCaptureDeviceList, &alcCaptureDeviceListSize, CAPTURE_DEVICE_PROBE); } static void AppendList(const ALCchar *name, ALCchar **List, size_t *ListSize) { size_t len = strlen(name); void *temp; if(len == 0) return; temp = realloc(*List, (*ListSize) + len + 2); if(!temp) { ERR("Realloc failed to add %s!\n", name); return; } *List = temp; memcpy((*List)+(*ListSize), name, len+1); *ListSize += len+1; (*List)[*ListSize] = 0; } #define DECL_APPEND_LIST_FUNC(type) \ void Append##type##List(const ALCchar *name) \ { AppendList(name, &alc##type##List, &alc##type##ListSize); } DECL_APPEND_LIST_FUNC(AllDevices) DECL_APPEND_LIST_FUNC(CaptureDevice) #undef DECL_APPEND_LIST_FUNC /************************************************ * Device format information ************************************************/ const ALCchar *DevFmtTypeString(enum DevFmtType type) { switch(type) { case DevFmtByte: return "Signed Byte"; case DevFmtUByte: return "Unsigned Byte"; case DevFmtShort: return "Signed Short"; case DevFmtUShort: return "Unsigned Short"; case DevFmtInt: return "Signed Int"; case DevFmtUInt: return "Unsigned Int"; case DevFmtFloat: return "Float"; } return "(unknown type)"; } const ALCchar *DevFmtChannelsString(enum DevFmtChannels chans) { switch(chans) { case DevFmtMono: return "Mono"; case DevFmtStereo: return "Stereo"; case DevFmtQuad: return "Quadraphonic"; case DevFmtX51: return "5.1 Surround"; case DevFmtX51Side: return "5.1 Side"; case DevFmtX61: return "6.1 Surround"; case DevFmtX71: return "7.1 Surround"; } return "(unknown channels)"; } ALuint BytesFromDevFmt(enum DevFmtType type) { switch(type) { case DevFmtByte: return sizeof(ALbyte); case DevFmtUByte: return sizeof(ALubyte); case DevFmtShort: return sizeof(ALshort); case DevFmtUShort: return sizeof(ALushort); case DevFmtInt: return sizeof(ALint); case DevFmtUInt: return sizeof(ALuint); case DevFmtFloat: return sizeof(ALfloat); } return 0; } ALuint ChannelsFromDevFmt(enum DevFmtChannels chans) { switch(chans) { case DevFmtMono: return 1; case DevFmtStereo: return 2; case DevFmtQuad: return 4; case DevFmtX51: return 6; case DevFmtX51Side: return 6; case DevFmtX61: return 7; case DevFmtX71: return 8; } return 0; } static ALboolean DecomposeDevFormat(ALenum format, enum DevFmtChannels *chans, enum DevFmtType *type) { static const struct { ALenum format; enum DevFmtChannels channels; enum DevFmtType type; } list[] = { { AL_FORMAT_MONO8, DevFmtMono, DevFmtUByte }, { AL_FORMAT_MONO16, DevFmtMono, DevFmtShort }, { AL_FORMAT_MONO_FLOAT32, DevFmtMono, DevFmtFloat }, { AL_FORMAT_STEREO8, DevFmtStereo, DevFmtUByte }, { AL_FORMAT_STEREO16, DevFmtStereo, DevFmtShort }, { AL_FORMAT_STEREO_FLOAT32, DevFmtStereo, DevFmtFloat }, { AL_FORMAT_QUAD8, DevFmtQuad, DevFmtUByte }, { AL_FORMAT_QUAD16, DevFmtQuad, DevFmtShort }, { AL_FORMAT_QUAD32, DevFmtQuad, DevFmtFloat }, { AL_FORMAT_51CHN8, DevFmtX51, DevFmtUByte }, { AL_FORMAT_51CHN16, DevFmtX51, DevFmtShort }, { AL_FORMAT_51CHN32, DevFmtX51, DevFmtFloat }, { AL_FORMAT_61CHN8, DevFmtX61, DevFmtUByte }, { AL_FORMAT_61CHN16, DevFmtX61, DevFmtShort }, { AL_FORMAT_61CHN32, DevFmtX61, DevFmtFloat }, { AL_FORMAT_71CHN8, DevFmtX71, DevFmtUByte }, { AL_FORMAT_71CHN16, DevFmtX71, DevFmtShort }, { AL_FORMAT_71CHN32, DevFmtX71, DevFmtFloat }, }; ALuint i; for(i = 0;i < COUNTOF(list);i++) { if(list[i].format == format) { *chans = list[i].channels; *type = list[i].type; return AL_TRUE; } } return AL_FALSE; } static ALCboolean IsValidALCType(ALCenum type) { switch(type) { case ALC_BYTE_SOFT: case ALC_UNSIGNED_BYTE_SOFT: case ALC_SHORT_SOFT: case ALC_UNSIGNED_SHORT_SOFT: case ALC_INT_SOFT: case ALC_UNSIGNED_INT_SOFT: case ALC_FLOAT_SOFT: return ALC_TRUE; } return ALC_FALSE; } static ALCboolean IsValidALCChannels(ALCenum channels) { switch(channels) { case ALC_MONO_SOFT: case ALC_STEREO_SOFT: case ALC_QUAD_SOFT: case ALC_5POINT1_SOFT: case ALC_6POINT1_SOFT: case ALC_7POINT1_SOFT: return ALC_TRUE; } return ALC_FALSE; } /************************************************ * Miscellaneous ALC helpers ************************************************/ void ALCdevice_LockDefault(ALCdevice *device) { EnterCriticalSection(&device->Mutex); } void ALCdevice_UnlockDefault(ALCdevice *device) { LeaveCriticalSection(&device->Mutex); } ALint64 ALCdevice_GetLatencyDefault(ALCdevice *device) { (void)device; return 0; } /* SetDefaultWFXChannelOrder * * Sets the default channel order used by WaveFormatEx. */ void SetDefaultWFXChannelOrder(ALCdevice *device) { switch(device->FmtChans) { case DevFmtMono: device->DevChannels[0] = FrontCenter; break; case DevFmtStereo: device->DevChannels[0] = FrontLeft; device->DevChannels[1] = FrontRight; break; case DevFmtQuad: device->DevChannels[0] = FrontLeft; device->DevChannels[1] = FrontRight; device->DevChannels[2] = BackLeft; device->DevChannels[3] = BackRight; break; case DevFmtX51: device->DevChannels[0] = FrontLeft; device->DevChannels[1] = FrontRight; device->DevChannels[2] = FrontCenter; device->DevChannels[3] = LFE; device->DevChannels[4] = BackLeft; device->DevChannels[5] = BackRight; break; case DevFmtX51Side: device->DevChannels[0] = FrontLeft; device->DevChannels[1] = FrontRight; device->DevChannels[2] = FrontCenter; device->DevChannels[3] = LFE; device->DevChannels[4] = SideLeft; device->DevChannels[5] = SideRight; break; case DevFmtX61: device->DevChannels[0] = FrontLeft; device->DevChannels[1] = FrontRight; device->DevChannels[2] = FrontCenter; device->DevChannels[3] = LFE; device->DevChannels[4] = BackCenter; device->DevChannels[5] = SideLeft; device->DevChannels[6] = SideRight; break; case DevFmtX71: device->DevChannels[0] = FrontLeft; device->DevChannels[1] = FrontRight; device->DevChannels[2] = FrontCenter; device->DevChannels[3] = LFE; device->DevChannels[4] = BackLeft; device->DevChannels[5] = BackRight; device->DevChannels[6] = SideLeft; device->DevChannels[7] = SideRight; break; } } /* SetDefaultChannelOrder * * Sets the default channel order used by most non-WaveFormatEx-based APIs. */ void SetDefaultChannelOrder(ALCdevice *device) { switch(device->FmtChans) { case DevFmtX51: device->DevChannels[0] = FrontLeft; device->DevChannels[1] = FrontRight; device->DevChannels[2] = BackLeft; device->DevChannels[3] = BackRight; device->DevChannels[4] = FrontCenter; device->DevChannels[5] = LFE; return; case DevFmtX71: device->DevChannels[0] = FrontLeft; device->DevChannels[1] = FrontRight; device->DevChannels[2] = BackLeft; device->DevChannels[3] = BackRight; device->DevChannels[4] = FrontCenter; device->DevChannels[5] = LFE; device->DevChannels[6] = SideLeft; device->DevChannels[7] = SideRight; return; /* Same as WFX order */ case DevFmtMono: case DevFmtStereo: case DevFmtQuad: case DevFmtX51Side: case DevFmtX61: break; } SetDefaultWFXChannelOrder(device); } /* alcSetError * * Stores the latest ALC device error */ static void alcSetError(ALCdevice *device, ALCenum errorCode) { if(TrapALCError) { #ifdef _WIN32 /* DebugBreak() will cause an exception if there is no debugger */ if(IsDebuggerPresent()) DebugBreak(); #elif defined(SIGTRAP) raise(SIGTRAP); #endif } if(device) device->LastError = errorCode; else LastNullDeviceError = errorCode; } /* UpdateDeviceParams * * Updates device parameters according to the attribute list (caller is * responsible for holding the list lock). */ static ALCenum UpdateDeviceParams(ALCdevice *device, const ALCint *attrList) { ALCcontext *context; enum DevFmtChannels oldChans; enum DevFmtType oldType; ALCuint oldFreq; FPUCtl oldMode; ALuint i; // Check for attributes if(device->Type == Loopback) { enum { GotFreq = 1<<0, GotChans = 1<<1, GotType = 1<<2, GotAll = GotFreq|GotChans|GotType }; ALCuint freq, numMono, numStereo, numSends; enum DevFmtChannels schans; enum DevFmtType stype; ALCuint attrIdx = 0; ALCint gotFmt = 0; if(!attrList) { WARN("Missing attributes for loopback device\n"); return ALC_INVALID_VALUE; } numMono = device->NumMonoSources; numStereo = device->NumStereoSources; numSends = device->NumAuxSends; schans = device->FmtChans; stype = device->FmtType; freq = device->Frequency; while(attrList[attrIdx]) { if(attrList[attrIdx] == ALC_FORMAT_CHANNELS_SOFT) { ALCint val = attrList[attrIdx + 1]; if(!IsValidALCChannels(val) || !ChannelsFromDevFmt(val)) return ALC_INVALID_VALUE; schans = val; gotFmt |= GotChans; } if(attrList[attrIdx] == ALC_FORMAT_TYPE_SOFT) { ALCint val = attrList[attrIdx + 1]; if(!IsValidALCType(val) || !BytesFromDevFmt(val)) return ALC_INVALID_VALUE; stype = val; gotFmt |= GotType; } if(attrList[attrIdx] == ALC_FREQUENCY) { freq = attrList[attrIdx + 1]; if(freq < MIN_OUTPUT_RATE) return ALC_INVALID_VALUE; gotFmt |= GotFreq; } if(attrList[attrIdx] == ALC_STEREO_SOURCES) { numStereo = attrList[attrIdx + 1]; if(numStereo > device->MaxNoOfSources) numStereo = device->MaxNoOfSources; numMono = device->MaxNoOfSources - numStereo; } if(attrList[attrIdx] == ALC_MAX_AUXILIARY_SENDS) numSends = attrList[attrIdx + 1]; attrIdx += 2; } if(gotFmt != GotAll) { WARN("Missing format for loopback device\n"); return ALC_INVALID_VALUE; } ConfigValueUInt(NULL, "sends", &numSends); numSends = minu(MAX_SENDS, numSends); if((device->Flags&DEVICE_RUNNING)) ALCdevice_StopPlayback(device); device->Flags &= ~DEVICE_RUNNING; device->Frequency = freq; device->FmtChans = schans; device->FmtType = stype; device->NumMonoSources = numMono; device->NumStereoSources = numStereo; device->NumAuxSends = numSends; } else if(attrList && attrList[0]) { ALCuint freq, numMono, numStereo, numSends; ALCuint attrIdx = 0; /* If a context is already running on the device, stop playback so the * device attributes can be updated. */ if((device->Flags&DEVICE_RUNNING)) ALCdevice_StopPlayback(device); device->Flags &= ~DEVICE_RUNNING; freq = device->Frequency; numMono = device->NumMonoSources; numStereo = device->NumStereoSources; numSends = device->NumAuxSends; while(attrList[attrIdx]) { if(attrList[attrIdx] == ALC_FREQUENCY) { freq = attrList[attrIdx + 1]; device->Flags |= DEVICE_FREQUENCY_REQUEST; } if(attrList[attrIdx] == ALC_STEREO_SOURCES) { numStereo = attrList[attrIdx + 1]; if(numStereo > device->MaxNoOfSources) numStereo = device->MaxNoOfSources; numMono = device->MaxNoOfSources - numStereo; } if(attrList[attrIdx] == ALC_MAX_AUXILIARY_SENDS) numSends = attrList[attrIdx + 1]; attrIdx += 2; } ConfigValueUInt(NULL, "frequency", &freq); freq = maxu(freq, MIN_OUTPUT_RATE); ConfigValueUInt(NULL, "sends", &numSends); numSends = minu(MAX_SENDS, numSends); device->UpdateSize = (ALuint64)device->UpdateSize * freq / device->Frequency; /* SSE does best with the update size being a multiple of 4 */ if((CPUCapFlags&CPU_CAP_SSE)) device->UpdateSize = (device->UpdateSize+3)&~3; device->Frequency = freq; device->NumMonoSources = numMono; device->NumStereoSources = numStereo; device->NumAuxSends = numSends; } if((device->Flags&DEVICE_RUNNING)) return ALC_NO_ERROR; oldFreq = device->Frequency; oldChans = device->FmtChans; oldType = device->FmtType; TRACE("Format pre-setup: %s%s, %s%s, %uhz%s, %u update size x%d\n", DevFmtChannelsString(device->FmtChans), (device->Flags&DEVICE_CHANNELS_REQUEST)?" (requested)":"", DevFmtTypeString(device->FmtType), (device->Flags&DEVICE_SAMPLE_TYPE_REQUEST)?" (requested)":"", device->Frequency, (device->Flags&DEVICE_FREQUENCY_REQUEST)?" (requested)":"", device->UpdateSize, device->NumUpdates); if(ALCdevice_ResetPlayback(device) == ALC_FALSE) return ALC_INVALID_DEVICE; if(device->FmtChans != oldChans && (device->Flags&DEVICE_CHANNELS_REQUEST)) { ERR("Failed to set %s, got %s instead\n", DevFmtChannelsString(oldChans), DevFmtChannelsString(device->FmtChans)); device->Flags &= ~DEVICE_CHANNELS_REQUEST; } if(device->FmtType != oldType && (device->Flags&DEVICE_SAMPLE_TYPE_REQUEST)) { ERR("Failed to set %s, got %s instead\n", DevFmtTypeString(oldType), DevFmtTypeString(device->FmtType)); device->Flags &= ~DEVICE_SAMPLE_TYPE_REQUEST; } if(device->Frequency != oldFreq && (device->Flags&DEVICE_FREQUENCY_REQUEST)) { ERR("Failed to set %uhz, got %uhz instead\n", oldFreq, device->Frequency); device->Flags &= ~DEVICE_FREQUENCY_REQUEST; } TRACE("Format post-setup: %s, %s, %uhz, %u update size x%d\n", DevFmtChannelsString(device->FmtChans), DevFmtTypeString(device->FmtType), device->Frequency, device->UpdateSize, device->NumUpdates); aluInitPanning(device); for(i = 0;i < MaxChannels;i++) { device->ClickRemoval[i] = 0.0f; device->PendingClicks[i] = 0.0f; } device->Hrtf = NULL; if(device->Type != Loopback && GetConfigValueBool(NULL, "hrtf", AL_FALSE)) device->Hrtf = GetHrtf(device); TRACE("HRTF %s\n", device->Hrtf?"enabled":"disabled"); if(!device->Hrtf && device->Bs2bLevel > 0 && device->Bs2bLevel <= 6) { if(!device->Bs2b) { device->Bs2b = calloc(1, sizeof(*device->Bs2b)); bs2b_clear(device->Bs2b); } bs2b_set_srate(device->Bs2b, device->Frequency); bs2b_set_level(device->Bs2b, device->Bs2bLevel); TRACE("BS2B level %d\n", device->Bs2bLevel); } else { free(device->Bs2b); device->Bs2b = NULL; TRACE("BS2B disabled\n"); } device->Flags &= ~DEVICE_WIDE_STEREO; if(device->Type != Loopback && !device->Hrtf && GetConfigValueBool(NULL, "wide-stereo", AL_FALSE)) device->Flags |= DEVICE_WIDE_STEREO; if(!device->Hrtf && (device->UpdateSize&3)) { if((CPUCapFlags&CPU_CAP_SSE)) WARN("SSE performs best with multiple of 4 update sizes (%u)\n", device->UpdateSize); } SetMixerFPUMode(&oldMode); ALCdevice_Lock(device); context = device->ContextList; while(context) { ALsizei pos; context->UpdateSources = AL_FALSE; LockUIntMapRead(&context->EffectSlotMap); for(pos = 0;pos < context->EffectSlotMap.size;pos++) { ALeffectslot *slot = context->EffectSlotMap.array[pos].value; if(ALeffectState_DeviceUpdate(slot->EffectState, device) == AL_FALSE) { UnlockUIntMapRead(&context->EffectSlotMap); ALCdevice_Unlock(device); RestoreFPUMode(&oldMode); return ALC_INVALID_DEVICE; } slot->NeedsUpdate = AL_FALSE; ALeffectState_Update(slot->EffectState, device, slot); } UnlockUIntMapRead(&context->EffectSlotMap); LockUIntMapRead(&context->SourceMap); for(pos = 0;pos < context->SourceMap.size;pos++) { ALsource *source = context->SourceMap.array[pos].value; ALuint s = device->NumAuxSends; while(s < MAX_SENDS) { if(source->Send[s].Slot) DecrementRef(&source->Send[s].Slot->ref); source->Send[s].Slot = NULL; source->Send[s].Gain = 1.0f; source->Send[s].GainHF = 1.0f; s++; } source->NeedsUpdate = AL_FALSE; ALsource_Update(source, context); } UnlockUIntMapRead(&context->SourceMap); context = context->next; } if(device->DefaultSlot) { ALeffectslot *slot = device->DefaultSlot; if(ALeffectState_DeviceUpdate(slot->EffectState, device) == AL_FALSE) { ALCdevice_Unlock(device); RestoreFPUMode(&oldMode); return ALC_INVALID_DEVICE; } slot->NeedsUpdate = AL_FALSE; ALeffectState_Update(slot->EffectState, device, slot); } ALCdevice_Unlock(device); RestoreFPUMode(&oldMode); if(ALCdevice_StartPlayback(device) == ALC_FALSE) return ALC_INVALID_DEVICE; device->Flags |= DEVICE_RUNNING; return ALC_NO_ERROR; } /* FreeDevice * * Frees the device structure, and destroys any objects the app failed to * delete. Called once there's no more references on the device. */ static ALCvoid FreeDevice(ALCdevice *device) { TRACE("%p\n", device); if(device->Type != Capture) ALCdevice_ClosePlayback(device); else ALCdevice_CloseCapture(device); if(device->DefaultSlot) { ALeffectState_Destroy(device->DefaultSlot->EffectState); device->DefaultSlot->EffectState = NULL; } if(device->BufferMap.size > 0) { WARN("(%p) Deleting %d Buffer(s)\n", device, device->BufferMap.size); ReleaseALBuffers(device); } ResetUIntMap(&device->BufferMap); if(device->EffectMap.size > 0) { WARN("(%p) Deleting %d Effect(s)\n", device, device->EffectMap.size); ReleaseALEffects(device); } ResetUIntMap(&device->EffectMap); if(device->FilterMap.size > 0) { WARN("(%p) Deleting %d Filter(s)\n", device, device->FilterMap.size); ReleaseALFilters(device); } ResetUIntMap(&device->FilterMap); free(device->Bs2b); device->Bs2b = NULL; free(device->DeviceName); device->DeviceName = NULL; DeleteCriticalSection(&device->Mutex); al_free(device); } void ALCdevice_IncRef(ALCdevice *device) { RefCount ref; ref = IncrementRef(&device->ref); TRACEREF("%p increasing refcount to %u\n", device, ref); } void ALCdevice_DecRef(ALCdevice *device) { RefCount ref; ref = DecrementRef(&device->ref); TRACEREF("%p decreasing refcount to %u\n", device, ref); if(ref == 0) FreeDevice(device); } /* VerifyDevice * * Checks if the device handle is valid, and increments its ref count if so. */ static ALCdevice *VerifyDevice(ALCdevice *device) { ALCdevice *tmpDevice; if(!device) return NULL; LockLists(); tmpDevice = DeviceList; while(tmpDevice && tmpDevice != device) tmpDevice = tmpDevice->next; if(tmpDevice) ALCdevice_IncRef(tmpDevice); UnlockLists(); return tmpDevice; } /* InitContext * * Initializes context fields */ static ALvoid InitContext(ALCcontext *Context) { ALint i, j; //Initialise listener Context->Listener.Gain = 1.0f; Context->Listener.MetersPerUnit = 1.0f; Context->Listener.Position[0] = 0.0f; Context->Listener.Position[1] = 0.0f; Context->Listener.Position[2] = 0.0f; Context->Listener.Velocity[0] = 0.0f; Context->Listener.Velocity[1] = 0.0f; Context->Listener.Velocity[2] = 0.0f; Context->Listener.Forward[0] = 0.0f; Context->Listener.Forward[1] = 0.0f; Context->Listener.Forward[2] = -1.0f; Context->Listener.Up[0] = 0.0f; Context->Listener.Up[1] = 1.0f; Context->Listener.Up[2] = 0.0f; for(i = 0;i < 4;i++) { for(j = 0;j < 4;j++) Context->Listener.Matrix[i][j] = ((i==j) ? 1.0f : 0.0f); } //Validate Context Context->LastError = AL_NO_ERROR; Context->UpdateSources = AL_FALSE; Context->ActiveSourceCount = 0; InitUIntMap(&Context->SourceMap, Context->Device->MaxNoOfSources); InitUIntMap(&Context->EffectSlotMap, Context->Device->AuxiliaryEffectSlotMax); //Set globals Context->DistanceModel = AL_INVERSE_DISTANCE_CLAMPED; Context->SourceDistanceModel = AL_FALSE; Context->DopplerFactor = 1.0f; Context->DopplerVelocity = 1.0f; Context->SpeedOfSound = SPEEDOFSOUNDMETRESPERSEC; Context->DeferUpdates = AL_FALSE; Context->ExtensionList = alExtList; } /* FreeContext * * Cleans up the context, and destroys any remaining objects the app failed to * delete. Called once there's no more references on the context. */ static ALCvoid FreeContext(ALCcontext *context) { TRACE("%p\n", context); if(context->SourceMap.size > 0) { ERR("(%p) Deleting %d Source(s)\n", context, context->SourceMap.size); ReleaseALSources(context); } ResetUIntMap(&context->SourceMap); if(context->EffectSlotMap.size > 0) { ERR("(%p) Deleting %d AuxiliaryEffectSlot(s)\n", context, context->EffectSlotMap.size); ReleaseALAuxiliaryEffectSlots(context); } ResetUIntMap(&context->EffectSlotMap); context->ActiveSourceCount = 0; free(context->ActiveSources); context->ActiveSources = NULL; context->MaxActiveSources = 0; context->ActiveEffectSlotCount = 0; free(context->ActiveEffectSlots); context->ActiveEffectSlots = NULL; context->MaxActiveEffectSlots = 0; ALCdevice_DecRef(context->Device); context->Device = NULL; //Invalidate context memset(context, 0, sizeof(ALCcontext)); free(context); } /* ReleaseContext * * Removes the context reference from the given device and removes it from * being current on the running thread or globally. */ static void ReleaseContext(ALCcontext *context, ALCdevice *device) { ALCcontext *volatile*tmp_ctx; if(pthread_getspecific(LocalContext) == context) { WARN("%p released while current on thread\n", context); pthread_setspecific(LocalContext, NULL); ALCcontext_DecRef(context); } if(CompExchangePtr((XchgPtr*)&GlobalContext, context, NULL)) ALCcontext_DecRef(context); ALCdevice_Lock(device); tmp_ctx = &device->ContextList; while(*tmp_ctx) { if(CompExchangePtr((XchgPtr*)tmp_ctx, context, context->next)) break; tmp_ctx = &(*tmp_ctx)->next; } ALCdevice_Unlock(device); ALCcontext_DecRef(context); } void ALCcontext_IncRef(ALCcontext *context) { RefCount ref; ref = IncrementRef(&context->ref); TRACEREF("%p increasing refcount to %u\n", context, ref); } void ALCcontext_DecRef(ALCcontext *context) { RefCount ref; ref = DecrementRef(&context->ref); TRACEREF("%p decreasing refcount to %u\n", context, ref); if(ref == 0) FreeContext(context); } static void ReleaseThreadCtx(void *ptr) { WARN("%p current for thread being destroyed\n", ptr); ALCcontext_DecRef(ptr); } /* VerifyContext * * Checks that the given context is valid, and increments its reference count. */ static ALCcontext *VerifyContext(ALCcontext *context) { ALCdevice *dev; LockLists(); dev = DeviceList; while(dev) { ALCcontext *tmp_ctx = dev->ContextList; while(tmp_ctx) { if(tmp_ctx == context) { ALCcontext_IncRef(tmp_ctx); UnlockLists(); return tmp_ctx; } tmp_ctx = tmp_ctx->next; } dev = dev->next; } UnlockLists(); return NULL; } /* GetContextRef * * Returns the currently active context for this thread, and adds a reference * without locking it. */ ALCcontext *GetContextRef(void) { ALCcontext *context; context = pthread_getspecific(LocalContext); if(context) ALCcontext_IncRef(context); else { LockLists(); context = GlobalContext; if(context) ALCcontext_IncRef(context); UnlockLists(); } return context; } /************************************************ * Standard ALC functions ************************************************/ /* alcGetError * * Return last ALC generated error code for the given device */ ALC_API ALCenum ALC_APIENTRY alcGetError(ALCdevice *device) { ALCenum errorCode; if(VerifyDevice(device)) { errorCode = ExchangeInt(&device->LastError, ALC_NO_ERROR); ALCdevice_DecRef(device); } else errorCode = ExchangeInt(&LastNullDeviceError, ALC_NO_ERROR); return errorCode; } /* alcSuspendContext * * Not functional */ ALC_API ALCvoid ALC_APIENTRY alcSuspendContext(ALCcontext *Context) { (void)Context; } /* alcProcessContext * * Not functional */ ALC_API ALCvoid ALC_APIENTRY alcProcessContext(ALCcontext *Context) { (void)Context; } /* alcGetString * * Returns information about the device, and error strings */ ALC_API const ALCchar* ALC_APIENTRY alcGetString(ALCdevice *Device, ALCenum param) { const ALCchar *value = NULL; switch(param) { case ALC_NO_ERROR: value = alcNoError; break; case ALC_INVALID_ENUM: value = alcErrInvalidEnum; break; case ALC_INVALID_VALUE: value = alcErrInvalidValue; break; case ALC_INVALID_DEVICE: value = alcErrInvalidDevice; break; case ALC_INVALID_CONTEXT: value = alcErrInvalidContext; break; case ALC_OUT_OF_MEMORY: value = alcErrOutOfMemory; break; case ALC_DEVICE_SPECIFIER: value = alcDefaultName; break; case ALC_ALL_DEVICES_SPECIFIER: if(VerifyDevice(Device)) { value = Device->DeviceName; ALCdevice_DecRef(Device); } else { ProbeAllDevicesList(); value = alcAllDevicesList; } break; case ALC_CAPTURE_DEVICE_SPECIFIER: if(VerifyDevice(Device)) { value = Device->DeviceName; ALCdevice_DecRef(Device); } else { ProbeCaptureDeviceList(); value = alcCaptureDeviceList; } break; /* Default devices are always first in the list */ case ALC_DEFAULT_DEVICE_SPECIFIER: value = alcDefaultName; break; case ALC_DEFAULT_ALL_DEVICES_SPECIFIER: if(!alcAllDevicesList) ProbeAllDevicesList(); Device = VerifyDevice(Device); free(alcDefaultAllDevicesSpecifier); alcDefaultAllDevicesSpecifier = strdup(alcAllDevicesList ? alcAllDevicesList : ""); if(!alcDefaultAllDevicesSpecifier) alcSetError(Device, ALC_OUT_OF_MEMORY); value = alcDefaultAllDevicesSpecifier; if(Device) ALCdevice_DecRef(Device); break; case ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER: if(!alcCaptureDeviceList) ProbeCaptureDeviceList(); Device = VerifyDevice(Device); free(alcCaptureDefaultDeviceSpecifier); alcCaptureDefaultDeviceSpecifier = strdup(alcCaptureDeviceList ? alcCaptureDeviceList : ""); if(!alcCaptureDefaultDeviceSpecifier) alcSetError(Device, ALC_OUT_OF_MEMORY); value = alcCaptureDefaultDeviceSpecifier; if(Device) ALCdevice_DecRef(Device); break; case ALC_EXTENSIONS: if(!VerifyDevice(Device)) value = alcNoDeviceExtList; else { value = alcExtensionList; ALCdevice_DecRef(Device); } break; default: Device = VerifyDevice(Device); alcSetError(Device, ALC_INVALID_ENUM); if(Device) ALCdevice_DecRef(Device); break; } return value; } /* alcGetIntegerv * * Returns information about the device and the version of OpenAL */ ALC_API ALCvoid ALC_APIENTRY alcGetIntegerv(ALCdevice *device,ALCenum param,ALsizei size,ALCint *data) { device = VerifyDevice(device); if(size == 0 || data == NULL) { alcSetError(device, ALC_INVALID_VALUE); if(device) ALCdevice_DecRef(device); return; } if(!device) { switch(param) { case ALC_MAJOR_VERSION: *data = alcMajorVersion; break; case ALC_MINOR_VERSION: *data = alcMinorVersion; break; case ALC_ATTRIBUTES_SIZE: case ALC_ALL_ATTRIBUTES: case ALC_FREQUENCY: case ALC_REFRESH: case ALC_SYNC: case ALC_MONO_SOURCES: case ALC_STEREO_SOURCES: case ALC_CAPTURE_SAMPLES: case ALC_FORMAT_CHANNELS_SOFT: case ALC_FORMAT_TYPE_SOFT: alcSetError(NULL, ALC_INVALID_DEVICE); break; default: alcSetError(NULL, ALC_INVALID_ENUM); break; } } else if(device->Type == Capture) { switch(param) { case ALC_CAPTURE_SAMPLES: LockLists(); /* Re-validate the device since it may have been closed */ ALCdevice_DecRef(device); if((device=VerifyDevice(device)) != NULL) *data = ALCdevice_AvailableSamples(device); else alcSetError(NULL, ALC_INVALID_DEVICE); UnlockLists(); break; case ALC_CONNECTED: *data = device->Connected; break; default: alcSetError(device, ALC_INVALID_ENUM); break; } } else /* render device */ { switch(param) { case ALC_MAJOR_VERSION: *data = alcMajorVersion; break; case ALC_MINOR_VERSION: *data = alcMinorVersion; break; case ALC_EFX_MAJOR_VERSION: *data = alcEFXMajorVersion; break; case ALC_EFX_MINOR_VERSION: *data = alcEFXMinorVersion; break; case ALC_ATTRIBUTES_SIZE: *data = 13; break; case ALC_ALL_ATTRIBUTES: if(size < 13) alcSetError(device, ALC_INVALID_VALUE); else { int i = 0; data[i++] = ALC_FREQUENCY; data[i++] = device->Frequency; if(device->Type != Loopback) { data[i++] = ALC_REFRESH; data[i++] = device->Frequency / device->UpdateSize; data[i++] = ALC_SYNC; data[i++] = ALC_FALSE; } else { data[i++] = ALC_FORMAT_CHANNELS_SOFT; data[i++] = device->FmtChans; data[i++] = ALC_FORMAT_TYPE_SOFT; data[i++] = device->FmtType; } data[i++] = ALC_MONO_SOURCES; data[i++] = device->NumMonoSources; data[i++] = ALC_STEREO_SOURCES; data[i++] = device->NumStereoSources; data[i++] = ALC_MAX_AUXILIARY_SENDS; data[i++] = device->NumAuxSends; data[i++] = 0; } break; case ALC_FREQUENCY: *data = device->Frequency; break; case ALC_REFRESH: if(device->Type == Loopback) alcSetError(device, ALC_INVALID_DEVICE); else *data = device->Frequency / device->UpdateSize; break; case ALC_SYNC: if(device->Type == Loopback) alcSetError(device, ALC_INVALID_DEVICE); else *data = ALC_FALSE; break; case ALC_FORMAT_CHANNELS_SOFT: if(device->Type != Loopback) alcSetError(device, ALC_INVALID_DEVICE); else *data = device->FmtChans; break; case ALC_FORMAT_TYPE_SOFT: if(device->Type != Loopback) alcSetError(device, ALC_INVALID_DEVICE); else *data = device->FmtType; break; case ALC_MONO_SOURCES: *data = device->NumMonoSources; break; case ALC_STEREO_SOURCES: *data = device->NumStereoSources; break; case ALC_MAX_AUXILIARY_SENDS: *data = device->NumAuxSends; break; case ALC_CONNECTED: *data = device->Connected; break; default: alcSetError(device, ALC_INVALID_ENUM); break; } } if(device) ALCdevice_DecRef(device); } /* alcIsExtensionPresent * * Determines if there is support for a particular extension */ ALC_API ALCboolean ALC_APIENTRY alcIsExtensionPresent(ALCdevice *device, const ALCchar *extName) { ALCboolean bResult = ALC_FALSE; device = VerifyDevice(device); if(!extName) alcSetError(device, ALC_INVALID_VALUE); else { size_t len = strlen(extName); const char *ptr = (device ? alcExtensionList : alcNoDeviceExtList); while(ptr && *ptr) { if(strncasecmp(ptr, extName, len) == 0 && (ptr[len] == '\0' || isspace(ptr[len]))) { bResult = ALC_TRUE; break; } if((ptr=strchr(ptr, ' ')) != NULL) { do { ++ptr; } while(isspace(*ptr)); } } } if(device) ALCdevice_DecRef(device); return bResult; } /* alcGetProcAddress * * Retrieves the function address for a particular extension function */ ALC_API ALCvoid* ALC_APIENTRY alcGetProcAddress(ALCdevice *device, const ALCchar *funcName) { ALCvoid *ptr = NULL; if(!funcName) { device = VerifyDevice(device); alcSetError(device, ALC_INVALID_VALUE); if(device) ALCdevice_DecRef(device); } else { ALsizei i = 0; while(alcFunctions[i].funcName && strcmp(alcFunctions[i].funcName, funcName) != 0) i++; ptr = alcFunctions[i].address; } return ptr; } /* alcGetEnumValue * * Get the value for a particular ALC enumeration name */ ALC_API ALCenum ALC_APIENTRY alcGetEnumValue(ALCdevice *device, const ALCchar *enumName) { ALCenum val = 0; if(!enumName) { device = VerifyDevice(device); alcSetError(device, ALC_INVALID_VALUE); if(device) ALCdevice_DecRef(device); } else { ALsizei i = 0; while(enumeration[i].enumName && strcmp(enumeration[i].enumName, enumName) != 0) i++; val = enumeration[i].value; } return val; } /* alcCreateContext * * Create and attach a context to the given device. */ ALC_API ALCcontext* ALC_APIENTRY alcCreateContext(ALCdevice *device, const ALCint *attrList) { ALCcontext *ALContext; ALCenum err; LockLists(); if(!(device=VerifyDevice(device)) || device->Type == Capture || !device->Connected) { UnlockLists(); alcSetError(device, ALC_INVALID_DEVICE); if(device) ALCdevice_DecRef(device); return NULL; } device->LastError = ALC_NO_ERROR; if((err=UpdateDeviceParams(device, attrList)) != ALC_NO_ERROR) { UnlockLists(); alcSetError(device, err); if(err == ALC_INVALID_DEVICE) aluHandleDisconnect(device); ALCdevice_DecRef(device); return NULL; } ALContext = calloc(1, sizeof(ALCcontext)); if(ALContext) { ALContext->ref = 1; ALContext->MaxActiveSources = 256; ALContext->ActiveSources = malloc(sizeof(ALContext->ActiveSources[0]) * ALContext->MaxActiveSources); } if(!ALContext || !ALContext->ActiveSources) { if(!device->ContextList) { ALCdevice_StopPlayback(device); device->Flags &= ~DEVICE_RUNNING; } UnlockLists(); free(ALContext); ALContext = NULL; alcSetError(device, ALC_OUT_OF_MEMORY); ALCdevice_DecRef(device); return NULL; } ALContext->Device = device; ALCdevice_IncRef(device); InitContext(ALContext); do { ALContext->next = device->ContextList; } while(!CompExchangePtr((XchgPtr*)&device->ContextList, ALContext->next, ALContext)); UnlockLists(); ALCdevice_DecRef(device); TRACE("Created context %p\n", ALContext); return ALContext; } /* alcDestroyContext * * Remove a context from its device */ ALC_API ALCvoid ALC_APIENTRY alcDestroyContext(ALCcontext *context) { ALCdevice *Device; LockLists(); /* alcGetContextsDevice sets an error for invalid contexts */ Device = alcGetContextsDevice(context); if(Device) { ReleaseContext(context, Device); if(!Device->ContextList) { ALCdevice_StopPlayback(Device); Device->Flags &= ~DEVICE_RUNNING; } } UnlockLists(); } /* alcGetCurrentContext * * Returns the currently active context on the calling thread */ ALC_API ALCcontext* ALC_APIENTRY alcGetCurrentContext(void) { ALCcontext *Context; Context = pthread_getspecific(LocalContext); if(!Context) Context = GlobalContext; return Context; } /* alcGetThreadContext * * Returns the currently active thread-local context */ ALC_API ALCcontext* ALC_APIENTRY alcGetThreadContext(void) { ALCcontext *Context; Context = pthread_getspecific(LocalContext); return Context; } /* alcMakeContextCurrent * * Makes the given context the active process-wide context, and removes the * thread-local context for the calling thread. */ ALC_API ALCboolean ALC_APIENTRY alcMakeContextCurrent(ALCcontext *context) { /* context must be valid or NULL */ if(context && !(context=VerifyContext(context))) { alcSetError(NULL, ALC_INVALID_CONTEXT); return ALC_FALSE; } /* context's reference count is already incremented */ context = ExchangePtr((XchgPtr*)&GlobalContext, context); if(context) ALCcontext_DecRef(context); if((context=pthread_getspecific(LocalContext)) != NULL) { pthread_setspecific(LocalContext, NULL); ALCcontext_DecRef(context); } return ALC_TRUE; } /* alcSetThreadContext * * Makes the given context the active context for the current thread */ ALC_API ALCboolean ALC_APIENTRY alcSetThreadContext(ALCcontext *context) { ALCcontext *old; /* context must be valid or NULL */ if(context && !(context=VerifyContext(context))) { alcSetError(NULL, ALC_INVALID_CONTEXT); return ALC_FALSE; } /* context's reference count is already incremented */ old = pthread_getspecific(LocalContext); pthread_setspecific(LocalContext, context); if(old) ALCcontext_DecRef(old); return ALC_TRUE; } /* alcGetContextsDevice * * Returns the device that a particular context is attached to */ ALC_API ALCdevice* ALC_APIENTRY alcGetContextsDevice(ALCcontext *Context) { ALCdevice *Device; if(!(Context=VerifyContext(Context))) { alcSetError(NULL, ALC_INVALID_CONTEXT); return NULL; } Device = Context->Device; ALCcontext_DecRef(Context); return Device; } /* alcOpenDevice * * Opens the named device. */ ALC_API ALCdevice* ALC_APIENTRY alcOpenDevice(const ALCchar *deviceName) { const ALCchar *fmt; ALCdevice *device; ALCenum err; DO_INITCONFIG(); if(!PlaybackBackend.name) { alcSetError(NULL, ALC_INVALID_VALUE); return NULL; } if(deviceName && (!deviceName[0] || strcasecmp(deviceName, alcDefaultName) == 0 || strcasecmp(deviceName, "openal-soft") == 0)) deviceName = NULL; device = al_calloc(16, sizeof(ALCdevice)+15+sizeof(ALeffectslot)); if(!device) { alcSetError(NULL, ALC_OUT_OF_MEMORY); return NULL; } //Validate device device->Funcs = &PlaybackBackend.Funcs; device->ref = 1; device->Connected = ALC_TRUE; device->Type = Playback; InitializeCriticalSection(&device->Mutex); device->LastError = ALC_NO_ERROR; device->Flags = 0; device->Bs2b = NULL; device->Bs2bLevel = 0; device->DeviceName = NULL; device->ContextList = NULL; device->MaxNoOfSources = 256; device->AuxiliaryEffectSlotMax = 4; device->NumAuxSends = MAX_SENDS; InitUIntMap(&device->BufferMap, ~0); InitUIntMap(&device->EffectMap, ~0); InitUIntMap(&device->FilterMap, ~0); //Set output format device->FmtChans = DevFmtChannelsDefault; device->FmtType = DevFmtTypeDefault; device->Frequency = DEFAULT_OUTPUT_RATE; device->NumUpdates = 4; device->UpdateSize = 1024; if(ConfigValueStr(NULL, "channels", &fmt)) { static const struct { const char name[16]; enum DevFmtChannels chans; } chanlist[] = { { "mono", DevFmtMono }, { "stereo", DevFmtStereo }, { "quad", DevFmtQuad }, { "surround51", DevFmtX51 }, { "surround61", DevFmtX61 }, { "surround71", DevFmtX71 }, }; size_t i; for(i = 0;i < COUNTOF(chanlist);i++) { if(strcasecmp(chanlist[i].name, fmt) == 0) { device->FmtChans = chanlist[i].chans; device->Flags |= DEVICE_CHANNELS_REQUEST; break; } } if(i == COUNTOF(chanlist)) ERR("Unsupported channels: %s\n", fmt); } if(ConfigValueStr(NULL, "sample-type", &fmt)) { static const struct { const char name[16]; enum DevFmtType type; } typelist[] = { { "int8", DevFmtByte }, { "uint8", DevFmtUByte }, { "int16", DevFmtShort }, { "uint16", DevFmtUShort }, { "int32", DevFmtInt }, { "uint32", DevFmtUInt }, { "float32", DevFmtFloat }, }; size_t i; for(i = 0;i < COUNTOF(typelist);i++) { if(strcasecmp(typelist[i].name, fmt) == 0) { device->FmtType = typelist[i].type; device->Flags |= DEVICE_SAMPLE_TYPE_REQUEST; break; } } if(i == COUNTOF(typelist)) ERR("Unsupported sample-type: %s\n", fmt); } #define DEVICE_FORMAT_REQUEST (DEVICE_CHANNELS_REQUEST|DEVICE_SAMPLE_TYPE_REQUEST) if((device->Flags&DEVICE_FORMAT_REQUEST) != DEVICE_FORMAT_REQUEST && ConfigValueStr(NULL, "format", &fmt)) { static const struct { const char name[32]; enum DevFmtChannels channels; enum DevFmtType type; } formats[] = { { "AL_FORMAT_MONO32", DevFmtMono, DevFmtFloat }, { "AL_FORMAT_STEREO32", DevFmtStereo, DevFmtFloat }, { "AL_FORMAT_QUAD32", DevFmtQuad, DevFmtFloat }, { "AL_FORMAT_51CHN32", DevFmtX51, DevFmtFloat }, { "AL_FORMAT_61CHN32", DevFmtX61, DevFmtFloat }, { "AL_FORMAT_71CHN32", DevFmtX71, DevFmtFloat }, { "AL_FORMAT_MONO16", DevFmtMono, DevFmtShort }, { "AL_FORMAT_STEREO16", DevFmtStereo, DevFmtShort }, { "AL_FORMAT_QUAD16", DevFmtQuad, DevFmtShort }, { "AL_FORMAT_51CHN16", DevFmtX51, DevFmtShort }, { "AL_FORMAT_61CHN16", DevFmtX61, DevFmtShort }, { "AL_FORMAT_71CHN16", DevFmtX71, DevFmtShort }, { "AL_FORMAT_MONO8", DevFmtMono, DevFmtByte }, { "AL_FORMAT_STEREO8", DevFmtStereo, DevFmtByte }, { "AL_FORMAT_QUAD8", DevFmtQuad, DevFmtByte }, { "AL_FORMAT_51CHN8", DevFmtX51, DevFmtByte }, { "AL_FORMAT_61CHN8", DevFmtX61, DevFmtByte }, { "AL_FORMAT_71CHN8", DevFmtX71, DevFmtByte } }; size_t i; ERR("Option 'format' is deprecated, please use 'channels' and 'sample-type'\n"); for(i = 0;i < COUNTOF(formats);i++) { if(strcasecmp(fmt, formats[i].name) == 0) { if(!(device->Flags&DEVICE_CHANNELS_REQUEST)) device->FmtChans = formats[i].channels; if(!(device->Flags&DEVICE_SAMPLE_TYPE_REQUEST)) device->FmtType = formats[i].type; device->Flags |= DEVICE_FORMAT_REQUEST; break; } } if(i == COUNTOF(formats)) ERR("Unsupported format: %s\n", fmt); } #undef DEVICE_FORMAT_REQUEST if(ConfigValueUInt(NULL, "frequency", &device->Frequency)) { device->Flags |= DEVICE_FREQUENCY_REQUEST; if(device->Frequency < MIN_OUTPUT_RATE) ERR("%uhz request clamped to %uhz minimum\n", device->Frequency, MIN_OUTPUT_RATE); device->Frequency = maxu(device->Frequency, MIN_OUTPUT_RATE); } ConfigValueUInt(NULL, "periods", &device->NumUpdates); device->NumUpdates = clampu(device->NumUpdates, 2, 16); ConfigValueUInt(NULL, "period_size", &device->UpdateSize); device->UpdateSize = clampu(device->UpdateSize, 64, 8192); if((CPUCapFlags&CPU_CAP_SSE)) device->UpdateSize = (device->UpdateSize+3)&~3; ConfigValueUInt(NULL, "sources", &device->MaxNoOfSources); if(device->MaxNoOfSources == 0) device->MaxNoOfSources = 256; ConfigValueUInt(NULL, "slots", &device->AuxiliaryEffectSlotMax); if(device->AuxiliaryEffectSlotMax == 0) device->AuxiliaryEffectSlotMax = 4; ConfigValueUInt(NULL, "sends", &device->NumAuxSends); if(device->NumAuxSends > MAX_SENDS) device->NumAuxSends = MAX_SENDS; ConfigValueInt(NULL, "cf_level", &device->Bs2bLevel); device->NumStereoSources = 1; device->NumMonoSources = device->MaxNoOfSources - device->NumStereoSources; // Find a playback device to open LockLists(); if((err=ALCdevice_OpenPlayback(device, deviceName)) != ALC_NO_ERROR) { UnlockLists(); DeleteCriticalSection(&device->Mutex); al_free(device); alcSetError(NULL, err); return NULL; } UnlockLists(); if(DefaultEffect.type != AL_EFFECT_NULL) { device->DefaultSlot = (ALeffectslot*)((ALintptrEXT)(device+1)&~15); if(InitEffectSlot(device->DefaultSlot) != AL_NO_ERROR) { device->DefaultSlot = NULL; ERR("Failed to initialize the default effect slot\n"); } else if(InitializeEffect(device, device->DefaultSlot, &DefaultEffect) != AL_NO_ERROR) { ALeffectState_Destroy(device->DefaultSlot->EffectState); device->DefaultSlot = NULL; ERR("Failed to initialize the default effect\n"); } } do { device->next = DeviceList; } while(!CompExchangePtr((XchgPtr*)&DeviceList, device->next, device)); TRACE("Created device %p, \"%s\"\n", device, device->DeviceName); return device; } /* alcCloseDevice * * Closes the given device. */ ALC_API ALCboolean ALC_APIENTRY alcCloseDevice(ALCdevice *Device) { ALCdevice *volatile*list; ALCcontext *ctx; LockLists(); list = &DeviceList; while(*list && *list != Device) list = &(*list)->next; if(!*list || (*list)->Type == Capture) { alcSetError(*list, ALC_INVALID_DEVICE); UnlockLists(); return ALC_FALSE; } *list = (*list)->next; UnlockLists(); while((ctx=Device->ContextList) != NULL) { WARN("Releasing context %p\n", ctx); ReleaseContext(ctx, Device); } if((Device->Flags&DEVICE_RUNNING)) ALCdevice_StopPlayback(Device); Device->Flags &= ~DEVICE_RUNNING; ALCdevice_DecRef(Device); return ALC_TRUE; } /************************************************ * ALC capture functions ************************************************/ ALC_API ALCdevice* ALC_APIENTRY alcCaptureOpenDevice(const ALCchar *deviceName, ALCuint frequency, ALCenum format, ALCsizei samples) { ALCdevice *device = NULL; ALCenum err; DO_INITCONFIG(); if(!CaptureBackend.name) { alcSetError(NULL, ALC_INVALID_VALUE); return NULL; } if(samples <= 0) { alcSetError(NULL, ALC_INVALID_VALUE); return NULL; } if(deviceName && (!deviceName[0] || strcasecmp(deviceName, alcDefaultName) == 0 || strcasecmp(deviceName, "openal-soft") == 0)) deviceName = NULL; device = al_calloc(16, sizeof(ALCdevice)); if(!device) { alcSetError(NULL, ALC_OUT_OF_MEMORY); return NULL; } //Validate device device->Funcs = &CaptureBackend.Funcs; device->ref = 1; device->Connected = ALC_TRUE; device->Type = Capture; InitializeCriticalSection(&device->Mutex); InitUIntMap(&device->BufferMap, ~0); InitUIntMap(&device->EffectMap, ~0); InitUIntMap(&device->FilterMap, ~0); device->DeviceName = NULL; device->Flags |= DEVICE_FREQUENCY_REQUEST; device->Frequency = frequency; device->Flags |= DEVICE_CHANNELS_REQUEST | DEVICE_SAMPLE_TYPE_REQUEST; if(DecomposeDevFormat(format, &device->FmtChans, &device->FmtType) == AL_FALSE) { DeleteCriticalSection(&device->Mutex); al_free(device); alcSetError(NULL, ALC_INVALID_ENUM); return NULL; } device->UpdateSize = samples; device->NumUpdates = 1; LockLists(); if((err=ALCdevice_OpenCapture(device, deviceName)) != ALC_NO_ERROR) { UnlockLists(); DeleteCriticalSection(&device->Mutex); al_free(device); alcSetError(NULL, err); return NULL; } UnlockLists(); do { device->next = DeviceList; } while(!CompExchangePtr((XchgPtr*)&DeviceList, device->next, device)); TRACE("Created device %p\n", device); return device; } ALC_API ALCboolean ALC_APIENTRY alcCaptureCloseDevice(ALCdevice *Device) { ALCdevice *volatile*list; LockLists(); list = &DeviceList; while(*list && *list != Device) list = &(*list)->next; if(!*list || (*list)->Type != Capture) { alcSetError(*list, ALC_INVALID_DEVICE); UnlockLists(); return ALC_FALSE; } *list = (*list)->next; UnlockLists(); ALCdevice_DecRef(Device); return ALC_TRUE; } ALC_API void ALC_APIENTRY alcCaptureStart(ALCdevice *device) { LockLists(); if(!(device=VerifyDevice(device)) || device->Type != Capture) { UnlockLists(); alcSetError(device, ALC_INVALID_DEVICE); if(device) ALCdevice_DecRef(device); return; } if(device->Connected) { if(!(device->Flags&DEVICE_RUNNING)) ALCdevice_StartCapture(device); device->Flags |= DEVICE_RUNNING; } UnlockLists(); ALCdevice_DecRef(device); } ALC_API void ALC_APIENTRY alcCaptureStop(ALCdevice *device) { LockLists(); if(!(device=VerifyDevice(device)) || device->Type != Capture) { UnlockLists(); alcSetError(device, ALC_INVALID_DEVICE); if(device) ALCdevice_DecRef(device); return; } if((device->Flags&DEVICE_RUNNING)) ALCdevice_StopCapture(device); device->Flags &= ~DEVICE_RUNNING; UnlockLists(); ALCdevice_DecRef(device); } ALC_API void ALC_APIENTRY alcCaptureSamples(ALCdevice *device, ALCvoid *buffer, ALCsizei samples) { ALCenum err = ALC_INVALID_DEVICE; LockLists(); if((device=VerifyDevice(device)) != NULL && device->Type == Capture) { err = ALC_INVALID_VALUE; if(samples >= 0 && ALCdevice_AvailableSamples(device) >= (ALCuint)samples) err = ALCdevice_CaptureSamples(device, buffer, samples); } UnlockLists(); if(err != ALC_NO_ERROR) alcSetError(device, err); if(device) ALCdevice_DecRef(device); } /************************************************ * ALC loopback functions ************************************************/ /* alcLoopbackOpenDeviceSOFT * * Open a loopback device, for manual rendering. */ ALC_API ALCdevice* ALC_APIENTRY alcLoopbackOpenDeviceSOFT(const ALCchar *deviceName) { ALCdevice *device; DO_INITCONFIG(); /* Make sure the device name, if specified, is us. */ if(deviceName && strcmp(deviceName, alcDefaultName) != 0) { alcSetError(NULL, ALC_INVALID_VALUE); return NULL; } device = al_calloc(16, sizeof(ALCdevice)); if(!device) { alcSetError(NULL, ALC_OUT_OF_MEMORY); return NULL; } //Validate device device->Funcs = &BackendLoopback.Funcs; device->ref = 1; device->Connected = ALC_TRUE; device->Type = Loopback; InitializeCriticalSection(&device->Mutex); device->LastError = ALC_NO_ERROR; device->Flags = 0; device->Bs2b = NULL; device->Bs2bLevel = 0; device->DeviceName = NULL; device->ContextList = NULL; device->MaxNoOfSources = 256; device->AuxiliaryEffectSlotMax = 4; device->NumAuxSends = MAX_SENDS; InitUIntMap(&device->BufferMap, ~0); InitUIntMap(&device->EffectMap, ~0); InitUIntMap(&device->FilterMap, ~0); //Set output format device->NumUpdates = 0; device->UpdateSize = 0; device->Frequency = DEFAULT_OUTPUT_RATE; device->FmtChans = DevFmtChannelsDefault; device->FmtType = DevFmtTypeDefault; ConfigValueUInt(NULL, "sources", &device->MaxNoOfSources); if(device->MaxNoOfSources == 0) device->MaxNoOfSources = 256; ConfigValueUInt(NULL, "slots", &device->AuxiliaryEffectSlotMax); if(device->AuxiliaryEffectSlotMax == 0) device->AuxiliaryEffectSlotMax = 4; ConfigValueUInt(NULL, "sends", &device->NumAuxSends); if(device->NumAuxSends > MAX_SENDS) device->NumAuxSends = MAX_SENDS; device->NumStereoSources = 1; device->NumMonoSources = device->MaxNoOfSources - device->NumStereoSources; // Open the "backend" ALCdevice_OpenPlayback(device, "Loopback"); do { device->next = DeviceList; } while(!CompExchangePtr((XchgPtr*)&DeviceList, device->next, device)); TRACE("Created device %p\n", device); return device; } /* alcIsRenderFormatSupportedSOFT * * Determines if the loopback device supports the given format for rendering. */ ALC_API ALCboolean ALC_APIENTRY alcIsRenderFormatSupportedSOFT(ALCdevice *device, ALCsizei freq, ALCenum channels, ALCenum type) { ALCboolean ret = ALC_FALSE; if(!(device=VerifyDevice(device)) || device->Type != Loopback) alcSetError(device, ALC_INVALID_DEVICE); else if(freq <= 0) alcSetError(device, ALC_INVALID_VALUE); else { if(IsValidALCType(type) && BytesFromDevFmt(type) > 0 && IsValidALCChannels(channels) && ChannelsFromDevFmt(channels) > 0 && freq >= MIN_OUTPUT_RATE) ret = ALC_TRUE; } if(device) ALCdevice_DecRef(device); return ret; } /* alcRenderSamplesSOFT * * Renders some samples into a buffer, using the format last set by the * attributes given to alcCreateContext. */ ALC_API void ALC_APIENTRY alcRenderSamplesSOFT(ALCdevice *device, ALCvoid *buffer, ALCsizei samples) { if(!(device=VerifyDevice(device)) || device->Type != Loopback) alcSetError(device, ALC_INVALID_DEVICE); else if(samples < 0 || (samples > 0 && buffer == NULL)) alcSetError(device, ALC_INVALID_VALUE); else aluMixData(device, buffer, samples); if(device) ALCdevice_DecRef(device); }
Java
#ifndef __NEURO_H #define __NEURO_H #define OK 0 #define rassert(x) if (!(x)) { void exit(int); fprintf(stderr, "FAIL: %s:%d:%s\n", __FILE__, __LINE__, #x); exit(1); } #include <neuro/stringtable.h> #include <neuro/cmdhandler.h> #include <neuro/ns2net.h> #endif
Java
using System; using System.Linq; using System.Threading; using BruTile; using Mapsui.Layers; using Mapsui.Providers; using NUnit.Framework; using BruTile.Predefined; using Mapsui.Rendering; using Mapsui.Rendering.Xaml; namespace Mapsui.Tests.Layers { [TestFixture] public class RasterizingLayerTests { [Test] public void TestTimer() { // arrange var layer = new RasterizingLayer(CreatePointLayer()); var schema = new GlobalSphericalMercator(); var box = schema.Extent.ToBoundingBox(); var resolution = schema.Resolutions.First().Value.UnitsPerPixel; var waitHandle = new AutoResetEvent(false); DefaultRendererFactory.Create = () => new MapRenderer(); // Using xaml renderer here to test rasterizer. Suboptimal. Assert.AreEqual(0, layer.GetFeaturesInView(box, resolution).Count()); layer.DataChanged += (sender, args) => { // assert waitHandle.Set(); }; // act layer.RefreshData(box, resolution, true); waitHandle.WaitOne(); Assert.AreEqual(layer.GetFeaturesInView(box, resolution).Count(), 1); } private static MemoryLayer CreatePointLayer() { var random = new Random(); var features = new Features(); for (var i = 0; i < 100; i++) { var feature = new Feature { Geometry = new Geometries.Point(random.Next(100000, 5000000), random.Next(100000, 5000000)) }; features.Add(feature); } var provider = new MemoryProvider(features); return new MemoryLayer { DataSource = provider }; } } }
Java
/* * This file is part of the QuickServer library * Copyright (C) QuickServer.org * * Use, modification, copying and distribution of this software is subject to * the terms and conditions of the GNU Lesser General Public License. * You should have received a copy of the GNU LGP License along with this * library; if not, you can download a copy from <http://www.quickserver.org/>. * * For questions, suggestions, bug-reports, enhancement-requests etc. * visit http://www.quickserver.org * */ package org.quickserver.security; import java.io.*; import java.util.logging.*; import org.quickserver.util.xmlreader.*; import org.quickserver.util.io.*; import javax.net.ssl.*; import java.security.*; import org.quickserver.swing.*; /** * Class that loads Key Managers, Trust Managers, SSLContext and other secure * objects from QuickServer configuration passed. See &lt;secure-store-manager&gt; * in &lt;secure-store&gt; to set new manger to load your SecureStore. This * class can be overridden to change the way QuickServer configures the * secure mode. * @see org.quickserver.util.xmlreader.SecureStore * @author Akshathkumar Shetty * @since 1.4 */ public class SecureStoreManager { private static Logger logger = Logger.getLogger( SecureStoreManager.class.getName()); private SensitiveInput sensitiveInput = null; /** * Loads KeyManagers. KeyManagers are responsible for managing * the key material which is used to authenticate the local * SSLSocket to its peer. Can return null. */ public KeyManager[] loadKeyManagers(QuickServerConfig config) throws GeneralSecurityException, IOException { Secure secure = config.getSecure(); SecureStore secureStore = secure.getSecureStore(); if(secureStore==null) { logger.fine("SecureStore configuration not set! "+ "So returning null for KeyManager"); return null; } KeyStoreInfo keyStoreInfo = secureStore.getKeyStoreInfo(); if(keyStoreInfo==null) { logger.fine("KeyStoreInfo configuration not set! "+ "So returning null for KeyManager"); return null; } logger.finest("Loading KeyManagers"); KeyStore ks = getKeyStoreForKey(secureStore.getType(), secureStore.getProvider()); logger.info("KeyManager Provider: "+ks.getProvider()); char storepass[] = null; if(keyStoreInfo.getStorePassword()!=null) { logger.finest("KeyStore: Store password was present!"); storepass = keyStoreInfo.getStorePassword().toCharArray(); } else { logger.finest("KeyStore: Store password was not set.. so asking!"); if(sensitiveInput==null) { sensitiveInput = new SensitiveInput(config.getName()+" - Input Prompt"); } storepass = sensitiveInput.getInput("Store password for KeyStore"); if(storepass==null) { logger.finest("No password entered.. will pass null"); } } InputStream keyStoreStream = null; try { if(keyStoreInfo.getStoreFile().equalsIgnoreCase("none")==false) { logger.finest("KeyStore location: "+ ConfigReader.makeAbsoluteToConfig(keyStoreInfo.getStoreFile(), config)); keyStoreStream = new FileInputStream( ConfigReader.makeAbsoluteToConfig(keyStoreInfo.getStoreFile(), config)); } ks.load(keyStoreStream, storepass); logger.finest("KeyStore loaded"); } finally { if(keyStoreStream != null) { keyStoreStream.close(); keyStoreStream = null; } } char keypass[] = null; if(keyStoreInfo.getKeyPassword()!=null) { logger.finest("KeyStore: key password was present!"); keypass = keyStoreInfo.getKeyPassword().toCharArray(); } else { logger.finest("KeyStore: Key password was not set.. so asking!"); if(sensitiveInput==null) { sensitiveInput = new SensitiveInput(config.getName()+" - Input Prompt"); } keypass = sensitiveInput.getInput("Key password for KeyStore"); if(keypass==null) { logger.finest("No password entered.. will pass blank"); keypass = "".toCharArray(); } } KeyManagerFactory kmf = KeyManagerFactory.getInstance( secureStore.getAlgorithm()); kmf.init(ks, keypass); storepass = " ".toCharArray(); storepass = null; keypass = " ".toCharArray(); keypass = null; return kmf.getKeyManagers(); } /** * Loads TrustManagers. TrustManagers are responsible for managing the * trust material that is used when making trust decisions, and for * deciding whether credentials presented by a peer should be accepted. * Can return null. */ public TrustManager[] loadTrustManagers(QuickServerConfig config) throws GeneralSecurityException, IOException { Secure secure = config.getSecure(); SecureStore secureStore = secure.getSecureStore(); TrustStoreInfo trustStoreInfo = secureStore.getTrustStoreInfo(); if(trustStoreInfo==null) { return null; } logger.finest("Loading TrustManagers"); String type = null; if(trustStoreInfo.getType()!=null && trustStoreInfo.getType().trim().length()!=0) type = trustStoreInfo.getType(); else type = secureStore.getType(); String provider = null; if(trustStoreInfo.getProvider()!=null && trustStoreInfo.getProvider().trim().length()!=0) provider = trustStoreInfo.getProvider(); else provider = secureStore.getProvider(); KeyStore ts = getKeyStoreForTrust(type, provider); char trustpass[] = null; if(trustStoreInfo.getStorePassword()!=null) { logger.finest("TrustStore: Store password was present!"); trustpass = trustStoreInfo.getStorePassword().toCharArray(); } else { logger.finest("TrustStore: Store password was not set.. so asking!"); if(sensitiveInput==null) { sensitiveInput = new SensitiveInput(config.getName()+" - Input Prompt"); } trustpass = sensitiveInput.getInput("Store password for TrustStore"); if(trustpass==null) { logger.finest("No password entered.. will pass null"); } } InputStream trustStoreStream = null; try { if(trustStoreInfo.getStoreFile().equalsIgnoreCase("none")==false) { logger.finest("TrustStore location: "+ ConfigReader.makeAbsoluteToConfig( trustStoreInfo.getStoreFile(), config)); trustStoreStream = new FileInputStream( ConfigReader.makeAbsoluteToConfig( trustStoreInfo.getStoreFile(), config)); } ts.load(trustStoreStream, trustpass); logger.finest("TrustStore loaded"); } finally { if(trustStoreStream!=null) { trustStoreStream.close(); trustStoreStream = null; } } TrustManagerFactory tmf = TrustManagerFactory.getInstance( secureStore.getAlgorithm()); tmf.init(ts); return tmf.getTrustManagers(); } /** * Generates a SSLContext object that implements the specified secure * socket protocol. */ public SSLContext getSSLContext(String protocol) throws NoSuchAlgorithmException { return SSLContext.getInstance(protocol); } public SSLContext getSSLContext(QuickServerConfig config) throws NoSuchAlgorithmException, NoSuchProviderException { if(config.getSecure().getSecureStore().getProvider()!=null) { return SSLContext.getInstance( config.getSecure().getProtocol(), config.getSecure().getSecureStore().getProvider()); } else { return SSLContext.getInstance(config.getSecure().getProtocol()); } } /** * Generates a keystore object for the specified keystore type from * the specified provider to be used for loading/storeing keys. * @param type the type of keystore * @param provider the name of the provider if <code>null</code> any * provider package that implements this type of key may be given based * on the priority. */ protected KeyStore getKeyStoreForKey(String type, String provider) throws KeyStoreException, NoSuchProviderException { if(provider==null) return KeyStore.getInstance(type); return KeyStore.getInstance(type, provider); } /** * Generates a keystore object for the specified keystore type from * the specified provider to be used for loading/storing trusted * keys/certificates. * @param type the type of keystore * @param provider the name of the provider if <code>null</code> any * provider package that implements this type of key may be given based * on the priority. */ protected KeyStore getKeyStoreForTrust(String type, String provider) throws KeyStoreException, NoSuchProviderException { if(provider==null) return KeyStore.getInstance(type); return KeyStore.getInstance(type, provider); } /** * Returns a SSLSocketFactory object to be used for creating SSLSockets. */ public SSLSocketFactory getSocketFactory(SSLContext context) { return context.getSocketFactory(); } /** * Can be used to log details about the SSLServerSocket used to * create a secure server [SSL/TLS]. This method can also be * overridden to change the enabled cipher suites and/or enabled protocols. */ public void logSSLServerSocketInfo(SSLServerSocket sslServerSocket) { if(logger.isLoggable(Level.FINEST)==false) { return; } logger.finest("SecureServer Info: ClientAuth: "+ sslServerSocket.getNeedClientAuth()); logger.finest("SecureServer Info: ClientMode: "+ sslServerSocket.getUseClientMode()); String supportedSuites[] = sslServerSocket.getSupportedCipherSuites(); logger.finest("SecureServer Info: Supported Cipher Suites --------"); for(int i=0;i<supportedSuites.length;i++) logger.finest(supportedSuites[i]); logger.finest("---------------------------------------------------"); String enabledSuites[] = sslServerSocket.getEnabledCipherSuites(); logger.finest("SecureServer Info: Enabled Cipher Suites ----------"); for(int i=0;i<enabledSuites.length;i++) logger.finest(enabledSuites[i]); logger.finest("---------------------------------------------------"); String supportedProtocols[] = sslServerSocket.getSupportedProtocols(); logger.finest("SecureServer Info: Supported Protocols ------------"); for(int i=0;i<supportedProtocols.length;i++) logger.finest(supportedProtocols[i]); logger.finest("---------------------------------------------------"); String enabledProtocols[] = sslServerSocket.getEnabledProtocols(); logger.finest("SecureServer Info: Enabled Protocols --------------"); for(int i=0;i<enabledProtocols.length;i++) logger.finest(enabledProtocols[i]); logger.finest("---------------------------------------------------"); } }
Java
#include <mystdlib.h> #include "meshing.hpp" namespace netgen { extern double minother; extern double minwithoutother; static double CalcElementBadness (const Array<Point3d, PointIndex::BASE> & points, const Element & elem) { double vol, l, l4, l5, l6; if (elem.GetNP() != 4) { if (elem.GetNP() == 5) { double z = points[elem.PNum(5)].Z(); if (z > -1e-8) return 1e8; return (-1 / z) - z; // - 2; } return 0; } Vec3d v1 = points[elem.PNum(2)] - points[elem.PNum(1)]; Vec3d v2 = points[elem.PNum(3)] - points[elem.PNum(1)]; Vec3d v3 = points[elem.PNum(4)] - points[elem.PNum(1)]; vol = - (Cross (v1, v2) * v3); l4 = Dist (points[elem.PNum(2)], points[elem.PNum(3)]); l5 = Dist (points[elem.PNum(2)], points[elem.PNum(4)]); l6 = Dist (points[elem.PNum(3)], points[elem.PNum(4)]); l = v1.Length() + v2.Length() + v3.Length() + l4 + l5 + l6; // testout << "vol = " << vol << " l = " << l << endl; if (vol < 1e-8) return 1e10; // (*testout) << "l^3/vol = " << (l*l*l / vol) << endl; double err = pow (l*l*l/vol, 1.0/3.0) / 12; return err; } int Meshing3 :: ApplyRules ( Array<Point3d, PointIndex::BASE> & lpoints, // in: local points, out: old+new local points Array<int, PointIndex::BASE> & allowpoint, // in: 2 .. it is allowed to use pointi, 1..will be allowed later, 0..no means Array<MiniElement2d> & lfaces, // in: local faces, out: old+new local faces INDEX lfacesplit, // for local faces in outer radius INDEX_2_HASHTABLE<int> & connectedpairs, // connected pairs for prism-meshing Array<Element> & elements, // out: new elements Array<INDEX> & delfaces, // out: face indices of faces to delete int tolerance, // quality class: 1 best double sloppy, // quality strength int rotind1, // how to rotate base element float & retminerr // element error ) { NgProfiler::RegionTimer regtot(97); float err, minerr, teterr, minteterr; char ok, found, hc; // vnetrule * rule; Vector oldu, newu, newu1, newu2, allp; Vec3d ui; Point3d np; const MiniElement2d * locface = NULL; int loktestmode; Array<int, PointIndex::BASE> pused; // point is already mapped, number of uses Array<char> fused; // face is already mapped Array<PointIndex> pmap; // map of reference point to local point Array<bool> pfixed; // point mapped by face-map Array<int> fmapi; // face in reference is mapped to face nr ... Array<int> fmapr; // face in reference is rotated to map Array<Point3d> transfreezone; // transformed free-zone INDEX_2_CLOSED_HASHTABLE<int> ledges(100); // edges in local environment Array<Point3d> tempnewpoints; Array<MiniElement2d> tempnewfaces; Array<int> tempdelfaces; Array<Element> tempelements; Array<Box3d> triboxes; // bounding boxes of local faces Array<int, PointIndex::BASE> pnearness; Array<int> fnearness; static int cnt = 0; cnt++; delfaces.SetSize (0); elements.SetSize (0); // determine topological distance of faces and points to // base element pnearness.SetSize (lpoints.Size()); fnearness.SetSize (lfacesplit); pnearness = INT_MAX/10; for (PointIndex pi : lfaces[0].PNums()) pnearness[pi] = 0; NgProfiler::RegionTimer reg2(98); NgProfiler::StartTimer (90); for (int loop = 0; loop < 2; loop++) { for (int i = 0; i < lfacesplit; i++) { const MiniElement2d & hface = lfaces[i]; int minn = INT_MAX-1; for (PointIndex pi : hface.PNums()) { int hi = pnearness[pi]; if (hi < minn) minn = hi; } if (minn < INT_MAX/10) for (PointIndex pi : hface.PNums()) if (pnearness[pi] > minn+1) pnearness[pi] = minn+1; } for (int i = 1; i <= connectedpairs.GetNBags(); i++) for (int j = 1; j <= connectedpairs.GetBagSize(i); j++) { INDEX_2 edge; int val; connectedpairs.GetData (i, j, edge, val); if (pnearness[edge.I1()] > pnearness[edge.I2()] + 1) pnearness[edge.I1()] = pnearness[edge.I2()] + 1; if (pnearness[edge.I2()] > pnearness[edge.I1()] + 1) pnearness[edge.I2()] = pnearness[edge.I1()] + 1; } } for (int i : fnearness.Range()) { int sum = 0; for (PointIndex pi : lfaces[i].PNums()) sum += pnearness[pi]; fnearness[i] = sum; } NgProfiler::StopTimer (90); NgProfiler::StartTimer (91); // find bounding boxes of faces triboxes.SetSize (lfaces.Size()); // for (int i = 0; i < lfaces.Size(); i++) for (auto i : lfaces.Range()) { const MiniElement2d & face = lfaces[i]; triboxes[i].SetPoint (lpoints[face[0]]); for (int j = 1; j < face.GetNP(); j++) triboxes[i].AddPoint (lpoints[face[j]]); } NgProfiler::StopTimer (91); NgProfiler::StartTimer (92); bool useedges = false; for (int ri = 0; ri < rules.Size(); ri++) if (rules[ri]->GetNEd()) useedges = true; if (useedges) { ledges.SetSize (5 * lfacesplit); for (int j = 0; j < lfacesplit; j++) // if (fnearness[j] <= 5) { const MiniElement2d & face = lfaces[j]; int newp, oldp; newp = face[face.GetNP()-1]; for (int k = 0; k < face.GetNP(); k++) { oldp = newp; newp = face[k]; ledges.Set (INDEX_2::Sort(oldp, newp), 1); } } } NgProfiler::StopTimer (92); NgProfiler::RegionTimer reg3(99); pused.SetSize (lpoints.Size()); fused.SetSize (lfaces.Size()); found = 0; minerr = tolfak * tolerance * tolerance; minteterr = sloppy * tolerance; if (testmode) (*testout) << "cnt = " << cnt << " class = " << tolerance << endl; // impossible, if no rule can be applied at any tolerance class bool impossible = 1; // check each rule: for (int ri = 1; ri <= rules.Size(); ri++) { int base = (lfaces[0].GetNP() == 3) ? 100 : 200; NgProfiler::RegionTimer regx1(base); NgProfiler::RegionTimer regx(base+ri); // sprintf (problems.Elem(ri), ""); *problems.Elem(ri) = '\0'; vnetrule * rule = rules.Get(ri); if (rule->GetNP(1) != lfaces[0].GetNP()) continue; if (rule->GetQuality() > tolerance) { if (rule->GetQuality() < 100) impossible = 0; if (testmode) sprintf (problems.Elem(ri), "Quality not ok"); continue; } if (testmode) sprintf (problems.Elem(ri), "no mapping found"); loktestmode = testmode || rule->TestFlag ('t') || tolerance > 5; if (loktestmode) (*testout) << "Rule " << ri << " = " << rule->Name() << endl; pmap.SetSize (rule->GetNP()); fmapi.SetSize (rule->GetNF()); fmapr.SetSize (rule->GetNF()); fused = 0; pused = 0; for (auto & p : pmap) p.Invalidate(); fmapi = 0; for (int i : fmapr.Range()) fmapr[i] = rule->GetNP(i+1); fused[0] = 1; fmapi[0] = 1; fmapr[0] = rotind1; for (int j = 1; j <= lfaces[0].GetNP(); j++) { PointIndex locpi = lfaces[0].PNumMod (j+rotind1); pmap.Set (rule->GetPointNr (1, j), locpi); pused[locpi]++; } /* map all faces nfok .. first nfok-1 faces are mapped properly */ int nfok = 2; NgProfiler::RegionTimer regfa(300); NgProfiler::RegionTimer regx2(base+50+ri); while (nfok >= 2) { if (nfok <= rule->GetNOldF()) { // not all faces mapped ok = 0; int locfi = fmapi.Get(nfok); int locfr = fmapr.Get(nfok); int actfnp = rule->GetNP(nfok); while (!ok) { locfr++; if (locfr == actfnp + 1) { locfr = 1; locfi++; if (locfi > lfacesplit) break; } if (fnearness.Get(locfi) > rule->GetFNearness (nfok) || fused.Get(locfi) || actfnp != lfaces.Get(locfi).GetNP() ) { // face not feasible in any rotation locfr = actfnp; } else { ok = 1; locface = &lfaces.Get(locfi); // reference point already mapped differently ? for (int j = 1; j <= actfnp && ok; j++) { PointIndex locpi = pmap.Get(rule->GetPointNr (nfok, j)); if (locpi.IsValid() && locpi != locface->PNumMod(j+locfr)) ok = 0; } // local point already used or point outside tolerance ? for (int j = 1; j <= actfnp && ok; j++) { int refpi = rule->GetPointNr (nfok, j); if (!pmap.Get(refpi).IsValid()) { PointIndex locpi = locface->PNumMod (j + locfr); if (pused[locpi]) ok = 0; else { const Point3d & lp = lpoints[locpi]; const Point3d & rp = rule->GetPoint(refpi); if ( Dist2 (lp, rp) * rule->PointDistFactor(refpi) > minerr) { impossible = 0; ok = 0; } } } } } } if (ok) { // map face nfok fmapi.Set (nfok, locfi); fmapr.Set (nfok, locfr); fused.Set (locfi, 1); for (int j = 1; j <= rule->GetNP (nfok); j++) { PointIndex locpi = locface->PNumMod(j+locfr); if (rule->GetPointNr (nfok, j) <= 3 && pmap.Get(rule->GetPointNr(nfok, j)) != locpi) (*testout) << "change face1 point, mark1" << endl; pmap.Set(rule->GetPointNr (nfok, j), locpi); pused[locpi]++; } nfok++; } else { // backtrack one face fmapi.Set (nfok, 0); fmapr.Set (nfok, rule->GetNP(nfok)); nfok--; fused.Set (fmapi.Get(nfok), 0); for (int j = 1; j <= rule->GetNP (nfok); j++) { int refpi = rule->GetPointNr (nfok, j); pused[pmap.Get(refpi)]--; if (pused[pmap.Get(refpi)] == 0) { // pmap.Set(refpi, 0); pmap.Elem(refpi).Invalidate(); } } } } else { NgProfiler::RegionTimer regfb(301); // all faces are mapped // now map all isolated points: if (loktestmode) { (*testout) << "Faces Ok" << endl; sprintf (problems.Elem(ri), "Faces Ok"); } int npok = 1; int incnpok = 1; pfixed.SetSize (pmap.Size()); /* for (int i = 1; i <= pmap.Size(); i++) pfixed.Set(i, (pmap.Get(i) != 0) ); */ for (int i : pmap.Range()) pfixed[i] = pmap[i].IsValid(); while (npok >= 1) { if (npok <= rule->GetNOldP()) { if (pfixed.Get(npok)) { if (incnpok) npok++; else npok--; } else { PointIndex locpi = pmap.Elem(npok); ok = 0; if (locpi.IsValid()) pused[locpi]--; while (!ok && locpi < lpoints.Size()-1+PointIndex::BASE) { ok = 1; locpi++; if (pused[locpi] || pnearness[locpi] > rule->GetPNearness(npok)) { ok = 0; } else if (allowpoint[locpi] != 2) { ok = 0; if (allowpoint[locpi] == 1) impossible = 0; } else { const Point3d & lp = lpoints[locpi]; const Point3d & rp = rule->GetPoint(npok); if ( Dist2 (lp, rp) * rule->PointDistFactor(npok) > minerr) { ok = 0; impossible = 0; } } } if (ok) { pmap.Set (npok, locpi); if (npok <= 3) (*testout) << "set face1 point, mark3" << endl; pused[locpi]++; npok++; incnpok = 1; } else { // pmap.Set (npok, 0); pmap.Elem(npok).Invalidate(); if (npok <= 3) (*testout) << "set face1 point, mark4" << endl; npok--; incnpok = 0; } } } else { NgProfiler::RegionTimer regfa2(302); // all points are mapped if (loktestmode) { (*testout) << "Mapping found!!: Rule " << rule->Name() << endl; for (auto pi : pmap) (*testout) << pi << " "; (*testout) << endl; sprintf (problems.Elem(ri), "mapping found"); (*testout) << rule->GetNP(1) << " = " << lfaces.Get(1).GetNP() << endl; } ok = 1; // check mapedges: for (int i = 1; i <= rule->GetNEd(); i++) { INDEX_2 in2(pmap.Get(rule->GetEdge(i).i1), pmap.Get(rule->GetEdge(i).i2)); in2.Sort(); if (!ledges.Used (in2)) ok = 0; } // check prism edges: for (int i = 1; i <= rule->GetNE(); i++) { const Element & el = rule->GetElement (i); if (el.GetType() == PRISM) { for (int j = 1; j <= 3; j++) { INDEX_2 in2(pmap.Get(el.PNum(j)), pmap.Get(el.PNum(j+3))); in2.Sort(); if (!connectedpairs.Used (in2)) ok = 0; } } if (el.GetType() == PYRAMID) { if (loktestmode) (*testout) << "map pyramid, rule = " << rule->Name() << endl; for (int j = 1; j <= 2; j++) { INDEX_2 in2; if (j == 1) { in2.I1() = pmap.Get(el.PNum(2)); in2.I2() = pmap.Get(el.PNum(3)); } else { in2.I1() = pmap.Get(el.PNum(1)); in2.I2() = pmap.Get(el.PNum(4)); } in2.Sort(); if (!connectedpairs.Used (in2)) { ok = 0; if (loktestmode) (*testout) << "no pair" << endl; } } } } for (int i = rule->GetNOldF() + 1; i <= rule->GetNF(); i++) fmapi.Set(i, 0); if (ok) { foundmap.Elem(ri)++; } // deviation of existing points oldu.SetSize (3 * rule->GetNOldP()); newu.SetSize (3 * (rule->GetNP() - rule->GetNOldP())); allp.SetSize (3 * rule->GetNP()); for (int i = 1; i <= rule->GetNOldP(); i++) { const Point3d & lp = lpoints[pmap.Get(i)]; const Point3d & rp = rule->GetPoint(i); oldu (3*i-3) = lp.X()-rp.X(); oldu (3*i-2) = lp.Y()-rp.Y(); oldu (3*i-1) = lp.Z()-rp.Z(); allp (3*i-3) = lp.X(); allp (3*i-2) = lp.Y(); allp (3*i-1) = lp.Z(); } if (rule->GetNP() > rule->GetNOldP()) { newu.SetSize (rule->GetOldUToNewU().Height()); rule->GetOldUToNewU().Mult (oldu, newu); } // int idiff = 3 * (rule->GetNP()-rule->GetNOldP()); int idiff = 3 * rule->GetNOldP(); for (int i = rule->GetNOldP()+1; i <= rule->GetNP(); i++) { const Point3d & rp = rule->GetPoint(i); allp (3*i-3) = rp.X() + newu(3*i-3 - idiff); allp (3*i-2) = rp.Y() + newu(3*i-2 - idiff); allp (3*i-1) = rp.Z() + newu(3*i-1 - idiff); } rule->SetFreeZoneTransformation (allp, tolerance + int(sloppy)); if (!rule->ConvexFreeZone()) { ok = 0; sprintf (problems.Elem(ri), "Freezone not convex"); if (loktestmode) (*testout) << "Freezone not convex" << endl; } if (loktestmode) { const Array<Point3d> & fz = rule->GetTransFreeZone(); (*testout) << "Freezone: " << endl; for (int i = 1; i <= fz.Size(); i++) (*testout) << fz.Get(i) << endl; } // check freezone: for (int i = 1; i <= lpoints.Size(); i++) { if ( !pused.Get(i) ) { const Point3d & lp = lpoints.Get(i); if (rule->fzbox.IsIn (lp)) { if (rule->IsInFreeZone(lp)) { if (loktestmode) { (*testout) << "Point " << i << " in Freezone" << endl; sprintf (problems.Elem(ri), "locpoint %d in Freezone", i); } ok = 0; break; } } } } for (int i = 1; i <= lfaces.Size() && ok; i++) { static Array<int> lpi(4); if (!fused.Get(i)) { int triin; const MiniElement2d & lfacei = lfaces.Get(i); if (!triboxes.Elem(i).Intersect (rule->fzbox)) triin = 0; else { int li, lj; for (li = 1; li <= lfacei.GetNP(); li++) { int lpii = 0; PointIndex pi = lfacei.PNum(li); for (lj = 1; lj <= rule->GetNOldP(); lj++) if (pmap.Get(lj) == pi) lpii = lj; lpi.Elem(li) = lpii; } if (lfacei.GetNP() == 3) { triin = rule->IsTriangleInFreeZone ( lpoints[lfacei.PNum(1)], lpoints[lfacei.PNum(2)], lpoints[lfacei.PNum(3)], lpi, 1 ); } else { triin = rule->IsQuadInFreeZone ( lpoints[lfacei.PNum(1)], lpoints[lfacei.PNum(2)], lpoints[lfacei.PNum(3)], lpoints[lfacei.PNum(4)], lpi, 1 ); } } if (triin == -1) { ok = 0; } if (triin == 1) { #ifdef TEST_JS ok = 0; if (loktestmode) { (*testout) << "El with " << lfaces.Get(i).GetNP() << " points in freezone: " << lfaces.Get(i).PNum(1) << " - " << lfaces.Get(i).PNum(2) << " - " << lfaces.Get(i).PNum(3) << " - " << lfaces.Get(i).PNum(4) << endl; for (int lj = 1; lj <= lfaces.Get(i).GetNP(); lj++) (*testout) << lpoints[lfaces.Get(i).PNum(lj)] << " "; (*testout) << endl; sprintf (problems.Elem(ri), "triangle (%d, %d, %d) in Freezone", lfaces.Get(i).PNum(1), lfaces.Get(i).PNum(2), lfaces.Get(i).PNum(3)); } #else if (loktestmode) { if (lfacei.GetNP() == 3) { (*testout) << "Triangle in freezone: " << lfacei.PNum(1) << " - " << lfacei.PNum(2) << " - " << lfacei.PNum(3) << ", or " << lpoints[lfacei.PNum(1)] << " - " << lpoints[lfacei.PNum(2)] << " - " << lpoints[lfacei.PNum(3)] << endl; (*testout) << "lpi = " << lpi.Get(1) << ", " << lpi.Get(2) << ", " << lpi.Get(3) << endl; } else (*testout) << "Quad in freezone: " << lfacei.PNum(1) << " - " << lfacei.PNum(2) << " - " << lfacei.PNum(3) << " - " << lfacei.PNum(4) << ", or " << lpoints[lfacei.PNum(1)] << " - " << lpoints[lfacei.PNum(2)] << " - " << lpoints[lfacei.PNum(3)] << " - " << lpoints[lfacei.PNum(4)] << endl; sprintf (problems.Elem(ri), "triangle (%d, %d, %d) in Freezone", int(lfaces.Get(i).PNum(1)), int(lfaces.Get(i).PNum(2)), int(lfaces.Get(i).PNum(3))); } hc = 0; for (int k = rule->GetNOldF() + 1; k <= rule->GetNF(); k++) { if (rule->GetPointNr(k, 1) <= rule->GetNOldP() && rule->GetPointNr(k, 2) <= rule->GetNOldP() && rule->GetPointNr(k, 3) <= rule->GetNOldP()) { for (int j = 1; j <= 3; j++) if (lfaces.Get(i).PNumMod(j ) == pmap.Get(rule->GetPointNr(k, 1)) && lfaces.Get(i).PNumMod(j+1) == pmap.Get(rule->GetPointNr(k, 3)) && lfaces.Get(i).PNumMod(j+2) == pmap.Get(rule->GetPointNr(k, 2))) { fmapi.Elem(k) = i; hc = 1; // (*testout) << "found from other side: " // << rule->Name() // << " ( " << pmap.Get (rule->GetPointNr(k, 1)) // << " - " << pmap.Get (rule->GetPointNr(k, 2)) // << " - " << pmap.Get (rule->GetPointNr(k, 3)) << " ) " // << endl; strcpy (problems.Elem(ri), "other"); } } } if (!hc) { if (loktestmode) { (*testout) << "Triangle in freezone: " << lfaces.Get(i).PNum(1) << " - " << lfaces.Get(i).PNum(2) << " - " << lfaces.Get(i).PNum(3) << endl; sprintf (problems.Elem(ri), "triangle (%d, %d, %d) in Freezone", int (lfaces.Get(i).PNum(1)), int (lfaces.Get(i).PNum(2)), int (lfaces.Get(i).PNum(3))); } ok = 0; } #endif } } } if (ok) { err = 0; for (int i = 1; i <= rule->GetNOldP(); i++) { double hf = rule->CalcPointDist (i, lpoints[pmap.Get(i)]); if (hf > err) err = hf; } if (loktestmode) { (*testout) << "Rule ok" << endl; sprintf (problems.Elem(ri), "Rule ok, err = %f", err); } // newu = rule->GetOldUToNewU() * oldu; // set new points: int oldnp = rule->GetNOldP(); int noldlp = lpoints.Size(); int noldlf = lfaces.Size(); for (int i = oldnp + 1; i <= rule->GetNP(); i++) { np = rule->GetPoint(i); np.X() += newu (3 * (i-oldnp) - 3); np.Y() += newu (3 * (i-oldnp) - 2); np.Z() += newu (3 * (i-oldnp) - 1); lpoints.Append (np); pmap.Elem(i) = lpoints.Size()-1+PointIndex::BASE; } // Set new Faces: for (int i = rule->GetNOldF() + 1; i <= rule->GetNF(); i++) if (!fmapi.Get(i)) { MiniElement2d nface(rule->GetNP(i)); for (int j = 1; j <= nface.GetNP(); j++) nface.PNum(j) = pmap.Get(rule->GetPointNr (i, j)); lfaces.Append (nface); } // Delete old Faces: for (int i = 1; i <= rule->GetNDelF(); i++) delfaces.Append (fmapi.Get(rule->GetDelFace(i))); for (int i = rule->GetNOldF()+1; i <= rule->GetNF(); i++) if (fmapi.Get(i)) { delfaces.Append (fmapi.Get(i)); fmapi.Elem(i) = 0; } // check orientation for (int i = 1; i <= rule->GetNO() && ok; i++) { const fourint * fouri; fouri = &rule->GetOrientation(i); Vec3d v1 (lpoints[pmap.Get(fouri->i1)], lpoints[pmap.Get(fouri->i2)]); Vec3d v2 (lpoints[pmap.Get(fouri->i1)], lpoints[pmap.Get(fouri->i3)]); Vec3d v3 (lpoints[pmap.Get(fouri->i1)], lpoints[pmap.Get(fouri->i4)]); Vec3d n; Cross (v1, v2, n); //if (n * v3 >= -1e-7*n.Length()*v3.Length()) // OR -1e-7??? if (n * v3 >= -1e-9) { if (loktestmode) { sprintf (problems.Elem(ri), "Orientation wrong"); (*testout) << "Orientation wrong ("<< n*v3 << ")" << endl; } ok = 0; } } // new points in free-zone ? for (int i = rule->GetNOldP() + 1; i <= rule->GetNP() && ok; i++) if (!rule->IsInFreeZone (lpoints.Get(pmap.Get(i)))) { if (loktestmode) { (*testout) << "Newpoint " << lpoints.Get(pmap.Get(i)) << " outside convex hull" << endl; sprintf (problems.Elem(ri), "newpoint outside convex hull"); } ok = 0; } // insert new elements for (int i = 1; i <= rule->GetNE(); i++) { elements.Append (rule->GetElement(i)); for (int j = 1; j <= elements.Get(i).NP(); j++) elements.Elem(i).PNum(j) = pmap.Get(elements.Get(i).PNum(j)); } // Calculate Element badness teterr = 0; for (int i = 1; i <= elements.Size(); i++) { double hf = CalcElementBadness (lpoints, elements.Get(i)); if (hf > teterr) teterr = hf; } /* // keine gute Erfahrung am 25.1.2000, js if (ok && teterr < 100 && (rule->TestFlag('b') || tolerance > 10) ) { (*mycout) << "Reset teterr " << rule->Name() << " err = " << teterr << endl; teterr = 1; } */ // compare edgelength if (rule->TestFlag('l')) { double oldlen = 0; double newlen = 0; for (int i = 1; i <= rule->GetNDelF(); i++) { const Element2d & face = rule->GetFace (rule->GetDelFace(i)); for (int j = 1; j <= 3; j++) { const Point3d & p1 = lpoints[pmap.Get(face.PNumMod(j))]; const Point3d & p2 = lpoints[pmap.Get(face.PNumMod(j+1))]; oldlen += Dist(p1, p2); } } for (int i = rule->GetNOldF()+1; i <= rule->GetNF(); i++) { const Element2d & face = rule->GetFace (i); for (int j = 1; j <= 3; j++) { const Point3d & p1 = lpoints[pmap.Get(face.PNumMod(j))]; const Point3d & p2 = lpoints[pmap.Get(face.PNumMod(j+1))]; newlen += Dist(p1, p2); } } if (oldlen < newlen) { ok = 0; if (loktestmode) sprintf (problems.Elem(ri), "oldlen < newlen"); } } if (loktestmode) (*testout) << "ok = " << int(ok) << "teterr = " << teterr << "minteterr = " << minteterr << endl; if (ok && teterr < tolerance) { canuse.Elem(ri) ++; /* (*testout) << "can use rule " << rule->Name() << ", err = " << teterr << endl; for (i = 1; i <= pmap.Size(); i++) (*testout) << pmap.Get(i) << " "; (*testout) << endl; */ if (strcmp (problems.Elem(ri), "other") == 0) { if (teterr < minother) minother = teterr; } else { if (teterr < minwithoutother) minwithoutother = teterr; } } if (teterr > minteterr) impossible = 0; if (ok && teterr < minteterr) { if (loktestmode) (*testout) << "use rule" << endl; found = ri; minteterr = teterr; if (testmode) { for (int i = 1; i <= rule->GetNOldP(); i++) { (*testout) << "P" << i << ": Ref: " << rule->GetPoint (i) << " is: " << lpoints.Get(pmap.Get(i)) << endl; } } tempnewpoints.SetSize (0); for (int i = noldlp+1; i <= lpoints.Size(); i++) tempnewpoints.Append (lpoints.Get(i)); tempnewfaces.SetSize (0); for (int i = noldlf+1; i <= lfaces.Size(); i++) tempnewfaces.Append (lfaces.Get(i)); tempdelfaces.SetSize (0); for (int i = 1; i <= delfaces.Size(); i++) tempdelfaces.Append (delfaces.Get(i)); tempelements.SetSize (0); for (int i = 1; i <= elements.Size(); i++) tempelements.Append (elements.Get(i)); } lpoints.SetSize (noldlp); lfaces.SetSize (noldlf); delfaces.SetSize (0); elements.SetSize (0); } npok = rule->GetNOldP(); incnpok = 0; } } nfok = rule->GetNOldF(); for (int j = 1; j <= rule->GetNP (nfok); j++) { int refpi = rule->GetPointNr (nfok, j); pused[pmap.Get(refpi)]--; if (pused[pmap.Get(refpi)] == 0) pmap.Elem(refpi).Invalidate(); } } } if (loktestmode) (*testout) << "end rule" << endl; } if (found) { /* for (i = 1; i <= tempnewpoints.Size(); i++) lpoints.Append (tempnewpoints.Get(i)); */ for (Point3d p : tempnewpoints) lpoints.Append(p); /* for (i = 1; i <= tempnewfaces.Size(); i++) if (tempnewfaces.Get(i).PNum(1)) lfaces.Append (tempnewfaces.Get(i)); */ for (int i : tempnewfaces.Range()) if (tempnewfaces[i].PNum(1).IsValid()) lfaces.Append (tempnewfaces[i]); /* for (i = 1; i <= tempdelfaces.Size(); i++) delfaces.Append (tempdelfaces.Get(i)); */ for (int i : tempdelfaces.Range()) delfaces.Append (tempdelfaces[i]); /* for (i = 1; i <= tempelements.Size(); i++) elements.Append (tempelements.Get(i)); */ for (int i : tempelements.Range()) elements.Append (tempelements[i]); } retminerr = minerr; if (impossible && found == 0) return -1; return found; } }
Java
/*$Id$ * * This source file is a part of the Fresco Project. * Copyright (C) 2000 Stefan Seefeld <stefan@fresco.org> * http://www.fresco.org * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 675 Mass Ave, Cambridge, * MA 02139, USA. */ #ifndef _Berlin_Console_GGIDrawableFactory_hh #define _Berlin_Console_GGIDrawableFactory_hh #include <Berlin/config.hh> #include <Berlin/Console.hh> #include <string> extern "C" { #include <ggi/ggi-unix.h> } namespace Berlin { namespace Console_Extension { class GGIDrawable : public virtual Berlin::Console::Drawable { public: virtual const std::string &name() const = 0; virtual ggi_mode mode() const = 0; virtual ggi_visual_t visual() const = 0; }; class GGIDrawableFactory : virtual public Berlin::Console::Extension { public: //. Creates a new Drawable of the given size (x, y) and depth. //. It is accessable under the given shm-id. virtual GGIDrawable *create_drawable(int shmid, Fresco::PixelCoord, Fresco::PixelCoord, Fresco::PixelCoord) = 0; }; } // namespace } // namespace #endif
Java
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QRGB_H #define QRGB_H #include <QtCore/qglobal.h> QT_BEGIN_HEADER QT_BEGIN_NAMESPACE QT_MODULE(Gui) typedef unsigned int QRgb; // RGB triplet const QRgb RGB_MASK = 0x00ffffff; // masks RGB values Q_GUI_EXPORT_INLINE int qRed(QRgb rgb) // get red part of RGB { return ((rgb >> 16) & 0xff); } Q_GUI_EXPORT_INLINE int qGreen(QRgb rgb) // get green part of RGB { return ((rgb >> 8) & 0xff); } Q_GUI_EXPORT_INLINE int qBlue(QRgb rgb) // get blue part of RGB { return (rgb & 0xff); } Q_GUI_EXPORT_INLINE int qAlpha(QRgb rgb) // get alpha part of RGBA { return ((rgb >> 24) & 0xff); } Q_GUI_EXPORT_INLINE QRgb qRgb(int r, int g, int b)// set RGB value { return (0xffu << 24) | ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff); } Q_GUI_EXPORT_INLINE QRgb qRgba(int r, int g, int b, int a)// set RGBA value { return ((a & 0xff) << 24) | ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff); } Q_GUI_EXPORT_INLINE int qGray(int r, int g, int b)// convert R,G,B to gray 0..255 { return (r*11+g*16+b*5)/32; } Q_GUI_EXPORT_INLINE int qGray(QRgb rgb) // convert RGB to gray 0..255 { return qGray(qRed(rgb), qGreen(rgb), qBlue(rgb)); } Q_GUI_EXPORT_INLINE bool qIsGray(QRgb rgb) { return qRed(rgb) == qGreen(rgb) && qRed(rgb) == qBlue(rgb); } QT_END_NAMESPACE QT_END_HEADER #endif // QRGB_H
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_25) on Mon Sep 29 10:45:19 PDT 2014 --> <title>Uses of Class org.minueto.MinuetoInvalidColorValueException (MinuetoAPI API)</title> <meta name="date" content="2014-09-29"> <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.minueto.MinuetoInvalidColorValueException (MinuetoAPI API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../org/minueto/MinuetoInvalidColorValueException.html" title="class in org.minueto">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../overview-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../index.html?org/minueto/class-use/MinuetoInvalidColorValueException.html" target="_top">Frames</a></li> <li><a href="MinuetoInvalidColorValueException.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.minueto.MinuetoInvalidColorValueException" class="title">Uses of Class<br>org.minueto.MinuetoInvalidColorValueException</h2> </div> <div class="classUseContainer">No usage of org.minueto.MinuetoInvalidColorValueException</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../org/minueto/MinuetoInvalidColorValueException.html" title="class in org.minueto">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../overview-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../index.html?org/minueto/class-use/MinuetoInvalidColorValueException.html" target="_top">Frames</a></li> <li><a href="MinuetoInvalidColorValueException.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
Java
/** * @defgroup Win Win * @ingroup Elementary * * @image html win_inheritance_tree.png * @image latex win_inheritance_tree.eps * * @image html img/widget/win/preview-00.png * @image latex img/widget/win/preview-00.eps * * The window class of Elementary. Contains functions to manipulate * windows. The Evas engine used to render the window contents is specified * in the system or user elementary config files (whichever is found last), * and can be overridden with the ELM_ENGINE environment variable for * testing. Engines that may be supported (depending on Evas and Ecore-Evas * compilation setup and modules actually installed at runtime) are (listed * in order of best supported and most likely to be complete and work to * lowest quality). Note that ELM_ENGINE is really only needed for special * cases and debugging. you should normally use ELM_DISPLAY and ELM_ACCEL * environment variables, or core elementary config. ELM_DISPLAY can be set to * "x11" or "wl" to indicate the target display system (as on Linux systems * you may have both display systems available, so this selects which to use). * ELM_ACCEL may also be set to indicate if you want accelerations and which * kind to use. see elm_config_accel_preference_set(0 for details on this * environment variable values. * * @li "x11", "x", "software-x11", "software_x11" (Software rendering in X11) * @li "gl", "opengl", "opengl-x11", "opengl_x11" (OpenGL or OpenGL-ES2 * rendering in X11) * @li "shot:..." (Virtual screenshot renderer - renders to output file and * exits) * @li "fb", "software-fb", "software_fb" (Linux framebuffer direct software * rendering) * @li "fb", "software-fb", "software_fb" (Linux framebuffer accelerated * rendering) * @li "sdl", "software-sdl", "software_sdl" (SDL software rendering to SDL * buffer) * @li "gl-sdl", "gl_sdl", "opengl-sdl", "opengl_sdl" (OpenGL or OpenGL-ES2 * rendering using SDL as the buffer) * @li "gdi", "software-gdi", "software_gdi" (Windows WIN32 rendering via * GDI with software) * @li "ews" (rendering to EWS - Ecore + Evas Single Process Windowing System) * @li "gl-cocoa", "gl_cocoa", "opengl-cocoa", "opengl_cocoa" (OpenGL rendering in Cocoa) * @li "wayland_shm" (Wayland client SHM rendering) * @li "wayland_egl" (Wayland client OpenGL/EGL rendering) * @li "drm" (Linux drm/kms etc. direct display) * * All engines use a simple string to select the engine to render, EXCEPT * the "shot" engine. This actually encodes the output of the virtual * screenshot and how long to delay in the engine string. The engine string * is encoded in the following way: * * "shot:[delay=XX][:][repeat=DDD][:][file=XX]" * * Where options are separated by a ":" char if more than one option is * given, with delay, if provided being the first option and file the last * (order is important). The delay specifies how long to wait after the * window is shown before doing the virtual "in memory" rendering and then * save the output to the file specified by the file option (and then exit). * If no delay is given, the default is 0.5 seconds. If no file is given the * default output file is "out.png". Repeat option is for continuous * capturing screenshots. Repeat range is from 1 to 999 and filename is * fixed to "out001.png" Some examples of using the shot engine: * * ELM_ENGINE="shot:delay=1.0:repeat=5:file=elm_test.png" elementary_test * ELM_ENGINE="shot:delay=1.0:file=elm_test.png" elementary_test * ELM_ENGINE="shot:file=elm_test2.png" elementary_test * ELM_ENGINE="shot:delay=2.0" elementary_test * ELM_ENGINE="shot:" elementary_test * * Signals that you can add callbacks for are: * * @li "delete,request": the user requested to close the window. See * elm_win_autodel_set() and elm_win_autohide_set(). * @li "focus,in": window got focus (deprecated. use "focused" instead.) * @li "focus,out": window lost focus (deprecated. use "unfocused" instead.) * @li "moved": window that holds the canvas was moved * @li "withdrawn": window is still managed normally but removed from view * @li "iconified": window is minimized (perhaps into an icon or taskbar) * @li "normal": window is in a normal state (not withdrawn or iconified) * @li "stick": window has become sticky (shows on all desktops) * @li "unstick": window has stopped being sticky * @li "fullscreen": window has become fullscreen * @li "unfullscreen": window has stopped being fullscreen * @li "maximized": window has been maximized * @li "unmaximized": window has stopped being maximized * @li "ioerr": there has been a low-level I/O error with the display system * @li "indicator,prop,changed": an indicator's property has been changed * @li "rotation,changed": window rotation has been changed * @li "profile,changed": profile of the window has been changed * @li "focused" : When the win has received focus. (since 1.8) * @li "unfocused" : When the win has lost focus. (since 1.8) * @li "theme,changed" - The theme was changed. (since 1.13) * * Note that calling evas_object_show() after window contents creation is * recommended. It will trigger evas_smart_objects_calculate() and some backend * calls directly. For example, XMapWindow is called directly during * evas_object_show() in X11 engine. * * Examples: * @li @ref win_example_01 * * @{ */ #include <elm_win_common.h> #ifdef EFL_EO_API_SUPPORT #include <elm_win_eo.h> #endif #ifndef EFL_NOLEGACY_API_SUPPORT #include <elm_win_legacy.h> #endif /** * @} */
Java
<?php /** * @package tikiwiki */ // (c) Copyright 2002-2016 by authors of the Tiki Wiki CMS Groupware Project // // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // $Id$ $section = 'surveys'; require_once('tiki-setup.php'); include_once('lib/surveys/surveylib.php'); $auto_query_args = ['sort_mode', 'offset', 'find']; $access->check_feature('feature_surveys'); $access->check_permission('tiki_p_view_survey_stats'); if (! isset($_REQUEST["sort_mode"])) { $sort_mode = 'created_desc'; } else { $sort_mode = $_REQUEST["sort_mode"]; } if (! isset($_REQUEST["offset"])) { $offset = 0; } else { $offset = $_REQUEST["offset"]; } $smarty->assign_by_ref('offset', $offset); if (isset($_REQUEST["find"])) { $find = $_REQUEST["find"]; } else { $find = ''; } $smarty->assign('find', $find); $smarty->assign_by_ref('sort_mode', $sort_mode); $channels = $srvlib->list_surveys($offset, $maxRecords, $sort_mode, $find); $temp_max = count($channels["data"]); for ($i = 0; $i < $temp_max; $i++) { if ($userlib->object_has_one_permission($channels["data"][$i]["surveyId"], 'survey')) { $channels["data"][$i]["individual"] = 'y'; if ($userlib->object_has_permission($user, $channels["data"][$i]["surveyId"], 'survey', 'tiki_p_take_survey')) { $channels["data"][$i]["individual_tiki_p_take_survey"] = 'y'; } else { $channels["data"][$i]["individual_tiki_p_take_survey"] = 'n'; } if ($userlib->object_has_permission($user, $channels["data"][$i]["surveyId"], 'survey', 'tiki_p_view_survey_stats')) { $channels["data"][$i]["individual_tiki_p_view_survey_stats"] = 'y'; } else { $channels["data"][$i]["individual_tiki_p_view_survey_stats"] = 'n'; } if ($tiki_p_admin == 'y' || $userlib->object_has_permission($user, $channels["data"][$i]["surveyId"], 'survey', 'tiki_p_admin_surveys')) { $channels["data"][$i]["individual_tiki_p_take_survey"] = 'y'; $channels["data"][$i]["individual_tiki_p_view_survey_stats"] = 'y'; $channels["data"][$i]["individual_tiki_p_admin_surveys"] = 'y'; } } else { $channels["data"][$i]["individual"] = 'n'; } } $smarty->assign_by_ref('cant_pages', $channels["cant"]); $smarty->assign_by_ref('channels', $channels["data"]); $smarty->assign('section', $section); include_once('tiki-section_options.php'); ask_ticket('survey-stats'); // Display the template $smarty->assign('mid', 'tiki-survey_stats.tpl'); $smarty->display("tiki.tpl");
Java
/* * Interfaces MIB group interface - interfaces.h * */ #ifndef _MIBGROUP_INTERFACES_H #define _MIBGROUP_INTERFACES_H /*********************************************************************** * configure macros */ config_require(util_funcs) /* * conflicts with the new MFD rewrite */ config_exclude(if-mib/ifTable/ifTable) #if !defined(WIN32) && !defined(cygwin) config_require(if-mib/data_access/interface) #endif config_arch_require(solaris2, kernel_sunos5) /* * need get_address in var_route for some platforms (USE_SYSCTL_IFLIST). * Not sure if that can be translated into a config_arch_require, so be * indiscriminate for now. */ config_require(mibII/var_route) /*********************************************************************** */ #ifndef USING_IF_MIB_IFTABLE_MODULE #ifdef hpux11 #include <sys/mib.h> #else struct in_ifaddr; struct ifnet; #endif int Interface_Scan_Get_Count(void); int Interface_Index_By_Name(char *, int); void Interface_Scan_Init(void); #if defined(linux) || defined(sunV3) struct in_ifaddr { int dummy; }; #endif #if defined(hpux11) int Interface_Scan_Next(short *, char *, nmapi_phystat *); #else int Interface_Scan_Next(short *, char *, struct ifnet *, struct in_ifaddr *); #endif void init_interfaces(void); extern FindVarMethod var_interfaces; extern FindVarMethod var_ifEntry; #endif /* USING_IF_MIB_IFTABLE_MODULE */ #define IFNUMBER 0 #define IFINDEX 1 #define IFDESCR 2 #define NETSNMP_IFTYPE 3 #define IFMTU 4 #define IFSPEED 5 #define IFPHYSADDRESS 6 #define IFADMINSTATUS 7 #define IFOPERSTATUS 8 #define IFLASTCHANGE 9 #define IFINOCTETS 10 #define IFINUCASTPKTS 11 #define IFINNUCASTPKTS 12 #define IFINDISCARDS 13 #define IFINERRORS 14 #define IFINUNKNOWNPROTOS 15 #define IFOUTOCTETS 16 #define IFOUTUCASTPKTS 17 #define IFOUTNUCASTPKTS 18 #define IFOUTDISCARDS 19 #define IFOUTERRORS 20 #define IFOUTQLEN 21 #define IFSPECIFIC 22 #ifdef linux /* * this struct ifnet is cloned from the generic type and somewhat modified. * it will not work for other un*x'es... */ struct ifnet { char *if_name; /* name, e.g. ``en'' or ``lo'' */ char *if_unit; /* sub-unit for lower level driver */ short if_mtu; /* maximum transmission unit */ short if_flags; /* up/down, broadcast, etc. */ int if_metric; /* routing metric (external only) */ char if_hwaddr[6]; /* ethernet address */ int if_type; /* interface type: 1=generic, * 28=slip, ether=6, loopback=24 */ u_long if_speed; /* interface speed: in bits/sec */ struct sockaddr if_addr; /* interface's address */ struct sockaddr ifu_broadaddr; /* broadcast address */ struct sockaddr ia_subnetmask; /* interface's mask */ struct ifqueue { int ifq_len; int ifq_drops; } if_snd; /* output queue */ u_long if_ibytes; /* octets received on interface */ u_long if_ipackets; /* packets received on interface */ u_long if_ierrors; /* input errors on interface */ u_long if_iqdrops; /* input queue overruns */ u_long if_obytes; /* octets sent on interface */ u_long if_opackets; /* packets sent on interface */ u_long if_oerrors; /* output errors on interface */ u_long if_collisions; /* collisions on csma interfaces */ /* * end statistics */ struct ifnet *if_next; }; #endif /* linux */ #endif /* _MIBGROUP_INTERFACES_H */
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_60) on Sun Mar 20 22:06:58 PDT 2016 --> <title>Uses of Package com.JasonILTG.ScienceMod.item.armor</title> <meta name="date" content="2016-03-20"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Package com.JasonILTG.ScienceMod.item.armor"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Use</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/JasonILTG/ScienceMod/item/armor/package-use.html" target="_top">Frames</a></li> <li><a href="package-use.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 title="Uses of Package com.JasonILTG.ScienceMod.item.armor" class="title">Uses of Package<br>com.JasonILTG.ScienceMod.item.armor</h1> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../com/JasonILTG/ScienceMod/item/armor/package-summary.html">com.JasonILTG.ScienceMod.item.armor</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#com.JasonILTG.ScienceMod.init">com.JasonILTG.ScienceMod.init</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#com.JasonILTG.ScienceMod.item.armor">com.JasonILTG.ScienceMod.item.armor</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"><a name="com.JasonILTG.ScienceMod.init"> <!-- --> </a> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../../com/JasonILTG/ScienceMod/item/armor/package-summary.html">com.JasonILTG.ScienceMod.item.armor</a> used by <a href="../../../../../com/JasonILTG/ScienceMod/init/package-summary.html">com.JasonILTG.ScienceMod.init</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colOne"><a href="../../../../../com/JasonILTG/ScienceMod/item/armor/class-use/ArmorScience.html#com.JasonILTG.ScienceMod.init">ArmorScience</a> <div class="block">Wrapper class for all armor items in the mod.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="com.JasonILTG.ScienceMod.item.armor"> <!-- --> </a> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../../com/JasonILTG/ScienceMod/item/armor/package-summary.html">com.JasonILTG.ScienceMod.item.armor</a> used by <a href="../../../../../com/JasonILTG/ScienceMod/item/armor/package-summary.html">com.JasonILTG.ScienceMod.item.armor</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colOne"><a href="../../../../../com/JasonILTG/ScienceMod/item/armor/class-use/ArmorScience.html#com.JasonILTG.ScienceMod.item.armor">ArmorScience</a> <div class="block">Wrapper class for all armor items in the mod.</div> </td> </tr> <tr class="rowColor"> <td class="colOne"><a href="../../../../../com/JasonILTG/ScienceMod/item/armor/class-use/ArmorScienceSpecial.html#com.JasonILTG.ScienceMod.item.armor">ArmorScienceSpecial</a> <div class="block">Wrapper class for all armor items with special properties in the mod.</div> </td> </tr> <tr class="altColor"> <td class="colOne"><a href="../../../../../com/JasonILTG/ScienceMod/item/armor/class-use/Exoskeleton.html#com.JasonILTG.ScienceMod.item.armor">Exoskeleton</a>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colOne"><a href="../../../../../com/JasonILTG/ScienceMod/item/armor/class-use/IShieldProvider.html#com.JasonILTG.ScienceMod.item.armor">IShieldProvider</a>&nbsp;</td> </tr> <tr class="altColor"> <td class="colOne"><a href="../../../../../com/JasonILTG/ScienceMod/item/armor/class-use/ScienceShield.html#com.JasonILTG.ScienceMod.item.armor">ScienceShield</a>&nbsp;</td> </tr> </tbody> </table> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Use</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/JasonILTG/ScienceMod/item/armor/package-use.html" target="_top">Frames</a></li> <li><a href="package-use.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
Java
/* * Button representing user's Avatar * * Copyright (C) 2011 Martin Klapetek <martin.klapetek@gmail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "avatar-button.h" #include <QtGui/QWidgetAction> #include <QDataStream> #include <KFileDialog> #include <KMenu> #include <KLocalizedString> #include <KMessageBox> #include <KImageFilePreview> #include <TelepathyQt/Account> #include <KDE/KDebug> #include <KGlobalSettings> #include <KPixmapRegionSelectorDialog> #include <KPixmapRegionSelectorWidget> // It has been decided by a fair dice roll that 128px is a reasonable avatar // size limit in case the server (or Telepathy backend) does not provide // such information #define AVATAR_MIN_SIZE 64 #define AVATAR_MAX_SIZE 128 AvatarButton::AvatarButton(QWidget *parent) : QToolButton(parent) { KMenu *menu = new KMenu(this); setPopupMode(QToolButton::InstantPopup); setIconSize(QSize(64,64)); menu->addAction(KIcon(QLatin1String("document-open-folder")), i18n("Load from file..."), this, SLOT(onLoadAvatarFromFile())); menu->addAction(KIcon(QLatin1String("edit-clear")), i18n("Clear Avatar"), this, SLOT(onClearAvatar())); setMenu(menu); } AvatarButton::~AvatarButton() { } void AvatarButton::setAvatar(const Tp::Avatar &avatar) { m_avatar = avatar; if (! avatar.avatarData.isNull()) { KIcon avatarIcon; QPixmap avatarPixmap = QPixmap::fromImage(QImage::fromData(avatar.avatarData)); //scale oversized avatars to fit, but don't stretch smaller avatars avatarIcon.addPixmap(avatarPixmap.scaled(iconSize().boundedTo(avatarPixmap.size()), Qt::KeepAspectRatio, Qt::SmoothTransformation)); setIcon(avatarIcon); } else { setIcon(KIcon(QLatin1String("im-user"))); } } Tp::Avatar AvatarButton::avatar() const { return m_avatar; } void AvatarButton::setAccount(const Tp::AccountPtr& account) { m_account = account; } void AvatarButton::onLoadAvatarFromFile() { QStringList mimeTypes; if (m_account) { mimeTypes = m_account->avatarRequirements().supportedMimeTypes(); } if (mimeTypes.isEmpty()) { mimeTypes << QLatin1String("image/jpeg") << QLatin1String("image/png") << QLatin1String("imgae/gif"); } QPointer<KFileDialog> dialog = new KFileDialog(KUrl::fromPath(KGlobalSettings::picturesPath()), mimeTypes.join(QLatin1String(" ")), this); dialog->setOperationMode(KFileDialog::Opening); dialog->setPreviewWidget(new KImageFilePreview(dialog)); dialog->setCaption(i18n("Please choose your avatar")); KUrl fileUrl; if (dialog->exec()) { if (!dialog) { return; } fileUrl = dialog->selectedUrl(); } delete dialog; if (fileUrl.isEmpty()) { return; } const QPixmap pixmap(fileUrl.toLocalFile()); const Tp::AvatarSpec spec = m_account->avatarRequirements(); const int maxWidth = spec.maximumWidth() > 0 ? spec.maximumWidth() : AVATAR_MAX_SIZE; const int maxHeight = spec.maximumHeight() > 0 ? spec.maximumHeight() : AVATAR_MAX_SIZE; const int minWidth = spec.minimumWidth() > 0 ? spec.minimumWidth() : AVATAR_MIN_SIZE; const int minHeight = spec.minimumHeight() > 0 ? spec.minimumHeight() : AVATAR_MIN_SIZE; QPixmap finalPixmap; if (pixmap.width() > spec.maximumWidth() || pixmap.height() > spec.maximumHeight()) { finalPixmap = cropPixmap(pixmap, maxWidth, maxHeight, minWidth, minHeight); } else { finalPixmap = pixmap; if (pixmap.width() < minWidth) { finalPixmap = finalPixmap.scaledToWidth(minWidth, Qt::SmoothTransformation); } if (pixmap.height() < minHeight) { finalPixmap = finalPixmap.scaledToHeight(minHeight, Qt::SmoothTransformation); } } if (finalPixmap.isNull()) { return; } Tp::Avatar avatar; avatar.MIMEType = QLatin1String("image/png"); QDataStream stream(&avatar.avatarData, QIODevice::WriteOnly); if (!finalPixmap.save(stream.device(), "PNG")) { KMessageBox::error(this, i18n("Failed to load avatar.")); return; } setAvatar(avatar); Q_EMIT avatarChanged(); } QPixmap AvatarButton::cropPixmap(const QPixmap &pixmap, int maxWidth, int maxHeight, int minWidth, int minHeight) const { //if there's no image we don't need to select a region if (pixmap.isNull()) { return pixmap; } QPointer<KPixmapRegionSelectorDialog> regionDlg = new KPixmapRegionSelectorDialog(); KPixmapRegionSelectorWidget *widget = regionDlg->pixmapRegionSelectorWidget(); widget->setPixmap(pixmap); widget->setSelectionAspectRatio(maxWidth, maxHeight); if (regionDlg->exec()) { if (!regionDlg) { return QPixmap(); } delete regionDlg; QImage selectedImage = widget->selectedImage(); if (selectedImage.width() > maxWidth || selectedImage.height() > maxHeight) { return QPixmap::fromImage(selectedImage.scaled(maxWidth, maxHeight, Qt::KeepAspectRatio)); } else if (selectedImage.width() < minWidth || selectedImage.height() < minHeight) { return QPixmap::fromImage(selectedImage.scaled(minWidth, minHeight, Qt::KeepAspectRatio)); } else { return QPixmap::fromImage(widget->selectedImage()); } } delete regionDlg; return QPixmap(); } void AvatarButton::onClearAvatar() { setAvatar(Tp::Avatar()); Q_EMIT avatarChanged(); }
Java
/****************************************************************************** * $Id: ogr_core.h 23947 2012-02-11 17:37:02Z rouault $ * * Project: OpenGIS Simple Features Reference Implementation * Purpose: Define some core portability services for cross-platform OGR code. * Author: Frank Warmerdam, warmerdam@pobox.com * ****************************************************************************** * Copyright (c) 1999, Frank Warmerdam * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef OGR_CORE_H_INCLUDED #define OGR_CORE_H_INCLUDED #include "cpl_port.h" #include "gdal_version.h" /** * \file * * Core portability services for cross-platform OGR code. */ /** * Simple container for a bounding region. */ #if defined(__cplusplus) && !defined(CPL_SUPRESS_CPLUSPLUS) class CPL_DLL OGREnvelope { public: OGREnvelope() : MinX(0.0), MaxX(0.0), MinY(0.0), MaxY(0.0) {} OGREnvelope(const OGREnvelope &oOther) : MinX(oOther.MinX), MaxX(oOther.MaxX), MinY(oOther.MinY), MaxY(oOther.MaxY) {} double MinX; double MaxX; double MinY; double MaxY; int IsInit() const { return MinX != 0 || MinY != 0 || MaxX != 0 || MaxY != 0; } void Merge(OGREnvelope const &sOther) { if (IsInit()) { MinX = MIN(MinX, sOther.MinX); MaxX = MAX(MaxX, sOther.MaxX); MinY = MIN(MinY, sOther.MinY); MaxY = MAX(MaxY, sOther.MaxY); } else { MinX = sOther.MinX; MaxX = sOther.MaxX; MinY = sOther.MinY; MaxY = sOther.MaxY; } } void Merge(double dfX, double dfY) { if (IsInit()) { MinX = MIN(MinX, dfX); MaxX = MAX(MaxX, dfX); MinY = MIN(MinY, dfY); MaxY = MAX(MaxY, dfY); } else { MinX = MaxX = dfX; MinY = MaxY = dfY; } } void Intersect(OGREnvelope const &sOther) { if (Intersects(sOther)) { if (IsInit()) { MinX = MAX(MinX, sOther.MinX); MaxX = MIN(MaxX, sOther.MaxX); MinY = MAX(MinY, sOther.MinY); MaxY = MIN(MaxY, sOther.MaxY); } else { MinX = sOther.MinX; MaxX = sOther.MaxX; MinY = sOther.MinY; MaxY = sOther.MaxY; } } else { MinX = 0; MaxX = 0; MinY = 0; MaxY = 0; } } int Intersects(OGREnvelope const &other) const { return MinX <= other.MaxX && MaxX >= other.MinX && MinY <= other.MaxY && MaxY >= other.MinY; } int Contains(OGREnvelope const &other) const { return MinX <= other.MinX && MinY <= other.MinY && MaxX >= other.MaxX && MaxY >= other.MaxY; } }; #else typedef struct { double MinX; double MaxX; double MinY; double MaxY; } OGREnvelope; #endif /** * Simple container for a bounding region in 3D. */ #if defined(__cplusplus) && !defined(CPL_SUPRESS_CPLUSPLUS) class CPL_DLL OGREnvelope3D : public OGREnvelope { public: OGREnvelope3D() : OGREnvelope(), MinZ(0.0), MaxZ(0.0) {} OGREnvelope3D(const OGREnvelope3D &oOther) : OGREnvelope(oOther), MinZ(oOther.MinZ), MaxZ(oOther.MaxZ) {} double MinZ; double MaxZ; int IsInit() const { return MinX != 0 || MinY != 0 || MaxX != 0 || MaxY != 0 || MinZ != 0 || MaxZ != 0; } void Merge(OGREnvelope3D const &sOther) { if (IsInit()) { MinX = MIN(MinX, sOther.MinX); MaxX = MAX(MaxX, sOther.MaxX); MinY = MIN(MinY, sOther.MinY); MaxY = MAX(MaxY, sOther.MaxY); MinZ = MIN(MinZ, sOther.MinZ); MaxZ = MAX(MaxZ, sOther.MaxZ); } else { MinX = sOther.MinX; MaxX = sOther.MaxX; MinY = sOther.MinY; MaxY = sOther.MaxY; MinZ = sOther.MinZ; MaxZ = sOther.MaxZ; } } void Merge(double dfX, double dfY, double dfZ) { if (IsInit()) { MinX = MIN(MinX, dfX); MaxX = MAX(MaxX, dfX); MinY = MIN(MinY, dfY); MaxY = MAX(MaxY, dfY); MinZ = MIN(MinZ, dfZ); MaxZ = MAX(MaxZ, dfZ); } else { MinX = MaxX = dfX; MinY = MaxY = dfY; MinZ = MaxZ = dfZ; } } void Intersect(OGREnvelope3D const &sOther) { if (Intersects(sOther)) { if (IsInit()) { MinX = MAX(MinX, sOther.MinX); MaxX = MIN(MaxX, sOther.MaxX); MinY = MAX(MinY, sOther.MinY); MaxY = MIN(MaxY, sOther.MaxY); MinZ = MAX(MinZ, sOther.MinZ); MaxZ = MIN(MaxZ, sOther.MaxZ); } else { MinX = sOther.MinX; MaxX = sOther.MaxX; MinY = sOther.MinY; MaxY = sOther.MaxY; MinZ = sOther.MinZ; MaxZ = sOther.MaxZ; } } else { MinX = 0; MaxX = 0; MinY = 0; MaxY = 0; MinZ = 0; MaxZ = 0; } } int Intersects(OGREnvelope3D const &other) const { return MinX <= other.MaxX && MaxX >= other.MinX && MinY <= other.MaxY && MaxY >= other.MinY && MinZ <= other.MaxZ && MaxZ >= other.MinZ; } int Contains(OGREnvelope3D const &other) const { return MinX <= other.MinX && MinY <= other.MinY && MaxX >= other.MaxX && MaxY >= other.MaxY && MaxZ >= other.MaxZ && MaxZ >= other.MaxZ; } }; #else typedef struct { double MinX; double MaxX; double MinY; double MaxY; double MinZ; double MaxZ; } OGREnvelope3D; #endif CPL_C_START void CPL_DLL*OGRMalloc(size_t); void CPL_DLL*OGRCalloc(size_t, size_t); void CPL_DLL*OGRRealloc(void*, size_t); char CPL_DLL* OGRStrdup(const char*); void CPL_DLL OGRFree(void*); typedef int OGRErr; #define OGRERR_NONE 0 #define OGRERR_NOT_ENOUGH_DATA 1 /* not enough data to deserialize */ #define OGRERR_NOT_ENOUGH_MEMORY 2 #define OGRERR_UNSUPPORTED_GEOMETRY_TYPE 3 #define OGRERR_UNSUPPORTED_OPERATION 4 #define OGRERR_CORRUPT_DATA 5 #define OGRERR_FAILURE 6 #define OGRERR_UNSUPPORTED_SRS 7 #define OGRERR_INVALID_HANDLE 8 typedef int OGRBoolean; /* -------------------------------------------------------------------- */ /* ogr_geometry.h related definitions. */ /* -------------------------------------------------------------------- */ /** * List of well known binary geometry types. These are used within the BLOBs * but are also returned from OGRGeometry::getGeometryType() to identify the * type of a geometry object. */ typedef enum { wkbUnknown = 0, /**< unknown type, non-standard */ wkbPoint = 1, /**< 0-dimensional geometric object, standard WKB */ wkbLineString = 2, /**< 1-dimensional geometric object with linear * interpolation between Points, standard WKB */ wkbPolygon = 3, /**< planar 2-dimensional geometric object defined * by 1 exterior boundary and 0 or more interior * boundaries, standard WKB */ wkbMultiPoint = 4, /**< GeometryCollection of Points, standard WKB */ wkbMultiLineString = 5, /**< GeometryCollection of LineStrings, standard WKB */ wkbMultiPolygon = 6, /**< GeometryCollection of Polygons, standard WKB */ wkbGeometryCollection = 7, /**< geometric object that is a collection of 1 or more geometric objects, standard WKB */ wkbNone = 100, /**< non-standard, for pure attribute records */ wkbLinearRing = 101, /**< non-standard, just for createGeometry() */ wkbPoint25D = 0x80000001, /**< 2.5D extension as per 99-402 */ wkbLineString25D = 0x80000002, /**< 2.5D extension as per 99-402 */ wkbPolygon25D = 0x80000003, /**< 2.5D extension as per 99-402 */ wkbMultiPoint25D = 0x80000004, /**< 2.5D extension as per 99-402 */ wkbMultiLineString25D = 0x80000005, /**< 2.5D extension as per 99-402 */ wkbMultiPolygon25D = 0x80000006, /**< 2.5D extension as per 99-402 */ wkbGeometryCollection25D = 0x80000007 /**< 2.5D extension as per 99-402 */ } OGRwkbGeometryType; #define wkb25DBit 0x80000000 #define wkbFlatten(x) ((OGRwkbGeometryType) ((x)& (~wkb25DBit))) #define ogrZMarker 0x21125711 const char CPL_DLL* OGRGeometryTypeToName(OGRwkbGeometryType eType); OGRwkbGeometryType CPL_DLL OGRMergeGeometryTypes(OGRwkbGeometryType eMain, OGRwkbGeometryType eExtra); typedef enum { wkbXDR = 0, /* MSB/Sun/Motoroloa: Most Significant Byte First */ wkbNDR = 1 /* LSB/Intel/Vax: Least Significant Byte First */ } OGRwkbByteOrder; #ifndef NO_HACK_FOR_IBM_DB2_V72 # define HACK_FOR_IBM_DB2_V72 #endif #ifdef HACK_FOR_IBM_DB2_V72 # define DB2_V72_FIX_BYTE_ORDER(x) ((((x) & 0x31) == (x)) ? (OGRwkbByteOrder) ((x) & 0x1) : (x)) # define DB2_V72_UNFIX_BYTE_ORDER(x) ((unsigned char) (OGRGeometry::bGenerate_DB2_V72_BYTE_ORDER ? ((x) | 0x30) : (x))) #else # define DB2_V72_FIX_BYTE_ORDER(x) (x) # define DB2_V72_UNFIX_BYTE_ORDER(x) (x) #endif #define ALTER_NAME_FLAG 0x1 #define ALTER_TYPE_FLAG 0x2 #define ALTER_WIDTH_PRECISION_FLAG 0x4 #define ALTER_ALL_FLAG (ALTER_NAME_FLAG | ALTER_TYPE_FLAG | ALTER_WIDTH_PRECISION_FLAG) /************************************************************************/ /* ogr_feature.h related definitions. */ /************************************************************************/ /** * List of feature field types. This list is likely to be extended in the * future ... avoid coding applications based on the assumption that all * field types can be known. */ typedef enum { /** Simple 32bit integer */ OFTInteger = 0, /** List of 32bit integers */ OFTIntegerList = 1, /** Double Precision floating point */ OFTReal = 2, /** List of doubles */ OFTRealList = 3, /** String of ASCII chars */ OFTString = 4, /** Array of strings */ OFTStringList = 5, /** deprecated */ OFTWideString = 6, /** deprecated */ OFTWideStringList = 7, /** Raw Binary data */ OFTBinary = 8, /** Date */ OFTDate = 9, /** Time */ OFTTime = 10, /** Date and Time */ OFTDateTime = 11, OFTMaxType = 11 } OGRFieldType; /** * Display justification for field values. */ typedef enum { OJUndefined = 0, OJLeft = 1, OJRight = 2 } OGRJustification; #define OGRNullFID -1 #define OGRUnsetMarker -21121 /************************************************************************/ /* OGRField */ /************************************************************************/ /** * OGRFeature field attribute value union. */ typedef union { int Integer; double Real; char *String; struct { int nCount; int *paList; } IntegerList; struct { int nCount; double *paList; } RealList; struct { int nCount; char **paList; } StringList; struct { int nCount; GByte *paData; } Binary; struct { int nMarker1; int nMarker2; } Set; struct { GInt16 Year; GByte Month; GByte Day; GByte Hour; GByte Minute; GByte Second; GByte TZFlag; /* 0=unknown, 1=localtime(ambiguous), 100=GMT, 104=GMT+1, 80=GMT-5, etc */ } Date; } OGRField; int CPL_DLL OGRParseDate(const char *pszInput, OGRField *psOutput, int nOptions); /* -------------------------------------------------------------------- */ /* Constants from ogrsf_frmts.h for capabilities. */ /* -------------------------------------------------------------------- */ #define OLCRandomRead "RandomRead" #define OLCSequentialWrite "SequentialWrite" #define OLCRandomWrite "RandomWrite" #define OLCFastSpatialFilter "FastSpatialFilter" #define OLCFastFeatureCount "FastFeatureCount" #define OLCFastGetExtent "FastGetExtent" #define OLCCreateField "CreateField" #define OLCDeleteField "DeleteField" #define OLCReorderFields "ReorderFields" #define OLCAlterFieldDefn "AlterFieldDefn" #define OLCTransactions "Transactions" #define OLCDeleteFeature "DeleteFeature" #define OLCFastSetNextByIndex "FastSetNextByIndex" #define OLCStringsAsUTF8 "StringsAsUTF8" #define OLCIgnoreFields "IgnoreFields" #define ODsCCreateLayer "CreateLayer" #define ODsCDeleteLayer "DeleteLayer" #define ODrCCreateDataSource "CreateDataSource" #define ODrCDeleteDataSource "DeleteDataSource" /************************************************************************/ /* ogr_featurestyle.h related definitions. */ /************************************************************************/ /** * OGRStyleTool derived class types (returned by GetType()). */ typedef enum ogr_style_tool_class_id { OGRSTCNone = 0, OGRSTCPen = 1, OGRSTCBrush = 2, OGRSTCSymbol = 3, OGRSTCLabel = 4, OGRSTCVector = 5 } OGRSTClassId; /** * List of units supported by OGRStyleTools. */ typedef enum ogr_style_tool_units_id { OGRSTUGround = 0, OGRSTUPixel = 1, OGRSTUPoints = 2, OGRSTUMM = 3, OGRSTUCM = 4, OGRSTUInches = 5 } OGRSTUnitId; /** * List of parameters for use with OGRStylePen. */ typedef enum ogr_style_tool_param_pen_id { OGRSTPenColor = 0, OGRSTPenWidth = 1, OGRSTPenPattern = 2, OGRSTPenId = 3, OGRSTPenPerOffset = 4, OGRSTPenCap = 5, OGRSTPenJoin = 6, OGRSTPenPriority = 7, OGRSTPenLast = 8 } OGRSTPenParam; /** * List of parameters for use with OGRStyleBrush. */ typedef enum ogr_style_tool_param_brush_id { OGRSTBrushFColor = 0, OGRSTBrushBColor = 1, OGRSTBrushId = 2, OGRSTBrushAngle = 3, OGRSTBrushSize = 4, OGRSTBrushDx = 5, OGRSTBrushDy = 6, OGRSTBrushPriority = 7, OGRSTBrushLast = 8 } OGRSTBrushParam; /** * List of parameters for use with OGRStyleSymbol. */ typedef enum ogr_style_tool_param_symbol_id { OGRSTSymbolId = 0, OGRSTSymbolAngle = 1, OGRSTSymbolColor = 2, OGRSTSymbolSize = 3, OGRSTSymbolDx = 4, OGRSTSymbolDy = 5, OGRSTSymbolStep = 6, OGRSTSymbolPerp = 7, OGRSTSymbolOffset = 8, OGRSTSymbolPriority = 9, OGRSTSymbolFontName = 10, OGRSTSymbolOColor = 11, OGRSTSymbolLast = 12 } OGRSTSymbolParam; /** * List of parameters for use with OGRStyleLabel. */ typedef enum ogr_style_tool_param_label_id { OGRSTLabelFontName = 0, OGRSTLabelSize = 1, OGRSTLabelTextString = 2, OGRSTLabelAngle = 3, OGRSTLabelFColor = 4, OGRSTLabelBColor = 5, OGRSTLabelPlacement = 6, OGRSTLabelAnchor = 7, OGRSTLabelDx = 8, OGRSTLabelDy = 9, OGRSTLabelPerp = 10, OGRSTLabelBold = 11, OGRSTLabelItalic = 12, OGRSTLabelUnderline = 13, OGRSTLabelPriority = 14, OGRSTLabelStrikeout = 15, OGRSTLabelStretch = 16, OGRSTLabelAdjHor = 17, OGRSTLabelAdjVert = 18, OGRSTLabelHColor = 19, OGRSTLabelOColor = 20, OGRSTLabelLast = 21 } OGRSTLabelParam; /* ------------------------------------------------------------------- */ /* Version checking */ /* -------------------------------------------------------------------- */ /* Note to developers : please keep this section in sync with gdal.h */ #ifndef GDAL_VERSION_INFO_DEFINED #define GDAL_VERSION_INFO_DEFINED const char CPL_DLL * CPL_STDCALL GDALVersionInfo(const char*); #endif #ifndef GDAL_CHECK_VERSION /** Return TRUE if GDAL library version at runtime matches nVersionMajor.nVersionMinor. The purpose of this method is to ensure that calling code will run with the GDAL version it is compiled for. It is primarly intented for external plugins. @param nVersionMajor Major version to be tested against @param nVersionMinor Minor version to be tested against @param pszCallingComponentName If not NULL, in case of version mismatch, the method will issue a failure mentionning the name of the calling component. */ int CPL_DLL CPL_STDCALL GDALCheckVersion(int nVersionMajor, int nVersionMinor, const char *pszCallingComponentName); /** Helper macro for GDALCheckVersion */ #define GDAL_CHECK_VERSION(pszCallingComponentName) \ GDALCheckVersion(GDAL_VERSION_MAJOR, GDAL_VERSION_MINOR, pszCallingComponentName) #endif CPL_C_END #endif /* ndef OGR_CORE_H_INCLUDED */
Java
/*========================================================================= Program: FEMUS Module: PetscLinearEquationSolver Authors: Eugenio Aulisa, Simone Bnà Copyright (c) FEMTTU All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #ifndef __femus_algebra_GmresPetscLinearEquationSolver_hpp__ #define __femus_algebra_GmresPetscLinearEquationSolver_hpp__ #include "FemusConfig.hpp" #ifdef HAVE_PETSC #ifdef HAVE_MPI #include <mpi.h> #endif //---------------------------------------------------------------------------- // includes : //---------------------------------------------------------------------------- #include "LinearEquationSolver.hpp" namespace femus { /** * This class inherits the abstract class LinearEquationSolver. In this class the solver is implemented using the PETSc package */ class GmresPetscLinearEquationSolver : public LinearEquationSolver { public: /** Constructor. Initializes Petsc data structures */ GmresPetscLinearEquationSolver(const unsigned &igrid, Solution *other_solution); /// Destructor. ~GmresPetscLinearEquationSolver(); protected: /// Release all memory and clear data structures. void Clear(); void SetTolerances(const double &rtol, const double &atol, const double &divtol, const unsigned &maxits, const unsigned &restart); void Init(Mat& Amat, Mat &Pmat); void Solve(const vector <unsigned>& variable_to_be_solved, const bool &ksp_clean); void MGInit(const MgSmootherType & mg_smoother_type, const unsigned &levelMax, const char* outer_ksp_solver = KSPGMRES); void MGSetLevel(LinearEquationSolver *LinSolver, const unsigned &maxlevel, const vector <unsigned> &variable_to_be_solved, SparseMatrix* PP, SparseMatrix* RR, const unsigned &npre, const unsigned &npost); void RemoveNullSpace(); void GetNullSpaceBase( std::vector < Vec > &nullspBase); void ZerosBoundaryResiduals(); void SetPenalty(); void SetRichardsonScaleFactor(const double & richardsonScaleFactor){ _richardsonScaleFactor = richardsonScaleFactor; } virtual void BuildBdcIndex(const vector <unsigned> &variable_to_be_solved); virtual void SetPreconditioner(KSP& subksp, PC& subpc); void MGSolve(const bool ksp_clean); inline void MGClear() { KSPDestroy(&_ksp); } inline KSP* GetKSP() { return &_ksp; }; /// Set the user-specified solver stored in \p _solver_type void SetPetscSolverType(KSP &ksp); /** @deprecated, remove soon */ std::pair<unsigned int, double> solve(SparseMatrix& matrix_in, SparseMatrix& precond_in, NumericVector& solution_in, NumericVector& rhs_in, const double tol, const unsigned int m_its); /** @deprecated, remove soon */ void init(SparseMatrix* matrix); protected: // member data KSP _ksp; ///< Krylov subspace context PC _pc; ///< Preconditioner context PetscReal _rtol; PetscReal _abstol; PetscReal _dtol; PetscInt _maxits; PetscInt _restart; vector <PetscInt> _bdcIndex; bool _bdcIndexIsInitialized; double _richardsonScaleFactor; }; // ============================================= inline GmresPetscLinearEquationSolver::GmresPetscLinearEquationSolver(const unsigned &igrid, Solution *other_solution) : LinearEquationSolver(igrid, other_solution) { if(igrid == 0) { this->_preconditioner_type = MLU_PRECOND; this->_solver_type = PREONLY; } else { this->_preconditioner_type = ILU_PRECOND; this->_solver_type = GMRES; } _rtol = 1.e-5; _abstol = 1.e-50; _dtol = 1.e+5; _maxits = 1000; _restart = 30; _richardsonScaleFactor = 0.5; _bdcIndexIsInitialized = 0; _printSolverInfo = false; } // ============================================= inline GmresPetscLinearEquationSolver::~GmresPetscLinearEquationSolver() { this->Clear(); } // ================================================ inline void GmresPetscLinearEquationSolver::Clear() { // if(this->initialized()) { this->_is_initialized = false; KSPDestroy(&_ksp); } } } //end namespace femus #endif #endif
Java
#include <math.h> #include <stdlib.h> #include <stdio.h> #include <rpnmacros.h> #include <unistd.h> #include <zfstlib.h> #include <malloc.h> #include <string.h> int c_armn_compress32(unsigned char *, float *, int, int, int, int); int c_armn_uncompress32(float *fld, unsigned char *zstream, int ni, int nj, int nk, int nchiffres_sign); int c_fstzip32(unsigned int *zfld, unsigned int *fld, int ni, int nj, int nk, int step, int nbits, int remaining_space); int c_fstzip_parallelogram32(unsigned int *zfld, int *zlng, unsigned int *fld, int ni, int nj, int step, int nbits, word *header); int f77name(armn_compress32)(unsigned char *, float *, int *, int *, int *, int *); int f77name(armn_uncompress32)(float *fld, unsigned char *zstream, int *ni, int *nj, int *nk, int *nchiffres_sign); void c_fstunzip(unsigned int *fld, unsigned int *zfld, int ni, int nj, int nbits); void pack1bitRLE(unsigned int z[], unsigned int *zlng, unsigned char ufld[], int npts); void packTokensParallelogram(unsigned int z[], unsigned int *zlng, unsigned short ufld[], int ni, int nj, int nbits, int istep, word *header); void packTokensParallelogram32(unsigned int z[], int *zlng, unsigned int ufld[], int ni, int nj, int nbits, int istep, int remaining_space); void packTokensParallelogram_8(unsigned int z[], unsigned int *zlng, unsigned char ufld[], int ni, int nj, int nbits, int istep); void pack_stream_nbits_32(unsigned int z[], unsigned int *zlng, unsigned int ufld[], int npts, int nbits); void unpackTokensParallelogram(unsigned short ufld[], unsigned int z[], int ni, int nj, int nbits, int istep, word *header); void unpackTokensParallelogram32(unsigned int ufld[], unsigned int z[], int ni, int nj, int nbits, int istep); void unpackTokensParallelogram_8(unsigned char ufld[], unsigned int z[], int ni, int nj, int nbits, int istep); int compact_mask_char(unsigned int *dest, unsigned char *src, int npts); int uncompact_mask_char(int *dest, unsigned int *src, int npts); void pack1bitRLE(unsigned int z[], unsigned int *zlng, unsigned char ufld[], int npts); void pack_stream_nbits_16(unsigned int z[], unsigned int *zlng, unsigned short ufld[], int npts, int nbits); void pack_stream_nbits_32(unsigned int z[], unsigned int *zlng, unsigned int ufld[], int npts, int nbits); void pack_stream_nbits_8(unsigned int z[], unsigned int *zlng, unsigned char ufld[], int npts, int nbits); void unpack1bitRLE(unsigned char ufld[], unsigned int z[], unsigned int *zlng, int npts); void unpack_stream_nbits_16(unsigned short ufld[], unsigned int z[], int npts, int nbits); void unpack_stream_nbits_32(unsigned int ufld[], unsigned int z[], int npts, int nbits); void unpack_stream_nbits_8(unsigned char ufld[], unsigned int z[], int npts, int nbits); #define MEME_SIGNE_POSITIF 0x00 #define MEME_SIGNE_NEGATIF 0x10 #define DIFF_SIGNE_PACKED 0x20 #define DIFF_SIGNE_STREAM 0x30 #define MEME_EXPOSANT 0x00 #define DIFF_EXPOSANT_PACKED 0x08 #define DIFF_EXPOSANT_STREAM 0x0C #define MANTISSE_PACKED 0x00 #define MANTISSE_STREAM 0x01 #define SEQUENCE 0 #define COUNT 1 #define ZERO 0 #define UN 1 static unsigned char fastlog[256]; static int once = 0; extern int zfst_msglevel; int f77name(armn_compress32)(unsigned char *zstream, float *fld, int *ni, int *nj, int *nk, int *nbits) { return c_armn_compress32(zstream, fld, *ni, *nj, *nk, *nbits); } int c_armn_compress32(unsigned char *zstream, float *fld, int ni, int nj, int nk, int znbits) { float *p_fld; int i, meme_signe, remaining_space; int nbits; unsigned char *exposant, *exposant2; unsigned char *le_pointeur, *pos_lng_signe, *pos_lng_exposant, *pos_lng_mantisse; unsigned char *signe, *zsigne, code_signe, code_exposant, code_mantisse; unsigned char codes; unsigned int *mantisse, *mantisse_stream, *la_mantisse,*zmantisse, exp_base; unsigned int *temp; unsigned int exp_min, exp_max, *zexposant; unsigned int le_signe_or, le_signe_and; unsigned int npts, zlng, lng_signe, lng_exposant,lng_mantisse,nbits_needed; unsigned int zieee_info; _fstzip zfstzip; _floatint r_exp_max; if (ni < 16 || nj < 16) { zlng = -1; fprintf(stderr, "*** <armn_compress32> : The dimensions of NI and NJ have to be > 16\n"); return zlng; } nbits = znbits - 9; memset(&zfstzip, (int)NULL, sizeof(_fstzip)); zfstzip.predictor_type = PARALLELOGRAM32; zfstzip.step = 3; zfstzip.degree = 1; zfstzip.nbits = nbits; zfstzip.levels = 1; zfstzip.version = 2; mantisse_stream = NULL; pos_lng_signe = NULL; npts = ni * nj; signe = (unsigned char *) malloc(2*npts * sizeof(unsigned char)); zsigne = (unsigned char *) malloc(2*npts * sizeof(unsigned char)); exposant = (unsigned char *) malloc(2*npts * sizeof(unsigned char)); exposant2 = (unsigned char *) malloc(2*npts * sizeof(unsigned char)); zexposant = (unsigned int *) malloc(npts*sizeof(unsigned int)); mantisse = (unsigned int *) malloc(2*npts * sizeof(unsigned int)); zmantisse = (unsigned int *) malloc(2*npts * sizeof(unsigned int)); le_signe_or = 0; le_signe_and = 0xFFFFFFFF; p_fld = fld; for (i=0; i < npts; i++) { temp = (unsigned int *) p_fld; signe[i] = *temp >> 31; le_signe_or |= *temp; le_signe_and &= *temp; exposant[i] = (*temp >> 23) & 0xff; exposant2[i] = exposant[i]; mantisse[i] = (*temp & 0x07fffff); p_fld++; } if (nbits < 23) { for (i=0; i < npts; i++) { mantisse[i] = (mantisse[i] >> (23-nbits)); } } meme_signe=0; if ((le_signe_or>>31) == (le_signe_and>>31)) { meme_signe=1; } exp_min = exposant2[0]; exp_max = exp_min; for (i=0; i < npts; i++) { if (exposant2[i] < exp_min) exp_min = exposant2[i]; if (exposant2[i] > exp_max) exp_max = exposant2[i]; } exp_base = exp_min; exp_max = exp_max - exp_min; exp_min = 0; for (i=0; i < npts; i++) { exposant2[i] = exposant2[i]- exp_base; } if (exp_max == exp_min) { nbits_needed =0; } else { nbits_needed =(int)(1+log(exp_max+0.5)/log(2.0)); r_exp_max.f = (float)(exp_max); nbits_needed = (r_exp_max.i >> 23) - 126; } /* ------------------- Encodage du stream de signe ------------------------- */ le_pointeur = &(zstream[8]); if (meme_signe == 1) { lng_signe = 0; if ((le_signe_or >> 31) == 1) { code_signe = MEME_SIGNE_NEGATIF; } else { code_signe = MEME_SIGNE_POSITIF; } } else { pos_lng_signe = le_pointeur; le_pointeur += sizeof(unsigned int); pack1bitRLE((unsigned int *)le_pointeur, &lng_signe, signe, npts); code_signe = DIFF_SIGNE_PACKED; } if (lng_signe > (npts/4)) { compact_mask_char((unsigned int *) le_pointeur, signe, npts); lng_signe = 1 + (npts >> 5); code_signe = DIFF_SIGNE_STREAM; } if (0 != (lng_signe%4)) { lng_signe += (4 - (lng_signe%4)); } le_pointeur+= lng_signe; if (code_signe == DIFF_SIGNE_PACKED || code_signe == DIFF_SIGNE_STREAM ) { memcpy(pos_lng_signe, &lng_signe, sizeof(unsigned int)); } /* ------------------- Encodage du stream d'exposants ------------------------- */ pos_lng_exposant = le_pointeur; if (nbits_needed == 0) { lng_exposant = 0; code_exposant = MEME_EXPOSANT; } else { code_exposant = DIFF_EXPOSANT_PACKED; le_pointeur += sizeof(unsigned int); packTokensParallelogram_8((unsigned int *)le_pointeur, &lng_exposant, exposant2, ni, nj, nbits_needed, 3); if (lng_exposant > ni*nj) { zlng = -1; fprintf(stderr, "*** <armn_compress32> : Exponent range too large\n"); fprintf(stderr, "*** <armn_compress32> : Original field left uncompressed\n"); return zlng; /*pack_stream_nbits_8((unsigned int *)le_pointeur, &lng_exposant, exposant2, npts, nbits_needed); code_exposant = DIFF_EXPOSANT_STREAM;*/ } if (0 != (lng_exposant%4)) { lng_exposant += 4 - (lng_exposant%4); } memcpy(pos_lng_exposant, &lng_exposant, sizeof(unsigned int)); le_pointeur += lng_exposant; } /* ------------------- Encodage du stream de mantisse ------------------------- */ pos_lng_mantisse = le_pointeur; le_pointeur += sizeof(unsigned int); code_mantisse = MANTISSE_PACKED; remaining_space = (ni*nj*znbits)/32; remaining_space = remaining_space - (le_pointeur - zstream)/sizeof(unsigned int); lng_mantisse = c_fstzip32((unsigned int *)le_pointeur, mantisse, ni, nj, nk, zfstzip.step, nbits, remaining_space); la_mantisse = zmantisse; if (lng_mantisse == 0) { free(signe); free(zsigne); free(exposant); free(exposant2); free(zexposant); if (la_mantisse != mantisse) { free(mantisse_stream); } free(mantisse); free(zmantisse); return -1; } if (0 != (lng_mantisse%4)) { lng_mantisse += 4 - (lng_mantisse%4); } memcpy(pos_lng_mantisse, &lng_signe, sizeof(unsigned int)); /* ------------------- ------------------------------- ------------------------- */ /* ------------------- ----------- Assemblage final ------------------- */ /* ------------------- Entete et codes ------------------- */ zstream[0] = (unsigned char)'\0'; i = 0; memcpy(&zstream[0], &zfstzip, sizeof(unsigned int)); zieee_info = 0; i+= sizeof(unsigned int); codes = (unsigned char)(code_signe | code_exposant | code_mantisse); zieee_info = ((unsigned char) exp_base) << 16; zieee_info = zieee_info | ((unsigned char)nbits_needed) << 8; zieee_info = zieee_info | (unsigned char) codes; memcpy(&zstream[i], &zieee_info, sizeof(unsigned int)); i+=sizeof(unsigned int); le_pointeur += lng_mantisse; zlng = le_pointeur - zstream; /* ---------------- Menage avant de s'en aller ------------------- */ free(signe); free(zsigne); free(exposant); free(exposant2); free(zexposant); if (la_mantisse != mantisse) { free(mantisse_stream); } free(mantisse); free(zmantisse); return zlng; } int f77name(armn_uncompress32)(float *fld, unsigned char *zstream, int *ni, int *nj, int *nk, int *nbits) { return c_armn_uncompress32(fld, zstream, *ni, *nj, *nk, *nbits); } int c_armn_uncompress32(float *fld, unsigned char *zstream, int ni, int nj, int nk, int znbits) { _fstzip zfstzip; int bitPackInWord, saut, zlng; int i, nbits_mantisse, nbits; unsigned char *exposant, *exposant2; unsigned char *signe, *zsigne, code_signe, code_exposant, code_mantisse; unsigned char codes; unsigned int *cur, curword, nbits_needed_exposant; unsigned int *mantisse; unsigned int *temp; unsigned int exp_min; unsigned int npts, lng_signe, lng_exposant,lng_mantisse, zieee_info; npts = ni * nj; signe = (unsigned char *) malloc(2*npts * sizeof(unsigned char)); zsigne = (unsigned char *) malloc(2*npts * sizeof(unsigned char)); exposant = (unsigned char *) malloc(2*npts * sizeof(unsigned char)); exposant2 = (unsigned char *) malloc(2*npts * sizeof(unsigned char)); mantisse = (unsigned int *) malloc(2*npts * sizeof(unsigned int)); bitPackInWord = 32; cur = (unsigned int *)zstream; curword = *cur; memcpy(&zfstzip, cur, sizeof(unsigned int)); cur++; memcpy(&zieee_info, cur, sizeof(unsigned int)); cur++; exp_min = zieee_info >> 16; nbits_needed_exposant = (zieee_info >> 8) & 0xFF; nbits_mantisse = zfstzip.nbits; nbits = nbits_mantisse; codes = zieee_info& 0xFF; code_signe = (codes & 0x30); code_exposant = (codes & 0xC); code_mantisse = (codes & 0x3); if (code_signe == DIFF_SIGNE_PACKED || code_signe == DIFF_SIGNE_STREAM) { memcpy(&lng_signe, cur, sizeof(unsigned int)); cur++; unpack1bitRLE(signe, cur, (unsigned int *)&zlng,npts); saut = (lng_signe >> 2); cur += saut; } else { if (code_signe == MEME_SIGNE_POSITIF) { for (i=0; i < npts; i++) { signe[i] = 0; } } else { for (i=0; i < npts; i++) { signe[i] = 1; } } } if (code_exposant == DIFF_EXPOSANT_PACKED || code_exposant == DIFF_EXPOSANT_STREAM) { memcpy(&lng_exposant, cur, sizeof(unsigned int)); cur++; unpackTokensParallelogram_8(exposant2, cur, ni, nj, nbits_needed_exposant, 3); /* lng_exposant = armn_compress(exposant2, *ni, *nj, *nk, nbits_needed_exposant, 2);*/ saut = (lng_exposant >> 2); cur += saut; for (i=0; i < npts; i++) { exposant2[i] = exposant2[i] + exp_min; } } else { for (i=0; i < npts; i++) { exposant2[i] = exp_min; } } memcpy(&lng_mantisse, cur, sizeof(unsigned int)); cur++; if (code_mantisse == MANTISSE_PACKED) { unpackTokensParallelogram32(mantisse, cur, ni, nj, nbits_mantisse, 3); } else { unpack_stream_nbits_32(mantisse, cur, npts, nbits_mantisse); } switch(code_signe) { case MEME_SIGNE_POSITIF: for (i=0; i < npts; i++) { temp = (unsigned int *)&fld[i]; *temp = 0; *temp |= (exposant2[i] << 23); *temp |= (mantisse[i] << (23-nbits)); } break; case MEME_SIGNE_NEGATIF: for (i=0; i < npts; i++) { temp = (unsigned int *)&fld[i]; *temp = 0x80000000; *temp = *temp | (exposant2[i] << 23); *temp = *temp | (mantisse[i] << (23-nbits)); } break; default: for (i=0; i < npts; i++) { temp = (unsigned int *)&fld[i]; *temp = signe[i] << 31; *temp |= (exposant2[i] << 23); *temp |= (mantisse[i] << (23-nbits)); } break; } free(signe); free(zsigne); free(exposant); free(exposant2); free(mantisse); return ni*nj; } int c_fstzip32(unsigned int *zfld, unsigned int *fld, int ni, int nj, int nk, int step, int nbits, int remaining_space) { int zlng, lng_origin; lng_origin = (1+(ni*nj*nk*1.0*nbits)/8); if (ni == 1 || nj == 1) { return lng_origin; } packTokensParallelogram32(zfld, &zlng, fld, ni, nj, step, nbits, remaining_space); if (zlng == 0 && zfst_msglevel <= 2) { fprintf(stdout, "IEEE compressed field is larger than original... Returning original\n\n"); return 0; } return zlng; } void packTokensParallelogram32(unsigned int z[], int *zlng, unsigned int ufld[], int ni, int nj, int istep, int nbits, int remaining_space) { _floatint r_lmax; int *ufld_dst; int k22, nbits2; int lcl_m, lcl_n; int local_max; unsigned int *cur; unsigned int i, j, k, m, n; unsigned int lastWordShifted, spaceInLastWord, lastSlot; unsigned int lcl, nbits_needed; unsigned int nbits_req_container, token; lastSlot = 0; cur = z; ufld_dst=(int *) malloc(ni*nj*sizeof(int)); for (j=1; j <= nj; j++) { k = FTN2C(1,j,ni); ufld_dst[k] = 0; } for (i=1; i <= ni; i++) { k = FTN2C(i,1,ni); ufld_dst[k] = 0; } for (j=2; j<=nj; j++) { for (i=2; i <=ni; i++) { k22 = FTN2C(i, j, ni); ufld_dst[k22] = ufld[k22] - (ufld[k22-ni]+ufld[k22-1]-ufld[k22-1-ni]); } } nbits_req_container = 5; lastWordShifted = 0; spaceInLastWord = 32; *cur = 0; stuff(nbits_req_container, cur, 32, istep, lastWordShifted, spaceInLastWord); for (i=1; i <= ni; i++) { k = FTN2C(i,1,ni); stuff(ufld[k], cur, 32, nbits, lastWordShifted, spaceInLastWord); } for (j=2; j <= nj; j++) { k = FTN2C(1,j,ni); stuff(ufld[k], cur, 32, nbits, lastWordShifted, spaceInLastWord); } for (j=2; j <= nj; j+=istep) { lcl_n = ((j + istep - 1) >= nj ? nj - j : istep - 1); for (i=2; i <= ni; i+=istep) { k = FTN2C(i,j,ni); local_max = ufld_dst[k]; lcl_m = ((i + istep - 1) >= ni ? ni - i : istep - 1); for (n=0; n <= lcl_n; n++) { for (m=0; m <= lcl_m; m++) { k = FTN2C(i+m,j+n,ni); if (local_max < abs(ufld_dst[k])) local_max = abs(ufld_dst[k]); } } if (local_max == 0) { nbits_needed = 0; } else { r_lmax.f = (float)local_max; nbits_needed = (r_lmax.i >> 23) - 126; } stuff(nbits_needed, cur, 32, nbits_req_container, lastWordShifted, spaceInLastWord); switch (nbits_needed) { case 0: break; default: nbits2 = nbits_needed + 1; for (n=0; n <= lcl_n; n++) { for (m=0; m <= lcl_m; m++) { k = FTN2C(i+m,j+n,ni); token = (unsigned int) (ufld_dst[k] & ~((-1)<<nbits2)); stuff(token, cur, 32, nbits2, lastWordShifted, spaceInLastWord); } } if (remaining_space < ((cur - z)+(1+((nbits_needed+9*nbits)>>5)))) { *zlng = 0; return; } break; } } } lcl = 0; stuff(lcl, cur, 32, 16, lastWordShifted, spaceInLastWord); stuff(lcl, cur, 32, 16, lastWordShifted, spaceInLastWord); *zlng = 1 + (int) (cur-z) * 4; free(ufld_dst); } void unpackTokensParallelogram32(unsigned int ufld[], unsigned int z[], int ni, int nj, int nbits, int istep) { int *ufld_tmp; int bitPackInWord; int i, j, k, m, n; int k11, k12, k21, k22; int lcl_m, lcl_n; unsigned int nbits_needed, curword; unsigned int *cur; unsigned int nbits_req_container, token, nbits2; bitPackInWord = 32; cur = z; curword = *cur; ufld_tmp = (int *) malloc(ni*nj*sizeof(int)); extract(nbits_req_container, cur, 32, istep, curword, bitPackInWord); for (i=1; i <= ni; i++) { k = FTN2C(i,1,ni); extract(token, cur, 32, nbits, curword, bitPackInWord); ufld[k] = token; } for (j=2; j <= nj; j++) { k = FTN2C(1,j,ni); extract(token, cur, 32, nbits, curword, bitPackInWord); ufld[k] = token; } for (j=2; j <= nj; j+=istep) { lcl_n = ((j + istep - 1) >= nj ? nj - j : istep - 1); for (i=2; i <= ni; i+=istep) { lcl_m = ((i + istep - 1) >= ni ? ni - i : istep - 1); extract(nbits_needed, cur, 32, nbits_req_container, curword, bitPackInWord); switch (nbits_needed) { case 0: for (n=0; n <= lcl_n; n++) { for (m=0; m <= lcl_m; m++) { k = FTN2C(i+m,j+n,ni); ufld_tmp[k] = 0; } } break; default: nbits2 = nbits_needed + 1; for (n=0; n <= lcl_n; n++) { for (m=0; m <= lcl_m; m++) { k = FTN2C(i+m,j+n,ni); extract(token, cur, 32, nbits2, curword, bitPackInWord); ufld_tmp[k] = token; ufld_tmp[k] = (ufld_tmp[k] << (32-nbits2)) >> (32-nbits2); } } } } } for (j=2; j<=nj; j++) { for (i=2; i <=ni; i++) { k11 = FTN2C(i-1,j-1,ni); k12 = FTN2C(i-1,j ,ni); k21 = FTN2C(i, j-1,ni); k22 = FTN2C(i, j, ni); ufld[k22] = ufld_tmp[k22] + (ufld[k21]+ufld[k12]-ufld[k11]); } } free(ufld_tmp); } void packTokensParallelogram_8(unsigned int z[], unsigned int *zlng, unsigned char ufld[], int ni, int nj, int nbits, int istep) { float rlog2; int *ufld_dst; int k22, nbits2; int lcl_m, lcl_n; int local_max; unsigned int *cur; unsigned int i, j, k, m, n; unsigned int lastWordShifted, spaceInLastWord, lastSlot; unsigned int lcl, nbits_needed; unsigned int nbits_req_container, token; lastSlot = 0; cur = z; if (once == 0) { rlog2 = 1.0/log(2.0); for (i=0; i < 256; i++) { fastlog[i] = (int)(1+log(i+0.5)*rlog2); } once = 1; } ufld_dst=(int *) malloc(ni*nj*sizeof(int)); for (j=1; j <= nj; j++) { k = FTN2C(1,j,ni); ufld_dst[k] = 0; } for (i=1; i <= ni; i++) { k = FTN2C(i,1,ni); ufld_dst[k] = 0; } for (j=2; j<=nj; j++) { for (i=2; i <=ni; i++) { k22 = FTN2C(i, j, ni); ufld_dst[k22] = ufld[k22] - (ufld[k22-ni]+ufld[k22-1]-ufld[k22-1-ni]); } } nbits_req_container = 4; lastWordShifted = 0; spaceInLastWord = 32; *cur = 0; stuff(nbits_req_container, cur, 32, istep, lastWordShifted, spaceInLastWord); for (i=1; i <= ni; i++) { k = FTN2C(i,1,ni); stuff(ufld[k], cur, 32, nbits, lastWordShifted, spaceInLastWord); } for (j=2; j <= nj; j++) { k = FTN2C(1,j,ni); stuff(ufld[k], cur, 32, nbits, lastWordShifted, spaceInLastWord); } for (j=2; j <= nj; j+=istep) { lcl_n = ((j + istep - 1) >= nj ? nj - j : istep - 1); for (i=2; i <= ni; i+=istep) { k = FTN2C(i,j,ni); local_max = ufld_dst[k]; lcl_m = ((i + istep - 1) >= ni ? ni - i : istep - 1); for (n=0; n <= lcl_n; n++) { for (m=0; m <= lcl_m; m++) { k = FTN2C(i+m,j+n,ni); if (local_max < abs(ufld_dst[k])) local_max = abs(ufld_dst[k]); } } if (local_max == 0) { nbits_needed = 0; } else { if (local_max < 256) { nbits_needed = fastlog[local_max]; } else { nbits_needed = 8 + fastlog[local_max>>8]; } } stuff(nbits_needed, cur, 32, nbits_req_container, lastWordShifted, spaceInLastWord); switch (nbits_needed) { case 0: break; default: nbits2 = nbits_needed + 1; for (n=0; n <= lcl_n; n++) { for (m=0; m <= lcl_m; m++) { k = FTN2C(i+m,j+n,ni); token = (unsigned int) (ufld_dst[k] & ~((-1)<<nbits2)); stuff(token, cur, 32, nbits2, lastWordShifted, spaceInLastWord); } } break; } } } lcl = 0; stuff(lcl, cur, 32, 16, lastWordShifted, spaceInLastWord); stuff(lcl, cur, 32, 16, lastWordShifted, spaceInLastWord); *zlng = 1 + (int) (cur-z) * 4; free(ufld_dst); } void unpackTokensParallelogram_8(unsigned char ufld[], unsigned int z[], int ni, int nj, int nbits, int istep) { int *ufld_tmp; int bitPackInWord; int i, j, k, m, n; int k11, k12, k21, k22; int lcl_m, lcl_n; unsigned int nbits_needed, curword; unsigned int *cur; unsigned int nbits_req_container, token, nbits2; bitPackInWord = 32; cur = z; curword = *cur; ufld_tmp = (int *) malloc(ni*nj*sizeof(int)); extract(nbits_req_container, cur, 32, istep, curword, bitPackInWord); for (i=1; i <= ni; i++) { k = FTN2C(i,1,ni); extract(token, cur, 32, nbits, curword, bitPackInWord); ufld[k] = token; } for (j=2; j <= nj; j++) { k = FTN2C(1,j,ni); extract(token, cur, 32, nbits, curword, bitPackInWord); ufld[k] = token; } for (j=2; j <= nj; j+=istep) { lcl_n = ((j + istep - 1) >= nj ? nj - j : istep - 1); for (i=2; i <= ni; i+=istep) { lcl_m = ((i + istep - 1) >= ni ? ni - i : istep - 1); extract(nbits_needed, cur, 32, nbits_req_container, curword, bitPackInWord); switch (nbits_needed) { case 0: for (n=0; n <= lcl_n; n++) { for (m=0; m <= lcl_m; m++) { k = FTN2C(i+m,j+n,ni); ufld_tmp[k] = 0; } } break; default: nbits2 = nbits_needed + 1; for (n=0; n <= lcl_n; n++) { for (m=0; m <= lcl_m; m++) { k = FTN2C(i+m,j+n,ni); extract(token, cur, 32, nbits2, curword, bitPackInWord); ufld_tmp[k] = token; ufld_tmp[k] = (ufld_tmp[k] << (32-nbits2)) >> (32-nbits2); } } } } } for (j=2; j<=nj; j++) { for (i=2; i <=ni; i++) { k11 = FTN2C(i-1,j-1,ni); k12 = FTN2C(i-1,j ,ni); k21 = FTN2C(i, j-1,ni); k22 = FTN2C(i, j, ni); ufld[k22] = ufld_tmp[k22] + (ufld[k21]+ufld[k12]-ufld[k11]); } } free(ufld_tmp); } void pack1bitRLE(unsigned int z[], unsigned int *zlng, unsigned char ufld[], int npts) { unsigned int i, j; unsigned int lastWordShifted, spaceInLastWord, lastSlot; unsigned int *cur; unsigned int lcl, indx, last_indx; unsigned char lcl_count; int count, limite, repeat; lastSlot = 0; cur = z; lastWordShifted = 0; spaceInLastWord = 32; *cur = 0; last_indx=0; indx=1; while (indx <= npts) { while (ufld[indx] == ufld[last_indx] && indx < npts) { indx++; } count = indx - last_indx; if (count < 8) { stuff(SEQUENCE, cur, 32, 1, lastWordShifted, spaceInLastWord); limite = (last_indx + 7) > npts ? (npts - last_indx) : 7; for (i=0; i < limite; i++) { stuff(ufld[last_indx+i], cur, 32, 1, lastWordShifted, spaceInLastWord); } last_indx +=7; indx = last_indx + 1; } else { i = 0; repeat = 0; while (i < count) { lcl_count = (count-i) >= 63 ? 62 : (count - i); if (lcl_count < 8) { stuff(SEQUENCE, cur, 32, 1, lastWordShifted, spaceInLastWord); limite = (last_indx + 7) > npts ? (npts - last_indx) : 7; for (j=0; j < limite; j++) { stuff(ufld[last_indx+j], cur, 32, 1, lastWordShifted, spaceInLastWord); } last_indx +=7; indx = last_indx + 1; } else { if (lcl_count == 62) { if ((count - i) > 256 && (repeat == 1)) { lcl_count = 0xFF; stuff(lcl_count, cur, 32, 8,lastWordShifted, spaceInLastWord); last_indx+=lcl_count; indx = last_indx + 1; } else { stuff(COUNT, cur, 32, 1, lastWordShifted, spaceInLastWord); stuff(ufld[last_indx], cur, 32, 1,lastWordShifted, spaceInLastWord); stuff(lcl_count, cur, 32, 6,lastWordShifted, spaceInLastWord); last_indx+=lcl_count; indx = last_indx + 1; repeat = 1; } } else { stuff(COUNT, cur, 32, 1, lastWordShifted, spaceInLastWord); stuff(ufld[last_indx], cur, 32, 1,lastWordShifted, spaceInLastWord); stuff(lcl_count, cur, 32, 6,lastWordShifted, spaceInLastWord); last_indx+=lcl_count; indx = last_indx + 1; } } i += lcl_count; } } } lcl = 0; stuff(lcl, cur, 32, 16, lastWordShifted, spaceInLastWord); stuff(lcl, cur, 32, 16, lastWordShifted, spaceInLastWord); *zlng = 1 + (int) (cur-z) * 4; } void unpack1bitRLE(unsigned char ufld[], unsigned int z[], unsigned int *zlng, int npts) { unsigned int i, j; unsigned int *cur, seq_type, val, last_val; int count, limite; int bitPackInWord; unsigned int curword; unsigned int token; bitPackInWord = 32; cur = z; curword = *cur; last_val = 0xFFFFFFFF; i = 0; while (i < npts) { extract(seq_type, cur, 32, 1, curword, bitPackInWord); switch(seq_type) { case SEQUENCE: limite = (i + 7) > npts ? (npts - i) : 7; for (j=0; j < limite; j++) { extract(token, cur, 32, 1, curword, bitPackInWord); ufld[i+j] = (unsigned char) token; } i+=limite; break; case COUNT: extract(val, cur, 32, 1, curword, bitPackInWord); extract(count, cur, 32, 6, curword, bitPackInWord); switch (count) { case 63: for (j=0; j < 255; j++) { ufld[i+j] = (unsigned char) last_val; } i+=255; break; default: for (j=0; j < count; j++) { ufld[i+j] = (unsigned char) val; } i+=count; last_val = val; break; } break; } } } int compact_mask_char(unsigned int *dest, unsigned char *src, int npts) { int i,entier, fraction,npts32; npts32 = 1 + (npts >> 5); for (i=0; i < npts32; i++) { dest[i] = 0; } for (i=0; i < npts; i++) { entier = i >> 5; fraction = i - (entier << 5); dest[entier] |= (src[i] << fraction); } return 0; } int uncompact_mask_char(int *dest, unsigned int *src, int npts) { int i,entier, fraction; for (i=0; i < npts; i++) { entier = i >> 5; fraction = i - (entier << 5); dest[i] = (src[entier] & (1 << fraction)) >> fraction; } return 0; } void pack_stream_nbits_32(unsigned int z[], unsigned int *zlng, unsigned int ufld[], int npts, int nbits) { unsigned int i; unsigned int lastWordShifted, spaceInLastWord, lastSlot; unsigned int *cur; unsigned int lcl; lastSlot = 0; cur = z; lastWordShifted = 0; spaceInLastWord = 32; *cur = 0; for (i=0; i < npts; i++) { stuff(ufld[i], cur, 32, nbits, lastWordShifted, spaceInLastWord); } lcl = 0; stuff(lcl, cur, 32, 16, lastWordShifted, spaceInLastWord); stuff(lcl, cur, 32, 16, lastWordShifted, spaceInLastWord); *zlng = 1 + (int) (cur-z) * 4; } void unpack_stream_nbits_32(unsigned int ufld[], unsigned int z[], int npts, int nbits) { unsigned int i; unsigned int lastSlot; unsigned int *cur; int bitPackInWord; unsigned int curword; lastSlot = 0; cur = z; bitPackInWord = 32; curword = *cur; for (i=0; i < npts; i++) { extract(ufld[i], cur, 32, nbits, curword, bitPackInWord); } } void pack_stream_nbits_16(unsigned int z[], unsigned int *zlng, unsigned short ufld[], int npts, int nbits) { unsigned int i; unsigned int lastWordShifted, spaceInLastWord, lastSlot; unsigned int *cur; unsigned int lcl; lastSlot = 0; cur = z; lastWordShifted = 0; spaceInLastWord = 32; *cur = 0; for (i=0; i < npts; i++) { stuff(ufld[i], cur, 32, nbits, lastWordShifted, spaceInLastWord); } lcl = 0; stuff(lcl, cur, 32, 16, lastWordShifted, spaceInLastWord); stuff(lcl, cur, 32, 16, lastWordShifted, spaceInLastWord); *zlng = 1 + (int) (cur-z) * 4; } void unpack_stream_nbits_16(unsigned short ufld[], unsigned int z[], int npts, int nbits) { unsigned int i; unsigned int lastSlot; unsigned int *cur; int bitPackInWord; unsigned int curword; lastSlot = 0; cur = z; bitPackInWord = 32; curword = *cur; for (i=0; i < npts; i++) { extract(ufld[i], cur, 32, nbits, curword, bitPackInWord); } } void pack_stream_nbits_8(unsigned int z[], unsigned int *zlng, unsigned char ufld[], int npts, int nbits) { unsigned int i; unsigned int lastWordShifted, spaceInLastWord, lastSlot; unsigned int *cur; unsigned int lcl; lastSlot = 0; cur = z; lastWordShifted = 0; spaceInLastWord = 32; *cur = 0; for (i=0; i < npts; i++) { stuff(ufld[i], cur, 32, nbits, lastWordShifted, spaceInLastWord); } lcl = 0; stuff(lcl, cur, 32, 16, lastWordShifted, spaceInLastWord); stuff(lcl, cur, 32, 16, lastWordShifted, spaceInLastWord); *zlng = 1 + (int) (cur-z) * 4; } void unpack_stream_nbits_8(unsigned char ufld[], unsigned int z[], int npts, int nbits) { unsigned int i; unsigned int lastSlot; unsigned int *cur; int bitPackInWord; unsigned int curword; lastSlot = 0; cur = z; bitPackInWord = 32; curword = *cur; for (i=0; i < npts; i++) { extract(ufld[i], cur, 32, nbits, curword, bitPackInWord); } }
Java
package com.quickserverlab.quickcached; import java.io.IOException; import java.net.SocketTimeoutException; import java.util.logging.Level; import java.util.logging.Logger; import com.quickserverlab.quickcached.cache.CacheException; import com.quickserverlab.quickcached.cache.CacheInterface; import org.quickserver.net.server.ClientHandler; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * * @author Akshathkumar Shetty */ public class TextCommandProcessor { private static final Logger logger = Logger.getLogger(TextCommandProcessor.class.getName()); private static String versionOutput = null; static { versionOutput = "VERSION " + QuickCached.version + "\r\n"; } private CacheInterface cache; public void setCache(CacheInterface cache) { this.cache = cache; } public void handleTextCommand(ClientHandler handler, String command) throws SocketTimeoutException, IOException, CacheException { if (QuickCached.DEBUG) { logger.log(Level.FINE, "command: {0}", command); } if (command.startsWith("get ") || command.startsWith("gets ")) { handleGetCommands(handler, command); } else if (command.equals("version")) { sendResponse(handler, versionOutput); } else if (command.startsWith("set ") || command.startsWith("add ") || command.startsWith("replace ") || command.startsWith("append ") || command.startsWith("prepend ") || command.startsWith("cas ")) { handleStorageCommands(handler, command); Data data = (Data) handler.getClientData(); if (data.isAllDataIn()) { processStorageCommands(handler); return; } else { return; } } else if (command.startsWith("delete ")) { handleDeleteCommands(handler, command); } else if (command.startsWith("flush_all")) { handleFlushAll(handler, command); } else if (command.equals("stats")) { Map stats = CommandHandler.getStats(handler.getServer()); Set keySet = stats.keySet(); Iterator iterator = keySet.iterator(); String key = null; String value = null; while (iterator.hasNext()) { key = (String) iterator.next(); value = (String) stats.get(key); sendResponse(handler, "STAT " + key + " " + value + "\r\n"); } sendResponse(handler, "END\r\n"); } else if (command.startsWith("stats ")) { //TODO sendResponse(handler, "ERROR\r\n"); } else if (command.equals("quit")) { handler.closeConnection(); } else if (command.startsWith("incr ") || command.startsWith("decr ")) { handleIncrDecrCommands(handler, command); } else if (command.startsWith("touch ")) { handleTouchCommands(handler, command); } else { logger.log(Level.WARNING, "unknown command! {0}", command); sendResponse(handler, "ERROR\r\n"); } } private void handleFlushAll(ClientHandler handler, String command) throws SocketTimeoutException, IOException, CacheException { /* flush_all [exptime] [noreply]\r\n */ String cmdData[] = command.split(" "); String cmd = cmdData[0]; String exptime = null; if(QuickCached.DEBUG==false) { logger.log(Level.FINE, "cmd: {0}", new Object[]{cmd}); } boolean noreplay = false; if(cmdData[cmdData.length-1].equals("noreply")) { noreplay = true; } if (noreplay==false && cmdData.length >= 2) { exptime = cmdData[1]; } else if (noreplay==true && cmdData.length >= 3) { exptime = cmdData[1]; } if (exptime == null) { cache.flush(); } else { final int sleeptime = Integer.parseInt(exptime); Thread t = new Thread() { public void run() { try { sleep(1000 * sleeptime); } catch (InterruptedException ex) { logger.log(Level.WARNING, "Error: "+ex, ex); } try { cache.flush(); } catch (CacheException ex) { logger.log(Level.SEVERE, "Error: "+ex, ex); } } }; t.start(); } if (noreplay) { return; } sendResponse(handler, "OK\r\n"); } private void handleDeleteCommands(ClientHandler handler, String command) throws SocketTimeoutException, IOException, CacheException { /* delete <key> [noreply]\r\n */ String cmdData[] = command.split(" "); String cmd = cmdData[0]; String key = cmdData[1]; if(QuickCached.DEBUG==false) { logger.log(Level.FINE, "cmd: {0}, key: {1}", new Object[]{cmd, key}); } boolean noreplay = false; if (cmdData.length == 3) { if ("noreply".equals(cmdData[2])) { noreplay = true; } } boolean flag = cache.delete(key); if (noreplay) { return; } if (flag == true) { sendResponse(handler, "DELETED\r\n"); } else { sendResponse(handler, "NOT_FOUND\r\n"); } } private void handleTouchCommands(ClientHandler handler, String command) throws SocketTimeoutException, IOException, CacheException { /* touch <key> <exptime> [noreply]\r\n */ String cmdData[] = command.split(" "); String cmd = cmdData[0]; String key = cmdData[1]; int exptime = Integer.parseInt(cmdData[2]); boolean noreplay = false; if (cmdData.length >= 4) { if ("noreply".equals(cmdData[3])) { noreplay = true; } } if(QuickCached.DEBUG==false) { logger.log(Level.FINE, "cmd: {0}, key: {1}", new Object[]{cmd, key}); } boolean flag = cache.touch(key, exptime); if(noreplay) return; if(flag==false) { sendResponse(handler, "NOT_FOUND\r\n"); } else { sendResponse(handler, "TOUCHED\r\n"); } } private void handleGetCommands(ClientHandler handler, String command) throws SocketTimeoutException, IOException, CacheException { /* get <key>*\r\n gets <key>*\r\n */ String cmdData[] = command.split(" "); String cmd = cmdData[0]; String key = null; for (int i = 1; i < cmdData.length; i++) { key = cmdData[i]; if(QuickCached.DEBUG==false) { logger.log(Level.FINE, "cmd: {0}, key: {1}", new Object[]{cmd, key}); } DataCarrier dc = (DataCarrier) cache.get(key); if (dc != null) { StringBuilder sb = new StringBuilder(); sb.append("VALUE "); sb.append(key); sb.append(" "); sb.append(dc.getFlags()); sb.append(" "); sb.append(dc.getData().length); sb.append(" "); sb.append(dc.getCas()); sb.append("\r\n"); sendResponse(handler, sb.toString()); sendResponse(handler, dc.getData()); sendResponse(handler, "\r\n"); } } sendResponse(handler, "END\r\n"); /* VALUE <key> <flags> <bytes> [<cas unique>]\r\n <data block>\r\n */ } private void handleIncrDecrCommands(ClientHandler handler, String command) throws SocketTimeoutException, IOException, CacheException { /* incr <key> <value> [noreply]\r\n decr <key> <value> [noreply]\r\n */ String cmdData[] = command.split(" "); if (cmdData.length < 3) { sendResponse(handler, "CLIENT_ERROR Bad number of args passed\r\n"); if (cmdData[0].equals("incr")) { CommandHandler.incrMisses++; } else if (cmdData[0].equals("decr")) { CommandHandler.decrMisses++; } return; } String cmd = cmdData[0]; String key = cmdData[1]; String _value = cmdData[2]; long value = 0; try { value = Long.parseLong(_value); } catch (Exception e) { sendResponse(handler, "CLIENT_ERROR parse of client value failed\r\n"); if (cmd.equals("incr")) { CommandHandler.incrMisses++; } else if (cmd.equals("decr")) { CommandHandler.decrMisses++; } return; } if(QuickCached.DEBUG==false) { logger.log(Level.FINE, "cmd: {0}, key: {1}", new Object[]{cmd, key}); } boolean noreplay = false; if (cmdData.length >= 4) { if ("noreply".equals(cmdData[3])) { noreplay = true; } } DataCarrier dc = (DataCarrier) cache.get(key, false); if (dc == null) { if (noreplay == false) { sendResponse(handler, "NOT_FOUND\r\n"); } if (cmd.equals("incr")) { CommandHandler.incrMisses++; } else if (cmd.equals("decr")) { CommandHandler.decrMisses++; } return; } StringBuilder sb = new StringBuilder(); dc.writeLock.lock(); try { long oldvalue = Long.parseLong(new String(dc.getData(), HexUtil.getCharset())); if (cmd.equals("incr")) { value = oldvalue + value; } else if (cmd.equals("decr")) { value = oldvalue - value; if (value < 0) { value = 0; } } else { throw new IllegalArgumentException("Unknown command "+cmd); } sb.append(value); dc.setData(sb.toString().getBytes(HexUtil.getCharset())); cache.update(key, dc, dc.getSize()); } catch(Exception e) { if(noreplay == false) { sendResponse(handler, "CLIENT_ERROR parse of server value failed\r\n"); } if (cmd.equals("incr")) { CommandHandler.incrMisses++; } else if (cmd.equals("decr")) { CommandHandler.decrMisses++; } return; } finally { dc.writeLock.unlock(); } if (cmd.equals("incr")) { CommandHandler.incrHits++; } else if (cmd.equals("decr")) { CommandHandler.decrHits++; } if (noreplay) { return; } sb.append("\r\n"); sendResponse(handler, sb.toString()); } private void handleStorageCommands(ClientHandler handler, String command) throws SocketTimeoutException, IOException { Data data = (Data) handler.getClientData(); /* <command name> <key> <flags> <exptime> <bytes> [noreply]\r\n cas <key> <flags> <exptime> <bytes> <cas unique> [noreply]\r\n */ String cmdData[] = command.split(" "); String cmd = cmdData[0]; String key = cmdData[1]; String flags = cmdData[2]; int exptime = Integer.parseInt(cmdData[3]); long bytes = Integer.parseInt(cmdData[4]); String casunique = null; boolean noreplay = false; if (cmdData.length >= 6) { if ("noreply".equals(cmdData[5])) { noreplay = true; } else { casunique = cmdData[5]; } if (cmdData.length >= 7) { if ("noreply".equals(cmdData[6])) { noreplay = true; } } } if(key.length()>Data.getMaxSizeAllowedForKey()) { throw new IllegalArgumentException( "key passed to big to store "+key); } if(Data.getMaxSizeAllowedForValue()>0) { if(bytes > Data.getMaxSizeAllowedForValue()) { throw new IllegalArgumentException( "value passed to big to store "+bytes+" for key "+key); } } data.setCmd(cmd); data.setKey(key); data.setFlags(flags); data.setExptime(exptime); data.setDataRequiredLength(bytes); data.setCasUnique(casunique); data.setNoreplay(noreplay); } public void processStorageCommands(ClientHandler handler) throws SocketTimeoutException, IOException, CacheException { Data data = (Data) handler.getClientData(); if(QuickCached.DEBUG==false) { logger.log(Level.FINE, "cmd: {0}, key: {1}", new Object[]{data.getCmd(), data.getKey()}); } byte dataToStore[] = data.getDataByte(); DataCarrier dc = new DataCarrier(dataToStore); dc.setFlags(data.getFlags()); if (data.getCmd().equals("set")) { DataCarrier olddata = (DataCarrier) cache.get(data.getKey(), false); if(olddata==null) { cache.set(data.getKey(), dc, dc.getSize(), data.getExptime()); } else { olddata.writeLock.lock(); try { olddata.setData(dc.getData()); olddata.setFlags(dc.getFlags()); cache.update(data.getKey(), olddata, olddata.getSize(), data.getExptime()); } finally { olddata.writeLock.unlock(); } } if (data.isNoreplay() == false) { sendResponse(handler, "STORED\r\n"); } } else if (data.getCmd().equals("add")) { Object olddata = cache.get(data.getKey(), false); if (olddata == null) { cache.set(data.getKey(), dc, dc.getSize(), data.getExptime()); if (data.isNoreplay() == false) { sendResponse(handler, "STORED\r\n"); } } else { if (data.isNoreplay() == false) { sendResponse(handler, "NOT_STORED\r\n"); } } } else if (data.getCmd().equals("replace")) { DataCarrier olddata = (DataCarrier) cache.get(data.getKey(), false); if (olddata != null) { olddata.writeLock.lock(); try { olddata.setData(dc.getData()); cache.update(data.getKey(), olddata, olddata.getSize()); } finally { olddata.writeLock.unlock(); } dc.setData(null); dc = null; if (data.isNoreplay() == false) { if (data.isNoreplay() == false) { sendResponse(handler, "STORED\r\n"); } } } else { if (data.isNoreplay() == false) { sendResponse(handler, "NOT_STORED\r\n"); } } } else if (data.getCmd().equals("append")) { DataCarrier olddata = (DataCarrier) cache.get(data.getKey(), false); if (olddata != null) { olddata.writeLock.lock(); try { olddata.append(dc.getData()); cache.update(data.getKey(), olddata, olddata.getSize()); } finally { olddata.writeLock.unlock(); } dc.setData(null); dc = null; if (data.isNoreplay() == false) { if (data.isNoreplay() == false) { sendResponse(handler, "STORED\r\n"); } } } else { if (data.isNoreplay() == false) { sendResponse(handler, "NOT_STORED\r\n"); } } } else if (data.getCmd().equals("prepend")) { DataCarrier olddata = (DataCarrier) cache.get(data.getKey(), false); if (olddata != null) { olddata.writeLock.lock(); try { olddata.prepend(dc.getData()); cache.update(data.getKey(), olddata, olddata.getSize()); } finally { olddata.writeLock.unlock(); } dc.setData(null); dc = null; if (data.isNoreplay() == false) { if (data.isNoreplay() == false) { sendResponse(handler, "STORED\r\n"); } } } else { if (data.isNoreplay() == false) { sendResponse(handler, "NOT_STORED\r\n"); } } } else if (data.getCmd().equals("cas")) { String reply = null; DataCarrier olddata = (DataCarrier) cache.get(data.getKey(), false); if(olddata != null) { olddata.writeLock.lock(); try { int oldcas = olddata.getCas(); int passedcas = Integer.parseInt(data.getCasUnique()); if (oldcas == passedcas) { olddata.setData(dc.getData()); cache.update(data.getKey(), olddata, olddata.getSize()); dc.setData(null); dc = null; CommandHandler.casHits++; if (data.isNoreplay() == false) { reply = "STORED\r\n"; } } else { CommandHandler.casBadval++; if (data.isNoreplay() == false) { reply = "EXISTS\r\n"; } } } finally { olddata.writeLock.unlock(); } } else { CommandHandler.casMisses++; if (data.isNoreplay() == false) { reply = "NOT_FOUND\r\n"; } } if(reply!=null) { sendResponse(handler, reply); } } data.clear(); } public void sendResponse(ClientHandler handler, String data) throws SocketTimeoutException, IOException { sendResponse(handler, data.getBytes(HexUtil.getCharset())); } public void sendResponse(ClientHandler handler, byte data[]) throws SocketTimeoutException, IOException { if(handler.getCommunicationLogging() || QuickCached.DEBUG) { logger.log(Level.FINE, "S: {0}", new String(data, HexUtil.getCharset())); } else { logger.log(Level.FINE, "S: {0} bytes", data.length); } handler.sendClientBinary(data); } }
Java
/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor ** the names of its contributors may be used to endorse or promote ** products derived from this software without specific prior written ** permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "mainwindow.h" #include <QtGui> #include "svgview.h" MainWindow::MainWindow() : QMainWindow() , m_view(new SvgView) { QMenu *fileMenu = new QMenu(tr("&File"), this); QAction *openAction = fileMenu->addAction(tr("&Open...")); openAction->setShortcut(QKeySequence(tr("Ctrl+O"))); QAction *quitAction = fileMenu->addAction(tr("E&xit")); quitAction->setShortcuts(QKeySequence::Quit); menuBar()->addMenu(fileMenu); QMenu *viewMenu = new QMenu(tr("&View"), this); m_backgroundAction = viewMenu->addAction(tr("&Background")); m_backgroundAction->setEnabled(false); m_backgroundAction->setCheckable(true); m_backgroundAction->setChecked(false); connect(m_backgroundAction, SIGNAL(toggled(bool)), m_view, SLOT(setViewBackground(bool))); m_outlineAction = viewMenu->addAction(tr("&Outline")); m_outlineAction->setEnabled(false); m_outlineAction->setCheckable(true); m_outlineAction->setChecked(true); connect(m_outlineAction, SIGNAL(toggled(bool)), m_view, SLOT(setViewOutline(bool))); menuBar()->addMenu(viewMenu); QMenu *rendererMenu = new QMenu(tr("&Renderer"), this); m_nativeAction = rendererMenu->addAction(tr("&Native")); m_nativeAction->setCheckable(true); m_nativeAction->setChecked(true); #ifndef QT_NO_OPENGL m_glAction = rendererMenu->addAction(tr("&OpenGL")); m_glAction->setCheckable(true); #endif m_imageAction = rendererMenu->addAction(tr("&Image")); m_imageAction->setCheckable(true); #ifndef QT_NO_OPENGL rendererMenu->addSeparator(); m_highQualityAntialiasingAction = rendererMenu->addAction(tr("&High Quality Antialiasing")); m_highQualityAntialiasingAction->setEnabled(false); m_highQualityAntialiasingAction->setCheckable(true); m_highQualityAntialiasingAction->setChecked(false); connect(m_highQualityAntialiasingAction, SIGNAL(toggled(bool)), m_view, SLOT(setHighQualityAntialiasing(bool))); #endif QActionGroup *rendererGroup = new QActionGroup(this); rendererGroup->addAction(m_nativeAction); #ifndef QT_NO_OPENGL rendererGroup->addAction(m_glAction); #endif rendererGroup->addAction(m_imageAction); menuBar()->addMenu(rendererMenu); connect(openAction, SIGNAL(triggered()), this, SLOT(openFile())); connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit())); connect(rendererGroup, SIGNAL(triggered(QAction*)), this, SLOT(setRenderer(QAction*))); setCentralWidget(m_view); setWindowTitle(tr("SVG Viewer")); } void MainWindow::openFile(const QString &path) { QString fileName; if (path.isNull()) fileName = QFileDialog::getOpenFileName(this, tr("Open SVG File"), m_currentPath, "SVG files (*.svg *.svgz *.svg.gz)"); else fileName = path; if (!fileName.isEmpty()) { QFile file(fileName); if (!file.exists()) { QMessageBox::critical(this, tr("Open SVG File"), QString("Could not open file '%1'.").arg(fileName)); m_outlineAction->setEnabled(false); m_backgroundAction->setEnabled(false); return; } m_view->openFile(file); if (!fileName.startsWith(":/")) { m_currentPath = fileName; setWindowTitle(tr("%1 - SVGViewer").arg(m_currentPath)); } m_outlineAction->setEnabled(true); m_backgroundAction->setEnabled(true); resize(m_view->sizeHint() + QSize(80, 80 + menuBar()->height())); } } void MainWindow::setRenderer(QAction *action) { #ifndef QT_NO_OPENGL m_highQualityAntialiasingAction->setEnabled(false); #endif if (action == m_nativeAction) m_view->setRenderer(SvgView::Native); #ifndef QT_NO_OPENGL else if (action == m_glAction) { m_highQualityAntialiasingAction->setEnabled(true); m_view->setRenderer(SvgView::OpenGL); } #endif else if (action == m_imageAction) { m_view->setRenderer(SvgView::Image); } }
Java
/* * GPAC Multimedia Framework * * Authors: Jean Le Feuvre * Copyright (c) Telecom ParisTech 2005-2012 * All rights reserved * * This file is part of GPAC / X11 video output module * * GPAC 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, or (at your option) * any later version. * * GPAC is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * */ #ifndef _X11_OUT_H #define _X11_OUT_H #ifdef __cplusplus extern "C" { #endif #include <gpac/modules/video_out.h> #include <gpac/thread.h> #include <gpac/list.h> #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/keysym.h> #if !defined(GPAC_DISABLE_3D) && !defined(GPAC_USE_OGL_ES) && !defined(GPAC_USE_TINYGL) #define GPAC_HAS_OPENGL #endif #ifdef GPAC_HAS_OPENGL #include <GL/glx.h> #endif #ifdef GPAC_HAS_X11_SHM #include <X11/extensions/XShm.h> #include <sys/ipc.h> #include <sys/shm.h> #endif #ifdef GPAC_HAS_X11_XV #include <X11/extensions/Xv.h> #include <X11/extensions/Xvlib.h> #endif #if defined(ENABLE_JOYSTICK) || defined(ENABLE_JOYSTICK_NO_CURSOR) #include <linux/joystick.h> #include <unistd.h> #include <fcntl.h> #endif #define X11VID() XWindow *xWindow = (XWindow *)vout->opaque; #define RGB555(r,g,b) (((r&248)<<7) + ((g&248)<<2) + (b>>3)) #define RGB565(r,g,b) (((r&248)<<8) + ((g&252)<<3) + (b>>3)) typedef struct { Window par_wnd; //main window handler passed to module, NULL otherwise Bool setup_done, no_select_input; //setup is done Display *display; //required by all X11 method, provide by XOpenDisplay, Mozilla wnd ... Window wnd; //window handler created by module Window full_wnd; //full screen Screen *screenptr; //X11 stuff int screennum; //... Visual *visual; //... GC the_gc; //graphics context XImage *surface; //main drawing image: software mode Pixmap pixmap; u32 pwidth, pheight; u32 init_flags; Atom WM_DELETE_WINDOW; //window deletion Bool use_shared_memory; // /*screensaver state*/ int ss_t, ss_b, ss_i, ss_e; #ifdef GPAC_HAS_X11_SHM XShmSegmentInfo *shmseginfo; #endif /*YUV overlay*/ #ifdef GPAC_HAS_X11_XV int xvport; u32 xv_pf_format; XvImage *overlay; #endif Bool is_init, fullscreen, has_focus; /*backbuffer size before entering fullscreen mode (used for restore) */ u32 store_width, store_height; u32 w_width, w_height; u32 depth, bpp, pixel_format; u32 output_3d_mode; #ifdef GPAC_HAS_OPENGL XVisualInfo *glx_visualinfo; GLXContext glx_context; Pixmap gl_pixmap; GLXPixmap gl_offscreen; Window gl_wnd; u32 offscreen_type; #endif #if defined(ENABLE_JOYSTICK) || defined(ENABLE_JOYSTICK_NO_CURSOR) /*joystick device file descriptor*/ s32 prev_x, prev_y, fd; #endif } XWindow; void StretchBits (void *dst, u32 dst_bpp, u32 dst_w, u32 dst_h, u32 dst_pitch, void *src, u32 src_bpp, u32 src_w, u32 src_h, u32 src_pitch, Bool FlipIt); #endif /* _X11_OUT_H */
Java
# -*- coding: utf-8 -*- """Additional helper functions for the optlang solvers. All functions integrate well with the context manager, meaning that all operations defined here are automatically reverted when used in a `with model:` block. The functions defined here together with the existing model functions should allow you to implement custom flux analysis methods with ease. """ from __future__ import absolute_import import re from functools import partial from collections import namedtuple from types import ModuleType from warnings import warn import optlang from optlang.symbolics import Basic, Zero from cobra.exceptions import OptimizationError, OPTLANG_TO_EXCEPTIONS_DICT from cobra.util.context import get_context class SolverNotFound(Exception): """A simple Exception when a solver can not be found.""" pass # Define all the solvers that are found in optlang. solvers = {match.split("_")[0]: getattr(optlang, match) for match in dir(optlang) if "_interface" in match} # Defines all the QP solvers implemented in optlang. qp_solvers = ["cplex"] # QP in gurobi not implemented yet def linear_reaction_coefficients(model, reactions=None): """Coefficient for the reactions in a linear objective. Parameters ---------- model : cobra model the model object that defined the objective reactions : list an optional list for the reactions to get the coefficients for. All reactions if left missing. Returns ------- dict A dictionary where the key is the reaction object and the value is the corresponding coefficient. Empty dictionary if there are no linear terms in the objective. """ linear_coefficients = {} reactions = model.reactions if not reactions else reactions try: objective_expression = model.solver.objective.expression coefficients = objective_expression.as_coefficients_dict() except AttributeError: return linear_coefficients for rxn in reactions: forward_coefficient = coefficients.get(rxn.forward_variable, 0) reverse_coefficient = coefficients.get(rxn.reverse_variable, 0) if forward_coefficient != 0: if forward_coefficient == -reverse_coefficient: linear_coefficients[rxn] = float(forward_coefficient) return linear_coefficients def _valid_atoms(model, expression): """Check whether a sympy expression references the correct variables. Parameters ---------- model : cobra.Model The model in which to check for variables. expression : sympy.Basic A sympy expression. Returns ------- boolean True if all referenced variables are contained in model, False otherwise. """ atoms = expression.atoms(optlang.interface.Variable) return all(a.problem is model.solver for a in atoms) def set_objective(model, value, additive=False): """Set the model objective. Parameters ---------- model : cobra model The model to set the objective for value : model.problem.Objective, e.g. optlang.glpk_interface.Objective, sympy.Basic or dict If the model objective is linear, the value can be a new Objective object or a dictionary with linear coefficients where each key is a reaction and the element the new coefficient (float). If the objective is not linear and `additive` is true, only values of class Objective. additive : bool If true, add the terms to the current objective, otherwise start with an empty objective. """ interface = model.problem reverse_value = model.solver.objective.expression reverse_value = interface.Objective( reverse_value, direction=model.solver.objective.direction, sloppy=True) if isinstance(value, dict): if not model.objective.is_Linear: raise ValueError('can only update non-linear objectives ' 'additively using object of class ' 'model.problem.Objective, not %s' % type(value)) if not additive: model.solver.objective = interface.Objective( Zero, direction=model.solver.objective.direction) for reaction, coef in value.items(): model.solver.objective.set_linear_coefficients( {reaction.forward_variable: coef, reaction.reverse_variable: -coef}) elif isinstance(value, (Basic, optlang.interface.Objective)): if isinstance(value, Basic): value = interface.Objective( value, direction=model.solver.objective.direction, sloppy=False) # Check whether expression only uses variables from current model # clone the objective if not, faster than cloning without checking if not _valid_atoms(model, value.expression): value = interface.Objective.clone(value, model=model.solver) if not additive: model.solver.objective = value else: model.solver.objective += value.expression else: raise TypeError( '%r is not a valid objective for %r.' % (value, model.solver)) context = get_context(model) if context: def reset(): model.solver.objective = reverse_value model.solver.objective.direction = reverse_value.direction context(reset) def interface_to_str(interface): """Give a string representation for an optlang interface. Parameters ---------- interface : string, ModuleType Full name of the interface in optlang or cobra representation. For instance 'optlang.glpk_interface' or 'optlang-glpk'. Returns ------- string The name of the interface as a string """ if isinstance(interface, ModuleType): interface = interface.__name__ return re.sub(r"optlang.|.interface", "", interface) def get_solver_name(mip=False, qp=False): """Select a solver for a given optimization problem. Parameters ---------- mip : bool Does the solver require mixed integer linear programming capabilities? qp : bool Does the solver require quadratic programming capabilities? Returns ------- string The name of feasible solver. Raises ------ SolverNotFound If no suitable solver could be found. """ if len(solvers) == 0: raise SolverNotFound("no solvers installed") # Those lists need to be updated as optlang implements more solvers mip_order = ["gurobi", "cplex", "glpk"] lp_order = ["glpk", "cplex", "gurobi"] qp_order = ["cplex"] if mip is False and qp is False: for solver_name in lp_order: if solver_name in solvers: return solver_name # none of them are in the list order - so return the first one return list(solvers)[0] elif qp: # mip does not yet matter for this determination for solver_name in qp_order: if solver_name in solvers: return solver_name raise SolverNotFound("no qp-capable solver found") else: for solver_name in mip_order: if solver_name in solvers: return solver_name raise SolverNotFound("no mip-capable solver found") def choose_solver(model, solver=None, qp=False): """Choose a solver given a solver name and model. This will choose a solver compatible with the model and required capabilities. Also respects model.solver where it can. Parameters ---------- model : a cobra model The model for which to choose the solver. solver : str, optional The name of the solver to be used. Optlang solvers should be prefixed by "optlang-", for instance "optlang-glpk". qp : boolean, optional Whether the solver needs Quadratic Programming capabilities. Returns ------- legacy : boolean Whether the returned solver is a legacy (old cobra solvers) version or an optlang solver (legacy = False). solver : a cobra or optlang solver interface Returns a valid solver for the problem. May be a cobra solver or an optlang interface. Raises ------ SolverNotFound If no suitable solver could be found. """ legacy = False if solver is None: solver = model.problem elif "optlang-" in solver: solver = interface_to_str(solver) solver = solvers[solver] else: legacy = True solver = legacy_solvers.solver_dict[solver] # Check for QP, raise error if no QP solver found # optlang only since old interface interprets None differently if qp and interface_to_str(solver) not in qp_solvers: solver = solvers[get_solver_name(qp=True)] return legacy, solver def add_cons_vars_to_problem(model, what, **kwargs): """Add variables and constraints to a Model's solver object. Useful for variables and constraints that can not be expressed with reactions and lower/upper bounds. Will integrate with the Model's context manager in order to revert changes upon leaving the context. Parameters ---------- model : a cobra model The model to which to add the variables and constraints. what : list or tuple of optlang variables or constraints. The variables or constraints to add to the model. Must be of class `model.problem.Variable` or `model.problem.Constraint`. **kwargs : keyword arguments passed to solver.add() """ context = get_context(model) model.solver.add(what, **kwargs) if context: context(partial(model.solver.remove, what)) def remove_cons_vars_from_problem(model, what): """Remove variables and constraints from a Model's solver object. Useful to temporarily remove variables and constraints from a Models's solver object. Parameters ---------- model : a cobra model The model from which to remove the variables and constraints. what : list or tuple of optlang variables or constraints. The variables or constraints to remove from the model. Must be of class `model.problem.Variable` or `model.problem.Constraint`. """ context = get_context(model) model.solver.remove(what) if context: context(partial(model.solver.add, what)) def add_absolute_expression(model, expression, name="abs_var", ub=None, difference=0, add=True): """Add the absolute value of an expression to the model. Also defines a variable for the absolute value that can be used in other objectives or constraints. Parameters ---------- model : a cobra model The model to which to add the absolute expression. expression : A sympy expression Must be a valid expression within the Model's solver object. The absolute value is applied automatically on the expression. name : string The name of the newly created variable. ub : positive float The upper bound for the variable. difference : positive float The difference between the expression and the variable. add : bool Whether to add the variable to the model at once. Returns ------- namedtuple A named tuple with variable and two constraints (upper_constraint, lower_constraint) describing the new variable and the constraints that assign the absolute value of the expression to it. """ Components = namedtuple('Components', ['variable', 'upper_constraint', 'lower_constraint']) variable = model.problem.Variable(name, lb=0, ub=ub) # The following constraints enforce variable > expression and # variable > -expression upper_constraint = model.problem.Constraint(expression - variable, ub=difference, name="abs_pos_" + name), lower_constraint = model.problem.Constraint(expression + variable, lb=difference, name="abs_neg_" + name) to_add = Components(variable, upper_constraint, lower_constraint) if add: add_cons_vars_to_problem(model, to_add) return to_add def fix_objective_as_constraint(model, fraction=1, bound=None, name='fixed_objective_{}'): """Fix current objective as an additional constraint. When adding constraints to a model, such as done in pFBA which minimizes total flux, these constraints can become too powerful, resulting in solutions that satisfy optimality but sacrifices too much for the original objective function. To avoid that, we can fix the current objective value as a constraint to ignore solutions that give a lower (or higher depending on the optimization direction) objective value than the original model. When done with the model as a context, the modification to the objective will be reverted when exiting that context. Parameters ---------- model : cobra.Model The model to operate on fraction : float The fraction of the optimum the objective is allowed to reach. bound : float, None The bound to use instead of fraction of maximum optimal value. If not None, fraction is ignored. name : str Name of the objective. May contain one `{}` placeholder which is filled with the name of the old objective. """ fix_objective_name = name.format(model.objective.name) if fix_objective_name in model.constraints: model.solver.remove(fix_objective_name) if bound is None: bound = model.slim_optimize(error_value=None) * fraction if model.objective.direction == 'max': ub, lb = None, bound else: ub, lb = bound, None constraint = model.problem.Constraint( model.objective.expression, name=fix_objective_name, ub=ub, lb=lb) add_cons_vars_to_problem(model, constraint, sloppy=True) def check_solver_status(status, raise_error=False): """Perform standard checks on a solver's status.""" if status == optlang.interface.OPTIMAL: return elif status == optlang.interface.INFEASIBLE and not raise_error: warn("solver status is '{}'".format(status), UserWarning) elif status is None: raise RuntimeError( "model was not optimized yet or solver context switched") else: raise OptimizationError("solver status is '{}'".format(status)) def assert_optimal(model, message='optimization failed'): """Assert model solver status is optimal. Do nothing if model solver status is optimal, otherwise throw appropriate exception depending on the status. Parameters ---------- model : cobra.Model The model to check the solver status for. message : str (optional) Message to for the exception if solver status was not optimal. """ if model.solver.status != optlang.interface.OPTIMAL: raise OPTLANG_TO_EXCEPTIONS_DICT[model.solver.status](message) import cobra.solvers as legacy_solvers # noqa
Java
// Copyright 2018 Google LLC. All Rights Reserved. /* Copyright (C) 2005-2017 Steven L. Scott This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ #include "Models/Mixtures/DirichletProcessMixture.hpp" #include "Models/Mixtures/PosteriorSamplers/SplitMerge.hpp" #include "cpputil/report_error.hpp" #include "cpputil/shift_element.hpp" #include "distributions.hpp" namespace BOOM { namespace { typedef DirichletProcessMixtureModel DPMM; typedef ConjugateDirichletProcessMixtureModel CDPMM; typedef DirichletProcessMixtureComponent DpMixtureComponent; typedef ConjugateDirichletProcessMixtureComponent ConjugateDpMixtureComponent; } // namespace DPMM::DirichletProcessMixtureModel( const Ptr<DirichletProcessMixtureComponent> &mixture_component_prototype, const Ptr<HierarchicalPosteriorSampler> &base_distribution, const Ptr<UnivParams> &concentration_parameter) : mixture_component_prototype_(mixture_component_prototype), base_distribution_(base_distribution), concentration_parameter_(concentration_parameter), mixing_weights_(1, 1.0), spare_mixture_component_target_buffer_size_(10) { observe_concentration_parameter(); } void DPMM::set_stick_fractions(const Vector &stick_fractions) { if (stick_fractions.size() != number_of_components()) { report_error("Stick fractions have the wrong dimension."); } stick_fractions_ = stick_fractions; compute_mixing_weights(); } int DPMM::cluster_indicator(int observation) const { const Ptr<Data> &data_point(dat()[observation]); auto it = cluster_indicators_.find(data_point); if (it != cluster_indicators_.end()) { // If the observation is currently unassigned then its cluster indicator // is the nullptr. Return -1 in that case. return !!it->second ? it->second->mixture_component_index() : -1; } else { report_error("Cluster indicator could not be found"); return -2; // Will never get here } } void DPMM::cluster_indicators(std::vector<int> &indicators) const { int sample_size = number_of_observations(); indicators.resize(sample_size); for (int i = 0; i < sample_size; ++i) { indicators[i] = cluster_indicator(i); } } void DPMM::add_data(const Ptr<Data> &dp) { data_.push_back(dp); cluster_indicators_[dp] = nullptr; } void DPMM::clear_data() { data_.clear(); for (int i = 0; i < mixture_components_.size(); ++i) { mixture_components_[i]->clear_data(); } cluster_indicators_.clear(); } void DPMM::combine_data(const Model &other_model, bool just_suf) { const DPMM &other(dynamic_cast<const DPMM &>(other_model)); const std::vector<Ptr<Data>> &other_data(other.dat()); for (int i = 0; i < other_data.size(); ++i) { add_data(other_data[i]); } } void DPMM::accept_split_merge_proposal(const SplitMerge::Proposal &proposal) { if (proposal.is_merge()) { replace_cluster( mixture_components_[proposal.split1()->mixture_component_index()], proposal.merged()); int component_index_2 = proposal.split2()->mixture_component_index(); mixture_components_[component_index_2]->clear_data(); remove_empty_cluster(mixture_components_[component_index_2], false); // The last element of proposal.merged_mixing_weights() is the mixing // weight for an empty cluster. Get rid of that and put in the collective // weight for all unpopulated components. mixing_weights_ = proposal.merged_mixing_weights(); mixing_weights_.back() = 0; mixing_weights_.back() = 1.0 - mixing_weights_.sum(); } else { // Accept a split move. replace_cluster( mixture_components_[proposal.merged()->mixture_component_index()], proposal.split1()); insert_cluster(proposal.split2(), proposal.split2()->mixture_component_index()); mixing_weights_ = proposal.split_mixing_weights(); mixing_weights_.push_back(1.0 - mixing_weights_.sum()); } compute_stick_fractions_from_mixing_weights(); } void DPMM::assign_data_to_cluster(const Ptr<Data> &dp, int cluster, RNG &rng) { if (cluster == number_of_components()) { add_empty_cluster(rng); } if (cluster < number_of_components()) { mixture_components_[cluster]->add_data(dp); cluster_indicators_[dp] = mixture_components_[cluster]; } else { report_error("Invalid cluster index."); } } void DPMM::remove_data_from_cluster(const Ptr<Data> &dp, bool remove_empty_cluster) { Ptr<DirichletProcessMixtureComponent> component = cluster_indicators_[dp]; if (!!component) { component->remove_data(dp); if (component->number_of_observations() == 0 && remove_empty_cluster) { this->remove_empty_cluster(component, true); } } cluster_indicators_[dp] = nullptr; } void DPMM::add_empty_cluster(RNG &rng) { repopulate_spare_mixture_components(); Ptr<DirichletProcessMixtureComponent> component = spare_mixture_components_.back(); assign_and_add_mixture_component(component, rng); pop_spare_component_stack(); } void DPMM::remove_empty_cluster(const Ptr<DpMixtureComponent> &component, bool adjust_mixing_weights) { if (component->number_of_observations() != 0) { report_error("Cluster to be removed is not empty."); } int which_cluster = component->mixture_component_index(); if (which_cluster < 0) { // The component is not currently assigned. return; } else if (which_cluster > number_of_components()) { report_error("Mixture component index too large."); } if (mixture_components_[which_cluster] != component) { report_error("Mixture components have become misaligned."); } component->set_mixture_component_index(-1); spare_mixture_components_.push_back(component); for (int i = which_cluster; i < mixture_components_.size(); ++i) { mixture_components_[i]->decrement_mixture_component_index(); } mixture_components_.erase(mixture_components_.begin() + which_cluster); if (adjust_mixing_weights) { stick_fractions_.erase(stick_fractions_.begin() + which_cluster); mixing_weights_.pop_back(); compute_mixing_weights(); } } void DPMM::remove_all_empty_clusters() { for (int i = 0; i < mixture_components_.size(); ++i) { if (cluster_count(i) == 0) { remove_empty_cluster(mixture_components_[i], true); --i; } } } void DPMM::shift_cluster(int from, int to) { shift_element(mixture_components_, from, to); for (int i = 0; i < number_of_components(); ++i) { mixture_components_[i]->set_mixture_component_index(i); } mixing_weights_.shift_element(from, to); compute_stick_fractions_from_mixing_weights(); } void DPMM::compute_mixing_weights() { mixing_weights_.resize(stick_fractions_.size() + 1); double fraction_remaining = 1.0; for (int i = 0; i < stick_fractions_.size(); ++i) { mixing_weights_[i] = stick_fractions_[i] * fraction_remaining; fraction_remaining *= (1 - stick_fractions_[i]); } mixing_weights_.back() = fraction_remaining; } void DPMM::compute_stick_fractions_from_mixing_weights() { stick_fractions_.resize(mixing_weights_.size() - 1); stick_fractions_[0] = mixing_weights_[0]; double probability_remaining = 1.0 - stick_fractions_[0]; for (int i = 1; i < stick_fractions_.size(); ++i) { stick_fractions_[i] = mixing_weights_[i] / probability_remaining; probability_remaining -= mixing_weights_[i]; } } // Here is the math for the stick breaking distribution. Let w = w1, w2, ..., // wn. The density factors as p(w) = p(w1) p(w2 | w1) ... p(wn | w1..wn). // Each wi is defined as vi * (1 - sum of previous weights), where vi ~ // Beta(1, alpha). // // That means p(wi | w1, ..., wi-1) = Beta(wi / previous) / previous, where // the extra factor is a Jacobian. // // There is some nice cancellation that falls out of the beta distribution. // Beta(v, 1, alpha) = Gamma(1 + alpha) // ------------------- * v^(1-1) * (1-v)^(alpha - 1). // Gamma(1) Gamma(alpha) // // Now, Gamma(1 + alpha) = alpha * Gamma(alpha), so the normalizing constant // here is just alpha, and the density is just (1-v)^(alpha-1). // // The Jacobian term is 1/previous, where we can write previous_i = // (1-v1)...(1-vi-1). Thus 1-v1 appears in the denominator of n-1 terms, 1-v2 // in n-2 terms etc. // // Putting all this together gives // p(w) = alpha^n \prod_{i=1}^n (1-v_i)^{\alpha + i - 1 - n)} // // In C's zero-based counting scheme we just replace i-1 with i. double DPMM::dstick(const Vector &weights, double alpha, bool logscale) { // The amount of probability remaining after subtracting off all previous // mixing weights. double log_alpha = log(alpha); int dim = weights.size(); double ans = dim * log_alpha; double previous_probability = 1.0; for (int i = 0; i < dim; ++i) { if (previous_probability > 0) { double stick_fraction = weights[i] / previous_probability; previous_probability -= weights[i]; ans += (alpha + i - dim) * log(1 - stick_fraction); } else { // Do some error checking to make sure previous_probability isn't so // more negative than can plausibly be attributed to numerical issues. if (fabs(previous_probability) > 1e-10) { report_error("Vector of weights sums to more than 1."); } else { // Assume all future weights (and thus all future stick fractions) are // zero. Each zero stick fraction increments ans by zero, so we're // done. break; } } } return logscale ? ans : exp(ans); } void DPMM::repopulate_spare_mixture_components() { if (spare_mixture_components_.empty()) { for (int i = 0; i < spare_mixture_component_target_buffer_size(); ++i) { Ptr<DirichletProcessMixtureComponent> component = mixture_component_prototype_->clone(); component->clear_data(); unassign_component_and_add_to_spares(component); } } } void DPMM::pop_spare_component_stack() { spare_mixture_components_.pop_back(); } void DPMM::unassign_component_and_add_to_spares( const Ptr<DirichletProcessMixtureComponent> &component) { spare_mixture_components_.push_back(component); spare_mixture_components_.back()->set_mixture_component_index(-1); } void DPMM::assign_and_add_mixture_component( const Ptr<DpMixtureComponent> &component, RNG &rng) { mixture_components_.push_back(component); base_distribution_->draw_model_parameters(*mixture_components_.back()); mixture_components_.back()->set_mixture_component_index( mixture_components_.size() - 1); stick_fractions_.push_back(rbeta_mt(rng, 1, concentration_parameter())); double remainder = mixing_weights_.back(); mixing_weights_.back() = remainder * stick_fractions_.back(); mixing_weights_.push_back(remainder * (1 - stick_fractions_.back())); } void DPMM::replace_cluster( const Ptr<DpMixtureComponent> &component_to_replace, const Ptr<DpMixtureComponent> &new_component) { int index = component_to_replace->mixture_component_index(); component_to_replace->set_mixture_component_index(-1); component_to_replace->clear_data(); spare_mixture_components_.push_back(component_to_replace); int buffer_size = spare_mixture_component_target_buffer_size_; if (spare_mixture_components_.size() > 2 * buffer_size) { spare_mixture_components_.erase( spare_mixture_components_.begin() + buffer_size, spare_mixture_components_.end()); } new_component->set_mixture_component_index(index); mixture_components_[index] = new_component; std::set<Ptr<Data>> data_set = new_component->abstract_data_set(); for (const auto &el : data_set) { cluster_indicators_[el] = new_component; } } void DPMM::insert_cluster(const Ptr<DpMixtureComponent> &component, int index) { mixture_components_.insert(mixture_components_.begin() + index, component); std::set<Ptr<Data>> data_set = component->abstract_data_set(); for (const auto &data_point : data_set) { cluster_indicators_[data_point] = component; } for (int i = index; i < mixture_components_.size(); ++i) { mixture_components_[i]->set_mixture_component_index(i); } } void DPMM::observe_concentration_parameter() { concentration_parameter_->add_observer([this]() { this->log_concentration_parameter_ = log(this->concentration_parameter()); }); concentration_parameter_->set(concentration_parameter()); } //====================================================================== CDPMM::ConjugateDirichletProcessMixtureModel( const Ptr<ConjugateDpMixtureComponent> &mixture_component_prototype, const Ptr<ConjugateHierarchicalPosteriorSampler> &base_distribution, const Ptr<UnivParams> &concentration_parameter) : DPMM(mixture_component_prototype, base_distribution, concentration_parameter), conjugate_mixture_component_prototype_(mixture_component_prototype), conjugate_base_distribution_(base_distribution) {} double ConjugateDirichletProcessMixtureModel::log_marginal_density( const Ptr<Data> &data_point, int which_component) const { if (which_component > 0) { return conjugate_base_distribution_->log_marginal_density( data_point, component(which_component)); } else { return conjugate_base_distribution_->log_marginal_density( data_point, conjugate_mixture_component_prototype_.get()); } } void CDPMM::add_empty_cluster(RNG &rng) { repopulate_spare_mixture_components(); Ptr<ConjugateDpMixtureComponent> component = spare_conjugate_components_.back(); conjugate_mixture_components_.push_back(component); DPMM::assign_and_add_mixture_component(component, rng); pop_spare_component_stack(); } void CDPMM::remove_empty_cluster(const Ptr<DpMixtureComponent> &component, bool adjust_mixing_weights) { int which_cluster = component->mixture_component_index(); if (conjugate_mixture_components_[which_cluster] != component) { report_error("Conjugate mixture components have become misaligned"); } spare_conjugate_components_.push_back( conjugate_mixture_components_[which_cluster]); conjugate_mixture_components_.erase(conjugate_mixture_components_.begin() + which_cluster); DPMM::remove_empty_cluster(component, adjust_mixing_weights); } void CDPMM::replace_cluster( const Ptr<DpMixtureComponent> &component_to_replace, const Ptr<DpMixtureComponent> &new_component) { int index = component_to_replace->mixture_component_index(); conjugate_mixture_components_[index] = new_component.dcast<ConjugateDirichletProcessMixtureComponent>(); DPMM::replace_cluster(component_to_replace, new_component); } void CDPMM::insert_cluster(const Ptr<DpMixtureComponent> &component, int index) { conjugate_mixture_components_.insert( conjugate_mixture_components_.begin() + index, component.dcast<ConjugateDpMixtureComponent>()); DPMM::insert_cluster(component, index); } void CDPMM::shift_cluster(int from, int to) { shift_element(conjugate_mixture_components_, from, to); DPMM::shift_cluster(from, to); } void CDPMM::repopulate_spare_mixture_components() { if (spare_conjugate_components_.empty()) { for (int i = 0; i < spare_mixture_component_target_buffer_size(); ++i) { Ptr<ConjugateDirichletProcessMixtureComponent> component = conjugate_mixture_component_prototype_->clone(); component->clear_data(); unassign_component_and_add_to_spares(component); spare_conjugate_components_.push_back(component); } } } void CDPMM::pop_spare_component_stack() { spare_conjugate_components_.pop_back(); DPMM::pop_spare_component_stack(); } } // namespace BOOM
Java
// // Created by anton on 21.03.15. // #include "wMotion.h" #include "Matrix.h" #include <nan.h> v8::Persistent<FunctionTemplate> wMotion::constructor; int buffersSize; unsigned char *cur; float *recent; float *bg; int motionThreshold, presenceThreshold; float motionWeight, presenceWeight; void wMotion::Init(Handle<Object> target) { NanScope(); //Class Local<FunctionTemplate> ctor = NanNew<FunctionTemplate>(wMotion::New); NanAssignPersistent(constructor, ctor); ctor->InstanceTemplate()->SetInternalFieldCount(1); ctor->SetClassName(NanNew("wMotion")); // Prototype NODE_SET_PROTOTYPE_METHOD(ctor, "process", Process); target->Set(NanNew("wMotion"), ctor->GetFunction()); } NAN_METHOD(wMotion::New) { NanScope(); NanReturnValue(args.Holder()); } wMotion::wMotion(): ObjectWrap() { if( cur ) delete[] cur; if( bg ) delete[] bg; if( recent ) delete[] recent; buffersSize = 0; cur = NULL; bg = recent = NULL; motionThreshold = 8; // min 0 max 255 presenceThreshold = 8; // min 0 max 255 motionWeight = 0.1; // min 0 max 2 presenceWeight = 0.0001; // min 0 max 2 } void quarterScale( unsigned char *to, unsigned char *from, int w, int h ) { for( int y=0; y<h-1; y+=2 ) { int yw = (y*w); for( int x=0; x<w-1; x+=2 ) { to[ (yw/4) + (x/2) ] = ( from[ yw + x ] +from[ yw + x + 1 ] +from[ yw + w + x ] +from[ yw + w + x + 1 ] ) / 4; } } } NAN_METHOD(wMotion::Reset) { NanScope(); buffersSize = -1; NanReturnNull(); } NAN_METHOD(wMotion::Process) { NanScope(); Matrix *src = ObjectWrap::Unwrap<Matrix>(args[0]->ToObject()); cv::Mat yuv; cv::cvtColor(src->mat, yuv, CV_RGB2YCrCb); motionThreshold = args[1]->IntegerValue(); presenceThreshold = args[2]->IntegerValue(); motionWeight = (float)args[3]->NumberValue(); presenceWeight = (float)args[4]->NumberValue(); int sz = yuv.cols*yuv.rows; int sz4 = ( (yuv.cols/2)*(yuv.rows/2)); unsigned char *Y = yuv.data; unsigned char *U = Y + sz; unsigned char *V = U + sz4; if( buffersSize != sz4 ) { if( cur ) delete[] cur; if( recent ) delete[] recent; if( bg ) delete[] bg; buffersSize = sz4; cur = new unsigned char[sz4]; recent = new float[sz4]; bg = new float[sz4]; quarterScale( cur, Y, yuv.cols, yuv.rows ); for( int i=0; i<sz4; i++ ) recent[i]=bg[i]=cur[i]; } else { quarterScale( cur, Y, yuv.cols, yuv.rows ); } unsigned char mthresh = motionThreshold; unsigned char pthresh = presenceThreshold; unsigned char *P = U; unsigned char *M = V; float pw = presenceWeight; float pwn = 1.-pw; float mw = motionWeight; float mwn = 1.-mw; for( int i=0; i<sz4; i++ ) { // 0-255, threshold //M[i] = abs( late[i]-cur[i] )>mthresh?255:0; //P[i] = abs( bg[i]-cur[i] )>pthresh?255:0; // good looking M[i] = abs( recent[i]-cur[i] )>mthresh?64:128; P[i] = abs( bg[i]-cur[i] )>pthresh?64:128; // "real" //M[i] = 128+(late[i]-cur[i]); //P[i] = 128+(bg[i]-cur[i]); bg[i] *= pwn; bg[i] += cur[i]*pw; recent[i] *= mwn; recent[i] += cur[i]*mw; } v8::Local<v8::Array> arr = NanNew<Array>(2); v8::Handle<v8::Object> currentArray = NanNew<v8::Object>(); currentArray->SetIndexedPropertiesToExternalArrayData(&cur, v8::kExternalUnsignedByteArray, sz4); v8::Handle<v8::Object> recentArray = NanNew<v8::Object>(); recentArray->SetIndexedPropertiesToExternalArrayData(&cur, v8::kExternalUnsignedByteArray, sz4); arr->Set(0, currentArray); arr->Set(1, recentArray); NanReturnValue(arr); }
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_02-ea) on Thu Dec 24 00:39:33 CET 2009 --> <TITLE> org.neuroph.nnet.comp </TITLE> <META NAME="date" CONTENT="2009-12-24"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="org.neuroph.nnet.comp"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../org/neuroph/nnet/package-summary.html"><B>PREV PACKAGE</B></A>&nbsp; &nbsp;<A HREF="../../../../org/neuroph/nnet/learning/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?org/neuroph/nnet/comp/package-summary.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <H2> Package org.neuroph.nnet.comp </H2> Provides components for the specific neural network models. <P> <B>See:</B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<A HREF="#package_description"><B>Description</B></A> <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Class Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../org/neuroph/nnet/comp/CompetitiveLayer.html" title="class in org.neuroph.nnet.comp">CompetitiveLayer</A></B></TD> <TD>Represents layer of competitive neurons, and provides methods for competition.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../org/neuroph/nnet/comp/CompetitiveNeuron.html" title="class in org.neuroph.nnet.comp">CompetitiveNeuron</A></B></TD> <TD>Provides neuron behaviour specific for competitive neurons which are used in competitive layers, and networks with competitive learning.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../org/neuroph/nnet/comp/DelayedConnection.html" title="class in org.neuroph.nnet.comp">DelayedConnection</A></B></TD> <TD>Represents the connection between neurons which can delay signal.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../org/neuroph/nnet/comp/DelayedNeuron.html" title="class in org.neuroph.nnet.comp">DelayedNeuron</A></B></TD> <TD>Provides behaviour for neurons with delayed output.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../org/neuroph/nnet/comp/InputOutputNeuron.html" title="class in org.neuroph.nnet.comp">InputOutputNeuron</A></B></TD> <TD>Provides behaviour specific for neurons which act as input and the output neurons within the same layer.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../org/neuroph/nnet/comp/ThresholdNeuron.html" title="class in org.neuroph.nnet.comp">ThresholdNeuron</A></B></TD> <TD>Provides behaviour for neurons with threshold.</TD> </TR> </TABLE> &nbsp; <P> <A NAME="package_description"><!-- --></A><H2> Package org.neuroph.nnet.comp Description </H2> <P> Provides components for the specific neural network models. <P> <P> <DL> </DL> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../org/neuroph/nnet/package-summary.html"><B>PREV PACKAGE</B></A>&nbsp; &nbsp;<A HREF="../../../../org/neuroph/nnet/learning/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?org/neuroph/nnet/comp/package-summary.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
Java
/* -*-c++-*- OpenThreads library, Copyright (C) 2002 - 2007 The Open Thread Group * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ // // PThreadMutex.c++ - C++ Mutex class built on top of posix threads. // ~~~~~~~~~~~~~~~~ // #include <unistd.h> #include <pthread.h> #include <OpenThreads/Mutex> #include "PThreadMutexPrivateData.h" using namespace OpenThreads; // ---------------------------------------------------------------------------- // // Decription: Constructor // // Use: public. // Mutex::Mutex(MutexType type) : _mutexType(type) { pthread_mutexattr_t mutex_attr; pthread_mutexattr_init(&mutex_attr); PThreadMutexPrivateData *pd = new PThreadMutexPrivateData(); if (type == MUTEX_RECURSIVE) { pthread_mutexattr_settype(&mutex_attr, PTHREAD_MUTEX_RECURSIVE); } else { #ifndef __linux__ // (not available until NPTL) [ pthread_mutexattr_settype(&mutex_attr, PTHREAD_MUTEX_ERRORCHECK); #endif // ] __linux__ } #ifdef ALLOW_PRIORITY_SCHEDULING // [ #ifdef __sun // [ pthread_mutexattr_setprotocol(&mutex_attr, PTHREAD_PRIO_NONE); #endif // ] __sun // ------------------------------------------------------------------------- // Initialization is a bit tricky, since we have to be able to be aware // that on many-to-many execution vehicle systems, we may run into // priority inversion deadlocks if a mutex is shared between threads // of differing priorities. Systems that do this should provide the // following protocol attributes to prevent deadlocks. Check at runtime. // // PRIO_INHERIT causes any thread locking the mutex to temporarily become // the same priority as the highest thread also blocked on the mutex. // Although more expensive, this is the preferred method. // // PRIO_PROTECT causes any thread locking the mutex to assume the priority // specified by setprioceiling. pthread_mutex_lock will fail if // the priority ceiling is lower than the thread's priority. Therefore, // the priority ceiling must be set to the max priority in order to // guarantee no deadlocks will occur. // #if defined (_POSIX_THREAD_PRIO_INHERIT) || defined (_POSIX_THREAD_PRIO_PROTECT) // [ if (sysconf(_POSIX_THREAD_PRIO_INHERIT)) { pthread_mutexattr_setprotocol(&mutex_attr, PTHREAD_PRIO_INHERIT); } else if (sysconf(_POSIX_THREAD_PRIO_PROTECT)) { int th_policy; struct sched_param th_param; pthread_getschedparam(pthread_self(), &th_policy, &th_param); pthread_mutexattr_setprotocol(&mutex_attr, PTHREAD_PRIO_PROTECT); pthread_mutexattr_setprioceiling(&mutex_attr, sched_get_priority_max(th_policy)); } #endif // ] Priority Scheduling. #endif // ] ALLOW_PRIORITY_SCHEDULING pthread_mutex_init(&pd->mutex, &mutex_attr); _prvData = static_cast<void*>(pd); } // ---------------------------------------------------------------------------- // // Decription: Destructor // // Use: public. // Mutex::~Mutex() { PThreadMutexPrivateData *pd = static_cast<PThreadMutexPrivateData*>(_prvData); pthread_mutex_destroy(&pd->mutex); delete pd; } // ---------------------------------------------------------------------------- // // Decription: lock the mutex // // Use: public. // int Mutex::lock() { PThreadMutexPrivateData *pd = static_cast<PThreadMutexPrivateData*>(_prvData); return pthread_mutex_lock(&pd->mutex); } // ---------------------------------------------------------------------------- // // Decription: unlock the mutex // // Use: public. // int Mutex::unlock() { PThreadMutexPrivateData *pd = static_cast<PThreadMutexPrivateData*>(_prvData); return pthread_mutex_unlock(&pd->mutex); } // ---------------------------------------------------------------------------- // // Decription: test if the mutex may be locked // // Use: public. // int Mutex::trylock() { PThreadMutexPrivateData *pd = static_cast<PThreadMutexPrivateData*>(_prvData); return pthread_mutex_trylock(&pd->mutex); }
Java
/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "buildprogress.h" #include "projectexplorerconstants.h" #include <coreplugin/coreconstants.h> #include <utils/stylehelper.h> #include <QVBoxLayout> #include <QHBoxLayout> #include <QLabel> #include <QFont> #include <QPixmap> #include <QDebug> using namespace ProjectExplorer; using namespace ProjectExplorer::Internal; BuildProgress::BuildProgress(TaskWindow *taskWindow, Qt::Orientation orientation) : m_contentWidget(new QWidget), m_errorIcon(new QLabel), m_warningIcon(new QLabel), m_errorLabel(new QLabel), m_warningLabel(new QLabel), m_taskWindow(taskWindow) { QHBoxLayout *contentLayout = new QHBoxLayout; contentLayout->setContentsMargins(0, 0, 0, 0); contentLayout->setSpacing(0); setLayout(contentLayout); contentLayout->addWidget(m_contentWidget); QBoxLayout *layout; if (orientation == Qt::Horizontal) layout = new QHBoxLayout; else layout = new QVBoxLayout; layout->setContentsMargins(8, 2, 0, 2); layout->setSpacing(2); m_contentWidget->setLayout(layout); QHBoxLayout *errorLayout = new QHBoxLayout; errorLayout->setSpacing(2); layout->addLayout(errorLayout); errorLayout->addWidget(m_errorIcon); errorLayout->addWidget(m_errorLabel); QHBoxLayout *warningLayout = new QHBoxLayout; warningLayout->setSpacing(2); layout->addLayout(warningLayout); warningLayout->addWidget(m_warningIcon); warningLayout->addWidget(m_warningLabel); // ### TODO this setup should be done by style QFont f = this->font(); f.setPointSizeF(Utils::StyleHelper::sidebarFontSize()); f.setBold(true); m_errorLabel->setFont(f); m_warningLabel->setFont(f); m_errorLabel->setPalette(Utils::StyleHelper::sidebarFontPalette(m_errorLabel->palette())); m_warningLabel->setPalette(Utils::StyleHelper::sidebarFontPalette(m_warningLabel->palette())); m_errorIcon->setAlignment(Qt::AlignRight); m_warningIcon->setAlignment(Qt::AlignRight); m_errorIcon->setPixmap(QPixmap(QLatin1String(Core::Constants::ICON_ERROR))); m_warningIcon->setPixmap(QPixmap(QLatin1String(Core::Constants::ICON_WARNING))); m_contentWidget->hide(); connect(m_taskWindow, SIGNAL(tasksChanged()), this, SLOT(updateState())); } void BuildProgress::updateState() { if (!m_taskWindow) return; int errors = m_taskWindow->errorTaskCount(Constants::TASK_CATEGORY_BUILDSYSTEM) + m_taskWindow->errorTaskCount(Constants::TASK_CATEGORY_COMPILE) + m_taskWindow->errorTaskCount(Constants::TASK_CATEGORY_DEPLOYMENT); bool haveErrors = (errors > 0); m_errorIcon->setEnabled(haveErrors); m_errorLabel->setEnabled(haveErrors); m_errorLabel->setText(QString::number(errors)); int warnings = m_taskWindow->warningTaskCount(Constants::TASK_CATEGORY_BUILDSYSTEM) + m_taskWindow->warningTaskCount(Constants::TASK_CATEGORY_COMPILE) + m_taskWindow->warningTaskCount(Constants::TASK_CATEGORY_DEPLOYMENT); bool haveWarnings = (warnings > 0); m_warningIcon->setEnabled(haveWarnings); m_warningLabel->setEnabled(haveWarnings); m_warningLabel->setText(QString::number(warnings)); // Hide warnings and errors unless you need them m_warningIcon->setVisible(haveWarnings); m_warningLabel->setVisible(haveWarnings); m_errorIcon->setVisible(haveErrors); m_errorLabel->setVisible(haveErrors); m_contentWidget->setVisible(haveWarnings || haveErrors); }
Java
/* * Copyright (C) 2009-2012 Felipe Contreras * * Author: Felipe Contreras <felipe.contreras@gmail.com> * * This file may be used under the terms of the GNU Lesser General Public * License version 2.1. */ #include "gstav_h264enc.h" #include "gstav_venc.h" #include "plugin.h" #include <libavcodec/avcodec.h> #include <libavutil/opt.h> #include <gst/tag/tag.h> #include <stdlib.h> #include <string.h> /* for memcpy */ #include <stdbool.h> #include "util.h" #define GST_CAT_DEFAULT gstav_debug struct obj { struct gst_av_venc parent; }; struct obj_class { GstElementClass parent_class; }; #if LIBAVUTIL_VERSION_MAJOR < 52 && !(LIBAVUTIL_VERSION_MAJOR == 51 && LIBAVUTIL_VERSION_MINOR >= 12) static int av_opt_set(void *obj, const char *name, const char *val, int search_flags) { return av_set_string3(obj, name, val, 0, NULL); } #endif static void init_ctx(struct gst_av_venc *base, AVCodecContext *ctx) { av_opt_set(ctx->priv_data, "preset", "medium", 0); av_opt_set(ctx->priv_data, "profile", "baseline", 0); av_opt_set(ctx->priv_data, "x264opts", "annexb=1", 0); av_opt_set_int(ctx->priv_data, "aud", 1, 0); } static GstCaps * generate_src_template(void) { GstCaps *caps; GstStructure *struc; caps = gst_caps_new_empty(); struc = gst_structure_new("video/x-h264", "stream-format", G_TYPE_STRING, "byte-stream", "alignment", G_TYPE_STRING, "au", NULL); gst_caps_append_structure(caps, struc); return caps; } static GstCaps * generate_sink_template(void) { GstCaps *caps; caps = gst_caps_new_simple("video/x-raw-yuv", "format", GST_TYPE_FOURCC, GST_MAKE_FOURCC('I', '4', '2', '0'), NULL); return caps; } static void instance_init(GTypeInstance *instance, void *g_class) { struct gst_av_venc *venc = (struct gst_av_venc *)instance; venc->codec_id = CODEC_ID_H264; venc->init_ctx = init_ctx; } static void base_init(void *g_class) { GstElementClass *element_class = g_class; GstPadTemplate *template; gst_element_class_set_details_simple(element_class, "av h264 video encoder", "Coder/Encoder/Video", "H.264 encoder wrapper for libavcodec", "Felipe Contreras"); template = gst_pad_template_new("src", GST_PAD_SRC, GST_PAD_ALWAYS, generate_src_template()); gst_element_class_add_pad_template(element_class, template); template = gst_pad_template_new("sink", GST_PAD_SINK, GST_PAD_ALWAYS, generate_sink_template()); gst_element_class_add_pad_template(element_class, template); } GType gst_av_h264enc_get_type(void) { static GType type; if (G_UNLIKELY(type == 0)) { GTypeInfo type_info = { .class_size = sizeof(struct obj_class), .base_init = base_init, .instance_size = sizeof(struct obj), .instance_init = instance_init, }; type = g_type_register_static(GST_AV_VENC_TYPE, "GstAVH264Enc", &type_info, 0); } return type; }
Java
/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qvideowidget_p.h" #include <qmediaobject.h> #include <qmediaservice.h> #include <qvideowindowcontrol.h> #include <qvideowidgetcontrol.h> #include <qpaintervideosurface_p.h> #include <qvideorenderercontrol.h> #include <qvideosurfaceformat.h> #include <qpainter.h> #include <qapplication.h> #include <qevent.h> #include <qdialog.h> #include <qboxlayout.h> #include <qnamespace.h> using namespace Qt; QT_BEGIN_NAMESPACE QVideoWidgetControlBackend::QVideoWidgetControlBackend( QMediaService *service, QVideoWidgetControl *control, QWidget *widget) : m_service(service) , m_widgetControl(control) { connect(control, SIGNAL(brightnessChanged(int)), widget, SLOT(_q_brightnessChanged(int))); connect(control, SIGNAL(contrastChanged(int)), widget, SLOT(_q_contrastChanged(int))); connect(control, SIGNAL(hueChanged(int)), widget, SLOT(_q_hueChanged(int))); connect(control, SIGNAL(saturationChanged(int)), widget, SLOT(_q_saturationChanged(int))); connect(control, SIGNAL(fullScreenChanged(bool)), widget, SLOT(_q_fullScreenChanged(bool))); QBoxLayout *layout = new QVBoxLayout; layout->setMargin(0); layout->setSpacing(0); #ifdef Q_OS_SYMBIAN // On some cases the flag is not reset automatically // This would lead to viewfinder not being visible on Symbian control->videoWidget()->setAttribute(Qt::WA_WState_ExplicitShowHide, false); #endif // Q_OS_SYMBIAN layout->addWidget(control->videoWidget()); widget->setLayout(layout); } void QVideoWidgetControlBackend::releaseControl() { m_service->releaseControl(m_widgetControl); } void QVideoWidgetControlBackend::setBrightness(int brightness) { m_widgetControl->setBrightness(brightness); } void QVideoWidgetControlBackend::setContrast(int contrast) { m_widgetControl->setContrast(contrast); } void QVideoWidgetControlBackend::setHue(int hue) { m_widgetControl->setHue(hue); } void QVideoWidgetControlBackend::setSaturation(int saturation) { m_widgetControl->setSaturation(saturation); } void QVideoWidgetControlBackend::setFullScreen(bool fullScreen) { m_widgetControl->setFullScreen(fullScreen); } Qt::AspectRatioMode QVideoWidgetControlBackend::aspectRatioMode() const { return m_widgetControl->aspectRatioMode(); } void QVideoWidgetControlBackend::setAspectRatioMode(Qt::AspectRatioMode mode) { m_widgetControl->setAspectRatioMode(mode); } QRendererVideoWidgetBackend::QRendererVideoWidgetBackend( QMediaService *service, QVideoRendererControl *control, QWidget *widget) : m_service(service) , m_rendererControl(control) , m_widget(widget) , m_surface(new QPainterVideoSurface) , m_aspectRatioMode(Qt::KeepAspectRatio) , m_updatePaintDevice(true) { connect(this, SIGNAL(brightnessChanged(int)), m_widget, SLOT(_q_brightnessChanged(int))); connect(this, SIGNAL(contrastChanged(int)), m_widget, SLOT(_q_contrastChanged(int))); connect(this, SIGNAL(hueChanged(int)), m_widget, SLOT(_q_hueChanged(int))); connect(this, SIGNAL(saturationChanged(int)), m_widget, SLOT(_q_saturationChanged(int))); connect(m_surface, SIGNAL(frameChanged()), this, SLOT(frameChanged())); connect(m_surface, SIGNAL(surfaceFormatChanged(QVideoSurfaceFormat)), this, SLOT(formatChanged(QVideoSurfaceFormat))); m_rendererControl->setSurface(m_surface); } QRendererVideoWidgetBackend::~QRendererVideoWidgetBackend() { delete m_surface; } void QRendererVideoWidgetBackend::releaseControl() { m_service->releaseControl(m_rendererControl); } void QRendererVideoWidgetBackend::clearSurface() { m_rendererControl->setSurface(0); } void QRendererVideoWidgetBackend::setBrightness(int brightness) { m_surface->setBrightness(brightness); emit brightnessChanged(brightness); } void QRendererVideoWidgetBackend::setContrast(int contrast) { m_surface->setContrast(contrast); emit contrastChanged(contrast); } void QRendererVideoWidgetBackend::setHue(int hue) { m_surface->setHue(hue); emit hueChanged(hue); } void QRendererVideoWidgetBackend::setSaturation(int saturation) { m_surface->setSaturation(saturation); emit saturationChanged(saturation); } Qt::AspectRatioMode QRendererVideoWidgetBackend::aspectRatioMode() const { return m_aspectRatioMode; } void QRendererVideoWidgetBackend::setAspectRatioMode(Qt::AspectRatioMode mode) { m_aspectRatioMode = mode; m_widget->updateGeometry(); } void QRendererVideoWidgetBackend::setFullScreen(bool) { } QSize QRendererVideoWidgetBackend::sizeHint() const { return m_surface->surfaceFormat().sizeHint(); } void QRendererVideoWidgetBackend::showEvent() { } void QRendererVideoWidgetBackend::hideEvent(QHideEvent *) { #if !defined(QT_NO_OPENGL) && !defined(QT_OPENGL_ES_1_CL) && !defined(QT_OPENGL_ES_1) m_updatePaintDevice = true; m_surface->setGLContext(0); #endif } void QRendererVideoWidgetBackend::resizeEvent(QResizeEvent *) { updateRects(); } void QRendererVideoWidgetBackend::moveEvent(QMoveEvent *) { } void QRendererVideoWidgetBackend::paintEvent(QPaintEvent *event) { QPainter painter(m_widget); if (m_widget->testAttribute(Qt::WA_OpaquePaintEvent)) { QRegion borderRegion = event->region(); borderRegion = borderRegion.subtracted(m_boundingRect); QBrush brush = m_widget->palette().window(); QVector<QRect> rects = borderRegion.rects(); for (QVector<QRect>::iterator it = rects.begin(), end = rects.end(); it != end; ++it) { painter.fillRect(*it, brush); } } if (m_surface->isActive() && m_boundingRect.intersects(event->rect())) { m_surface->paint(&painter, m_boundingRect, m_sourceRect); m_surface->setReady(true); } else { #if !defined(QT_NO_OPENGL) && !defined(QT_OPENGL_ES_1_CL) && !defined(QT_OPENGL_ES_1) if (m_updatePaintDevice && (painter.paintEngine()->type() == QPaintEngine::OpenGL || painter.paintEngine()->type() == QPaintEngine::OpenGL2)) { m_updatePaintDevice = false; m_surface->setGLContext(const_cast<QGLContext *>(QGLContext::currentContext())); if (m_surface->supportedShaderTypes() & QPainterVideoSurface::GlslShader) { m_surface->setShaderType(QPainterVideoSurface::GlslShader); } else { m_surface->setShaderType(QPainterVideoSurface::FragmentProgramShader); } } #endif } } void QRendererVideoWidgetBackend::formatChanged(const QVideoSurfaceFormat &format) { m_nativeSize = format.sizeHint(); updateRects(); m_widget->updateGeometry(); m_widget->update(); } void QRendererVideoWidgetBackend::frameChanged() { m_widget->update(m_boundingRect); } void QRendererVideoWidgetBackend::updateRects() { QRect rect = m_widget->rect(); if (m_nativeSize.isEmpty()) { m_boundingRect = QRect(); } else if (m_aspectRatioMode == Qt::IgnoreAspectRatio) { m_boundingRect = rect; m_sourceRect = QRectF(0, 0, 1, 1); } else if (m_aspectRatioMode == Qt::KeepAspectRatio) { QSize size = m_nativeSize; size.scale(rect.size(), Qt::KeepAspectRatio); m_boundingRect = QRect(0, 0, size.width(), size.height()); m_boundingRect.moveCenter(rect.center()); m_sourceRect = QRectF(0, 0, 1, 1); } else if (m_aspectRatioMode == Qt::KeepAspectRatioByExpanding) { m_boundingRect = rect; QSizeF size = rect.size(); size.scale(m_nativeSize, Qt::KeepAspectRatio); m_sourceRect = QRectF( 0, 0, size.width() / m_nativeSize.width(), size.height() / m_nativeSize.height()); m_sourceRect.moveCenter(QPointF(0.5, 0.5)); } } QWindowVideoWidgetBackend::QWindowVideoWidgetBackend( QMediaService *service, QVideoWindowControl *control, QWidget *widget) : m_service(service) , m_windowControl(control) , m_widget(widget) , m_aspectRatioMode(Qt::KeepAspectRatio) { connect(control, SIGNAL(brightnessChanged(int)), m_widget, SLOT(_q_brightnessChanged(int))); connect(control, SIGNAL(contrastChanged(int)), m_widget, SLOT(_q_contrastChanged(int))); connect(control, SIGNAL(hueChanged(int)), m_widget, SLOT(_q_hueChanged(int))); connect(control, SIGNAL(saturationChanged(int)), m_widget, SLOT(_q_saturationChanged(int))); connect(control, SIGNAL(fullScreenChanged(bool)), m_widget, SLOT(_q_fullScreenChanged(bool))); connect(control, SIGNAL(nativeSizeChanged()), m_widget, SLOT(_q_dimensionsChanged())); control->setWinId(widget->winId()); } QWindowVideoWidgetBackend::~QWindowVideoWidgetBackend() { } void QWindowVideoWidgetBackend::releaseControl() { m_service->releaseControl(m_windowControl); } void QWindowVideoWidgetBackend::setBrightness(int brightness) { m_windowControl->setBrightness(brightness); } void QWindowVideoWidgetBackend::setContrast(int contrast) { m_windowControl->setContrast(contrast); } void QWindowVideoWidgetBackend::setHue(int hue) { m_windowControl->setHue(hue); } void QWindowVideoWidgetBackend::setSaturation(int saturation) { m_windowControl->setSaturation(saturation); } void QWindowVideoWidgetBackend::setFullScreen(bool fullScreen) { m_windowControl->setFullScreen(fullScreen); } Qt::AspectRatioMode QWindowVideoWidgetBackend::aspectRatioMode() const { return m_windowControl->aspectRatioMode(); } void QWindowVideoWidgetBackend::setAspectRatioMode(Qt::AspectRatioMode mode) { m_windowControl->setAspectRatioMode(mode); } QSize QWindowVideoWidgetBackend::sizeHint() const { return m_windowControl->nativeSize(); } void QWindowVideoWidgetBackend::showEvent() { m_windowControl->setWinId(m_widget->winId()); m_windowControl->setDisplayRect(m_widget->rect()); #if defined(Q_WS_WIN) m_widget->setUpdatesEnabled(false); #endif } void QWindowVideoWidgetBackend::hideEvent(QHideEvent *) { #if defined(Q_WS_WIN) m_widget->setUpdatesEnabled(true); #endif } void QWindowVideoWidgetBackend::moveEvent(QMoveEvent *) { m_windowControl->setDisplayRect(m_widget->rect()); } void QWindowVideoWidgetBackend::resizeEvent(QResizeEvent *) { m_windowControl->setDisplayRect(m_widget->rect()); } void QWindowVideoWidgetBackend::paintEvent(QPaintEvent *event) { if (m_widget->testAttribute(Qt::WA_OpaquePaintEvent)) { QPainter painter(m_widget); painter.fillRect(event->rect(), m_widget->palette().window()); } m_windowControl->repaint(); event->accept(); } #if defined(Q_WS_WIN) bool QWindowVideoWidgetBackend::winEvent(MSG *message, long *) { if (message->message == WM_PAINT) m_windowControl->repaint(); return false; } #endif void QVideoWidgetPrivate::setCurrentControl(QVideoWidgetControlInterface *control) { if (currentControl != control) { currentControl = control; currentControl->setBrightness(brightness); currentControl->setContrast(contrast); currentControl->setHue(hue); currentControl->setSaturation(saturation); currentControl->setAspectRatioMode(aspectRatioMode); } } void QVideoWidgetPrivate::clearService() { if (service) { QObject::disconnect(service, SIGNAL(destroyed()), q_func(), SLOT(_q_serviceDestroyed())); if (widgetBackend) { QLayout *layout = q_func()->layout(); for (QLayoutItem *item = layout->takeAt(0); item; item = layout->takeAt(0)) { item->widget()->setParent(0); delete item; } delete layout; widgetBackend->releaseControl(); delete widgetBackend; widgetBackend = 0; } else if (rendererBackend) { rendererBackend->clearSurface(); rendererBackend->releaseControl(); delete rendererBackend; rendererBackend = 0; } else { windowBackend->releaseControl(); delete windowBackend; windowBackend = 0; } currentBackend = 0; currentControl = 0; service = 0; } } bool QVideoWidgetPrivate::createWidgetBackend() { if (QMediaControl *control = service->requestControl(QVideoWidgetControl_iid)) { if (QVideoWidgetControl *widgetControl = qobject_cast<QVideoWidgetControl *>(control)) { widgetBackend = new QVideoWidgetControlBackend(service, widgetControl, q_func()); setCurrentControl(widgetBackend); return true; } service->releaseControl(control); } return false; } bool QVideoWidgetPrivate::createWindowBackend() { if (QMediaControl *control = service->requestControl(QVideoWindowControl_iid)) { if (QVideoWindowControl *windowControl = qobject_cast<QVideoWindowControl *>(control)) { windowBackend = new QWindowVideoWidgetBackend(service, windowControl, q_func()); currentBackend = windowBackend; setCurrentControl(windowBackend); return true; } service->releaseControl(control); } return false; } bool QVideoWidgetPrivate::createRendererBackend() { if (QMediaControl *control = service->requestControl(QVideoRendererControl_iid)) { if (QVideoRendererControl *rendererControl = qobject_cast<QVideoRendererControl *>(control)) { rendererBackend = new QRendererVideoWidgetBackend(service, rendererControl, q_func()); currentBackend = rendererBackend; setCurrentControl(rendererBackend); return true; } service->releaseControl(control); } return false; } void QVideoWidgetPrivate::_q_serviceDestroyed() { if (widgetBackend) delete q_func()->layout(); delete widgetBackend; delete windowBackend; delete rendererBackend; widgetBackend = 0; windowBackend = 0; rendererBackend = 0; currentControl = 0; currentBackend = 0; service = 0; } void QVideoWidgetPrivate::_q_brightnessChanged(int b) { if (b != brightness) emit q_func()->brightnessChanged(brightness = b); } void QVideoWidgetPrivate::_q_contrastChanged(int c) { if (c != contrast) emit q_func()->contrastChanged(contrast = c); } void QVideoWidgetPrivate::_q_hueChanged(int h) { if (h != hue) emit q_func()->hueChanged(hue = h); } void QVideoWidgetPrivate::_q_saturationChanged(int s) { if (s != saturation) emit q_func()->saturationChanged(saturation = s); } void QVideoWidgetPrivate::_q_fullScreenChanged(bool fullScreen) { if (!fullScreen && q_func()->isFullScreen()) q_func()->showNormal(); } void QVideoWidgetPrivate::_q_dimensionsChanged() { q_func()->updateGeometry(); q_func()->update(); } /*! \class QVideoWidget \brief The QVideoWidget class provides a widget which presents video produced by a media object. \ingroup multimedia \inmodule QtMultimediaKit \since 1.0 \inmodule QtMultimediaKit Attaching a QVideoWidget to a QMediaObject allows it to display the video or image output of that media object. A QVideoWidget is attached to media object by passing a pointer to the QMediaObject in its constructor, and detached by destroying the QVideoWidget. \snippet doc/src/snippets/multimedia-snippets/video.cpp Video widget \bold {Note}: Only a single display output can be attached to a media object at one time. \sa QMediaObject, QMediaPlayer, QGraphicsVideoItem */ /*! Constructs a new video widget. The \a parent is passed to QWidget. */ QVideoWidget::QVideoWidget(QWidget *parent) : QWidget(parent, 0) , d_ptr(new QVideoWidgetPrivate) { d_ptr->q_ptr = this; } /*! \internal */ QVideoWidget::QVideoWidget(QVideoWidgetPrivate &dd, QWidget *parent) : QWidget(parent, 0) , d_ptr(&dd) { d_ptr->q_ptr = this; QPalette palette = QWidget::palette(); palette.setColor(QPalette::Background, Qt::black); setPalette(palette); } /*! Destroys a video widget. */ QVideoWidget::~QVideoWidget() { d_ptr->clearService(); delete d_ptr; } /*! \property QVideoWidget::mediaObject \brief the media object which provides the video displayed by a widget. */ QMediaObject *QVideoWidget::mediaObject() const { return d_func()->mediaObject; } /*! \internal */ bool QVideoWidget::setMediaObject(QMediaObject *object) { Q_D(QVideoWidget); if (object == d->mediaObject) return true; d->clearService(); d->mediaObject = object; if (d->mediaObject) d->service = d->mediaObject->service(); if (d->service) { if (d->createWidgetBackend()) { // Nothing to do here. } else if ((!window() || !window()->testAttribute(Qt::WA_DontShowOnScreen)) && d->createWindowBackend()) { if (isVisible()) d->windowBackend->showEvent(); } else if (d->createRendererBackend()) { if (isVisible()) d->rendererBackend->showEvent(); } else { d->service = 0; d->mediaObject = 0; return false; } connect(d->service, SIGNAL(destroyed()), SLOT(_q_serviceDestroyed())); } else { d->mediaObject = 0; return false; } return true; } /*! \property QVideoWidget::aspectRatioMode \brief how video is scaled with respect to its aspect ratio. */ Qt::AspectRatioMode QVideoWidget::aspectRatioMode() const { return d_func()->aspectRatioMode; } void QVideoWidget::setAspectRatioMode(Qt::AspectRatioMode mode) { Q_D(QVideoWidget); if (d->currentControl) { d->currentControl->setAspectRatioMode(mode); d->aspectRatioMode = d->currentControl->aspectRatioMode(); } else { d->aspectRatioMode = mode; } } /*! \property QVideoWidget::fullScreen \brief whether video display is confined to a window or is fullScreen. */ void QVideoWidget::setFullScreen(bool fullScreen) { Q_D(QVideoWidget); if (fullScreen) { Qt::WindowFlags flags = windowFlags(); d->nonFullScreenFlags = flags & (Qt::Window | Qt::SubWindow); flags |= Qt::Window; flags &= ~Qt::SubWindow; setWindowFlags(flags); showFullScreen(); } else { showNormal(); } } /*! \fn QVideoWidget::fullScreenChanged(bool fullScreen) Signals that the \a fullScreen mode of a video widget has changed. \sa fullScreen */ /*! \property QVideoWidget::brightness \brief an adjustment to the brightness of displayed video. Valid brightness values range between -100 and 100, the default is 0. */ int QVideoWidget::brightness() const { return d_func()->brightness; } void QVideoWidget::setBrightness(int brightness) { Q_D(QVideoWidget); int boundedBrightness = qBound(-100, brightness, 100); if (d->currentControl) d->currentControl->setBrightness(boundedBrightness); else if (d->brightness != boundedBrightness) emit brightnessChanged(d->brightness = boundedBrightness); } /*! \fn QVideoWidget::brightnessChanged(int brightness) Signals that a video widgets's \a brightness adjustment has changed. \sa brightness */ /*! \property QVideoWidget::contrast \brief an adjustment to the contrast of displayed video. Valid contrast values range between -100 and 100, the default is 0. */ int QVideoWidget::contrast() const { return d_func()->contrast; } void QVideoWidget::setContrast(int contrast) { Q_D(QVideoWidget); int boundedContrast = qBound(-100, contrast, 100); if (d->currentControl) d->currentControl->setContrast(boundedContrast); else if (d->contrast != boundedContrast) emit contrastChanged(d->contrast = boundedContrast); } /*! \fn QVideoWidget::contrastChanged(int contrast) Signals that a video widgets's \a contrast adjustment has changed. \sa contrast */ /*! \property QVideoWidget::hue \brief an adjustment to the hue of displayed video. Valid hue values range between -100 and 100, the default is 0. */ int QVideoWidget::hue() const { return d_func()->hue; } void QVideoWidget::setHue(int hue) { Q_D(QVideoWidget); int boundedHue = qBound(-100, hue, 100); if (d->currentControl) d->currentControl->setHue(boundedHue); else if (d->hue != boundedHue) emit hueChanged(d->hue = boundedHue); } /*! \fn QVideoWidget::hueChanged(int hue) Signals that a video widgets's \a hue has changed. \sa hue */ /*! \property QVideoWidget::saturation \brief an adjustment to the saturation of displayed video. Valid saturation values range between -100 and 100, the default is 0. */ int QVideoWidget::saturation() const { return d_func()->saturation; } void QVideoWidget::setSaturation(int saturation) { Q_D(QVideoWidget); int boundedSaturation = qBound(-100, saturation, 100); if (d->currentControl) d->currentControl->setSaturation(boundedSaturation); else if (d->saturation != boundedSaturation) emit saturationChanged(d->saturation = boundedSaturation); } /*! \fn QVideoWidget::saturationChanged(int saturation) Signals that a video widgets's \a saturation has changed. \sa saturation */ /*! Returns the size hint for the current back end, if there is one, or else the size hint from QWidget. */ QSize QVideoWidget::sizeHint() const { Q_D(const QVideoWidget); if (d->currentBackend) return d->currentBackend->sizeHint(); else return QWidget::sizeHint(); } /*! Current event \a event. Returns the value of the baseclass QWidget::event(QEvent *event) function. */ bool QVideoWidget::event(QEvent *event) { Q_D(QVideoWidget); if (event->type() == QEvent::WindowStateChange) { Qt::WindowFlags flags = windowFlags(); if (windowState() & Qt::WindowFullScreen) { if (d->currentControl) d->currentControl->setFullScreen(true); if (!d->wasFullScreen) emit fullScreenChanged(d->wasFullScreen = true); } else { if (d->currentControl) d->currentControl->setFullScreen(false); if (d->wasFullScreen) { flags &= ~(Qt::Window | Qt::SubWindow); //clear the flags... flags |= d->nonFullScreenFlags; //then we reset the flags (window and subwindow) setWindowFlags(flags); emit fullScreenChanged(d->wasFullScreen = false); } } } return QWidget::event(event); } /*! Handles the show \a event. */ void QVideoWidget::showEvent(QShowEvent *event) { Q_D(QVideoWidget); QWidget::showEvent(event); // The window backend won't work for re-directed windows so use the renderer backend instead. if (d->windowBackend && window()->testAttribute(Qt::WA_DontShowOnScreen)) { d->windowBackend->releaseControl(); delete d->windowBackend; d->windowBackend = 0; d->createRendererBackend(); } if (d->currentBackend) d->currentBackend->showEvent(); } /*! Handles the hide \a event. */ void QVideoWidget::hideEvent(QHideEvent *event) { Q_D(QVideoWidget); if (d->currentBackend) d->currentBackend->hideEvent(event); QWidget::hideEvent(event); } /*! Handles the resize \a event. */ void QVideoWidget::resizeEvent(QResizeEvent *event) { Q_D(QVideoWidget); QWidget::resizeEvent(event); if (d->currentBackend) d->currentBackend->resizeEvent(event); } /*! Handles the move \a event. */ void QVideoWidget::moveEvent(QMoveEvent *event) { Q_D(QVideoWidget); if (d->currentBackend) d->currentBackend->moveEvent(event); } /*! Handles the paint \a event. */ void QVideoWidget::paintEvent(QPaintEvent *event) { Q_D(QVideoWidget); if (d->currentBackend) { d->currentBackend->paintEvent(event); } else if (testAttribute(Qt::WA_OpaquePaintEvent)) { QPainter painter(this); painter.fillRect(event->rect(), palette().window()); } } #if defined(Q_WS_WIN) /*! \reimp \internal */ bool QVideoWidget::winEvent(MSG *message, long *result) { return d_func()->windowBackend && d_func()->windowBackend->winEvent(message, result) ? true : QWidget::winEvent(message, result); } #endif #include "moc_qvideowidget.cpp" #include "moc_qvideowidget_p.cpp" QT_END_NAMESPACE
Java
/* * Copyright (C) 2014 Red Hat, Inc. * * This library 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 licence, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, see <http://www.gnu.org/licenses/>. * * Author: Matthew Barnes <mbarnes@redhat.com> */ #ifndef __GDAV_SUPPORTED_CALENDAR_COMPONENT_SET_PROPERTY_H__ #define __GDAV_SUPPORTED_CALENDAR_COMPONENT_SET_PROPERTY_H__ #include <libgdav/gdav-property.h> /* Standard GObject macros */ #define GDAV_TYPE_SUPPORTED_CALENDAR_COMPONENT_SET_PROPERTY \ (gdav_supported_calendar_component_set_property_get_type ()) #define GDAV_SUPPORTED_CALENDAR_COMPONENT_SET_PROPERTY(obj) \ (G_TYPE_CHECK_INSTANCE_CAST \ ((obj), GDAV_TYPE_SUPPORTED_CALENDAR_COMPONENT_SET_PROPERTY, GDavSupportedCalendarComponentSetProperty)) #define GDAV_IS_SUPPORTED_CALENDAR_COMPONENT_SET_PROPERTY(obj) \ (G_TYPE_CHECK_INSTANCE_TYPE \ ((obj), GDAV_TYPE_SUPPORTED_CALENDAR_COMPONENT_SET_PROPERTY)) G_BEGIN_DECLS typedef struct _GDavSupportedCalendarComponentSetProperty GDavSupportedCalendarComponentSetProperty; typedef struct _GDavSupportedCalendarComponentSetPropertyClass GDavSupportedCalendarComponentSetPropertyClass; typedef struct _GDavSupportedCalendarComponentSetPropertyPrivate GDavSupportedCalendarComponentSetPropertyPrivate; struct _GDavSupportedCalendarComponentSetProperty { GDavProperty parent; GDavSupportedCalendarComponentSetPropertyPrivate *priv; }; struct _GDavSupportedCalendarComponentSetPropertyClass { GDavPropertyClass parent_class; }; GType gdav_supported_calendar_component_set_property_get_type (void) G_GNUC_CONST; G_END_DECLS #endif /* __GDAV_SUPPORTED_CALENDAR_COMPONENT_SET_PROPERTY_H__ */
Java
/* GStreamer * Copyright (C) <1999> Erik Walthinsen <omega@cse.ogi.edu> * Copyright (C) <2003> David Schleef <ds@schleef.org> * Copyright (C) <2010> Sebastian Dröge <sebastian.droege@collabora.co.uk> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ /* * This file was (probably) generated from gstvideobalance.c, * gstvideobalance.c,v 1.7 2003/11/08 02:48:59 dschleef Exp */ /** * SECTION:element-videobalance * * Adjusts brightness, contrast, hue, saturation on a video stream. * * <refsect2> * <title>Example launch line</title> * |[ * gst-launch videotestsrc ! videobalance saturation=0.0 ! ffmpegcolorspace ! ximagesink * ]| This pipeline converts the image to black and white by setting the * saturation to 0.0. * </refsect2> * * Last reviewed on 2010-04-18 (0.10.22) */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "gstvideobalance.h" #include <string.h> #include <math.h> #include <gst/controller/gstcontroller.h> #include <gst/interfaces/colorbalance.h> #ifndef M_PI #define M_PI 3.14159265358979323846 #endif #ifdef WIN32 #define rint(x) (floor((x)+0.5)) #endif GST_DEBUG_CATEGORY_STATIC (videobalance_debug); #define GST_CAT_DEFAULT videobalance_debug /* GstVideoBalance properties */ #define DEFAULT_PROP_CONTRAST 1.0 #define DEFAULT_PROP_BRIGHTNESS 0.0 #define DEFAULT_PROP_HUE 0.0 #define DEFAULT_PROP_SATURATION 1.0 enum { PROP_0, PROP_CONTRAST, PROP_BRIGHTNESS, PROP_HUE, PROP_SATURATION }; static GstStaticPadTemplate gst_video_balance_src_template = GST_STATIC_PAD_TEMPLATE ("src", GST_PAD_SRC, GST_PAD_ALWAYS, GST_STATIC_CAPS (GST_VIDEO_CAPS_YUV ("AYUV") ";" GST_VIDEO_CAPS_ARGB ";" GST_VIDEO_CAPS_BGRA ";" GST_VIDEO_CAPS_ABGR ";" GST_VIDEO_CAPS_RGBA ";" GST_VIDEO_CAPS_YUV ("Y444") ";" GST_VIDEO_CAPS_xRGB ";" GST_VIDEO_CAPS_RGBx ";" GST_VIDEO_CAPS_xBGR ";" GST_VIDEO_CAPS_BGRx ";" GST_VIDEO_CAPS_RGB ";" GST_VIDEO_CAPS_BGR ";" GST_VIDEO_CAPS_YUV ("Y42B") ";" GST_VIDEO_CAPS_YUV ("YUY2") ";" GST_VIDEO_CAPS_YUV ("UYVY") ";" GST_VIDEO_CAPS_YUV ("YVYU") ";" GST_VIDEO_CAPS_YUV ("I420") ";" GST_VIDEO_CAPS_YUV ("YV12") ";" GST_VIDEO_CAPS_YUV ("IYUV") ";" GST_VIDEO_CAPS_YUV ("Y41B") ) ); static GstStaticPadTemplate gst_video_balance_sink_template = GST_STATIC_PAD_TEMPLATE ("sink", GST_PAD_SINK, GST_PAD_ALWAYS, GST_STATIC_CAPS (GST_VIDEO_CAPS_YUV ("AYUV") ";" GST_VIDEO_CAPS_ARGB ";" GST_VIDEO_CAPS_BGRA ";" GST_VIDEO_CAPS_ABGR ";" GST_VIDEO_CAPS_RGBA ";" GST_VIDEO_CAPS_YUV ("Y444") ";" GST_VIDEO_CAPS_xRGB ";" GST_VIDEO_CAPS_RGBx ";" GST_VIDEO_CAPS_xBGR ";" GST_VIDEO_CAPS_BGRx ";" GST_VIDEO_CAPS_RGB ";" GST_VIDEO_CAPS_BGR ";" GST_VIDEO_CAPS_YUV ("Y42B") ";" GST_VIDEO_CAPS_YUV ("YUY2") ";" GST_VIDEO_CAPS_YUV ("UYVY") ";" GST_VIDEO_CAPS_YUV ("YVYU") ";" GST_VIDEO_CAPS_YUV ("I420") ";" GST_VIDEO_CAPS_YUV ("YV12") ";" GST_VIDEO_CAPS_YUV ("IYUV") ";" GST_VIDEO_CAPS_YUV ("Y41B") ) ); static void gst_video_balance_colorbalance_init (GstColorBalanceClass * iface); static void gst_video_balance_interface_init (GstImplementsInterfaceClass * klass); static void gst_video_balance_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec); static void gst_video_balance_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec); static void _do_init (GType video_balance_type) { static const GInterfaceInfo iface_info = { (GInterfaceInitFunc) gst_video_balance_interface_init, NULL, NULL, }; static const GInterfaceInfo colorbalance_info = { (GInterfaceInitFunc) gst_video_balance_colorbalance_init, NULL, NULL, }; g_type_add_interface_static (video_balance_type, GST_TYPE_IMPLEMENTS_INTERFACE, &iface_info); g_type_add_interface_static (video_balance_type, GST_TYPE_COLOR_BALANCE, &colorbalance_info); } GST_BOILERPLATE_FULL (GstVideoBalance, gst_video_balance, GstVideoFilter, GST_TYPE_VIDEO_FILTER, _do_init); /* * look-up tables (LUT). */ static void gst_video_balance_update_tables (GstVideoBalance * vb) { gint i, j; gdouble y, u, v, hue_cos, hue_sin; /* Y */ for (i = 0; i < 256; i++) { y = 16 + ((i - 16) * vb->contrast + vb->brightness * 255); if (y < 0) y = 0; else if (y > 255) y = 255; vb->tabley[i] = rint (y); } hue_cos = cos (M_PI * vb->hue); hue_sin = sin (M_PI * vb->hue); /* U/V lookup tables are 2D, since we need both U/V for each table * separately. */ for (i = -128; i < 128; i++) { for (j = -128; j < 128; j++) { u = 128 + ((i * hue_cos + j * hue_sin) * vb->saturation); v = 128 + ((-i * hue_sin + j * hue_cos) * vb->saturation); if (u < 0) u = 0; else if (u > 255) u = 255; if (v < 0) v = 0; else if (v > 255) v = 255; vb->tableu[i + 128][j + 128] = rint (u); vb->tablev[i + 128][j + 128] = rint (v); } } } static gboolean gst_video_balance_is_passthrough (GstVideoBalance * videobalance) { return videobalance->contrast == 1.0 && videobalance->brightness == 0.0 && videobalance->hue == 0.0 && videobalance->saturation == 1.0; } static void gst_video_balance_update_properties (GstVideoBalance * videobalance) { gboolean passthrough = gst_video_balance_is_passthrough (videobalance); GstBaseTransform *base = GST_BASE_TRANSFORM (videobalance); base->passthrough = passthrough; if (!passthrough) gst_video_balance_update_tables (videobalance); } static void gst_video_balance_planar_yuv (GstVideoBalance * videobalance, guint8 * data) { gint x, y; guint8 *ydata; guint8 *udata, *vdata; gint ystride, ustride, vstride; GstVideoFormat format; gint width, height; gint width2, height2; guint8 *tabley = videobalance->tabley; guint8 **tableu = videobalance->tableu; guint8 **tablev = videobalance->tablev; format = videobalance->format; width = videobalance->width; height = videobalance->height; ydata = data + gst_video_format_get_component_offset (format, 0, width, height); ystride = gst_video_format_get_row_stride (format, 0, width); for (y = 0; y < height; y++) { guint8 *yptr; yptr = ydata + y * ystride; for (x = 0; x < width; x++) { *ydata = tabley[*ydata]; ydata++; } } width2 = gst_video_format_get_component_width (format, 1, width); height2 = gst_video_format_get_component_height (format, 1, height); udata = data + gst_video_format_get_component_offset (format, 1, width, height); vdata = data + gst_video_format_get_component_offset (format, 2, width, height); ustride = gst_video_format_get_row_stride (format, 1, width); vstride = gst_video_format_get_row_stride (format, 1, width); for (y = 0; y < height2; y++) { guint8 *uptr, *vptr; guint8 u1, v1; uptr = udata + y * ustride; vptr = vdata + y * vstride; for (x = 0; x < width2; x++) { u1 = *uptr; v1 = *vptr; *uptr++ = tableu[u1][v1]; *vptr++ = tablev[u1][v1]; } } } static void gst_video_balance_packed_yuv (GstVideoBalance * videobalance, guint8 * data) { gint x, y; guint8 *ydata; guint8 *udata, *vdata; gint ystride, ustride, vstride; gint yoff, uoff, voff; GstVideoFormat format; gint width, height; gint width2, height2; guint8 *tabley = videobalance->tabley; guint8 **tableu = videobalance->tableu; guint8 **tablev = videobalance->tablev; format = videobalance->format; width = videobalance->width; height = videobalance->height; ydata = data + gst_video_format_get_component_offset (format, 0, width, height); ystride = gst_video_format_get_row_stride (format, 0, width); yoff = gst_video_format_get_pixel_stride (format, 0); for (y = 0; y < height; y++) { guint8 *yptr; yptr = ydata + y * ystride; for (x = 0; x < width; x++) { *ydata = tabley[*ydata]; ydata += yoff; } } width2 = gst_video_format_get_component_width (format, 1, width); height2 = gst_video_format_get_component_height (format, 1, height); udata = data + gst_video_format_get_component_offset (format, 1, width, height); vdata = data + gst_video_format_get_component_offset (format, 2, width, height); ustride = gst_video_format_get_row_stride (format, 1, width); vstride = gst_video_format_get_row_stride (format, 1, width); uoff = gst_video_format_get_pixel_stride (format, 1); voff = gst_video_format_get_pixel_stride (format, 2); for (y = 0; y < height2; y++) { guint8 *uptr, *vptr; guint8 u1, v1; uptr = udata + y * ustride; vptr = vdata + y * vstride; for (x = 0; x < width2; x++) { u1 = *uptr; v1 = *vptr; *uptr = tableu[u1][v1]; *vptr = tablev[u1][v1]; uptr += uoff; vptr += voff; } } } static const int cog_ycbcr_to_rgb_matrix_8bit_sdtv[] = { 298, 0, 409, -57068, 298, -100, -208, 34707, 298, 516, 0, -70870, }; static const gint cog_rgb_to_ycbcr_matrix_8bit_sdtv[] = { 66, 129, 25, 4096, -38, -74, 112, 32768, 112, -94, -18, 32768, }; #define APPLY_MATRIX(m,o,v1,v2,v3) ((m[o*4] * v1 + m[o*4+1] * v2 + m[o*4+2] * v3 + m[o*4+3]) >> 8) static void gst_video_balance_packed_rgb (GstVideoBalance * videobalance, guint8 * data) { gint i, j, height; gint width, row_stride, row_wrap; gint pixel_stride; gint offsets[3]; gint r, g, b; gint y, u, v; gint u_tmp, v_tmp; guint8 *tabley = videobalance->tabley; guint8 **tableu = videobalance->tableu; guint8 **tablev = videobalance->tablev; offsets[0] = gst_video_format_get_component_offset (videobalance->format, 0, videobalance->width, videobalance->height); offsets[1] = gst_video_format_get_component_offset (videobalance->format, 1, videobalance->width, videobalance->height); offsets[2] = gst_video_format_get_component_offset (videobalance->format, 2, videobalance->width, videobalance->height); width = gst_video_format_get_component_width (videobalance->format, 0, videobalance->width); height = gst_video_format_get_component_height (videobalance->format, 0, videobalance->height); row_stride = gst_video_format_get_row_stride (videobalance->format, 0, videobalance->width); pixel_stride = gst_video_format_get_pixel_stride (videobalance->format, 0); row_wrap = row_stride - pixel_stride * width; for (i = 0; i < height; i++) { for (j = 0; j < width; j++) { r = data[offsets[0]]; g = data[offsets[1]]; b = data[offsets[2]]; y = APPLY_MATRIX (cog_rgb_to_ycbcr_matrix_8bit_sdtv, 0, r, g, b); u_tmp = APPLY_MATRIX (cog_rgb_to_ycbcr_matrix_8bit_sdtv, 1, r, g, b); v_tmp = APPLY_MATRIX (cog_rgb_to_ycbcr_matrix_8bit_sdtv, 2, r, g, b); y = CLAMP (y, 0, 255); u_tmp = CLAMP (u_tmp, 0, 255); v_tmp = CLAMP (v_tmp, 0, 255); y = tabley[y]; u = tableu[u_tmp][v_tmp]; v = tablev[u_tmp][v_tmp]; r = APPLY_MATRIX (cog_ycbcr_to_rgb_matrix_8bit_sdtv, 0, y, u, v); g = APPLY_MATRIX (cog_ycbcr_to_rgb_matrix_8bit_sdtv, 1, y, u, v); b = APPLY_MATRIX (cog_ycbcr_to_rgb_matrix_8bit_sdtv, 2, y, u, v); data[offsets[0]] = CLAMP (r, 0, 255); data[offsets[1]] = CLAMP (g, 0, 255); data[offsets[2]] = CLAMP (b, 0, 255); data += pixel_stride; } data += row_wrap; } } /* get notified of caps and plug in the correct process function */ static gboolean gst_video_balance_set_caps (GstBaseTransform * base, GstCaps * incaps, GstCaps * outcaps) { GstVideoBalance *videobalance = GST_VIDEO_BALANCE (base); GST_DEBUG_OBJECT (videobalance, "in %" GST_PTR_FORMAT " out %" GST_PTR_FORMAT, incaps, outcaps); videobalance->process = NULL; if (!gst_video_format_parse_caps (incaps, &videobalance->format, &videobalance->width, &videobalance->height)) goto invalid_caps; videobalance->size = gst_video_format_get_size (videobalance->format, videobalance->width, videobalance->height); switch (videobalance->format) { case GST_VIDEO_FORMAT_I420: case GST_VIDEO_FORMAT_YV12: case GST_VIDEO_FORMAT_Y41B: case GST_VIDEO_FORMAT_Y42B: case GST_VIDEO_FORMAT_Y444: videobalance->process = gst_video_balance_planar_yuv; break; case GST_VIDEO_FORMAT_YUY2: case GST_VIDEO_FORMAT_UYVY: case GST_VIDEO_FORMAT_AYUV: case GST_VIDEO_FORMAT_YVYU: videobalance->process = gst_video_balance_packed_yuv; break; case GST_VIDEO_FORMAT_ARGB: case GST_VIDEO_FORMAT_ABGR: case GST_VIDEO_FORMAT_RGBA: case GST_VIDEO_FORMAT_BGRA: case GST_VIDEO_FORMAT_xRGB: case GST_VIDEO_FORMAT_xBGR: case GST_VIDEO_FORMAT_RGBx: case GST_VIDEO_FORMAT_BGRx: case GST_VIDEO_FORMAT_RGB: case GST_VIDEO_FORMAT_BGR: videobalance->process = gst_video_balance_packed_rgb; break; default: break; } return videobalance->process != NULL; invalid_caps: GST_ERROR_OBJECT (videobalance, "Invalid caps: %" GST_PTR_FORMAT, incaps); return FALSE; } static void gst_video_balance_before_transform (GstBaseTransform * base, GstBuffer * buf) { GstVideoBalance *balance = GST_VIDEO_BALANCE (base); GstClockTime timestamp, stream_time; timestamp = GST_BUFFER_TIMESTAMP (buf); stream_time = gst_segment_to_stream_time (&base->segment, GST_FORMAT_TIME, timestamp); GST_DEBUG_OBJECT (balance, "sync to %" GST_TIME_FORMAT, GST_TIME_ARGS (timestamp)); if (GST_CLOCK_TIME_IS_VALID (stream_time)) gst_object_sync_values (G_OBJECT (balance), stream_time); } static GstFlowReturn gst_video_balance_transform_ip (GstBaseTransform * base, GstBuffer * outbuf) { GstVideoBalance *videobalance = GST_VIDEO_BALANCE (base); guint8 *data; guint size; if (!videobalance->process) goto not_negotiated; /* if no change is needed, we are done */ if (base->passthrough) goto done; data = GST_BUFFER_DATA (outbuf); size = GST_BUFFER_SIZE (outbuf); if (size != videobalance->size) goto wrong_size; GST_OBJECT_LOCK (videobalance); videobalance->process (videobalance, data); GST_OBJECT_UNLOCK (videobalance); done: return GST_FLOW_OK; /* ERRORS */ wrong_size: { GST_ELEMENT_ERROR (videobalance, STREAM, FORMAT, (NULL), ("Invalid buffer size %d, expected %d", size, videobalance->size)); return GST_FLOW_ERROR; } not_negotiated: GST_ERROR_OBJECT (videobalance, "Not negotiated yet"); return GST_FLOW_NOT_NEGOTIATED; } static void gst_video_balance_base_init (gpointer g_class) { GstElementClass *element_class = GST_ELEMENT_CLASS (g_class); gst_element_class_set_details_simple (element_class, "Video balance", "Filter/Effect/Video", "Adjusts brightness, contrast, hue, saturation on a video stream", "David Schleef <ds@schleef.org>"); gst_element_class_add_pad_template (element_class, gst_static_pad_template_get (&gst_video_balance_sink_template)); gst_element_class_add_pad_template (element_class, gst_static_pad_template_get (&gst_video_balance_src_template)); } static void gst_video_balance_finalize (GObject * object) { GList *channels = NULL; GstVideoBalance *balance = GST_VIDEO_BALANCE (object); g_free (balance->tableu[0]); channels = balance->channels; while (channels) { GstColorBalanceChannel *channel = channels->data; g_object_unref (channel); channels->data = NULL; channels = g_list_next (channels); } if (balance->channels) g_list_free (balance->channels); G_OBJECT_CLASS (parent_class)->finalize (object); } static void gst_video_balance_class_init (GstVideoBalanceClass * klass) { GObjectClass *gobject_class = (GObjectClass *) klass; GstBaseTransformClass *trans_class = (GstBaseTransformClass *) klass; GST_DEBUG_CATEGORY_INIT (videobalance_debug, "videobalance", 0, "videobalance"); gobject_class->finalize = gst_video_balance_finalize; gobject_class->set_property = gst_video_balance_set_property; gobject_class->get_property = gst_video_balance_get_property; g_object_class_install_property (gobject_class, PROP_CONTRAST, g_param_spec_double ("contrast", "Contrast", "contrast", 0.0, 2.0, DEFAULT_PROP_CONTRAST, GST_PARAM_CONTROLLABLE | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_BRIGHTNESS, g_param_spec_double ("brightness", "Brightness", "brightness", -1.0, 1.0, DEFAULT_PROP_BRIGHTNESS, GST_PARAM_CONTROLLABLE | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_HUE, g_param_spec_double ("hue", "Hue", "hue", -1.0, 1.0, DEFAULT_PROP_HUE, GST_PARAM_CONTROLLABLE | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_SATURATION, g_param_spec_double ("saturation", "Saturation", "saturation", 0.0, 2.0, DEFAULT_PROP_SATURATION, GST_PARAM_CONTROLLABLE | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); trans_class->set_caps = GST_DEBUG_FUNCPTR (gst_video_balance_set_caps); trans_class->transform_ip = GST_DEBUG_FUNCPTR (gst_video_balance_transform_ip); trans_class->before_transform = GST_DEBUG_FUNCPTR (gst_video_balance_before_transform); } static void gst_video_balance_init (GstVideoBalance * videobalance, GstVideoBalanceClass * klass) { const gchar *channels[4] = { "HUE", "SATURATION", "BRIGHTNESS", "CONTRAST" }; gint i; /* Initialize propertiews */ videobalance->contrast = DEFAULT_PROP_CONTRAST; videobalance->brightness = DEFAULT_PROP_BRIGHTNESS; videobalance->hue = DEFAULT_PROP_HUE; videobalance->saturation = DEFAULT_PROP_SATURATION; videobalance->tableu[0] = g_new (guint8, 256 * 256 * 2); for (i = 0; i < 256; i++) { videobalance->tableu[i] = videobalance->tableu[0] + i * 256 * sizeof (guint8); videobalance->tablev[i] = videobalance->tableu[0] + 256 * 256 * sizeof (guint8) + i * 256 * sizeof (guint8); } gst_video_balance_update_properties (videobalance); /* Generate the channels list */ for (i = 0; i < G_N_ELEMENTS (channels); i++) { GstColorBalanceChannel *channel; channel = g_object_new (GST_TYPE_COLOR_BALANCE_CHANNEL, NULL); channel->label = g_strdup (channels[i]); channel->min_value = -1000; channel->max_value = 1000; videobalance->channels = g_list_append (videobalance->channels, channel); } } static gboolean gst_video_balance_interface_supported (GstImplementsInterface * iface, GType type) { g_assert (type == GST_TYPE_COLOR_BALANCE); return TRUE; } static void gst_video_balance_interface_init (GstImplementsInterfaceClass * klass) { klass->supported = gst_video_balance_interface_supported; } static const GList * gst_video_balance_colorbalance_list_channels (GstColorBalance * balance) { GstVideoBalance *videobalance = GST_VIDEO_BALANCE (balance); g_return_val_if_fail (videobalance != NULL, NULL); g_return_val_if_fail (GST_IS_VIDEO_BALANCE (videobalance), NULL); return videobalance->channels; } static void gst_video_balance_colorbalance_set_value (GstColorBalance * balance, GstColorBalanceChannel * channel, gint value) { GstVideoBalance *vb = GST_VIDEO_BALANCE (balance); gdouble new_val; gboolean changed; g_return_if_fail (vb != NULL); g_return_if_fail (GST_IS_VIDEO_BALANCE (vb)); g_return_if_fail (GST_IS_VIDEO_FILTER (vb)); g_return_if_fail (channel->label != NULL); GST_BASE_TRANSFORM_LOCK (vb); GST_OBJECT_LOCK (vb); if (!g_ascii_strcasecmp (channel->label, "HUE")) { new_val = (value + 1000.0) * 2.0 / 2000.0 - 1.0; changed = new_val != vb->hue; vb->hue = new_val; } else if (!g_ascii_strcasecmp (channel->label, "SATURATION")) { new_val = (value + 1000.0) * 2.0 / 2000.0; changed = new_val != vb->saturation; vb->saturation = new_val; } else if (!g_ascii_strcasecmp (channel->label, "BRIGHTNESS")) { new_val = (value + 1000.0) * 2.0 / 2000.0 - 1.0; changed = new_val != vb->brightness; vb->brightness = new_val; } else if (!g_ascii_strcasecmp (channel->label, "CONTRAST")) { new_val = (value + 1000.0) * 2.0 / 2000.0; changed = new_val != vb->contrast; vb->contrast = new_val; } gst_video_balance_update_properties (vb); GST_OBJECT_UNLOCK (vb); GST_BASE_TRANSFORM_UNLOCK (vb); gst_color_balance_value_changed (balance, channel, gst_color_balance_get_value (balance, channel)); } static gint gst_video_balance_colorbalance_get_value (GstColorBalance * balance, GstColorBalanceChannel * channel) { GstVideoBalance *vb = GST_VIDEO_BALANCE (balance); gint value = 0; g_return_val_if_fail (vb != NULL, 0); g_return_val_if_fail (GST_IS_VIDEO_BALANCE (vb), 0); g_return_val_if_fail (channel->label != NULL, 0); if (!g_ascii_strcasecmp (channel->label, "HUE")) { value = (vb->hue + 1) * 2000.0 / 2.0 - 1000.0; } else if (!g_ascii_strcasecmp (channel->label, "SATURATION")) { value = vb->saturation * 2000.0 / 2.0 - 1000.0; } else if (!g_ascii_strcasecmp (channel->label, "BRIGHTNESS")) { value = (vb->brightness + 1) * 2000.0 / 2.0 - 1000.0; } else if (!g_ascii_strcasecmp (channel->label, "CONTRAST")) { value = vb->contrast * 2000.0 / 2.0 - 1000.0; } return value; } static void gst_video_balance_colorbalance_init (GstColorBalanceClass * iface) { GST_COLOR_BALANCE_TYPE (iface) = GST_COLOR_BALANCE_SOFTWARE; iface->list_channels = gst_video_balance_colorbalance_list_channels; iface->set_value = gst_video_balance_colorbalance_set_value; iface->get_value = gst_video_balance_colorbalance_get_value; } static GstColorBalanceChannel * gst_video_balance_find_channel (GstVideoBalance * balance, const gchar * label) { GList *l; for (l = balance->channels; l; l = l->next) { GstColorBalanceChannel *channel = l->data; if (g_ascii_strcasecmp (channel->label, label) == 0) return channel; } return NULL; } static void gst_video_balance_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec) { GstVideoBalance *balance = GST_VIDEO_BALANCE (object); gdouble d; const gchar *label = NULL; GST_BASE_TRANSFORM_LOCK (balance); GST_OBJECT_LOCK (balance); switch (prop_id) { case PROP_CONTRAST: d = g_value_get_double (value); GST_DEBUG_OBJECT (balance, "Changing contrast from %lf to %lf", balance->contrast, d); if (d != balance->contrast) label = "CONTRAST"; balance->contrast = d; break; case PROP_BRIGHTNESS: d = g_value_get_double (value); GST_DEBUG_OBJECT (balance, "Changing brightness from %lf to %lf", balance->brightness, d); if (d != balance->brightness) label = "BRIGHTNESS"; balance->brightness = d; break; case PROP_HUE: d = g_value_get_double (value); GST_DEBUG_OBJECT (balance, "Changing hue from %lf to %lf", balance->hue, d); if (d != balance->hue) label = "HUE"; balance->hue = d; break; case PROP_SATURATION: d = g_value_get_double (value); GST_DEBUG_OBJECT (balance, "Changing saturation from %lf to %lf", balance->saturation, d); if (d != balance->saturation) label = "SATURATION"; balance->saturation = d; break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } gst_video_balance_update_properties (balance); GST_OBJECT_UNLOCK (balance); GST_BASE_TRANSFORM_UNLOCK (balance); if (label) { GstColorBalanceChannel *channel = gst_video_balance_find_channel (balance, label); gst_color_balance_value_changed (GST_COLOR_BALANCE (balance), channel, gst_color_balance_get_value (GST_COLOR_BALANCE (balance), channel)); } } static void gst_video_balance_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec) { GstVideoBalance *balance = GST_VIDEO_BALANCE (object); switch (prop_id) { case PROP_CONTRAST: g_value_set_double (value, balance->contrast); break; case PROP_BRIGHTNESS: g_value_set_double (value, balance->brightness); break; case PROP_HUE: g_value_set_double (value, balance->hue); break; case PROP_SATURATION: g_value_set_double (value, balance->saturation); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } }
Java
#include "rendertarget.h" #include <system/engine.h> #include <renderer/renderer.h> #include <renderer/forms.h> using namespace CGE; RenderTarget* RenderTarget::mCurrTarget = NULL; void RenderTarget::drawFullscreen(bool transform){ Renderer* rend = Engine::instance()->getRenderer(); if (transform){ rend->ortho(1, 1); rend->resetModelView(); } rend->enableDepthTest(false); CGE::Forms& forms = *CGE::Engine::instance()->getForms(); forms.activateQuad(); rend->enableTexturing(true); rend->setColor(1, 1, 1, 1); if (transform){ if (rend->getRenderType() != DirectX){ rend->switchMatrixStack(CGE::MatTexture); rend->resetModelView(); rend->scale(1, -1, 1); } } for (unsigned i = 0; i < getNumTextures(); ++i){ getTexture(i)->activate(i); } forms.drawQuad(Vec2f(), Vec2f(1, 1)); if (transform){ if (rend->getRenderType() != DirectX){ rend->resetModelView(); rend->switchMatrixStack(CGE::Modelview); } } }
Java
/* Static5 is engaged with type BIGINT and ggd(vec) */ #include "lie.h" #ifdef __STDC__ static entry gcd(entry x,entry y); static entry abs_minimum(vector* v_vec); static boolean equal_elements(vector* v_vec); #endif static bigint* bin_from_int(i) intcel* i; { entry k = i->intval; freemem(i); return entry2bigint(k); } static intcel* int_from_bin(b) bigint* b; { entry k = bigint2entry(b); freemem(b); return mkintcel(k); } static object vid_factor_bin(b) object b; { return (object) Factor((bigint *) b); } /* Transform a vector into a matrix with the same components as the vector, when read by rows */ static object mat_matvec_vec_int(object v,object nrows_object) { index size=v->v.ncomp, nrows, ncols=nrows_object->i.intval; if (ncols<=0) error("Number of columns should be positive.\n"); if (size%ncols!=0) error ("Number of columns should divide size of vector.\n"); { matrix* m=mkmatrix(nrows=size/ncols,ncols); index i,j,k=0; for (i=0; i<nrows; ++i) for (j=0; j<ncols; ++j) m->elm[i][j]=v->v.compon[k++]; /* |k==ncols*i+j| before increment */ return (object) m; } } static entry gcd(x,y) entry x,y; { /* Requirement 0<x <= y */ entry r = x; if (y==0) return 0; while (r) { x = y % r; y = r; r = x; /* x <= y */ } return y; } static entry abs_minimum(vector* v_vec) /* return minimal absoulte value of nonzero array elements, or 0 when all elements are 0. */ { index i; boolean is_zero=true; index n = v_vec->ncomp; entry* v = v_vec->compon; index minimum=0; for (i=0; i<n; ++i) if (v[i]!=0) if (is_zero) { is_zero=false; minimum=labs(v[i]); } else { entry c = labs(v[i]); if (c<minimum) minimum = c; } return minimum; } static boolean equal_elements(v_vec) vector* v_vec; /* Do all nonzero elements have the same absolute value? */ { index i, first = 0; index n = v_vec->ncomp; entry* v = v_vec->compon; /* Omit prefixed 0 */ while (first < n && v[first]==0) first++; if (first == n) return true; /* All zero */ i = first + 1; while (i < n && (v[i]== 0 || labs(v[first]) == labs(v[i]))) i++; if (i == n) return true; return false; } object int_gcd_vec(v_vec) vector *v_vec; { entry r = abs_minimum(v_vec); entry *v; index i; index n = v_vec->ncomp; if (isshared(v_vec)) v_vec = copyvector(v_vec); v = v_vec->compon; while (!equal_elements(v_vec)) { for (i=0;i<n;i++) v[i] = gcd(r, v[i]); r = abs_minimum(v_vec); } return (object) mkintcel(r); } Symbrec static5[] = { C1("$bigint", (fobject)bin_from_int, BIGINT, INTEGER) C1("$intbig", (fobject)int_from_bin, INTEGER, BIGINT) C1("factor", vid_factor_bin, VOID, BIGINT) C2("mat_vec", mat_matvec_vec_int,MATRIX,VECTOR,INTEGER) C1("gcd",int_gcd_vec, INTEGER, VECTOR) }; int nstatic5 = array_size(static5); #ifdef __STDC__ # define P(s) s #else # define P(s) () #endif bigint* (*int2bin) P((intcel*)) = bin_from_int; intcel* (*bin2int) P((bigint*)) = int_from_bin;
Java
/*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998-2007 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * *************** <auto-copyright.pl END do not edit this line> ***************/ #ifndef _VRJ_DRAW_MANAGER_H_ #define _VRJ_DRAW_MANAGER_H_ #include <vrj/vrjConfig.h> #include <iostream> #include <jccl/RTRC/ConfigElementHandler.h> #include <vrj/Display/DisplayPtr.h> namespace vrj { class DisplayManager; class App; /** \class DrawManager DrawManager.h vrj/Draw/DrawManager.h * * Abstract base class for API-specific Draw Manager. * * Concrete classes are resonsible for all rendering. * * @date 9-7-97 */ class VJ_CLASS_API DrawManager : public jccl::ConfigElementHandler { public: DrawManager() : mDisplayManager(NULL) { /* Do nothing. */ ; } virtual ~DrawManager() { /* Do nothing. */ ; } /** * Function to initialy config API-specific stuff. * Takes a jccl::Configuration and extracts API-specific stuff. */ //**//virtual void configInitial(jccl::Configuration* cfg) = 0; /// Enable a frame to be drawn virtual void draw() = 0; /** * Blocks until the end of the frame. * @post The frame has been drawn. */ virtual void sync() = 0; /** * Sets the application with which the Draw Manager will interact. * * @note The member variable is not in the base class because its "real" * type is only known in the derived classes. */ virtual void setApp(App* app) = 0; /** * Initializes the drawing API (if not already running). * * @note If the draw manager should be an active object, start the process * here. */ virtual void initAPI() = 0; /** Callback when display is added to Display Manager. */ virtual void addDisplay(DisplayPtr disp) = 0; /** Callback when display is removed to Display Manager. */ virtual void removeDisplay(DisplayPtr disp) = 0; /** * Shuts down the drawing API. * * @note If it was an active object, kill process here. */ virtual void closeAPI() = 0; /** Setter for Display Manager variable. */ void setDisplayManager(DisplayManager* dispMgr); DisplayManager* getDisplayManager(); friend VJ_API(std::ostream&) operator<<(std::ostream& out, DrawManager& drawMgr); virtual void outStream(std::ostream& out) { out << "vrj::DrawManager: outstream\n"; // Set a default } protected: DisplayManager* mDisplayManager; /**< The display manager dealing with */ }; } // End of vrj namespace #endif
Java
--TEST-- Test node order of EncryptedData children. --DESCRIPTION-- Makes sure that the child elements of EncryptedData appear in the correct order. --FILE-- <?php require($_SERVER['DOCUMENT_ROOT'] . '/../xmlseclibs.php'); $dom = new DOMDocument(); $dom->load($_SERVER['DOCUMENT_ROOT'] . '/basic-doc.xml'); $objKey = new XMLSecurityKey(XMLSecurityKey::AES256_CBC); $objKey->generateSessionKey(); $siteKey = new XMLSecurityKey(XMLSecurityKey::RSA_OAEP_MGF1P, array('type'=>'public')); $siteKey->loadKey($_SERVER['DOCUMENT_ROOT'] . '/mycert.pem', TRUE, TRUE); $enc = new XMLSecEnc(); $enc->setNode($dom->documentElement); $enc->encryptKey($siteKey, $objKey); $enc->type = XMLSecEnc::Content; $encNode = $enc->encryptNode($objKey); $nodeOrder = array( 'EncryptionMethod', 'KeyInfo', 'CipherData', 'EncryptionProperties', ); $prevNode = 0; for ($node = $encNode->firstChild; $node !== NULL; $node = $node->nextSibling) { if (! ($node instanceof DOMElement)) { /* Skip comment and text nodes. */ continue; } $name = $node->localName; $cIndex = array_search($name, $nodeOrder, TRUE); if ($cIndex === FALSE) { die("Unknown node: $name"); } if ($cIndex >= $prevNode) { /* In correct order. */ $prevNode = $cIndex; continue; } $prevName = $nodeOrder[$prevNode]; die("Incorrect order: $name must appear before $prevName"); } echo("OK\n"); ?> --EXPECTF-- OK
Java
/* * CrocoPat is a tool for relational programming. * This file is part of CrocoPat. * * Copyright (C) 2002-2008 Dirk Beyer * * CrocoPat 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. * * CrocoPat 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 CrocoPat; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Please find the GNU Lesser General Public License in file * License_LGPL.txt or at http://www.gnu.org/licenses/lgpl.txt * * Author: * Dirk Beyer (firstname.lastname@sfu.ca) * Simon Fraser University * * With contributions of: Andreas Noack, Michael Vogel */ #ifndef _relStrExpr_h #define _relStrExpr_h #include "relString.h" #include "relNumExpr.h" #include <string> #include <sstream> /// Global variables for interpreter. extern map<string, relDataType*> gVariables; /// Cmd line arg handling for the interpreter. extern char** gArgv; extern int gArgc; /// Global function. extern string double2string(double pNum); ////////////////////////////////////////////////////////////////////////////// class relStrExpr : public relObject { public: virtual relString interpret(bddSymTab* pSymTab) = 0; }; ////////////////////////////////////////////////////////////////////////////// class relStrExprVar : public relStrExpr { private: string* mVar; public: relStrExprVar(string* pVar) : mVar(pVar) {} ~relStrExprVar() { delete mVar; } virtual relString interpret(bddSymTab* pSymTab) { // Fetch result. map<string, relDataType*>::const_iterator lVarIt = gVariables.find(*mVar); assert(lVarIt != gVariables.end()); // Must be declared. assert(lVarIt->second != NULL); relString* lResult = dynamic_cast<relString*>(lVarIt->second); assert(lResult != NULL); // Must be a STRING variable. return *lResult; } }; ////////////////////////////////////////////////////////////////////////////// class relStrExprConst : public relStrExpr { private: string* mVal; public: relStrExprConst(string* pVal) : mVal(pVal) {} ~relStrExprConst() { delete mVal; } virtual relString interpret(bddSymTab* pSymTab) { return relString(*mVal); } }; ////////////////////////////////////////////////////////////////////////////// class relStrExprBinOp : public relStrExpr { public: typedef enum {CONCAT} relStrOP; private: relStrExpr* mExpr1; relStrOP mOp; relStrExpr* mExpr2; public: relStrExprBinOp( relStrExpr* pExpr1, relStrOP pOp, relStrExpr* pExpr2) : mExpr1(pExpr1), mOp(pOp), mExpr2(pExpr2) {} ~relStrExprBinOp() { delete mExpr1; delete mExpr2; } virtual relString interpret(bddSymTab* pSymTab) { relString lExpr1 = mExpr1->interpret(pSymTab); relString lExpr2 = mExpr2->interpret(pSymTab); relString result(""); if (mOp == CONCAT) result.setValue(lExpr1.getValue() + lExpr2.getValue()); else { cerr << "Internal error: Unknown operator in relStrExprBinOp::interpret." << endl; abort(); } return result; } }; ////////////////////////////////////////////////////////////////////////////// class relStrExprElem : public relStrExpr { private: relExpression* mExpr; public: relStrExprElem(relExpression* pExpr) : mExpr(pExpr) {} ~relStrExprElem(); virtual relString interpret(bddSymTab* pSymTab); }; ////////////////////////////////////////////////////////////////////////////// class relStrExprNum : public relStrExpr { private: relNumExpr* mExpr; public: relStrExprNum(relNumExpr* pExpr) : mExpr(pExpr) {} ~relStrExprNum() { delete mExpr; } virtual relString interpret(bddSymTab* pSymTab) { return relString(double2string(mExpr->interpret(pSymTab).getValue())); } }; ////////////////////////////////////////////////////////////////////////////// class relStrCmdArg : public relStrExpr { private: relNumExpr* mExpr; public: relStrCmdArg(relNumExpr* pExpr) : mExpr(pExpr) {} ~relStrCmdArg() { delete mExpr; } virtual relString interpret(bddSymTab* pSymTab) { int lPos = (int) mExpr->interpret(pSymTab).getValue(); if (lPos >= 0 && lPos < gArgc) { return relString(string(gArgv[lPos])); } else { cerr << "Error: Missing command line argument '$" << lPos << "'." << endl; exit(EXIT_FAILURE); } } }; #endif
Java
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>tinymce.util.Dispatcher tests</title> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-git.css" type="text/css" /> <script src="http://code.jquery.com/qunit/qunit-git.js"></script> <script src="qunit/connector.js"></script> <script type="text/javascript" src="qunit/runner.js"></script> <script type="text/javascript" src="js/utils.js"></script> <script type="text/javascript" src="js/tiny_mce_loader.js"></script> <script> module("tinymce.util.Dispatcher"); (function() { var Dispatcher = tinymce.util.Dispatcher; test('dispatcher', 5, function() { var ev, v, f; ev = new Dispatcher(); ev.add(function(a, b, c) { v = a + b + c; }); ev.dispatch(1, 2, 3); equal(v, 6); ev = new Dispatcher(); v = 0; f = ev.add(function(a, b, c) { v = a + b + c; }); ev.remove(f); ev.dispatch(1, 2, 3); equal(v, 0); ev = new Dispatcher({test : 1}); v = 0; f = ev.add(function(a, b, c) { v = a + b + c + this.test; }); ev.dispatch(1, 2, 3); equal(v, 7); ev = new Dispatcher(); v = 0; f = ev.add(function(a, b, c) { v = a + b + c + this.test; }, {test : 1}); ev.dispatch(1, 2, 3); equal(v, 7); ev = new Dispatcher(); v = ''; f = ev.add(function(a, b, c) { v += 'b'; }, {test : 1}); f = ev.addToTop(function(a, b, c) { v += 'a'; }, {test : 1}); ev.dispatch(); equal(v, 'ab'); }); })(); </script> </head> <body> <h1 id="qunit-header">tinymce.util.Dispatcher tests</h1> <h2 id="qunit-banner"></h2> <div id="qunit-testrunner-toolbar"></div> <h2 id="qunit-userAgent"></h2> <ol id="qunit-tests"></ol> <div id="content"></div> </body> </html>
Java
//////////////////////////////////////////////////////////////// // // Copyright (C) 2007 The Broad Institute and Affymetrix, Inc. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License (version 2) as // published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program;if not, write to the // // Free Software Foundation, Inc., // 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // //////////////////////////////////////////////////////////////// // #include "birdseed-dev/IntensitiesParser.h" // #include "broadutil/BroadException.h" #include "broadutil/BroadUtil.h" #include "broadutil/FileUtil.h" // #include <cerrno> #include <cstdio> using namespace std; using namespace birdseed::dev; IntensitiesParser::~IntensitiesParser() { if (fp != NULL) { fclose(fp); } } IntensitiesParser::IntensitiesParser(const std::string& path, bool calculateCorrectionFactor): dataPath(path), fp(fopen(path.c_str(), "r")), correctionFactor(0.0), header(), snpName(), intensities() { if (fp == NULL) { throw BroadException("Could not open file", __FILE__, __LINE__, path.c_str(), errno); } header = readHeader(fp, "probeset_id\t"); if (calculateCorrectionFactor) { long dataStartOffset = ftell(fp); if (dataStartOffset == -1) { throw BroadException("ftell error", __FILE__, __LINE__, path.c_str(), errno); } double total = 0.0; size_t numIntensities = 0; while (true) { // Skip over SNP name snpName = readWord(fp); if (snpName.empty()) { break; } double val; while (readDouble(fp, &val)) { total += val; ++numIntensities; } } correctionFactor = total/numIntensities; if (fseek(fp, dataStartOffset, SEEK_SET) == -1) { throw BroadException("fseek error", __FILE__, __LINE__, path.c_str(), errno); } } } bool IntensitiesParser::advanceSNP() { // Skip over first SNP name string snpNameA = readWord(fp); if (snpNameA.empty()) { snpName = ""; intensities.reset(NULL); return false; } if (!endswith(snpNameA.c_str(), "-A")) { std::stringstream strm; strm << "Did not find -A suffix for SNP name: " << snpNameA << "."; throw BroadException(strm.str().c_str(), __FILE__, __LINE__, dataPath.c_str()); } snpName = snpNameA.substr(0, snpNameA.size() - 2); vector<double> aValues; double val; while (readDouble(fp, &val)) { aValues.push_back(val); } // Skip over next SNP name string snpNameB = readWord(fp); if (!endswith(snpNameB.c_str(), "-B")) { std::stringstream strm; strm << "Did not find -B suffix for SNP name: " << snpNameB << "."; throw BroadException(strm.str().c_str(), __FILE__, __LINE__, dataPath.c_str()); } if (snpName != snpNameB.substr(0, snpNameB.size() - 2)) { std::stringstream strm; strm << "B intensities do not have same SNP name as A. SNP-A: " << snpNameA << "; SNP-B: " << snpNameB << " ."; throw BroadException(strm.str().c_str(), __FILE__, __LINE__, dataPath.c_str()); } intensities.reset(new IntensityMatrix(aValues.size())); // Syntactic sugar IntensityMatrix &intensitiesRef = *(intensities.get()); for (size_t i = 0; i < aValues.size(); ++i) { intensitiesRef[i][0] = aValues[i]; if (!readDouble(fp, &val)) { throw BroadException("Number of B values is less than number of A values", __FILE__, __LINE__, dataPath.c_str()); } intensitiesRef[i][1] = val; } return true; } /******************************************************************/ /**************************[END OF IntensitiesParser.cpp]*************************/ /******************************************************************/ /* Emacs configuration * Local Variables: * mode: C++ * tab-width:4 * End: */
Java
class TmsFakeIn < ActiveRecord::Base set_table_name "tms_fake_in" end # == Schema Information # # Table name: tms_fake_in # # id :integer(10) not null, primary key # message :text not null # created_at :datetime # priority :integer(10) default(0), not null #
Java
/* $Id: model_in.h,v 1.27 2004/10/25 11:37:40 aspert Exp $ */ /* * * Copyright (C) 2001-2004 EPFL (Swiss Federal Institute of Technology, * Lausanne) This program is free software; you can redistribute it * and/or modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA. * * In addition, as a special exception, EPFL gives permission to link * the code of this program with the Qt non-commercial edition library * (or with modified versions of Qt non-commercial edition that use the * same license as Qt non-commercial edition), and distribute linked * combinations including the two. You must obey the GNU General * Public License in all respects for all of the code used other than * Qt non-commercial edition. If you modify this file, you may extend * this exception to your version of the file, but you are not * obligated to do so. If you do not wish to do so, delete this * exception statement from your version. * * Authors : Nicolas Aspert, Diego Santa-Cruz and Davy Jacquet * * Web site : http://mesh.epfl.ch * * Reference : * "MESH : Measuring Errors between Surfaces using the Hausdorff distance" * in Proceedings of IEEE Intl. Conf. on Multimedia and Expo (ICME) 2002, * vol. I, pp. 705-708, available on http://mesh.epfl.ch * */ /* * Functions to read 3D model data from files * * Author: Diego Santa Cruz * * N. Aspert is guilty for all the cruft to read gzipped files + Inventor + * SMF and PLY parsers. * * Currently supported file formats: * * - Raw ascii: * Reads vertices, faces, vertex normals and face normals. * * - VRML 2 (aka VRML97): * Only the IndexedFaceSet nodes are read. All transformations are * ignored. DEF/USE and PROTO tags are not parsed. Vertices, faces, * vertex normals and face normals are read. Due to lack of support in * 'struct model' for indexed vertex normals, they are converted to * non-indexed ones by taking the last appearing normal for each vertex * (i.e. if multiple normals exist for a vertex only the last one is * considered). Likewise for indexed face normals. * * - Inventor 2: * Only the Coordinate3-point and IndexedFaceSet-coordIndex fields * are read. Normals and everything else is (hopefully) silently * ignored. * * - SMF : * Only the vertices and triangular faces are read (which should be * sufficient to read the output of QSlim for instance). Every * other field (normals, transforms, colors, begin/end, etc.) is * ignored. * * - Ply : * Only the vertices and triangular faces are read. The 'property' * fields are *not* read (only those describing vertex coordinates * and face indices are considered, others are skipped). Binary * PLY should be OK. However, changing the 'binary_big_endian' * into a 'binary_big_endian' (or the contrary) in the header can * improve things sometimes, especially if you converted your * ASCII file into a binary one using 'ply2binary'... * */ #ifndef _MODEL_IN_PROTO #define _MODEL_IN_PROTO /* --------------------------------------------------------------------------* * External includes * * --------------------------------------------------------------------------*/ #include <3dmodel.h> /* * 'zlib' is not part of the Window$ platforms. Comment out this to use zlib * under Windows (It *does* work ! I saw it on my PC !). */ #ifdef WIN32 # define DONT_USE_ZLIB #endif #ifndef DONT_USE_ZLIB # include <zlib.h> #endif #ifdef __cplusplus # define BEGIN_DECL extern "C" { # define END_DECL } #else # define BEGIN_DECL # define END_DECL #endif BEGIN_DECL #undef BEGIN_DECL /* -------------------------------------------------------------------------- BUFFERED FILE DATA STRUCTURE -------------------------------------------------------------------------- */ struct file_data { #ifdef DONT_USE_ZLIB FILE *f; #else gzFile f; #endif unsigned char *block; /* data block */ int size; /* size of the block */ int nbytes; /* actual number of valid bytes in block */ int pos; /* current position in block */ int is_binary; /* flag for binary data */ int eof_reached; }; /* -------------------------------------------------------------------------- FILE FORMATS -------------------------------------------------------------------------- */ #define MESH_FF_AUTO 0 /* Autodetect file format */ #define MESH_FF_RAW 1 /* Raw (ascii and binary) */ #define MESH_FF_VRML 2 /* VRML 2 utf8 (a.k.a. VRML97) */ #define MESH_FF_IV 3 /* Inventor 2 ascii */ #define MESH_FF_PLY 4 /* Ply ascii */ #define MESH_FF_SMF 5 /* SMF format (from QSlim) */ #define MESH_FF_OFF 6 /* OFF format (from geomview) */ /* -------------------------------------------------------------------------- ERROR CODES (always negative) -------------------------------------------------------------------------- */ #define MESH_NO_MEM -1 /* not enough memory */ #define MESH_CORRUPTED -2 /* corrupted file or I/O error */ #define MESH_MODEL_ERR -3 /* error in model */ #define MESH_NOT_TRIAG -4 /* not a triangular mesh */ #define MESH_BAD_FF -5 /* not a recognized file format */ #define MESH_BAD_FNAME -6 /* Could not open file name */ /* -------------------------------------------------------------------------- PARAMETERS FOR FF READERS -------------------------------------------------------------------------- */ /* Maximum allowed word length */ #define MAX_WORD_LEN 60 /* Default initial number of elements for an array */ #define SZ_INIT_DEF 16384 /* Maximum number of elements by which an array is grown */ #define SZ_MAX_INCR 16384 /* Characters that are considered whitespace in VRML */ #define VRML_WS_CHARS " \t,\n\r" /* Characters that start a comment in VRML */ #define VRML_COMM_ST_CHARS "#" /* Characters that start a quoted string in VRML */ #define VRML_STR_ST_CHARS "\"" /* Characters that are whitespace, or that start a comment in VRML */ #define VRML_WSCOMM_CHARS VRML_WS_CHARS VRML_COMM_ST_CHARS /* Characters that are whitespace, or that start a comment or string in VRML */ #define VRML_WSCOMMSTR_CHARS VRML_WS_CHARS VRML_COMM_ST_CHARS VRML_STR_ST_CHARS /* ------------------------------------------------------------------------- EXTERNAL FUNCTIONS ------------------------------------------------------------------------- */ /* * common part - make the [un]getc function point to the custom * versions that read from a buffer */ # undef getc # define getc buf_getc # undef ungetc # define ungetc buf_ungetc /* These two macros aliased to 'getc' and 'ungetc' in * 'model_in.h'. They behave (or at least should behave) identically * to glibc's 'getc' and 'ungetc', except that they read from a buffer * in memory instead of reading from a file. 'buf_getc' is able to * refill the buffer if there is no data left to be read in the block */ #ifndef buf_getc #define buf_getc(stream) \ (((stream)->nbytes > 0 && (stream)->pos < (stream)->nbytes)? \ ((int)(stream)->block[((stream)->pos)++]):buf_getc_func(stream)) #endif #ifndef buf_ungetc #define buf_ungetc(c, stream) \ (((c) != EOF && (stream)->pos > 0) ? \ ((stream)->block[--((stream)->pos)]):EOF) #endif /* * Adapt all calls to the situation. If we use zlib, use the gz* functions. * If not, use the f* ones. */ #ifdef DONT_USE_ZLIB # undef loc_fopen # define loc_fopen fopen # undef loc_fclose # define loc_fclose fclose # undef loc_fread # define loc_fread fread # undef loc_feof # define loc_feof feof # undef loc_getc # define loc_getc fgetc # undef loc_ferror # define loc_ferror ferror #else # undef loc_fopen # define loc_fopen gzopen # undef loc_fclose # define loc_fclose gzclose # undef loc_fread /* why the $%^ are they using different args ??? */ # define loc_fread(ptr, size, nemb, stream) gzread(stream, ptr, (nemb)*(size)) # undef loc_feof # define loc_feof gzeof # undef loc_getc # define loc_getc gzgetc # undef loc_ferror #define loc_ferror gz_ferror #endif /* Low-level functions used by model readers - see model_in.c for * details. Although they are exported, they should only be used in * the model_in*.c files */ int buf_getc_func(struct file_data*); int int_scanf(struct file_data*, int*); int float_scanf(struct file_data*, float*); int string_scanf(struct file_data*, char*); int buf_fscanf_1arg(struct file_data*, const char*, void*); void* grow_array(void*, size_t, int*, int); int skip_ws_comm(struct file_data*); int skip_ws_comm_str(struct file_data*); int find_chars(struct file_data*, const char*); int find_string(struct file_data*, const char*); size_t bin_read(void *, size_t, size_t, struct file_data*); /* File format reader functions - should be accessed only through * read_[f]model. See the model_in*.c files for more details about * their behaviour (esp. wrt. error handling and/or [un]implemented * features of each file format) */ int read_raw_tmesh(struct model**, struct file_data*); int read_smf_tmesh(struct model**, struct file_data*); int read_ply_tmesh(struct model**, struct file_data*); int read_vrml_tmesh(struct model**, struct file_data*, int); int read_iv_tmesh(struct model**, struct file_data*); int read_off_tmesh(struct model**, struct file_data*); /* Reads the 3D triangular mesh models from the input '*data' stream, in the * file format specified by 'fformat'. The model meshes are returned in the * new '*models_ref' array (allocate via malloc). If succesful it returns the * number of meshes read or the negative error code (MESH_CORRUPTED, * MESH_NOT_TRIAG, etc.). If an error occurs '*models_ref' is not modified. If * 'fformat' is MESH_FF_AUTO the file format is autodetected. If 'concat' is * non-zero only one mesh is returned, which is the concatenation of the the * ones read. */ int read_model(struct model **models_ref, struct file_data *data, int fformat, int concat); /* Reads the 3D triangular mesh models from the input file '*fname' file, in * the file format specified by 'fformat'. The model meshes are returned in * the new '*models_ref' array (allocated via malloc). It returns the number * of meshes read, if succesful, or the negative error code (MESH_CORRUPTED, * MESH_NOT_TRIAG, etc.) otherwise. If an error occurs opening the file * MESH_BAD_FNAME is returned (the detailed error is given in errno). If an * error occurs '*models_ref' is not modified. If 'fformat' is MESH_FF_AUTO * the file format is autodetected. If 'concat' is non-zero only one mesh is * returned, which is the concatenation of the the ones read. */ int read_fmodel(struct model **models_ref, const char *fname, int fformat, int concat); END_DECL #undef END_DECL #endif /* _MODEL_IN_PROTO */
Java
// Copyright (c) 2008 Roberto Raggi <roberto.raggi@gmail.com> // // 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. // // W A R N I N G // ------------- // // This file is automatically generated. // Changes will be lost. // #include "AST.h" #include "ASTMatcher.h" using namespace CPlusPlus; bool ObjCSelectorArgumentAST::match0(AST *pattern, ASTMatcher *matcher) { if (ObjCSelectorArgumentAST *_other = pattern->asObjCSelectorArgument()) return matcher->match(this, _other); return false; } bool ObjCSelectorAST::match0(AST *pattern, ASTMatcher *matcher) { if (ObjCSelectorAST *_other = pattern->asObjCSelector()) return matcher->match(this, _other); return false; } bool SimpleSpecifierAST::match0(AST *pattern, ASTMatcher *matcher) { if (SimpleSpecifierAST *_other = pattern->asSimpleSpecifier()) return matcher->match(this, _other); return false; } bool AttributeSpecifierAST::match0(AST *pattern, ASTMatcher *matcher) { if (AttributeSpecifierAST *_other = pattern->asAttributeSpecifier()) return matcher->match(this, _other); return false; } bool AttributeAST::match0(AST *pattern, ASTMatcher *matcher) { if (AttributeAST *_other = pattern->asAttribute()) return matcher->match(this, _other); return false; } bool TypeofSpecifierAST::match0(AST *pattern, ASTMatcher *matcher) { if (TypeofSpecifierAST *_other = pattern->asTypeofSpecifier()) return matcher->match(this, _other); return false; } bool DeclaratorAST::match0(AST *pattern, ASTMatcher *matcher) { if (DeclaratorAST *_other = pattern->asDeclarator()) return matcher->match(this, _other); return false; } bool SimpleDeclarationAST::match0(AST *pattern, ASTMatcher *matcher) { if (SimpleDeclarationAST *_other = pattern->asSimpleDeclaration()) return matcher->match(this, _other); return false; } bool EmptyDeclarationAST::match0(AST *pattern, ASTMatcher *matcher) { if (EmptyDeclarationAST *_other = pattern->asEmptyDeclaration()) return matcher->match(this, _other); return false; } bool AccessDeclarationAST::match0(AST *pattern, ASTMatcher *matcher) { if (AccessDeclarationAST *_other = pattern->asAccessDeclaration()) return matcher->match(this, _other); return false; } bool QtObjectTagAST::match0(AST *pattern, ASTMatcher *matcher) { if (QtObjectTagAST *_other = pattern->asQtObjectTag()) return matcher->match(this, _other); return false; } bool QtPrivateSlotAST::match0(AST *pattern, ASTMatcher *matcher) { if (QtPrivateSlotAST *_other = pattern->asQtPrivateSlot()) return matcher->match(this, _other); return false; } bool QtPropertyDeclarationItemAST::match0(AST *pattern, ASTMatcher *matcher) { if (QtPropertyDeclarationItemAST *_other = pattern->asQtPropertyDeclarationItem()) return matcher->match(this, _other); return false; } bool QtPropertyDeclarationAST::match0(AST *pattern, ASTMatcher *matcher) { if (QtPropertyDeclarationAST *_other = pattern->asQtPropertyDeclaration()) return matcher->match(this, _other); return false; } bool QtEnumDeclarationAST::match0(AST *pattern, ASTMatcher *matcher) { if (QtEnumDeclarationAST *_other = pattern->asQtEnumDeclaration()) return matcher->match(this, _other); return false; } bool QtFlagsDeclarationAST::match0(AST *pattern, ASTMatcher *matcher) { if (QtFlagsDeclarationAST *_other = pattern->asQtFlagsDeclaration()) return matcher->match(this, _other); return false; } bool QtInterfaceNameAST::match0(AST *pattern, ASTMatcher *matcher) { if (QtInterfaceNameAST *_other = pattern->asQtInterfaceName()) return matcher->match(this, _other); return false; } bool QtInterfacesDeclarationAST::match0(AST *pattern, ASTMatcher *matcher) { if (QtInterfacesDeclarationAST *_other = pattern->asQtInterfacesDeclaration()) return matcher->match(this, _other); return false; } bool AsmDefinitionAST::match0(AST *pattern, ASTMatcher *matcher) { if (AsmDefinitionAST *_other = pattern->asAsmDefinition()) return matcher->match(this, _other); return false; } bool BaseSpecifierAST::match0(AST *pattern, ASTMatcher *matcher) { if (BaseSpecifierAST *_other = pattern->asBaseSpecifier()) return matcher->match(this, _other); return false; } bool IdExpressionAST::match0(AST *pattern, ASTMatcher *matcher) { if (IdExpressionAST *_other = pattern->asIdExpression()) return matcher->match(this, _other); return false; } bool CompoundExpressionAST::match0(AST *pattern, ASTMatcher *matcher) { if (CompoundExpressionAST *_other = pattern->asCompoundExpression()) return matcher->match(this, _other); return false; } bool CompoundLiteralAST::match0(AST *pattern, ASTMatcher *matcher) { if (CompoundLiteralAST *_other = pattern->asCompoundLiteral()) return matcher->match(this, _other); return false; } bool QtMethodAST::match0(AST *pattern, ASTMatcher *matcher) { if (QtMethodAST *_other = pattern->asQtMethod()) return matcher->match(this, _other); return false; } bool QtMemberDeclarationAST::match0(AST *pattern, ASTMatcher *matcher) { if (QtMemberDeclarationAST *_other = pattern->asQtMemberDeclaration()) return matcher->match(this, _other); return false; } bool BinaryExpressionAST::match0(AST *pattern, ASTMatcher *matcher) { if (BinaryExpressionAST *_other = pattern->asBinaryExpression()) return matcher->match(this, _other); return false; } bool CastExpressionAST::match0(AST *pattern, ASTMatcher *matcher) { if (CastExpressionAST *_other = pattern->asCastExpression()) return matcher->match(this, _other); return false; } bool ClassSpecifierAST::match0(AST *pattern, ASTMatcher *matcher) { if (ClassSpecifierAST *_other = pattern->asClassSpecifier()) return matcher->match(this, _other); return false; } bool CaseStatementAST::match0(AST *pattern, ASTMatcher *matcher) { if (CaseStatementAST *_other = pattern->asCaseStatement()) return matcher->match(this, _other); return false; } bool CompoundStatementAST::match0(AST *pattern, ASTMatcher *matcher) { if (CompoundStatementAST *_other = pattern->asCompoundStatement()) return matcher->match(this, _other); return false; } bool ConditionAST::match0(AST *pattern, ASTMatcher *matcher) { if (ConditionAST *_other = pattern->asCondition()) return matcher->match(this, _other); return false; } bool ConditionalExpressionAST::match0(AST *pattern, ASTMatcher *matcher) { if (ConditionalExpressionAST *_other = pattern->asConditionalExpression()) return matcher->match(this, _other); return false; } bool CppCastExpressionAST::match0(AST *pattern, ASTMatcher *matcher) { if (CppCastExpressionAST *_other = pattern->asCppCastExpression()) return matcher->match(this, _other); return false; } bool CtorInitializerAST::match0(AST *pattern, ASTMatcher *matcher) { if (CtorInitializerAST *_other = pattern->asCtorInitializer()) return matcher->match(this, _other); return false; } bool DeclarationStatementAST::match0(AST *pattern, ASTMatcher *matcher) { if (DeclarationStatementAST *_other = pattern->asDeclarationStatement()) return matcher->match(this, _other); return false; } bool DeclaratorIdAST::match0(AST *pattern, ASTMatcher *matcher) { if (DeclaratorIdAST *_other = pattern->asDeclaratorId()) return matcher->match(this, _other); return false; } bool NestedDeclaratorAST::match0(AST *pattern, ASTMatcher *matcher) { if (NestedDeclaratorAST *_other = pattern->asNestedDeclarator()) return matcher->match(this, _other); return false; } bool FunctionDeclaratorAST::match0(AST *pattern, ASTMatcher *matcher) { if (FunctionDeclaratorAST *_other = pattern->asFunctionDeclarator()) return matcher->match(this, _other); return false; } bool ArrayDeclaratorAST::match0(AST *pattern, ASTMatcher *matcher) { if (ArrayDeclaratorAST *_other = pattern->asArrayDeclarator()) return matcher->match(this, _other); return false; } bool DeleteExpressionAST::match0(AST *pattern, ASTMatcher *matcher) { if (DeleteExpressionAST *_other = pattern->asDeleteExpression()) return matcher->match(this, _other); return false; } bool DoStatementAST::match0(AST *pattern, ASTMatcher *matcher) { if (DoStatementAST *_other = pattern->asDoStatement()) return matcher->match(this, _other); return false; } bool NamedTypeSpecifierAST::match0(AST *pattern, ASTMatcher *matcher) { if (NamedTypeSpecifierAST *_other = pattern->asNamedTypeSpecifier()) return matcher->match(this, _other); return false; } bool ElaboratedTypeSpecifierAST::match0(AST *pattern, ASTMatcher *matcher) { if (ElaboratedTypeSpecifierAST *_other = pattern->asElaboratedTypeSpecifier()) return matcher->match(this, _other); return false; } bool EnumSpecifierAST::match0(AST *pattern, ASTMatcher *matcher) { if (EnumSpecifierAST *_other = pattern->asEnumSpecifier()) return matcher->match(this, _other); return false; } bool EnumeratorAST::match0(AST *pattern, ASTMatcher *matcher) { if (EnumeratorAST *_other = pattern->asEnumerator()) return matcher->match(this, _other); return false; } bool ExceptionDeclarationAST::match0(AST *pattern, ASTMatcher *matcher) { if (ExceptionDeclarationAST *_other = pattern->asExceptionDeclaration()) return matcher->match(this, _other); return false; } bool ExceptionSpecificationAST::match0(AST *pattern, ASTMatcher *matcher) { if (ExceptionSpecificationAST *_other = pattern->asExceptionSpecification()) return matcher->match(this, _other); return false; } bool ExpressionOrDeclarationStatementAST::match0(AST *pattern, ASTMatcher *matcher) { if (ExpressionOrDeclarationStatementAST *_other = pattern->asExpressionOrDeclarationStatement()) return matcher->match(this, _other); return false; } bool ExpressionStatementAST::match0(AST *pattern, ASTMatcher *matcher) { if (ExpressionStatementAST *_other = pattern->asExpressionStatement()) return matcher->match(this, _other); return false; } bool FunctionDefinitionAST::match0(AST *pattern, ASTMatcher *matcher) { if (FunctionDefinitionAST *_other = pattern->asFunctionDefinition()) return matcher->match(this, _other); return false; } bool ForeachStatementAST::match0(AST *pattern, ASTMatcher *matcher) { if (ForeachStatementAST *_other = pattern->asForeachStatement()) return matcher->match(this, _other); return false; } bool ForStatementAST::match0(AST *pattern, ASTMatcher *matcher) { if (ForStatementAST *_other = pattern->asForStatement()) return matcher->match(this, _other); return false; } bool IfStatementAST::match0(AST *pattern, ASTMatcher *matcher) { if (IfStatementAST *_other = pattern->asIfStatement()) return matcher->match(this, _other); return false; } bool ArrayInitializerAST::match0(AST *pattern, ASTMatcher *matcher) { if (ArrayInitializerAST *_other = pattern->asArrayInitializer()) return matcher->match(this, _other); return false; } bool LabeledStatementAST::match0(AST *pattern, ASTMatcher *matcher) { if (LabeledStatementAST *_other = pattern->asLabeledStatement()) return matcher->match(this, _other); return false; } bool LinkageBodyAST::match0(AST *pattern, ASTMatcher *matcher) { if (LinkageBodyAST *_other = pattern->asLinkageBody()) return matcher->match(this, _other); return false; } bool LinkageSpecificationAST::match0(AST *pattern, ASTMatcher *matcher) { if (LinkageSpecificationAST *_other = pattern->asLinkageSpecification()) return matcher->match(this, _other); return false; } bool MemInitializerAST::match0(AST *pattern, ASTMatcher *matcher) { if (MemInitializerAST *_other = pattern->asMemInitializer()) return matcher->match(this, _other); return false; } bool NestedNameSpecifierAST::match0(AST *pattern, ASTMatcher *matcher) { if (NestedNameSpecifierAST *_other = pattern->asNestedNameSpecifier()) return matcher->match(this, _other); return false; } bool QualifiedNameAST::match0(AST *pattern, ASTMatcher *matcher) { if (QualifiedNameAST *_other = pattern->asQualifiedName()) return matcher->match(this, _other); return false; } bool OperatorFunctionIdAST::match0(AST *pattern, ASTMatcher *matcher) { if (OperatorFunctionIdAST *_other = pattern->asOperatorFunctionId()) return matcher->match(this, _other); return false; } bool ConversionFunctionIdAST::match0(AST *pattern, ASTMatcher *matcher) { if (ConversionFunctionIdAST *_other = pattern->asConversionFunctionId()) return matcher->match(this, _other); return false; } bool SimpleNameAST::match0(AST *pattern, ASTMatcher *matcher) { if (SimpleNameAST *_other = pattern->asSimpleName()) return matcher->match(this, _other); return false; } bool DestructorNameAST::match0(AST *pattern, ASTMatcher *matcher) { if (DestructorNameAST *_other = pattern->asDestructorName()) return matcher->match(this, _other); return false; } bool TemplateIdAST::match0(AST *pattern, ASTMatcher *matcher) { if (TemplateIdAST *_other = pattern->asTemplateId()) return matcher->match(this, _other); return false; } bool NamespaceAST::match0(AST *pattern, ASTMatcher *matcher) { if (NamespaceAST *_other = pattern->asNamespace()) return matcher->match(this, _other); return false; } bool NamespaceAliasDefinitionAST::match0(AST *pattern, ASTMatcher *matcher) { if (NamespaceAliasDefinitionAST *_other = pattern->asNamespaceAliasDefinition()) return matcher->match(this, _other); return false; } bool NewPlacementAST::match0(AST *pattern, ASTMatcher *matcher) { if (NewPlacementAST *_other = pattern->asNewPlacement()) return matcher->match(this, _other); return false; } bool NewArrayDeclaratorAST::match0(AST *pattern, ASTMatcher *matcher) { if (NewArrayDeclaratorAST *_other = pattern->asNewArrayDeclarator()) return matcher->match(this, _other); return false; } bool NewExpressionAST::match0(AST *pattern, ASTMatcher *matcher) { if (NewExpressionAST *_other = pattern->asNewExpression()) return matcher->match(this, _other); return false; } bool NewInitializerAST::match0(AST *pattern, ASTMatcher *matcher) { if (NewInitializerAST *_other = pattern->asNewInitializer()) return matcher->match(this, _other); return false; } bool NewTypeIdAST::match0(AST *pattern, ASTMatcher *matcher) { if (NewTypeIdAST *_other = pattern->asNewTypeId()) return matcher->match(this, _other); return false; } bool OperatorAST::match0(AST *pattern, ASTMatcher *matcher) { if (OperatorAST *_other = pattern->asOperator()) return matcher->match(this, _other); return false; } bool ParameterDeclarationAST::match0(AST *pattern, ASTMatcher *matcher) { if (ParameterDeclarationAST *_other = pattern->asParameterDeclaration()) return matcher->match(this, _other); return false; } bool ParameterDeclarationClauseAST::match0(AST *pattern, ASTMatcher *matcher) { if (ParameterDeclarationClauseAST *_other = pattern->asParameterDeclarationClause()) return matcher->match(this, _other); return false; } bool CallAST::match0(AST *pattern, ASTMatcher *matcher) { if (CallAST *_other = pattern->asCall()) return matcher->match(this, _other); return false; } bool ArrayAccessAST::match0(AST *pattern, ASTMatcher *matcher) { if (ArrayAccessAST *_other = pattern->asArrayAccess()) return matcher->match(this, _other); return false; } bool PostIncrDecrAST::match0(AST *pattern, ASTMatcher *matcher) { if (PostIncrDecrAST *_other = pattern->asPostIncrDecr()) return matcher->match(this, _other); return false; } bool MemberAccessAST::match0(AST *pattern, ASTMatcher *matcher) { if (MemberAccessAST *_other = pattern->asMemberAccess()) return matcher->match(this, _other); return false; } bool TypeidExpressionAST::match0(AST *pattern, ASTMatcher *matcher) { if (TypeidExpressionAST *_other = pattern->asTypeidExpression()) return matcher->match(this, _other); return false; } bool TypenameCallExpressionAST::match0(AST *pattern, ASTMatcher *matcher) { if (TypenameCallExpressionAST *_other = pattern->asTypenameCallExpression()) return matcher->match(this, _other); return false; } bool TypeConstructorCallAST::match0(AST *pattern, ASTMatcher *matcher) { if (TypeConstructorCallAST *_other = pattern->asTypeConstructorCall()) return matcher->match(this, _other); return false; } bool PointerToMemberAST::match0(AST *pattern, ASTMatcher *matcher) { if (PointerToMemberAST *_other = pattern->asPointerToMember()) return matcher->match(this, _other); return false; } bool PointerAST::match0(AST *pattern, ASTMatcher *matcher) { if (PointerAST *_other = pattern->asPointer()) return matcher->match(this, _other); return false; } bool ReferenceAST::match0(AST *pattern, ASTMatcher *matcher) { if (ReferenceAST *_other = pattern->asReference()) return matcher->match(this, _other); return false; } bool BreakStatementAST::match0(AST *pattern, ASTMatcher *matcher) { if (BreakStatementAST *_other = pattern->asBreakStatement()) return matcher->match(this, _other); return false; } bool ContinueStatementAST::match0(AST *pattern, ASTMatcher *matcher) { if (ContinueStatementAST *_other = pattern->asContinueStatement()) return matcher->match(this, _other); return false; } bool GotoStatementAST::match0(AST *pattern, ASTMatcher *matcher) { if (GotoStatementAST *_other = pattern->asGotoStatement()) return matcher->match(this, _other); return false; } bool ReturnStatementAST::match0(AST *pattern, ASTMatcher *matcher) { if (ReturnStatementAST *_other = pattern->asReturnStatement()) return matcher->match(this, _other); return false; } bool SizeofExpressionAST::match0(AST *pattern, ASTMatcher *matcher) { if (SizeofExpressionAST *_other = pattern->asSizeofExpression()) return matcher->match(this, _other); return false; } bool PointerLiteralAST::match0(AST *pattern, ASTMatcher *matcher) { if (PointerLiteralAST *_other = pattern->asPointerLiteral()) return matcher->match(this, _other); return false; } bool NumericLiteralAST::match0(AST *pattern, ASTMatcher *matcher) { if (NumericLiteralAST *_other = pattern->asNumericLiteral()) return matcher->match(this, _other); return false; } bool BoolLiteralAST::match0(AST *pattern, ASTMatcher *matcher) { if (BoolLiteralAST *_other = pattern->asBoolLiteral()) return matcher->match(this, _other); return false; } bool ThisExpressionAST::match0(AST *pattern, ASTMatcher *matcher) { if (ThisExpressionAST *_other = pattern->asThisExpression()) return matcher->match(this, _other); return false; } bool NestedExpressionAST::match0(AST *pattern, ASTMatcher *matcher) { if (NestedExpressionAST *_other = pattern->asNestedExpression()) return matcher->match(this, _other); return false; } bool StringLiteralAST::match0(AST *pattern, ASTMatcher *matcher) { if (StringLiteralAST *_other = pattern->asStringLiteral()) return matcher->match(this, _other); return false; } bool SwitchStatementAST::match0(AST *pattern, ASTMatcher *matcher) { if (SwitchStatementAST *_other = pattern->asSwitchStatement()) return matcher->match(this, _other); return false; } bool TemplateDeclarationAST::match0(AST *pattern, ASTMatcher *matcher) { if (TemplateDeclarationAST *_other = pattern->asTemplateDeclaration()) return matcher->match(this, _other); return false; } bool ThrowExpressionAST::match0(AST *pattern, ASTMatcher *matcher) { if (ThrowExpressionAST *_other = pattern->asThrowExpression()) return matcher->match(this, _other); return false; } bool TranslationUnitAST::match0(AST *pattern, ASTMatcher *matcher) { if (TranslationUnitAST *_other = pattern->asTranslationUnit()) return matcher->match(this, _other); return false; } bool TryBlockStatementAST::match0(AST *pattern, ASTMatcher *matcher) { if (TryBlockStatementAST *_other = pattern->asTryBlockStatement()) return matcher->match(this, _other); return false; } bool CatchClauseAST::match0(AST *pattern, ASTMatcher *matcher) { if (CatchClauseAST *_other = pattern->asCatchClause()) return matcher->match(this, _other); return false; } bool TypeIdAST::match0(AST *pattern, ASTMatcher *matcher) { if (TypeIdAST *_other = pattern->asTypeId()) return matcher->match(this, _other); return false; } bool TypenameTypeParameterAST::match0(AST *pattern, ASTMatcher *matcher) { if (TypenameTypeParameterAST *_other = pattern->asTypenameTypeParameter()) return matcher->match(this, _other); return false; } bool TemplateTypeParameterAST::match0(AST *pattern, ASTMatcher *matcher) { if (TemplateTypeParameterAST *_other = pattern->asTemplateTypeParameter()) return matcher->match(this, _other); return false; } bool UnaryExpressionAST::match0(AST *pattern, ASTMatcher *matcher) { if (UnaryExpressionAST *_other = pattern->asUnaryExpression()) return matcher->match(this, _other); return false; } bool UsingAST::match0(AST *pattern, ASTMatcher *matcher) { if (UsingAST *_other = pattern->asUsing()) return matcher->match(this, _other); return false; } bool UsingDirectiveAST::match0(AST *pattern, ASTMatcher *matcher) { if (UsingDirectiveAST *_other = pattern->asUsingDirective()) return matcher->match(this, _other); return false; } bool WhileStatementAST::match0(AST *pattern, ASTMatcher *matcher) { if (WhileStatementAST *_other = pattern->asWhileStatement()) return matcher->match(this, _other); return false; } bool ObjCClassForwardDeclarationAST::match0(AST *pattern, ASTMatcher *matcher) { if (ObjCClassForwardDeclarationAST *_other = pattern->asObjCClassForwardDeclaration()) return matcher->match(this, _other); return false; } bool ObjCClassDeclarationAST::match0(AST *pattern, ASTMatcher *matcher) { if (ObjCClassDeclarationAST *_other = pattern->asObjCClassDeclaration()) return matcher->match(this, _other); return false; } bool ObjCProtocolForwardDeclarationAST::match0(AST *pattern, ASTMatcher *matcher) { if (ObjCProtocolForwardDeclarationAST *_other = pattern->asObjCProtocolForwardDeclaration()) return matcher->match(this, _other); return false; } bool ObjCProtocolDeclarationAST::match0(AST *pattern, ASTMatcher *matcher) { if (ObjCProtocolDeclarationAST *_other = pattern->asObjCProtocolDeclaration()) return matcher->match(this, _other); return false; } bool ObjCProtocolRefsAST::match0(AST *pattern, ASTMatcher *matcher) { if (ObjCProtocolRefsAST *_other = pattern->asObjCProtocolRefs()) return matcher->match(this, _other); return false; } bool ObjCMessageArgumentAST::match0(AST *pattern, ASTMatcher *matcher) { if (ObjCMessageArgumentAST *_other = pattern->asObjCMessageArgument()) return matcher->match(this, _other); return false; } bool ObjCMessageExpressionAST::match0(AST *pattern, ASTMatcher *matcher) { if (ObjCMessageExpressionAST *_other = pattern->asObjCMessageExpression()) return matcher->match(this, _other); return false; } bool ObjCProtocolExpressionAST::match0(AST *pattern, ASTMatcher *matcher) { if (ObjCProtocolExpressionAST *_other = pattern->asObjCProtocolExpression()) return matcher->match(this, _other); return false; } bool ObjCTypeNameAST::match0(AST *pattern, ASTMatcher *matcher) { if (ObjCTypeNameAST *_other = pattern->asObjCTypeName()) return matcher->match(this, _other); return false; } bool ObjCEncodeExpressionAST::match0(AST *pattern, ASTMatcher *matcher) { if (ObjCEncodeExpressionAST *_other = pattern->asObjCEncodeExpression()) return matcher->match(this, _other); return false; } bool ObjCSelectorExpressionAST::match0(AST *pattern, ASTMatcher *matcher) { if (ObjCSelectorExpressionAST *_other = pattern->asObjCSelectorExpression()) return matcher->match(this, _other); return false; } bool ObjCInstanceVariablesDeclarationAST::match0(AST *pattern, ASTMatcher *matcher) { if (ObjCInstanceVariablesDeclarationAST *_other = pattern->asObjCInstanceVariablesDeclaration()) return matcher->match(this, _other); return false; } bool ObjCVisibilityDeclarationAST::match0(AST *pattern, ASTMatcher *matcher) { if (ObjCVisibilityDeclarationAST *_other = pattern->asObjCVisibilityDeclaration()) return matcher->match(this, _other); return false; } bool ObjCPropertyAttributeAST::match0(AST *pattern, ASTMatcher *matcher) { if (ObjCPropertyAttributeAST *_other = pattern->asObjCPropertyAttribute()) return matcher->match(this, _other); return false; } bool ObjCPropertyDeclarationAST::match0(AST *pattern, ASTMatcher *matcher) { if (ObjCPropertyDeclarationAST *_other = pattern->asObjCPropertyDeclaration()) return matcher->match(this, _other); return false; } bool ObjCMessageArgumentDeclarationAST::match0(AST *pattern, ASTMatcher *matcher) { if (ObjCMessageArgumentDeclarationAST *_other = pattern->asObjCMessageArgumentDeclaration()) return matcher->match(this, _other); return false; } bool ObjCMethodPrototypeAST::match0(AST *pattern, ASTMatcher *matcher) { if (ObjCMethodPrototypeAST *_other = pattern->asObjCMethodPrototype()) return matcher->match(this, _other); return false; } bool ObjCMethodDeclarationAST::match0(AST *pattern, ASTMatcher *matcher) { if (ObjCMethodDeclarationAST *_other = pattern->asObjCMethodDeclaration()) return matcher->match(this, _other); return false; } bool ObjCSynthesizedPropertyAST::match0(AST *pattern, ASTMatcher *matcher) { if (ObjCSynthesizedPropertyAST *_other = pattern->asObjCSynthesizedProperty()) return matcher->match(this, _other); return false; } bool ObjCSynthesizedPropertiesDeclarationAST::match0(AST *pattern, ASTMatcher *matcher) { if (ObjCSynthesizedPropertiesDeclarationAST *_other = pattern->asObjCSynthesizedPropertiesDeclaration()) return matcher->match(this, _other); return false; } bool ObjCDynamicPropertiesDeclarationAST::match0(AST *pattern, ASTMatcher *matcher) { if (ObjCDynamicPropertiesDeclarationAST *_other = pattern->asObjCDynamicPropertiesDeclaration()) return matcher->match(this, _other); return false; } bool ObjCFastEnumerationAST::match0(AST *pattern, ASTMatcher *matcher) { if (ObjCFastEnumerationAST *_other = pattern->asObjCFastEnumeration()) return matcher->match(this, _other); return false; } bool ObjCSynchronizedStatementAST::match0(AST *pattern, ASTMatcher *matcher) { if (ObjCSynchronizedStatementAST *_other = pattern->asObjCSynchronizedStatement()) return matcher->match(this, _other); return false; } bool LambdaExpressionAST::match0(AST *pattern, ASTMatcher *matcher) { if (LambdaExpressionAST *_other = pattern->asLambdaExpression()) return matcher->match(this, _other); return false; } bool LambdaIntroducerAST::match0(AST *pattern, ASTMatcher *matcher) { if (LambdaIntroducerAST *_other = pattern->asLambdaIntroducer()) return matcher->match(this, _other); return false; } bool LambdaCaptureAST::match0(AST *pattern, ASTMatcher *matcher) { if (LambdaCaptureAST *_other = pattern->asLambdaCapture()) return matcher->match(this, _other); return false; } bool CaptureAST::match0(AST *pattern, ASTMatcher *matcher) { if (CaptureAST *_other = pattern->asCapture()) return matcher->match(this, _other); return false; } bool LambdaDeclaratorAST::match0(AST *pattern, ASTMatcher *matcher) { if (LambdaDeclaratorAST *_other = pattern->asLambdaDeclarator()) return matcher->match(this, _other); return false; } bool TrailingReturnTypeAST::match0(AST *pattern, ASTMatcher *matcher) { if (TrailingReturnTypeAST *_other = pattern->asTrailingReturnType()) return matcher->match(this, _other); return false; } bool BracedInitializerAST::match0(AST *pattern, ASTMatcher *matcher) { if (BracedInitializerAST *_other = pattern->asBracedInitializer()) return matcher->match(this, _other); return false; }
Java
<?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Qt 4.6: textprogressbar.cpp Example File (network/downloadmanager/textprogressbar.cpp)</title> <link href="classic.css" rel="stylesheet" type="text/css" /> </head> <body> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr> <td align="left" valign="top" width="32"><a href="http://qt.nokia.com/"><img src="images/qt-logo.png" align="left" border="0" /></a></td> <td width="1">&nbsp;&nbsp;</td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a>&nbsp;&middot; <a href="classes.html"><font color="#004faf">All&nbsp;Classes</font></a>&nbsp;&middot; <a href="functions.html"><font color="#004faf">All&nbsp;Functions</font></a>&nbsp;&middot; <a href="overviews.html"><font color="#004faf">Overviews</font></a></td></tr></table><h1 class="title">textprogressbar.cpp Example File<br /><span class="small-subtitle">network/downloadmanager/textprogressbar.cpp</span> </h1> <pre><span class="comment"> /**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** $QT_END_LICENSE$ ** ****************************************************************************/</span> #include &quot;textprogressbar.h&quot; #include &lt;QByteArray&gt; #include &lt;stdio.h&gt; TextProgressBar::TextProgressBar() : value(0), maximum(-1), iteration(0) { } void TextProgressBar::clear() { printf(&quot;\n&quot;); fflush(stdout); iteration = 0; value = 0; maximum = -1; } void TextProgressBar::update() { ++iteration; if (maximum &gt; 0) { <span class="comment">// we know the maximum</span> <span class="comment">// draw a progress bar</span> int percent = value * 100 / maximum; int hashes = percent / 2; QByteArray progressbar(hashes, '#'); if (percent % 2) progressbar += '&gt;'; printf(&quot;\r[%-50s] %3d%% %s &quot;, progressbar.constData(), percent, qPrintable(message)); } else { <span class="comment">// we don't know the maximum, so we can't draw a progress bar</span> int center = (iteration % 48) + 1; <span class="comment">// 50 spaces, minus 2</span> QByteArray before(qMax(center - 2, 0), ' '); QByteArray after(qMin(center + 2, 50), ' '); printf(&quot;\r[%s###%s] %s &quot;, before.constData(), after.constData(), qPrintable(message)); } } void TextProgressBar::setMessage(const QString &amp;m) { message = m; } void TextProgressBar::setStatus(qint64 val, qint64 max) { value = val; maximum = max; }</pre> <p /><address><hr /><div align="center"> <table width="100%" cellspacing="0" border="0"><tr class="address"> <td width="40%" align="left">Copyright &copy; 2010 Nokia Corporation and/or its subsidiary(-ies)</td> <td width="20%" align="center"><a href="trademarks.html">Trademarks</a></td> <td width="40%" align="right"><div align="right">Qt 4.6.2</div></td> </tr></table></div></address></body> </html>
Java
// // YTS.c // // $Author: why $ // $Date: 2005/09/20 23:42:51 $ // // Copyright (C) 2004 why the lucky stiff // // Well, this is the Yaml Testing Suite in the form of a plain C // API. Basically, this is as good as C integration gets for Syck. // You've got to have a symbol table around. From there, you can // query your data. // #include "system.h" #include "syck.h" #include "CuTest.h" #include "debug.h" /* YAML test node structures */ #define T_STR 10 #define T_SEQ 20 #define T_MAP 30 #define T_END 40 #define ILEN 2 struct test_node { int type; char *tag; char *key; struct test_node *value; }; struct test_node end_node = { T_END }; /* * Assertion which compares a YAML document with an * equivalent set of test_node structs. */ SYMID syck_copy_handler(p, n) SyckParser *p; SyckNode *n; { int i = 0; struct test_node *tn = S_ALLOC_N( struct test_node, 1 ); switch ( n->kind ) { case syck_str_kind: tn->type = T_STR; tn->key = syck_strndup( n->data.str->ptr, n->data.str->len ); tn->value = 0; break; case syck_seq_kind: { struct test_node *val; struct test_node *seq = S_ALLOC_N( struct test_node, n->data.list->idx + 1 ); tn->type = T_SEQ; tn->key = 0; for ( i = 0; i < n->data.list->idx; i++ ) { SYMID oid = syck_seq_read( n, i ); syck_lookup_sym( p, oid, (char **)&val ); seq[i] = val[0]; } seq[n->data.list->idx] = end_node; tn->value = seq; } break; case syck_map_kind: { struct test_node *val; struct test_node *map = S_ALLOC_N( struct test_node, ( n->data.pairs->idx * 2 ) + 1 ); tn->type = T_MAP; tn->key = 0; for ( i = 0; i < n->data.pairs->idx; i++ ) { SYMID oid = syck_map_read( n, map_key, i ); syck_lookup_sym( p, oid, (char **)&val ); map[i * 2] = val[0]; oid = syck_map_read( n, map_value, i ); syck_lookup_sym( p, oid, (char **)&val ); map[(i * 2) + 1] = val[0]; } map[n->data.pairs->idx * 2] = end_node; tn->value = map; } break; } tn->tag = 0; if ( n->type_id != NULL ) { tn->tag = syck_strndup( n->type_id, strlen( n->type_id ) ); } return syck_add_sym( p, (char *) tn ); } int syck_free_copies( char *key, struct test_node *tn, char *arg ) { if ( tn != NULL ) { switch ( tn->type ) { case T_STR: S_FREE( tn->key ); break; case T_SEQ: case T_MAP: S_FREE( tn->value ); break; } if ( tn->tag != NULL ) S_FREE( tn->tag ); S_FREE( tn ); } tn = NULL; return ST_CONTINUE; } void CuStreamCompareX( CuTest* tc, struct test_node *s1, struct test_node *s2 ) { int i = 0; while ( 1 ) { CuAssertIntEquals( tc, s1[i].type, s2[i].type ); if ( s1[i].type == T_END ) return; if ( s1[i].tag != 0 && s2[i].tag != 0 ) CuAssertStrEquals( tc, s1[i].tag, s2[i].tag ); switch ( s1[i].type ) { case T_STR: CuAssertStrEquals( tc, s1[i].key, s2[i].key ); break; case T_SEQ: case T_MAP: CuStreamCompareX( tc, s1[i].value, s2[i].value ); break; } i++; } } void CuStreamCompare( CuTest* tc, char *yaml, struct test_node *stream ) { int doc_ct = 0; struct test_node *ystream = S_ALLOC_N( struct test_node, doc_ct + 1 ); /* Set up parser */ SyckParser *parser = syck_new_parser(); syck_parser_str_auto( parser, yaml, NULL ); syck_parser_handler( parser, syck_copy_handler ); syck_parser_error_handler( parser, NULL ); syck_parser_implicit_typing( parser, 1 ); syck_parser_taguri_expansion( parser, 1 ); /* Parse all streams */ while ( 1 ) { struct test_node *ydoc; SYMID oid = syck_parse( parser ); if ( parser->eof == 1 ) break; /* Add document to stream */ syck_lookup_sym( parser, oid, (char **)&ydoc ); ystream[doc_ct] = ydoc[0]; doc_ct++; S_REALLOC_N( ystream, struct test_node, doc_ct + 1 ); } ystream[doc_ct] = end_node; /* Traverse the struct and the symbol table side-by-side */ /* DEBUG: y( stream, 0 ); y( ystream, 0 ); */ CuStreamCompareX( tc, stream, ystream ); /* Free the node tables and the parser */ S_FREE( ystream ); if ( parser->syms != NULL ) st_foreach( parser->syms, (void *)syck_free_copies, 0 ); syck_free_parser( parser ); } /* * Setup for testing N->Y->N. */ void test_output_handler( emitter, str, len ) SyckEmitter *emitter; char *str; long len; { CuString *dest = (CuString *)emitter->bonus; CuStringAppendLen( dest, str, len ); } SYMID build_symbol_table( SyckEmitter *emitter, struct test_node *node ) { switch ( node->type ) { case T_SEQ: case T_MAP: { int i = 0; while ( node->value[i].type != T_END ) { build_symbol_table( emitter, &node->value[i] ); i++; } } return syck_emitter_mark_node( emitter, (st_data_t)node ); default: break; } return 0; } void test_emitter_handler( SyckEmitter *emitter, st_data_t data ) { struct test_node *node = (struct test_node *)data; switch ( node->type ) { case T_STR: syck_emit_scalar( emitter, node->tag, scalar_none, 0, 0, 0, node->key, strlen( node->key ) ); break; case T_SEQ: { int i = 0; syck_emit_seq( emitter, node->tag, seq_none ); while ( node->value[i].type != T_END ) { syck_emit_item( emitter, (st_data_t)&node->value[i] ); i++; } syck_emit_end( emitter ); } break; case T_MAP: { int i = 0; syck_emit_map( emitter, node->tag, map_none ); while ( node->value[i].type != T_END ) { syck_emit_item( emitter, (st_data_t)&node->value[i] ); i++; } syck_emit_end( emitter ); } break; } } void CuRoundTrip( CuTest* tc, struct test_node *stream ) { int i = 0; CuString *cs = CuStringNew(); SyckEmitter *emitter = syck_new_emitter(); /* Calculate anchors and tags */ build_symbol_table( emitter, stream ); /* Build the stream */ syck_output_handler( emitter, test_output_handler ); syck_emitter_handler( emitter, test_emitter_handler ); emitter->bonus = cs; while ( stream[i].type != T_END ) { syck_emit( emitter, (st_data_t)&stream[i] ); syck_emitter_flush( emitter, 0 ); i++; } /* Reload the stream and compare */ /* printf( "-- output for %s --\n%s\n--- end of output --\n", tc->name, cs->buffer ); */ CuStreamCompare( tc, cs->buffer, stream ); CuStringFree( cs ); syck_free_emitter( emitter ); } /* * ACTUAL TESTS FOR THE YAML TESTING SUITE BEGIN HERE * (EVERYTHING PREVIOUS WAS SET UP FOR THE TESTS) */ /* * Example : Trailing tab in plains */ void YtsFoldedScalars_7( CuTest *tc ) { struct test_node map[] = { { T_STR, 0, "a" }, { T_STR, 0, "b" }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "a: b\t \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example : Empty Sequence */ void YtsNullsAndEmpties_0( CuTest *tc ) { struct test_node seq[] = { end_node }; struct test_node map[] = { { T_STR, 0, "empty" }, { T_SEQ, 0, 0, seq }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "empty: [] \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example : Empty Mapping */ void YtsNullsAndEmpties_1( CuTest *tc ) { struct test_node map2[] = { end_node }; struct test_node map1[] = { { T_STR, 0, "empty" }, { T_MAP, 0, 0, map2 }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map1 }, end_node }; CuStreamCompare( tc, /* YAML document */ "empty: {} \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example : Empty Sequence as Entire Document */ void YtsNullsAndEmpties_2( CuTest *tc ) { struct test_node seq[] = { end_node }; struct test_node stream[] = { { T_SEQ, 0, 0, seq }, end_node }; CuStreamCompare( tc, /* YAML document */ "--- [] \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example : Empty Mapping as Entire Document */ void YtsNullsAndEmpties_3( CuTest *tc ) { struct test_node map[] = { end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "--- {} \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example : Null as Document */ void YtsNullsAndEmpties_4( CuTest *tc ) { struct test_node stream[] = { { T_STR, 0, "~" }, end_node }; CuStreamCompare( tc, /* YAML document */ "--- ~ \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example : Empty String */ void YtsNullsAndEmpties_5( CuTest *tc ) { struct test_node stream[] = { { T_STR, 0, "" }, end_node }; CuStreamCompare( tc, /* YAML document */ "--- '' \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.1: Sequence of scalars */ void YtsSpecificationExamples_0( CuTest *tc ) { struct test_node seq[] = { { T_STR, 0, "Mark McGwire" }, { T_STR, 0, "Sammy Sosa" }, { T_STR, 0, "Ken Griffey" }, end_node }; struct test_node stream[] = { { T_SEQ, 0, 0, seq }, end_node }; CuStreamCompare( tc, /* YAML document */ "- Mark McGwire \n" "- Sammy Sosa \n" "- Ken Griffey \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.2: Mapping of scalars to scalars */ void YtsSpecificationExamples_1( CuTest *tc ) { struct test_node map[] = { { T_STR, 0, "hr" }, { T_STR, 0, "65" }, { T_STR, 0, "avg" }, { T_STR, 0, "0.278" }, { T_STR, 0, "rbi" }, { T_STR, 0, "147" }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "hr: 65 \n" "avg: 0.278 \n" "rbi: 147 \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.3: Mapping of scalars to sequences */ void YtsSpecificationExamples_2( CuTest *tc ) { struct test_node seq1[] = { { T_STR, 0, "Boston Red Sox" }, { T_STR, 0, "Detroit Tigers" }, { T_STR, 0, "New York Yankees" }, end_node }; struct test_node seq2[] = { { T_STR, 0, "New York Mets" }, { T_STR, 0, "Chicago Cubs" }, { T_STR, 0, "Atlanta Braves" }, end_node }; struct test_node map[] = { { T_STR, 0, "american" }, { T_SEQ, 0, 0, seq1 }, { T_STR, 0, "national" }, { T_SEQ, 0, 0, seq2 }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "american: \n" " - Boston Red Sox \n" " - Detroit Tigers \n" " - New York Yankees \n" "national: \n" " - New York Mets \n" " - Chicago Cubs \n" " - Atlanta Braves \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.4: Sequence of mappings */ void YtsSpecificationExamples_3( CuTest *tc ) { struct test_node map1[] = { { T_STR, 0, "name" }, { T_STR, 0, "Mark McGwire" }, { T_STR, 0, "hr" }, { T_STR, 0, "65" }, { T_STR, 0, "avg" }, { T_STR, 0, "0.278" }, end_node }; struct test_node map2[] = { { T_STR, 0, "name" }, { T_STR, 0, "Sammy Sosa" }, { T_STR, 0, "hr" }, { T_STR, 0, "63" }, { T_STR, 0, "avg" }, { T_STR, 0, "0.288" }, end_node }; struct test_node seq[] = { { T_MAP, 0, 0, map1 }, { T_MAP, 0, 0, map2 }, end_node }; struct test_node stream[] = { { T_SEQ, 0, 0, seq }, end_node }; CuStreamCompare( tc, /* YAML document */ "- \n" " name: Mark McGwire \n" " hr: 65 \n" " avg: 0.278 \n" "- \n" " name: Sammy Sosa \n" " hr: 63 \n" " avg: 0.288 \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example legacy_A5: Legacy A5 */ void YtsSpecificationExamples_4( CuTest *tc ) { struct test_node seq1[] = { { T_STR, 0, "New York Yankees" }, { T_STR, 0, "Atlanta Braves" }, end_node }; struct test_node seq2[] = { { T_STR, 0, "2001-07-02" }, { T_STR, 0, "2001-08-12" }, { T_STR, 0, "2001-08-14" }, end_node }; struct test_node seq3[] = { { T_STR, 0, "Detroit Tigers" }, { T_STR, 0, "Chicago Cubs" }, end_node }; struct test_node seq4[] = { { T_STR, 0, "2001-07-23" }, end_node }; struct test_node map[] = { { T_SEQ, 0, 0, seq1 }, { T_SEQ, 0, 0, seq2 }, { T_SEQ, 0, 0, seq3 }, { T_SEQ, 0, 0, seq4 }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "? \n" " - New York Yankees \n" " - Atlanta Braves \n" ": \n" " - 2001-07-02 \n" " - 2001-08-12 \n" " - 2001-08-14 \n" "? \n" " - Detroit Tigers \n" " - Chicago Cubs \n" ": \n" " - 2001-07-23 \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.5: Sequence of sequences */ void YtsSpecificationExamples_5( CuTest *tc ) { struct test_node seq1[] = { { T_STR, 0, "name" }, { T_STR, 0, "hr" }, { T_STR, 0, "avg" }, end_node }; struct test_node seq2[] = { { T_STR, 0, "Mark McGwire" }, { T_STR, 0, "65" }, { T_STR, 0, "0.278" }, end_node }; struct test_node seq3[] = { { T_STR, 0, "Sammy Sosa" }, { T_STR, 0, "63" }, { T_STR, 0, "0.288" }, end_node }; struct test_node seq[] = { { T_SEQ, 0, 0, seq1 }, { T_SEQ, 0, 0, seq2 }, { T_SEQ, 0, 0, seq3 }, end_node }; struct test_node stream[] = { { T_SEQ, 0, 0, seq }, end_node }; CuStreamCompare( tc, /* YAML document */ "- [ name , hr , avg ] \n" "- [ Mark McGwire , 65 , 0.278 ] \n" "- [ Sammy Sosa , 63 , 0.288 ] \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.6: Mapping of mappings */ void YtsSpecificationExamples_6( CuTest *tc ) { struct test_node map1[] = { { T_STR, 0, "hr" }, { T_STR, 0, "65" }, { T_STR, 0, "avg" }, { T_STR, 0, "0.278" }, end_node }; struct test_node map2[] = { { T_STR, 0, "hr" }, { T_STR, 0, "63" }, { T_STR, 0, "avg" }, { T_STR, 0, "0.288" }, end_node }; struct test_node map[] = { { T_STR, 0, "Mark McGwire" }, { T_MAP, 0, 0, map1 }, { T_STR, 0, "Sammy Sosa" }, { T_MAP, 0, 0, map2 }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "Mark McGwire: {hr: 65, avg: 0.278}\n" "Sammy Sosa: {\n" " hr: 63,\n" " avg: 0.288\n" " }\n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.7: Two documents in a stream each with a leading comment */ void YtsSpecificationExamples_7( CuTest *tc ) { struct test_node seq1[] = { { T_STR, 0, "Mark McGwire" }, { T_STR, 0, "Sammy Sosa" }, { T_STR, 0, "Ken Griffey" }, end_node }; struct test_node seq2[] = { { T_STR, 0, "Chicago Cubs" }, { T_STR, 0, "St Louis Cardinals" }, end_node }; struct test_node stream[] = { { T_SEQ, 0, 0, seq1 }, { T_SEQ, 0, 0, seq2 }, end_node }; CuStreamCompare( tc, /* YAML document */ "# Ranking of 1998 home runs\n" "---\n" "- Mark McGwire\n" "- Sammy Sosa\n" "- Ken Griffey\n" "\n" "# Team ranking\n" "---\n" "- Chicago Cubs\n" "- St Louis Cardinals\n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.8: Play by play feed from a game */ void YtsSpecificationExamples_8( CuTest *tc ) { struct test_node map1[] = { { T_STR, 0, "time" }, { T_STR, 0, "20:03:20" }, { T_STR, 0, "player" }, { T_STR, 0, "Sammy Sosa" }, { T_STR, 0, "action" }, { T_STR, 0, "strike (miss)" }, end_node }; struct test_node map2[] = { { T_STR, 0, "time" }, { T_STR, 0, "20:03:47" }, { T_STR, 0, "player" }, { T_STR, 0, "Sammy Sosa" }, { T_STR, 0, "action" }, { T_STR, 0, "grand slam" }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map1 }, { T_MAP, 0, 0, map2 }, end_node }; CuStreamCompare( tc, /* YAML document */ "---\n" "time: 20:03:20\n" "player: Sammy Sosa\n" "action: strike (miss)\n" "...\n" "---\n" "time: 20:03:47\n" "player: Sammy Sosa\n" "action: grand slam\n" "...\n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.9: Single document with two comments */ void YtsSpecificationExamples_9( CuTest *tc ) { struct test_node seq1[] = { { T_STR, 0, "Mark McGwire" }, { T_STR, 0, "Sammy Sosa" }, end_node }; struct test_node seq2[] = { { T_STR, 0, "Sammy Sosa" }, { T_STR, 0, "Ken Griffey" }, end_node }; struct test_node map[] = { { T_STR, 0, "hr" }, { T_SEQ, 0, 0, seq1 }, { T_STR, 0, "rbi" }, { T_SEQ, 0, 0, seq2 }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "hr: # 1998 hr ranking \n" " - Mark McGwire \n" " - Sammy Sosa \n" "rbi: \n" " # 1998 rbi ranking \n" " - Sammy Sosa \n" " - Ken Griffey \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.1: Node for Sammy Sosa appears twice in this document */ void YtsSpecificationExamples_10( CuTest *tc ) { struct test_node seq1[] = { { T_STR, 0, "Mark McGwire" }, { T_STR, 0, "Sammy Sosa" }, end_node }; struct test_node seq2[] = { { T_STR, 0, "Sammy Sosa" }, { T_STR, 0, "Ken Griffey" }, end_node }; struct test_node map[] = { { T_STR, 0, "hr" }, { T_SEQ, 0, 0, seq1 }, { T_STR, 0, "rbi" }, { T_SEQ, 0, 0, seq2 }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "---\n" "hr: \n" " - Mark McGwire \n" " # Following node labeled SS \n" " - &SS Sammy Sosa \n" "rbi: \n" " - *SS # Subsequent occurance \n" " - Ken Griffey \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.11: Mapping between sequences */ void YtsSpecificationExamples_11( CuTest *tc ) { struct test_node seq1[] = { { T_STR, 0, "New York Yankees" }, { T_STR, 0, "Atlanta Braves" }, end_node }; struct test_node seq2[] = { { T_STR, 0, "2001-07-02" }, { T_STR, 0, "2001-08-12" }, { T_STR, 0, "2001-08-14" }, end_node }; struct test_node seq3[] = { { T_STR, 0, "Detroit Tigers" }, { T_STR, 0, "Chicago Cubs" }, end_node }; struct test_node seq4[] = { { T_STR, 0, "2001-07-23" }, end_node }; struct test_node map[] = { { T_SEQ, 0, 0, seq3 }, { T_SEQ, 0, 0, seq4 }, { T_SEQ, 0, 0, seq1 }, { T_SEQ, 0, 0, seq2 }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "? # PLAY SCHEDULE \n" " - Detroit Tigers \n" " - Chicago Cubs \n" ": \n" " - 2001-07-23 \n" "\n" "? [ New York Yankees, \n" " Atlanta Braves ] \n" ": [ 2001-07-02, 2001-08-12, \n" " 2001-08-14 ] \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.12: Sequence key shortcut */ void YtsSpecificationExamples_12( CuTest *tc ) { struct test_node map1[] = { { T_STR, 0, "item" }, { T_STR, 0, "Super Hoop" }, { T_STR, 0, "quantity" }, { T_STR, 0, "1" }, end_node }; struct test_node map2[] = { { T_STR, 0, "item" }, { T_STR, 0, "Basketball" }, { T_STR, 0, "quantity" }, { T_STR, 0, "4" }, end_node }; struct test_node map3[] = { { T_STR, 0, "item" }, { T_STR, 0, "Big Shoes" }, { T_STR, 0, "quantity" }, { T_STR, 0, "1" }, end_node }; struct test_node seq[] = { { T_MAP, 0, 0, map1 }, { T_MAP, 0, 0, map2 }, { T_MAP, 0, 0, map3 }, end_node }; struct test_node stream[] = { { T_SEQ, 0, 0, seq }, end_node }; CuStreamCompare( tc, /* YAML document */ "---\n" "# products purchased\n" "- item : Super Hoop\n" " quantity: 1\n" "- item : Basketball\n" " quantity: 4\n" "- item : Big Shoes\n" " quantity: 1\n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.13: Literal perserves newlines */ void YtsSpecificationExamples_13( CuTest *tc ) { struct test_node stream[] = { { T_STR, 0, "\\//||\\/||\n// || ||_\n" }, end_node }; CuStreamCompare( tc, /* YAML document */ "# ASCII Art\n" "--- | \n" " \\//||\\/||\n" " // || ||_\n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.14: Folded treats newlines as a space */ void YtsSpecificationExamples_14( CuTest *tc ) { struct test_node stream[] = { { T_STR, 0, "Mark McGwire's year was crippled by a knee injury." }, end_node }; CuStreamCompare( tc, /* YAML document */ "---\n" " Mark McGwire's\n" " year was crippled\n" " by a knee injury.\n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.15: Newlines preserved for indented and blank lines */ void YtsSpecificationExamples_15( CuTest *tc ) { struct test_node stream[] = { { T_STR, 0, "Sammy Sosa completed another fine season with great stats.\n\n 63 Home Runs\n 0.288 Batting Average\n\nWhat a year!\n" }, end_node }; CuStreamCompare( tc, /* YAML document */ "--- > \n" " Sammy Sosa completed another\n" " fine season with great stats.\n" "\n" " 63 Home Runs\n" " 0.288 Batting Average\n" "\n" " What a year!\n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.16: Indentation determines scope */ void YtsSpecificationExamples_16( CuTest *tc ) { struct test_node map[] = { { T_STR, 0, "name" }, { T_STR, 0, "Mark McGwire" }, { T_STR, 0, "accomplishment" }, { T_STR, 0, "Mark set a major league home run record in 1998.\n" }, { T_STR, 0, "stats" }, { T_STR, 0, "65 Home Runs\n0.278 Batting Average\n" }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "name: Mark McGwire \n" "accomplishment: > \n" " Mark set a major league\n" " home run record in 1998.\n" "stats: | \n" " 65 Home Runs\n" " 0.278 Batting Average\n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.18: Multiline flow scalars */ void YtsSpecificationExamples_18( CuTest *tc ) { struct test_node map[] = { { T_STR, 0, "plain" }, { T_STR, 0, "This unquoted scalar spans many lines." }, { T_STR, 0, "quoted" }, { T_STR, 0, "So does this quoted scalar.\n" }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "plain:\n" " This unquoted scalar\n" " spans many lines.\n" "\n" "quoted: \"So does this\n" " quoted scalar.\\n\"\n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.19: Integers */ void YtsSpecificationExamples_19( CuTest *tc ) { struct test_node map[] = { { T_STR, 0, "canonical" }, { T_STR, 0, "12345" }, { T_STR, 0, "decimal" }, { T_STR, 0, "+12,345" }, { T_STR, 0, "sexagecimal" }, { T_STR, 0, "3:25:45" }, { T_STR, 0, "octal" }, { T_STR, 0, "014" }, { T_STR, 0, "hexadecimal" }, { T_STR, 0, "0xC" }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "canonical: 12345 \n" "decimal: +12,345 \n" "sexagecimal: 3:25:45\n" "octal: 014 \n" "hexadecimal: 0xC \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.2: Floating point */ void YtsSpecificationExamples_20( CuTest *tc ) { struct test_node map[] = { { T_STR, 0, "canonical" }, { T_STR, 0, "1.23015e+3" }, { T_STR, 0, "exponential" }, { T_STR, 0, "12.3015e+02" }, { T_STR, 0, "sexagecimal" }, { T_STR, 0, "20:30.15" }, { T_STR, 0, "fixed" }, { T_STR, 0, "1,230.15" }, { T_STR, 0, "negative infinity" }, { T_STR, 0, "-.inf" }, { T_STR, 0, "not a number" }, { T_STR, 0, ".NaN" }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "canonical: 1.23015e+3 \n" "exponential: 12.3015e+02 \n" "sexagecimal: 20:30.15\n" "fixed: 1,230.15 \n" "negative infinity: -.inf\n" "not a number: .NaN \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.21: Miscellaneous */ void YtsSpecificationExamples_21( CuTest *tc ) { struct test_node map[] = { { T_STR, 0, "null" }, { T_STR, 0, "~" }, { T_STR, 0, "true" }, { T_STR, 0, "y" }, { T_STR, 0, "false" }, { T_STR, 0, "n" }, { T_STR, 0, "string" }, { T_STR, 0, "12345" }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "null: ~ \n" "true: y\n" "false: n \n" "string: '12345' \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.22: Timestamps */ void YtsSpecificationExamples_22( CuTest *tc ) { struct test_node map[] = { { T_STR, 0, "canonical" }, { T_STR, 0, "2001-12-15T02:59:43.1Z" }, { T_STR, 0, "iso8601" }, { T_STR, 0, "2001-12-14t21:59:43.10-05:00" }, { T_STR, 0, "spaced" }, { T_STR, 0, "2001-12-14 21:59:43.10 -05:00" }, { T_STR, 0, "date" }, { T_STR, 0, "2002-12-14" }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "canonical: 2001-12-15T02:59:43.1Z\n" "iso8601: 2001-12-14t21:59:43.10-05:00\n" "spaced: 2001-12-14 21:59:43.10 -05:00\n" "date: 2002-12-14 # Time is noon UTC\n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example legacy D4: legacy Timestamps test */ void YtsSpecificationExamples_23( CuTest *tc ) { struct test_node map[] = { { T_STR, 0, "canonical" }, { T_STR, 0, "2001-12-15T02:59:43.00Z" }, { T_STR, 0, "iso8601" }, { T_STR, 0, "2001-02-28t21:59:43.00-05:00" }, { T_STR, 0, "spaced" }, { T_STR, 0, "2001-12-14 21:59:43.00 -05:00" }, { T_STR, 0, "date" }, { T_STR, 0, "2002-12-14" }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "canonical: 2001-12-15T02:59:43.00Z\n" "iso8601: 2001-02-28t21:59:43.00-05:00\n" "spaced: 2001-12-14 21:59:43.00 -05:00\n" "date: 2002-12-14\n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.23: Various explicit families */ void YtsSpecificationExamples_24( CuTest *tc ) { struct test_node map[] = { { T_STR, 0, "not-date" }, { T_STR, "tag:yaml.org,2002:str", "2002-04-28" }, { T_STR, 0, "picture" }, { T_STR, "tag:yaml.org,2002:binary", "R0lGODlhDAAMAIQAAP//9/X\n17unp5WZmZgAAAOfn515eXv\nPz7Y6OjuDg4J+fn5OTk6enp\n56enmleECcgggoBADs=\n" }, { T_STR, 0, "application specific tag" }, { T_STR, "x-private:something", "The semantics of the tag\nabove may be different for\ndifferent documents.\n" }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "not-date: !str 2002-04-28\n" "picture: !binary |\n" " R0lGODlhDAAMAIQAAP//9/X\n" " 17unp5WZmZgAAAOfn515eXv\n" " Pz7Y6OjuDg4J+fn5OTk6enp\n" " 56enmleECcgggoBADs=\n" "\n" "application specific tag: !!something |\n" " The semantics of the tag\n" " above may be different for\n" " different documents.\n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.24: Application specific family */ void YtsSpecificationExamples_25( CuTest *tc ) { struct test_node point1[] = { { T_STR, 0, "x" }, { T_STR, 0, "73" }, { T_STR, 0, "y" }, { T_STR, 0, "129" }, end_node }; struct test_node point2[] = { { T_STR, 0, "x" }, { T_STR, 0, "89" }, { T_STR, 0, "y" }, { T_STR, 0, "102" }, end_node }; struct test_node map1[] = { { T_STR, 0, "center" }, { T_MAP, 0, 0, point1 }, { T_STR, 0, "radius" }, { T_STR, 0, "7" }, end_node }; struct test_node map2[] = { { T_STR, 0, "start" }, { T_MAP, 0, 0, point1 }, { T_STR, 0, "finish" }, { T_MAP, 0, 0, point2 }, end_node }; struct test_node map3[] = { { T_STR, 0, "start" }, { T_MAP, 0, 0, point1 }, { T_STR, 0, "color" }, { T_STR, 0, "0xFFEEBB" }, { T_STR, 0, "value" }, { T_STR, 0, "Pretty vector drawing." }, end_node }; struct test_node seq[] = { { T_MAP, "tag:clarkevans.com,2002:graph/circle", 0, map1 }, { T_MAP, "tag:clarkevans.com,2002:graph/line", 0, map2 }, { T_MAP, "tag:clarkevans.com,2002:graph/label", 0, map3 }, end_node }; struct test_node stream[] = { { T_SEQ, "tag:clarkevans.com,2002:graph/shape", 0, seq }, end_node }; CuStreamCompare( tc, /* YAML document */ "# Establish a tag prefix\n" "--- !clarkevans.com,2002/graph/^shape\n" " # Use the prefix: shorthand for\n" " # !clarkevans.com,2002/graph/circle\n" "- !^circle\n" " center: &ORIGIN {x: 73, 'y': 129}\n" " radius: 7\n" "- !^line # !clarkevans.com,2002/graph/line\n" " start: *ORIGIN\n" " finish: { x: 89, 'y': 102 }\n" "- !^label\n" " start: *ORIGIN\n" " color: 0xFFEEBB\n" " value: Pretty vector drawing.\n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.26: Ordered mappings */ void YtsSpecificationExamples_26( CuTest *tc ) { struct test_node map1[] = { { T_STR, 0, "Mark McGwire" }, { T_STR, 0, "65" }, end_node }; struct test_node map2[] = { { T_STR, 0, "Sammy Sosa" }, { T_STR, 0, "63" }, end_node }; struct test_node map3[] = { { T_STR, 0, "Ken Griffy" }, { T_STR, 0, "58" }, end_node }; struct test_node seq[] = { { T_MAP, 0, 0, map1 }, { T_MAP, 0, 0, map2 }, { T_MAP, 0, 0, map3 }, end_node }; struct test_node stream[] = { { T_SEQ, "tag:yaml.org,2002:omap", 0, seq }, end_node }; CuStreamCompare( tc, /* YAML document */ "# ordered maps are represented as\n" "# a sequence of mappings, with\n" "# each mapping having one key\n" "--- !omap\n" "- Mark McGwire: 65\n" "- Sammy Sosa: 63\n" "- Ken Griffy: 58\n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.27: Invoice */ void YtsSpecificationExamples_27( CuTest *tc ) { struct test_node prod1[] = { { T_STR, 0, "sku" }, { T_STR, 0, "BL394D" }, { T_STR, 0, "quantity" }, { T_STR, 0, "4" }, { T_STR, 0, "description" }, { T_STR, 0, "Basketball" }, { T_STR, 0, "price" }, { T_STR, 0, "450.00" }, end_node }; struct test_node prod2[] = { { T_STR, 0, "sku" }, { T_STR, 0, "BL4438H" }, { T_STR, 0, "quantity" }, { T_STR, 0, "1" }, { T_STR, 0, "description" }, { T_STR, 0, "Super Hoop" }, { T_STR, 0, "price" }, { T_STR, 0, "2392.00" }, end_node }; struct test_node products[] = { { T_MAP, 0, 0, prod1 }, { T_MAP, 0, 0, prod2 }, end_node }; struct test_node address[] = { { T_STR, 0, "lines" }, { T_STR, 0, "458 Walkman Dr.\nSuite #292\n" }, { T_STR, 0, "city" }, { T_STR, 0, "Royal Oak" }, { T_STR, 0, "state" }, { T_STR, 0, "MI" }, { T_STR, 0, "postal" }, { T_STR, 0, "48046" }, end_node }; struct test_node id001[] = { { T_STR, 0, "given" }, { T_STR, 0, "Chris" }, { T_STR, 0, "family" }, { T_STR, 0, "Dumars" }, { T_STR, 0, "address" }, { T_MAP, 0, 0, address }, end_node }; struct test_node map[] = { { T_STR, 0, "invoice" }, { T_STR, 0, "34843" }, { T_STR, 0, "date" }, { T_STR, 0, "2001-01-23" }, { T_STR, 0, "bill-to" }, { T_MAP, 0, 0, id001 }, { T_STR, 0, "ship-to" }, { T_MAP, 0, 0, id001 }, { T_STR, 0, "product" }, { T_SEQ, 0, 0, products }, { T_STR, 0, "tax" }, { T_STR, 0, "251.42" }, { T_STR, 0, "total" }, { T_STR, 0, "4443.52" }, { T_STR, 0, "comments" }, { T_STR, 0, "Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338.\n" }, end_node }; struct test_node stream[] = { { T_MAP, "tag:clarkevans.com,2002:invoice", 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "--- !clarkevans.com,2002/^invoice\n" "invoice: 34843\n" "date : 2001-01-23\n" "bill-to: &id001\n" " given : Chris\n" " family : Dumars\n" " address:\n" " lines: |\n" " 458 Walkman Dr.\n" " Suite #292\n" " city : Royal Oak\n" " state : MI\n" " postal : 48046\n" "ship-to: *id001\n" "product:\n" " - sku : BL394D\n" " quantity : 4\n" " description : Basketball\n" " price : 450.00\n" " - sku : BL4438H\n" " quantity : 1\n" " description : Super Hoop\n" " price : 2392.00\n" "tax : 251.42\n" "total: 4443.52\n" "comments: >\n" " Late afternoon is best.\n" " Backup contact is Nancy\n" " Billsmer @ 338-4338.\n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example 2.28: Log file */ void YtsSpecificationExamples_28( CuTest *tc ) { struct test_node map1[] = { { T_STR, 0, "Time" }, { T_STR, 0, "2001-11-23 15:01:42 -05:00" }, { T_STR, 0, "User" }, { T_STR, 0, "ed" }, { T_STR, 0, "Warning" }, { T_STR, 0, "This is an error message for the log file\n" }, end_node }; struct test_node map2[] = { { T_STR, 0, "Time" }, { T_STR, 0, "2001-11-23 15:02:31 -05:00" }, { T_STR, 0, "User" }, { T_STR, 0, "ed" }, { T_STR, 0, "Warning" }, { T_STR, 0, "A slightly different error message.\n" }, end_node }; struct test_node file1[] = { { T_STR, 0, "file" }, { T_STR, 0, "TopClass.py" }, { T_STR, 0, "line" }, { T_STR, 0, "23" }, { T_STR, 0, "code" }, { T_STR, 0, "x = MoreObject(\"345\\n\")\n" }, end_node }; struct test_node file2[] = { { T_STR, 0, "file" }, { T_STR, 0, "MoreClass.py" }, { T_STR, 0, "line" }, { T_STR, 0, "58" }, { T_STR, 0, "code" }, { T_STR, 0, "foo = bar" }, end_node }; struct test_node stack[] = { { T_MAP, 0, 0, file1 }, { T_MAP, 0, 0, file2 }, end_node }; struct test_node map3[] = { { T_STR, 0, "Date" }, { T_STR, 0, "2001-11-23 15:03:17 -05:00" }, { T_STR, 0, "User" }, { T_STR, 0, "ed" }, { T_STR, 0, "Fatal" }, { T_STR, 0, "Unknown variable \"bar\"\n" }, { T_STR, 0, "Stack" }, { T_SEQ, 0, 0, stack }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map1 }, { T_MAP, 0, 0, map2 }, { T_MAP, 0, 0, map3 }, end_node }; CuStreamCompare( tc, /* YAML document */ "---\n" "Time: 2001-11-23 15:01:42 -05:00\n" "User: ed\n" "Warning: >\n" " This is an error message\n" " for the log file\n" "---\n" "Time: 2001-11-23 15:02:31 -05:00\n" "User: ed\n" "Warning: >\n" " A slightly different error\n" " message.\n" "---\n" "Date: 2001-11-23 15:03:17 -05:00\n" "User: ed\n" "Fatal: >\n" " Unknown variable \"bar\"\n" "Stack:\n" " - file: TopClass.py\n" " line: 23\n" " code: |\n" " x = MoreObject(\"345\\n\")\n" " - file: MoreClass.py\n" " line: 58\n" " code: |-\n" " foo = bar\n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example : Throwaway comments */ void YtsSpecificationExamples_29( CuTest *tc ) { struct test_node map[] = { { T_STR, 0, "this" }, { T_STR, 0, "contains three lines of text.\nThe third one starts with a\n# character. This isn't a comment.\n" }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "### These are four throwaway comment ### \n" "\n" "### lines (the second line is empty). ### \n" "this: | # Comments may trail lines.\n" " contains three lines of text.\n" " The third one starts with a\n" " # character. This isn't a comment.\n" "\n" "# These are three throwaway comment\n" "# lines (the first line is empty).\n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example : Document with a single value */ void YtsSpecificationExamples_30( CuTest *tc ) { struct test_node stream[] = { { T_STR, 0, "This YAML stream contains a single text value. The next stream is a log file - a sequence of log entries. Adding an entry to the log is a simple matter of appending it at the end.\n" }, end_node }; CuStreamCompare( tc, /* YAML document */ "--- > \n" "This YAML stream contains a single text value.\n" "The next stream is a log file - a sequence of\n" "log entries. Adding an entry to the log is a\n" "simple matter of appending it at the end.\n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example : Document stream */ void YtsSpecificationExamples_31( CuTest *tc ) { struct test_node map1[] = { { T_STR, 0, "at" }, { T_STR, 0, "2001-08-12 09:25:00.00 Z" }, { T_STR, 0, "type" }, { T_STR, 0, "GET" }, { T_STR, 0, "HTTP" }, { T_STR, 0, "1.0" }, { T_STR, 0, "url" }, { T_STR, 0, "/index.html" }, end_node }; struct test_node map2[] = { { T_STR, 0, "at" }, { T_STR, 0, "2001-08-12 09:25:10.00 Z" }, { T_STR, 0, "type" }, { T_STR, 0, "GET" }, { T_STR, 0, "HTTP" }, { T_STR, 0, "1.0" }, { T_STR, 0, "url" }, { T_STR, 0, "/toc.html" }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map1 }, { T_MAP, 0, 0, map2 }, end_node }; CuStreamCompare( tc, /* YAML document */ "--- \n" "at: 2001-08-12 09:25:00.00 Z \n" "type: GET \n" "HTTP: '1.0' \n" "url: '/index.html' \n" "--- \n" "at: 2001-08-12 09:25:10.00 Z \n" "type: GET \n" "HTTP: '1.0' \n" "url: '/toc.html' \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example : Top level mapping */ void YtsSpecificationExamples_32( CuTest *tc ) { struct test_node map[] = { { T_STR, 0, "invoice" }, { T_STR, 0, "34843" }, { T_STR, 0, "date" }, { T_STR, 0, "2001-01-23" }, { T_STR, 0, "total" }, { T_STR, 0, "4443.52" }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "# This stream is an example of a top-level mapping. \n" "invoice : 34843 \n" "date : 2001-01-23 \n" "total : 4443.52 \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example : Single-line documents */ void YtsSpecificationExamples_33( CuTest *tc ) { struct test_node map[] = { end_node }; struct test_node seq[] = { end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, { T_SEQ, 0, 0, seq }, { T_STR, 0, "" }, end_node }; CuStreamCompare( tc, /* YAML document */ "# The following is a sequence of three documents. \n" "# The first contains an empty mapping, the second \n" "# an empty sequence, and the last an empty string. \n" "--- {} \n" "--- [ ] \n" "--- '' \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example : Document with pause */ void YtsSpecificationExamples_34( CuTest *tc ) { struct test_node map1[] = { { T_STR, 0, "sent at" }, { T_STR, 0, "2002-06-06 11:46:25.10 Z" }, { T_STR, 0, "payload" }, { T_STR, 0, "Whatever" }, end_node }; struct test_node map2[] = { { T_STR, 0, "sent at" }, { T_STR, 0, "2002-06-06 12:05:53.47 Z" }, { T_STR, 0, "payload" }, { T_STR, 0, "Whatever" }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map1 }, { T_MAP, 0, 0, map2 }, end_node }; CuStreamCompare( tc, /* YAML document */ "# A communication channel based on a YAML stream. \n" "--- \n" "sent at: 2002-06-06 11:46:25.10 Z \n" "payload: Whatever \n" "# Receiver can process this as soon as the following is sent: \n" "... \n" "# Even if the next message is sent long after: \n" "--- \n" "sent at: 2002-06-06 12:05:53.47 Z \n" "payload: Whatever \n" "... \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example : Explicit typing */ void YtsSpecificationExamples_35( CuTest *tc ) { struct test_node map[] = { { T_STR, 0, "integer" }, { T_STR, "tag:yaml.org,2002:int", "12" }, { T_STR, 0, "also int" }, { T_STR, "tag:yaml.org,2002:int", "12" }, { T_STR, 0, "string" }, { T_STR, "tag:yaml.org,2002:str", "12" }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "integer: 12 \n" "also int: ! \"12\" \n" "string: !str 12 \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example : Private types */ void YtsSpecificationExamples_36( CuTest *tc ) { struct test_node pool[] = { { T_STR, 0, "number" }, { T_STR, 0, "8" }, { T_STR, 0, "color" }, { T_STR, 0, "black" }, end_node }; struct test_node map1[] = { { T_STR, 0, "pool" }, { T_MAP, "x-private:ball", 0, pool }, end_node }; struct test_node bearing[] = { { T_STR, 0, "material" }, { T_STR, 0, "steel" }, end_node }; struct test_node map2[] = { { T_STR, 0, "bearing" }, { T_MAP, "x-private:ball", 0, bearing }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map1 }, { T_MAP, 0, 0, map2 }, end_node }; CuStreamCompare( tc, /* YAML document */ "# Both examples below make use of the 'x-private:ball' \n" "# type family URI, but with different semantics. \n" "--- \n" "pool: !!ball \n" " number: 8 \n" " color: black \n" "--- \n" "bearing: !!ball \n" " material: steel \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example : Type family under yaml.org */ void YtsSpecificationExamples_37( CuTest *tc ) { struct test_node seq[] = { { T_STR, "tag:yaml.org,2002:str", "a Unicode string" }, end_node }; struct test_node stream[] = { { T_SEQ, 0, 0, seq }, end_node }; CuStreamCompare( tc, /* YAML document */ "# The URI is 'tag:yaml.org,2002:str' \n" "- !str a Unicode string \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example : Type family under perl.yaml.org */ void YtsSpecificationExamples_38( CuTest *tc ) { struct test_node map[] = { end_node }; struct test_node seq[] = { { T_MAP, "tag:perl.yaml.org,2002:Text::Tabs", 0, map }, end_node }; struct test_node stream[] = { { T_SEQ, 0, 0, seq }, end_node }; CuStreamCompare( tc, /* YAML document */ "# The URI is 'tag:perl.yaml.org,2002:Text::Tabs' \n" "- !perl/Text::Tabs {} \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example : Type family under clarkevans.com */ void YtsSpecificationExamples_39( CuTest *tc ) { struct test_node map[] = { end_node }; struct test_node seq[] = { { T_MAP, "tag:clarkevans.com,2003-02:timesheet", 0, map }, end_node }; struct test_node stream[] = { { T_SEQ, 0, 0, seq }, end_node }; CuStreamCompare( tc, /* YAML document */ "# The URI is 'tag:clarkevans.com,2003-02:timesheet' \n" "- !clarkevans.com,2003-02/timesheet {}\n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example : URI Escaping */ void YtsSpecificationExamples_40( CuTest *tc ) { struct test_node same[] = { { T_STR, "tag:domain.tld,2002:type0", "value" }, { T_STR, "tag:domain.tld,2002:type0", "value" }, end_node }; struct test_node diff[] = { { T_STR, "tag:domain.tld,2002:type%30", "value" }, { T_STR, "tag:domain.tld,2002:type0", "value" }, end_node }; struct test_node map[] = { { T_STR, 0, "same" }, { T_SEQ, 0, 0, same }, { T_STR, 0, "different" }, { T_SEQ, 0, 0, diff }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "same: \n" " - !domain.tld,2002/type\\x30 value\n" " - !domain.tld,2002/type0 value\n" "different: # As far as the YAML parser is concerned \n" " - !domain.tld,2002/type%30 value\n" " - !domain.tld,2002/type0 value\n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example : Overriding anchors */ void YtsSpecificationExamples_42( CuTest *tc ) { struct test_node map[] = { { T_STR, 0, "anchor" }, { T_STR, 0, "This scalar has an anchor." }, { T_STR, 0, "override" }, { T_STR, 0, "The alias node below is a repeated use of this value.\n" }, { T_STR, 0, "alias" }, { T_STR, 0, "The alias node below is a repeated use of this value.\n" }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "anchor : &A001 This scalar has an anchor. \n" "override : &A001 >\n" " The alias node below is a\n" " repeated use of this value.\n" "alias : *A001\n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example : Flow and block formatting */ void YtsSpecificationExamples_43( CuTest *tc ) { struct test_node empty[] = { end_node }; struct test_node flow[] = { { T_STR, 0, "one" }, { T_STR, 0, "two" }, { T_STR, 0, "three" }, { T_STR, 0, "four" }, { T_STR, 0, "five" }, end_node }; struct test_node inblock[] = { { T_STR, 0, "Subordinate sequence entry" }, end_node }; struct test_node block[] = { { T_STR, 0, "First item in top sequence" }, { T_SEQ, 0, 0, inblock }, { T_STR, 0, "A folded sequence entry\n" }, { T_STR, 0, "Sixth item in top sequence" }, end_node }; struct test_node map[] = { { T_STR, 0, "empty" }, { T_SEQ, 0, 0, empty }, { T_STR, 0, "flow" }, { T_SEQ, 0, 0, flow }, { T_STR, 0, "block" }, { T_SEQ, 0, 0, block }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "empty: [] \n" "flow: [ one, two, three # May span lines, \n" " , four, # indentation is \n" " five ] # mostly ignored. \n" "block: \n" " - First item in top sequence \n" " - \n" " - Subordinate sequence entry \n" " - > \n" " A folded sequence entry\n" " - Sixth item in top sequence \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example : Literal combinations */ void YtsSpecificationExamples_47( CuTest *tc ) { struct test_node map[] = { { T_STR, 0, "empty" }, { T_STR, 0, "" }, { T_STR, 0, "literal" }, { T_STR, 0, "The \\ ' \" characters may be\nfreely used. Leading white\n space " "is significant.\n\nLine breaks are significant.\nThus this value contains one\n" "empty line and ends with a\nsingle line break, but does\nnot start with one.\n" }, { T_STR, 0, "is equal to" }, { T_STR, 0, "The \\ ' \" characters may be\nfreely used. Leading white\n space " "is significant.\n\nLine breaks are significant.\nThus this value contains one\n" "empty line and ends with a\nsingle line break, but does\nnot start with one.\n" }, { T_STR, 0, "indented and chomped" }, { T_STR, 0, " This has no newline." }, { T_STR, 0, "also written as" }, { T_STR, 0, " This has no newline." }, { T_STR, 0, "both are equal to" }, { T_STR, 0, " This has no newline." }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "empty: |\n" "\n" "literal: |\n" " The \\ ' \" characters may be\n" " freely used. Leading white\n" " space is significant.\n" "\n" " Line breaks are significant.\n" " Thus this value contains one\n" " empty line and ends with a\n" " single line break, but does\n" " not start with one.\n" "\n" "is equal to: \"The \\\\ ' \\\" characters may \\\n" " be\\nfreely used. Leading white\\n space \\\n" " is significant.\\n\\nLine breaks are \\\n" " significant.\\nThus this value contains \\\n" " one\\nempty line and ends with a\\nsingle \\\n" " line break, but does\\nnot start with one.\\n\"\n" "\n" "# Comments may follow a block \n" "# scalar value. They must be \n" "# less indented. \n" "\n" "# Modifiers may be combined in any order.\n" "indented and chomped: |2-\n" " This has no newline.\n" "\n" "also written as: |-2\n" " This has no newline.\n" "\n" "both are equal to: \" This has no newline.\"\n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } /* * Example : Timestamp */ void YtsSpecificationExamples_62( CuTest *tc ) { struct test_node map[] = { { T_STR, 0, "canonical" }, { T_STR, 0, "2001-12-15T02:59:43.1Z" }, { T_STR, 0, "valid iso8601" }, { T_STR, 0, "2001-12-14t21:59:43.10-05:00" }, { T_STR, 0, "space separated" }, { T_STR, 0, "2001-12-14 21:59:43.10 -05:00" }, { T_STR, 0, "date (noon UTC)" }, { T_STR, 0, "2002-12-14" }, end_node }; struct test_node stream[] = { { T_MAP, 0, 0, map }, end_node }; CuStreamCompare( tc, /* YAML document */ "canonical: 2001-12-15T02:59:43.1Z \n" "valid iso8601: 2001-12-14t21:59:43.10-05:00 \n" "space separated: 2001-12-14 21:59:43.10 -05:00 \n" "date (noon UTC): 2002-12-14 \n" , /* C structure of validations */ stream ); CuRoundTrip( tc, stream ); } CuSuite * SyckGetSuite() { CuSuite *suite = CuSuiteNew(); SUITE_ADD_TEST( suite, YtsFoldedScalars_7 ); SUITE_ADD_TEST( suite, YtsNullsAndEmpties_0 ); SUITE_ADD_TEST( suite, YtsNullsAndEmpties_1 ); SUITE_ADD_TEST( suite, YtsNullsAndEmpties_2 ); SUITE_ADD_TEST( suite, YtsNullsAndEmpties_3 ); SUITE_ADD_TEST( suite, YtsNullsAndEmpties_4 ); SUITE_ADD_TEST( suite, YtsNullsAndEmpties_5 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_0 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_1 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_2 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_3 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_4 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_5 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_6 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_7 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_8 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_9 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_10 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_11 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_12 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_13 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_14 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_15 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_16 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_18 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_19 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_20 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_21 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_22 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_23 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_24 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_25 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_26 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_27 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_28 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_29 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_30 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_31 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_32 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_33 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_34 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_35 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_36 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_37 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_38 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_39 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_40 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_42 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_43 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_47 ); SUITE_ADD_TEST( suite, YtsSpecificationExamples_62 ); return suite; } int main(void) { CuString *output = CuStringNew(); CuSuite* suite = SyckGetSuite(); int count; CuSuiteRun(suite); CuSuiteSummary(suite, output); CuSuiteDetails(suite, output); printf("%s\n", output->buffer); count = suite->failCount; CuStringFree( output ); CuSuiteFree( suite ); return count; }
Java
/*---------------------------------------------------------------------------*\ * OpenSG * * * * * * Copyright (C) 2000-2013 by the OpenSG Forum * * * * www.opensg.org * * * * contact: dirk@opensg.org, gerrit.voss@vossg.org, carsten_neumann@gmx.net * * * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * License * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Library General Public License as published * * by the Free Software Foundation, version 2. * * * * This library is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * Changes * * * * * * * * * * * * * \*---------------------------------------------------------------------------*/ /*****************************************************************************\ ***************************************************************************** ** ** ** This file is automatically generated. ** ** ** ** Any changes made to this file WILL be lost when it is ** ** regenerated, which can become necessary at any time. ** ** ** ** Do not change this file, changes should be done in the derived ** ** class TextureBackground ** ** ***************************************************************************** \*****************************************************************************/ #ifndef _OSGTEXTUREBACKGROUNDBASE_H_ #define _OSGTEXTUREBACKGROUNDBASE_H_ #ifdef __sgi #pragma once #endif #include "OSGConfig.h" #include "OSGWindowDef.h" //#include "OSGBaseTypes.h" #include "OSGBackground.h" // Parent #include "OSGBaseFields.h" // Color type #include "OSGTextureBaseChunkFields.h" // Texture type #include "OSGVecFields.h" // TexCoords type #include "OSGSysFields.h" // RadialDistortion type #include "OSGTextureBackgroundFields.h" OSG_BEGIN_NAMESPACE class TextureBackground; //! \brief TextureBackground Base Class. class OSG_WINDOW_DLLMAPPING TextureBackgroundBase : public Background { public: typedef Background Inherited; typedef Background ParentContainer; typedef Inherited::TypeObject TypeObject; typedef TypeObject::InitPhase InitPhase; OSG_GEN_INTERNALPTR(TextureBackground); /*========================== PUBLIC =================================*/ public: enum { ColorFieldId = Inherited::NextFieldId, TextureFieldId = ColorFieldId + 1, TexCoordsFieldId = TextureFieldId + 1, RadialDistortionFieldId = TexCoordsFieldId + 1, CenterOfDistortionFieldId = RadialDistortionFieldId + 1, HorFieldId = CenterOfDistortionFieldId + 1, VertFieldId = HorFieldId + 1, NextFieldId = VertFieldId + 1 }; static const OSG::BitVector ColorFieldMask = (TypeTraits<BitVector>::One << ColorFieldId); static const OSG::BitVector TextureFieldMask = (TypeTraits<BitVector>::One << TextureFieldId); static const OSG::BitVector TexCoordsFieldMask = (TypeTraits<BitVector>::One << TexCoordsFieldId); static const OSG::BitVector RadialDistortionFieldMask = (TypeTraits<BitVector>::One << RadialDistortionFieldId); static const OSG::BitVector CenterOfDistortionFieldMask = (TypeTraits<BitVector>::One << CenterOfDistortionFieldId); static const OSG::BitVector HorFieldMask = (TypeTraits<BitVector>::One << HorFieldId); static const OSG::BitVector VertFieldMask = (TypeTraits<BitVector>::One << VertFieldId); static const OSG::BitVector NextFieldMask = (TypeTraits<BitVector>::One << NextFieldId); typedef SFColor4f SFColorType; typedef SFUnrecTextureBaseChunkPtr SFTextureType; typedef MFPnt2f MFTexCoordsType; typedef SFReal32 SFRadialDistortionType; typedef SFVec2f SFCenterOfDistortionType; typedef SFUInt16 SFHorType; typedef SFUInt16 SFVertType; /*---------------------------------------------------------------------*/ /*! \name Class Get */ /*! \{ */ static FieldContainerType &getClassType (void); static UInt32 getClassTypeId (void); static UInt16 getClassGroupId(void); /*! \} */ /*---------------------------------------------------------------------*/ /*! \name FieldContainer Get */ /*! \{ */ virtual FieldContainerType &getType (void); virtual const FieldContainerType &getType (void) const; virtual UInt32 getContainerSize(void) const; /*! \} */ /*---------------------------------------------------------------------*/ /*! \name Field Get */ /*! \{ */ SFColor4f *editSFColor (void); const SFColor4f *getSFColor (void) const; const SFUnrecTextureBaseChunkPtr *getSFTexture (void) const; SFUnrecTextureBaseChunkPtr *editSFTexture (void); MFPnt2f *editMFTexCoords (void); const MFPnt2f *getMFTexCoords (void) const; SFReal32 *editSFRadialDistortion(void); const SFReal32 *getSFRadialDistortion (void) const; SFVec2f *editSFCenterOfDistortion(void); const SFVec2f *getSFCenterOfDistortion (void) const; SFUInt16 *editSFHor (void); const SFUInt16 *getSFHor (void) const; SFUInt16 *editSFVert (void); const SFUInt16 *getSFVert (void) const; Color4f &editColor (void); const Color4f &getColor (void) const; TextureBaseChunk * getTexture (void) const; MFPnt2f ::reference editTexCoords (const UInt32 index); const Pnt2f &getTexCoords (const UInt32 index) const; Real32 &editRadialDistortion(void); Real32 getRadialDistortion (void) const; Vec2f &editCenterOfDistortion(void); const Vec2f &getCenterOfDistortion (void) const; UInt16 &editHor (void); UInt16 getHor (void) const; UInt16 &editVert (void); UInt16 getVert (void) const; /*! \} */ /*---------------------------------------------------------------------*/ /*! \name Field Set */ /*! \{ */ void setColor (const Color4f &value); void setTexture (TextureBaseChunk * const value); void setRadialDistortion(const Real32 value); void setCenterOfDistortion(const Vec2f &value); void setHor (const UInt16 value); void setVert (const UInt16 value); /*! \} */ /*---------------------------------------------------------------------*/ /*! \name Ptr Field Set */ /*! \{ */ /*! \} */ /*---------------------------------------------------------------------*/ /*! \name Ptr MField Set */ /*! \{ */ /*! \} */ /*---------------------------------------------------------------------*/ /*! \name Binary Access */ /*! \{ */ virtual SizeT getBinSize (ConstFieldMaskArg whichField); virtual void copyToBin (BinaryDataHandler &pMem, ConstFieldMaskArg whichField); virtual void copyFromBin(BinaryDataHandler &pMem, ConstFieldMaskArg whichField); /*! \} */ /*---------------------------------------------------------------------*/ /*! \name Construction */ /*! \{ */ static TextureBackgroundTransitPtr create (void); static TextureBackground *createEmpty (void); static TextureBackgroundTransitPtr createLocal ( BitVector bFlags = FCLocal::All); static TextureBackground *createEmptyLocal( BitVector bFlags = FCLocal::All); static TextureBackgroundTransitPtr createDependent (BitVector bFlags); /*! \} */ /*---------------------------------------------------------------------*/ /*! \name Copy */ /*! \{ */ virtual FieldContainerTransitPtr shallowCopy (void) const; virtual FieldContainerTransitPtr shallowCopyLocal( BitVector bFlags = FCLocal::All) const; virtual FieldContainerTransitPtr shallowCopyDependent( BitVector bFlags) const; /*! \} */ /*========================= PROTECTED ===============================*/ protected: static TypeObject _type; static void classDescInserter(TypeObject &oType); static const Char8 *getClassname (void ); /*---------------------------------------------------------------------*/ /*! \name Fields */ /*! \{ */ SFColor4f _sfColor; SFUnrecTextureBaseChunkPtr _sfTexture; MFPnt2f _mfTexCoords; SFReal32 _sfRadialDistortion; SFVec2f _sfCenterOfDistortion; SFUInt16 _sfHor; SFUInt16 _sfVert; /*! \} */ /*---------------------------------------------------------------------*/ /*! \name Constructors */ /*! \{ */ TextureBackgroundBase(void); TextureBackgroundBase(const TextureBackgroundBase &source); /*! \} */ /*---------------------------------------------------------------------*/ /*! \name Destructors */ /*! \{ */ virtual ~TextureBackgroundBase(void); /*! \} */ /*---------------------------------------------------------------------*/ /*! \name onCreate */ /*! \{ */ void onCreate(const TextureBackground *source = NULL); /*! \} */ /*---------------------------------------------------------------------*/ /*! \name Generic Field Access */ /*! \{ */ GetFieldHandlePtr getHandleColor (void) const; EditFieldHandlePtr editHandleColor (void); GetFieldHandlePtr getHandleTexture (void) const; EditFieldHandlePtr editHandleTexture (void); GetFieldHandlePtr getHandleTexCoords (void) const; EditFieldHandlePtr editHandleTexCoords (void); GetFieldHandlePtr getHandleRadialDistortion (void) const; EditFieldHandlePtr editHandleRadialDistortion(void); GetFieldHandlePtr getHandleCenterOfDistortion (void) const; EditFieldHandlePtr editHandleCenterOfDistortion(void); GetFieldHandlePtr getHandleHor (void) const; EditFieldHandlePtr editHandleHor (void); GetFieldHandlePtr getHandleVert (void) const; EditFieldHandlePtr editHandleVert (void); /*! \} */ /*---------------------------------------------------------------------*/ /*! \name Sync */ /*! \{ */ #ifdef OSG_MT_CPTR_ASPECT virtual void execSyncV( FieldContainer &oFrom, ConstFieldMaskArg whichField, AspectOffsetStore &oOffsets, ConstFieldMaskArg syncMode , const UInt32 uiSyncInfo); void execSync ( TextureBackgroundBase *pFrom, ConstFieldMaskArg whichField, AspectOffsetStore &oOffsets, ConstFieldMaskArg syncMode , const UInt32 uiSyncInfo); #endif /*! \} */ /*---------------------------------------------------------------------*/ /*! \name Edit */ /*! \{ */ /*! \} */ /*---------------------------------------------------------------------*/ /*! \name Aspect Create */ /*! \{ */ #ifdef OSG_MT_CPTR_ASPECT virtual FieldContainer *createAspectCopy( const FieldContainer *pRefAspect) const; #endif /*! \} */ /*---------------------------------------------------------------------*/ /*! \name Edit */ /*! \{ */ /*! \} */ /*---------------------------------------------------------------------*/ /*! \name Sync */ /*! \{ */ virtual void resolveLinks(void); /*! \} */ /*========================== PRIVATE ================================*/ private: /*---------------------------------------------------------------------*/ // prohibit default functions (move to 'public' if you need one) void operator =(const TextureBackgroundBase &source); }; typedef TextureBackgroundBase *TextureBackgroundBaseP; OSG_END_NAMESPACE #endif /* _OSGTEXTUREBACKGROUNDBASE_H_ */
Java
# Makefile.in generated by automake 1.10.1 from Makefile.am. # gconf/GConf/Makefile. Generated from Makefile.in by configure. # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, # 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. pkgdatadir = $(datadir)/gnome-sharp pkglibdir = $(libdir)/gnome-sharp pkgincludedir = $(includedir)/gnome-sharp am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = x86_64-unknown-linux-gnu host_triplet = x86_64-unknown-linux-gnu target_triplet = x86_64-unknown-linux-gnu subdir = gconf/GConf DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in \ $(srcdir)/gconf-sharp-2.0.pc.in \ $(srcdir)/gconf-sharp.dll.config.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/configure.in am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = gconf-sharp.dll.config gconf-sharp-2.0.pc SOURCES = DIST_SOURCES = am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = `echo $$p | sed -e 's|^.*/||'`; am__installdirs = "$(DESTDIR)$(pkgconfigdir)" pkgconfigDATA_INSTALL = $(INSTALL_DATA) DATA = $(noinst_DATA) $(pkgconfig_DATA) DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = ${SHELL} /usr/local/src/gnome-sharp-2.24.1/missing --run aclocal-1.10 AL = /usr/local/bin/al AMTAR = ${SHELL} /usr/local/src/gnome-sharp-2.24.1/missing --run tar API_VERSION = 2.24.0.0 AR = ar AS = as AUTOCONF = ${SHELL} /usr/local/src/gnome-sharp-2.24.1/missing --run autoconf AUTOHEADER = ${SHELL} /usr/local/src/gnome-sharp-2.24.1/missing --run autoheader AUTOMAKE = ${SHELL} /usr/local/src/gnome-sharp-2.24.1/missing --run automake-1.10 AWK = gawk BUILD_EXEEXT = BUILD_GTK_CFLAGS = -pthread -I/usr/include/gtk-2.0 -I/usr/lib64/gtk-2.0/include -I/usr/include/atk-1.0 -I/usr/include/cairo -I/usr/include/gdk-pixbuf-2.0 -I/usr/include/pango-1.0 -I/usr/include/glib-2.0 -I/usr/lib64/glib-2.0/include -I/usr/include/pixman-1 -I/usr/include/freetype2 -I/usr/include/libpng15 -I/usr/include/libdrm -I/usr/include/harfbuzz BUILD_GTK_LIBS = -lgtk-x11-2.0 -lgdk-x11-2.0 -latk-1.0 -lgio-2.0 -lpangoft2-1.0 -lpangocairo-1.0 -lgdk_pixbuf-2.0 -lcairo -lpango-1.0 -lfontconfig -lgobject-2.0 -lglib-2.0 -lfreetype CC = gcc CCDEPMODE = depmode=gcc3 CC_FOR_BUILD = gcc CFLAGS = -g -Wall -Wunused -Wmissing-prototypes -Wmissing-declarations -Wstrict-prototypes -Wmissing-prototypes -Wnested-externs -Wshadow -Wpointer-arith -Wno-cast-qual -Wcast-align -Wwrite-strings CPP = gcc -E CPPFLAGS = CSC = /usr/local/bin/mcs CSFLAGS = -define:GTK_SHARP_2_6 -define:GTK_SHARP_2_8 -define:GNOME_SHARP_2_16 -define:GNOME_SHARP_2_20 -define:GNOME_SHARP_2_24 CXX = g++ CXXCPP = g++ -E CXXDEPMODE = depmode=gcc3 CXXFLAGS = -g -O2 CYGPATH_W = echo DEFS = -DHAVE_CONFIG_H DEPDIR = .deps DLLTOOL = dlltool DSYMUTIL = ECHO = echo ECHO_C = ECHO_N = -n ECHO_T = EGREP = /usr/bin/grep -E EXEEXT = F77 = FFLAGS = GACUTIL = /usr/local/bin/gacutil GACUTIL_FLAGS = /package $(PACKAGE_VERSION) /gacdir $(DESTDIR)$(prefix)/lib GAPI_CFLAGS = GAPI_CODEGEN = /usr/local/bin/gapi2-codegen GAPI_FIXUP = /usr/local/bin/gapi2-fixup GAPI_LIBS = GAPI_PARSER = /usr/local/bin/gapi2-parser GENERATED_SOURCES = generated/*.cs GLADESHARP_CFLAGS = -I:/usr/local/lib/pkgconfig/../../share/gapi-2.0/glade-api.xml -I:/usr/local/lib/pkgconfig/../../share/gapi-2.0/pango-api.xml -I:/usr/local/lib/pkgconfig/../../share/gapi-2.0/atk-api.xml -I:/usr/local/lib/pkgconfig/../../share/gapi-2.0/gdk-api.xml -I:/usr/local/lib/pkgconfig/../../share/gapi-2.0/gtk-api.xml -I:/usr/local/lib/pkgconfig/../../share/gapi-2.0/glib-api.xml GLADESHARP_LIBS = -r:/usr/local/lib/pkgconfig/../../lib/mono/gtk-sharp-2.0/glade-sharp.dll -r:/usr/local/lib/pkgconfig/../../lib/mono/gtk-sharp-2.0/pango-sharp.dll -r:/usr/local/lib/pkgconfig/../../lib/mono/gtk-sharp-2.0/atk-sharp.dll -r:/usr/local/lib/pkgconfig/../../lib/mono/gtk-sharp-2.0/gdk-sharp.dll -r:/usr/local/lib/pkgconfig/../../lib/mono/gtk-sharp-2.0/gtk-sharp.dll -r:/usr/local/lib/pkgconfig/../../lib/mono/gtk-sharp-2.0/glib-sharp.dll GNOMEVFS_CFLAGS = -pthread -I/usr/include/gnome-vfs-2.0 -I/usr/lib64/gnome-vfs-2.0/include -I/usr/include/gconf/2 -I/usr/include/dbus-1.0 -I/usr/lib64/dbus-1.0/include -I/usr/include/glib-2.0 -I/usr/lib64/glib-2.0/include GNOMEVFS_LIBS = -pthread -lgnomevfs-2 -lgconf-2 -lgthread-2.0 -lgmodule-2.0 -lgobject-2.0 -lglib-2.0 GNOME_CFLAGS = -pthread -DORBIT2=1 -D_REENTRANT -I/usr/include/libgnomecanvas-2.0 -I/usr/include/pango-1.0 -I/usr/include/gail-1.0 -I/usr/include/libart-2.0 -I/usr/include/gtk-2.0 -I/usr/include/glib-2.0 -I/usr/lib64/glib-2.0/include -I/usr/include/harfbuzz -I/usr/include/freetype2 -I/usr/include/atk-1.0 -I/usr/lib64/gtk-2.0/include -I/usr/include/cairo -I/usr/include/gdk-pixbuf-2.0 -I/usr/include/pixman-1 -I/usr/include/libpng15 -I/usr/include/libdrm -I/usr/include/libgnomeui-2.0 -I/usr/include/gconf/2 -I/usr/include/gnome-keyring-1 -I/usr/include/libgnome-2.0 -I/usr/include/libbonoboui-2.0 -I/usr/include/gnome-vfs-2.0 -I/usr/lib64/gnome-vfs-2.0/include -I/usr/include/dbus-1.0 -I/usr/lib64/dbus-1.0/include -I/usr/include/orbit-2.0 -I/usr/include/libbonobo-2.0 -I/usr/include/bonobo-activation-2.0 -I/usr/include/libxml2 GNOME_LIBS = -pthread -Wl,--export-dynamic -lgnomeui-2 -lSM -lICE -lbonoboui-2 -lgnomevfs-2 -lgnomecanvas-2 -lgnome-2 -lpopt -lbonobo-2 -lbonobo-activation -lORBit-2 -lart_lgpl_2 -lgconf-2 -lgthread-2.0 -lgtk-x11-2.0 -lgdk-x11-2.0 -latk-1.0 -lgio-2.0 -lpangoft2-1.0 -lpangocairo-1.0 -lgdk_pixbuf-2.0 -lcairo -lpango-1.0 -lfontconfig -lgobject-2.0 -lfreetype -lgmodule-2.0 -lglib-2.0 GREP = /usr/bin/grep GTKSHARP_CFLAGS = -I:/usr/local/lib/pkgconfig/../../share/gapi-2.0/pango-api.xml -I:/usr/local/lib/pkgconfig/../../share/gapi-2.0/atk-api.xml -I:/usr/local/lib/pkgconfig/../../share/gapi-2.0/gdk-api.xml -I:/usr/local/lib/pkgconfig/../../share/gapi-2.0/gtk-api.xml -I:/usr/local/lib/pkgconfig/../../share/gapi-2.0/glib-api.xml GTKSHARP_LIBS = -r:/usr/local/lib/pkgconfig/../../lib/mono/gtk-sharp-2.0/pango-sharp.dll -r:/usr/local/lib/pkgconfig/../../lib/mono/gtk-sharp-2.0/atk-sharp.dll -r:/usr/local/lib/pkgconfig/../../lib/mono/gtk-sharp-2.0/gdk-sharp.dll -r:/usr/local/lib/pkgconfig/../../lib/mono/gtk-sharp-2.0/gtk-sharp.dll -r:/usr/local/lib/pkgconfig/../../lib/mono/gtk-sharp-2.0/glib-sharp.dll GTK_SHARP_VERSION_CFLAGS = -DGTK_SHARP_2_6 -DGTK_SHARP_2_8 -DGNOME_SHARP_2_16 -DGNOME_SHARP_2_20 -DGNOME_SHARP_2_24 HOST_CC = INSTALL = /usr/bin/install -c INSTALL_DATA = ${INSTALL} -m 644 INSTALL_PROGRAM = ${INSTALL} INSTALL_SCRIPT = ${INSTALL} INSTALL_STRIP_PROGRAM = $(install_sh) -c -s LDFLAGS = LIBART_CFLAGS = -I/usr/include/libart-2.0 LIBART_LIBS = -lart_lgpl_2 LIBOBJS = LIBS = LIBTOOL = $(SHELL) $(top_builddir)/libtool LIB_PREFIX = .so LIB_SUFFIX = LN_S = ln -s LTLIBOBJS = MAINT = # MAKEINFO = ${SHELL} /usr/local/src/gnome-sharp-2.24.1/missing --run makeinfo MKDIR_P = /usr/bin/mkdir -p MONO_CAIRO_CFLAGS = MONO_CAIRO_LIBS = -r:Mono.Cairo MONO_DEPENDENCY_CFLAGS = MONO_DEPENDENCY_LIBS = NMEDIT = OBJDUMP = objdump OBJEXT = o PACKAGE = gnome-sharp PACKAGE_BUGREPORT = PACKAGE_NAME = PACKAGE_STRING = PACKAGE_TARNAME = PACKAGE_VERSION = gtk-sharp-2.0 PATH_SEPARATOR = : PKG_CONFIG = /usr/bin/pkg-config POLICY_VERSIONS = 2.4 2.6 2.8 2.16 2.20 RANLIB = ranlib RUNTIME = mono SED = /usr/bin/sed SET_MAKE = SHELL = /bin/sh STRIP = strip VERSION = 2.24.1 abs_builddir = /usr/local/src/gnome-sharp-2.24.1/gconf/GConf abs_srcdir = /usr/local/src/gnome-sharp-2.24.1/gconf/GConf abs_top_builddir = /usr/local/src/gnome-sharp-2.24.1 abs_top_srcdir = /usr/local/src/gnome-sharp-2.24.1 ac_ct_CC = gcc ac_ct_CXX = g++ ac_ct_F77 = am__include = include am__leading_dot = . am__quote = am__tar = ${AMTAR} chof - "$$tardir" am__untar = ${AMTAR} xf - bindir = ${exec_prefix}/bin build = x86_64-unknown-linux-gnu build_alias = build_cpu = x86_64 build_os = linux-gnu build_vendor = unknown builddir = . datadir = ${datarootdir} datarootdir = ${prefix}/share docdir = ${datarootdir}/doc/${PACKAGE} dvidir = ${docdir} exec_prefix = ${prefix} host = x86_64-unknown-linux-gnu host_alias = host_cpu = x86_64 host_os = linux-gnu host_vendor = unknown htmldir = ${docdir} includedir = ${prefix}/include infodir = ${datarootdir}/info install_sh = $(SHELL) /usr/local/src/gnome-sharp-2.24.1/install-sh libdir = ${exec_prefix}/lib libexecdir = ${exec_prefix}/libexec localedir = ${datarootdir}/locale localstatedir = ${prefix}/var mandir = ${datarootdir}/man mkdir_p = /usr/bin/mkdir -p oldincludedir = /usr/include pdfdir = ${docdir} prefix = /usr/local program_transform_name = s,x,x, psdir = ${docdir} sbindir = ${exec_prefix}/sbin sharedstatedir = ${prefix}/com srcdir = . sysconfdir = ${prefix}/etc target = x86_64-unknown-linux-gnu target_alias = target_cpu = x86_64 target_os = linux-gnu target_vendor = unknown top_build_prefix = ../../ top_builddir = ../.. top_srcdir = ../.. TARGET = $(ASSEMBLY) $(ASSEMBLY).config pkgconfigdir = $(libdir)/pkgconfig pkgconfig_DATA = gconf-sharp-2.0.pc noinst_DATA = $(TARGET) $(POLICY_ASSEMBLIES) CLEANFILES = $(ASSEMBLY) $(ASSEMBLY).mdb gtk-sharp.snk AssemblyInfo.cs $(POLICY_ASSEMBLIES) $(POLICY_CONFIGS) DISTCLEANFILES = gconf-sharp-2.0.pc $(ASSEMBLY).config POLICY_ASSEMBLIES = $(addsuffix .$(ASSEMBLY), $(addprefix policy., $(POLICY_VERSIONS))) POLICY_CONFIGS = $(addsuffix .config, $(addprefix policy., $(POLICY_VERSIONS))) ASSEMBLY = $(ASSEMBLY_NAME).dll ASSEMBLY_NAME = gconf-sharp EXTRA_DIST = \ $(sources) \ $(ASSEMBLY).config.in \ gconf-sharp-2.0.pc.in references = $(GTKSHARP_LIBS) sources = \ ClientBase.cs \ Client.cs \ ChangeSet.cs \ Engine.cs \ _Entry.cs \ NoSuchKeyException.cs \ NotifyEventArgs.cs \ NotifyEventHandler.cs \ NotifyWrapper.cs \ Value.cs build_sources = $(addprefix $(srcdir)/, $(sources)) GAPI_CDECL_INSERT = #GAPI_CDECL_INSERT = $(top_srcdir)/gapi-cdecl-insert --keyfile=gtk-sharp.snk $(ASSEMBLY) all: all-am .SUFFIXES: $(srcdir)/Makefile.in: # $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ && exit 0; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign gconf/GConf/Makefile'; \ cd $(top_srcdir) && \ $(AUTOMAKE) --foreign gconf/GConf/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: # $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): # $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh gconf-sharp.dll.config: $(top_builddir)/config.status $(srcdir)/gconf-sharp.dll.config.in cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ gconf-sharp-2.0.pc: $(top_builddir)/config.status $(srcdir)/gconf-sharp-2.0.pc.in cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs install-pkgconfigDATA: $(pkgconfig_DATA) @$(NORMAL_INSTALL) test -z "$(pkgconfigdir)" || $(MKDIR_P) "$(DESTDIR)$(pkgconfigdir)" @list='$(pkgconfig_DATA)'; for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ f=$(am__strip_dir) \ echo " $(pkgconfigDATA_INSTALL) '$$d$$p' '$(DESTDIR)$(pkgconfigdir)/$$f'"; \ $(pkgconfigDATA_INSTALL) "$$d$$p" "$(DESTDIR)$(pkgconfigdir)/$$f"; \ done uninstall-pkgconfigDATA: @$(NORMAL_UNINSTALL) @list='$(pkgconfig_DATA)'; for p in $$list; do \ f=$(am__strip_dir) \ echo " rm -f '$(DESTDIR)$(pkgconfigdir)/$$f'"; \ rm -f "$(DESTDIR)$(pkgconfigdir)/$$f"; \ done tags: TAGS TAGS: ctags: CTAGS CTAGS: distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ fi; \ cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ else \ test -f $(distdir)/$$file \ || cp -p $$d/$$file $(distdir)/$$file \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile $(DATA) installdirs: for dir in "$(DESTDIR)$(pkgconfigdir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ `test -z '$(STRIP)' || \ echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test -z "$(DISTCLEANFILES)" || rm -f $(DISTCLEANFILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libtool mostlyclean-am distclean: distclean-am -rm -f Makefile distclean-am: clean-am distclean-generic dvi: dvi-am dvi-am: html: html-am info: info-am info-am: install-data-am: install-data-local install-pkgconfigDATA install-dvi: install-dvi-am install-exec-am: install-html: install-html-am install-info: install-info-am install-man: install-pdf: install-pdf-am install-ps: install-ps-am installcheck-am: maintainer-clean: maintainer-clean-am -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-generic mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-local uninstall-pkgconfigDATA .MAKE: install-am install-strip .PHONY: all all-am check check-am clean clean-generic clean-libtool \ distclean distclean-generic distclean-libtool distdir dvi \ dvi-am html html-am info info-am install install-am \ install-data install-data-am install-data-local install-dvi \ install-dvi-am install-exec install-exec-am install-html \ install-html-am install-info install-info-am install-man \ install-pdf install-pdf-am install-pkgconfigDATA install-ps \ install-ps-am install-strip installcheck installcheck-am \ installdirs maintainer-clean maintainer-clean-generic \ mostlyclean mostlyclean-generic mostlyclean-libtool pdf pdf-am \ ps ps-am uninstall uninstall-am uninstall-local \ uninstall-pkgconfigDATA gtk-sharp.snk: $(top_srcdir)/gtk-sharp.snk cp $(top_srcdir)/gtk-sharp.snk . AssemblyInfo.cs: $(top_builddir)/AssemblyInfo.cs cp $(top_builddir)/AssemblyInfo.cs . $(ASSEMBLY): $(build_sources) gtk-sharp.snk AssemblyInfo.cs @rm -f $(ASSEMBLY).mdb $(CSC) $(CSFLAGS) /out:$(ASSEMBLY) /target:library $(references) $(build_sources) AssemblyInfo.cs $(GAPI_CDECL_INSERT) $(POLICY_ASSEMBLIES): $(top_builddir)/policy.config gtk-sharp.snk @for i in $(POLICY_VERSIONS); do \ echo "Creating policy.$$i.$(ASSEMBLY)"; \ sed -e "s/@ASSEMBLY_NAME@/$(ASSEMBLY_NAME)/" -e "s/@POLICY@/$$i/" $(top_builddir)/policy.config > policy.$$i.config; \ $(AL) -link:policy.$$i.config -out:policy.$$i.$(ASSEMBLY) -keyfile:gtk-sharp.snk; \ done install-data-local: @if test -n '$(TARGET)'; then \ echo "$(GACUTIL) /i $(ASSEMBLY) /f $(GACUTIL_FLAGS)"; \ $(GACUTIL) /i $(ASSEMBLY) /f $(GACUTIL_FLAGS) || exit 1; \ if test -n '$(POLICY_VERSIONS)'; then \ for i in $(POLICY_VERSIONS); do \ echo "$(GACUTIL) /i policy.$$i.$(ASSEMBLY) /f $(GACUTIL_FLAGS)"; \ $(GACUTIL) /i policy.$$i.$(ASSEMBLY) /f $(GACUTIL_FLAGS) || exit 1; \ done \ fi \ fi uninstall-local: @if test -n '$(TARGET)'; then \ echo "$(GACUTIL) /u $(ASSEMBLY_NAME) $(GACUTIL_FLAGS)"; \ $(GACUTIL) /u $(ASSEMBLY_NAME) $(GACUTIL_FLAGS) || exit 1; \ if test -n '$(POLICY_VERSIONS)'; then \ for i in $(POLICY_VERSIONS); do \ echo "$(GACUTIL) /u policy.$$i.$(ASSEMBLY_NAME) $(GACUTIL_FLAGS)"; \ $(GACUTIL) /u policy.$$i.$(ASSEMBLY_NAME) $(GACUTIL_FLAGS) || exit 1; \ done \ fi \ fi # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT:
Java
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.service.protocol.event; import java.util.*; import net.java.sip.communicator.service.protocol.*; /** * Events of this class represent the fact that a server stored * subscription/contact has been moved from one server stored group to another. * Such events are only generated by implementations of * OperationSetPersistentPresence as non persistent presence operation sets do * not support the notion of server stored groups. * * @author Emil Ivov */ public class SubscriptionMovedEvent extends EventObject { /** * Serial version UID. */ private static final long serialVersionUID = 0L; private ContactGroup oldParent = null; private ContactGroup newParent = null; private ProtocolProviderService sourceProvider = null; /** * Creates an event instance with the specified source contact and old and * new parent. * * @param sourceContact the <tt>Contact</tt> that has been moved. * @param sourceProvider a reference to the <tt>ProtocolProviderService</tt> * that the source <tt>Contact</tt> belongs to. * @param oldParent the <tt>ContactGroup</tt> that has previously been * the parent * @param newParent the new <tt>ContactGroup</tt> parent of * <tt>sourceContact</tt> */ public SubscriptionMovedEvent(Contact sourceContact, ProtocolProviderService sourceProvider, ContactGroup oldParent, ContactGroup newParent) { super(sourceContact); this.oldParent = oldParent; this.newParent = newParent; this.sourceProvider = sourceProvider; } /** * Returns a reference to the contact that has been moved. * @return a reference to the <tt>Contact</tt> that has been moved. */ public Contact getSourceContact() { return (Contact)getSource(); } /** * Returns a reference to the ContactGroup that contained the source contact * before it was moved. * @return a reference to the previous <tt>ContactGroup</tt> parent of * the source <tt>Contact</tt>. */ public ContactGroup getOldParentGroup() { return oldParent; } /** * Returns a reference to the ContactGroup that currently contains the * source contact. * * @return a reference to the current <tt>ContactGroup</tt> parent of * the source <tt>Contact</tt>. */ public ContactGroup getNewParentGroup() { return newParent; } /** * Returns the provider that the source contact belongs to. * @return the provider that the source contact belongs to. */ public ProtocolProviderService getSourceProvider() { return sourceProvider; } /** * Returns a String representation of this ContactPresenceStatusChangeEvent * * @return A a String representation of this * SubscriptionMovedEvent. */ public String toString() { StringBuffer buff = new StringBuffer("SubscriptionMovedEvent-[ ContactID="); buff.append(getSourceContact().getAddress()); buff.append(", OldParentGroup=").append(getOldParentGroup().getGroupName()); buff.append(", NewParentGroup=").append(getNewParentGroup().getGroupName()); return buff.toString(); } }
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/1998/REC-html40-19980424/loose.dtd"> <html><head> <title>Methods</title> <meta name="generator" content="HeaderDoc"> </head><body bgcolor="#ffffff"><h1><font face="Geneva,Arial,Helvtica">Methods</font></h1><hr><br> <a name="//apple_ref/occ/clm/GSNSDataExtensions.h/+dataWithBase64EncodedString:"></a> <h3><a name="+dataWithBase64EncodedString:">+dataWithBase64EncodedString:</a></h3> <blockquote><pre><tt>+ (NSData *)<B>dataWithBase64EncodedString:</B>(NSString *)<I>inBase64String;</I> </tt><br> </pre></blockquote> <p>This method returns an autoreleased NSData object. The NSData object is initialized with the contents of the Base 64 encoded string. This is a convenience function for -initWithBase64EncodedString:. </p> <h4>Parameters</h4> <blockquote> <table border="1" width="90%"> <thead><tr><th>Name</th><th>Description</th></tr></thead> <tr><td align="center"><tt>inBase64String</tt></td><td>An NSString object that contains only Base 64 encoded data.</td></tr> </table> </blockquote> <b>Result:</b> The NSData object. <hr> <a name="//apple_ref/occ/clm/GSNSDataExtensions.h/+isCharacterPartOfBase64Encoding:"></a> <h3><a name="+isCharacterPartOfBase64Encoding:">+isCharacterPartOfBase64Encoding:</a></h3> <blockquote><pre><tt>+ (BOOL)<B>isCharacterPartOfBase64Encoding:</B>(char)<I>inChar;</I> </tt><br> </pre></blockquote> <p>This method returns YES or NO depending on whether the given character is a part of the Base64 encoding table. </p> <h4>Parameters</h4> <blockquote> <table border="1" width="90%"> <thead><tr><th>Name</th><th>Description</th></tr></thead> <tr><td align="center"><tt>inChar</tt></td><td>An character in ASCII encoding.</td></tr> </table> </blockquote> <b>Result:</b> YES if the character is a part of the Base64 encoding table. <hr> <a name="//apple_ref/occ/instm/GSNSDataExtensions.h/-base64EncodingWithLineLength:"></a> <h3><a name="-base64EncodingWithLineLength:">-base64EncodingWithLineLength:</a></h3> <blockquote><pre><tt>- (NSString *)<B>base64EncodingWithLineLength:</B>(unsigned int)<I>inLineLength;</I> </tt><br> </pre></blockquote> <p>This method returns a Base 64 encoded string representation of the data object. </p> <h4>Parameters</h4> <blockquote> <table border="1" width="90%"> <thead><tr><th>Name</th><th>Description</th></tr></thead> <tr><td align="center"><tt>inLineLength</tt></td><td>A value of zero means no line breaks. This is crunched to a multiple of 4 (the next one greater than inLineLength).</td></tr> </table> </blockquote> <b>Result:</b> The base 64 encoded data. <hr> <a name="//apple_ref/occ/instm/GSNSDataExtensions.h/-initWithBase64EncodedString:"></a> <h3><a name="-initWithBase64EncodedString:">-initWithBase64EncodedString:</a></h3> <blockquote><pre><tt>- (id)<B>initWithBase64EncodedString:</B>(NSString *)<I>inBase64String;</I> </tt><br> </pre></blockquote> <p>The NSData object is initialized with the contents of the Base 64 encoded string. This method returns self as a convenience. </p> <h4>Parameters</h4> <blockquote> <table border="1" width="90%"> <thead><tr><th>Name</th><th>Description</th></tr></thead> <tr><td align="center"><tt>inBase64String</tt></td><td>An NSString object that contains only Base 64 encoded data.</td></tr> </table> </blockquote> <b>Result:</b> This method returns self. <hr> <p><p>&#169; 2001, 2005 Kyle Hammond (Last Updated 1/12/2005) </p></body></html>
Java
#include <ixlib_random.hpp>
Java
package net.gigimoi.zombietc.tile; import net.gigimoi.zombietc.ZombieTC; import net.gigimoi.zombietc.util.IListenerZTC; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.NetworkManager; import net.minecraft.network.Packet; import net.minecraft.network.play.server.S35PacketUpdateTileEntity; import net.minecraft.tileentity.TileEntity; /** * Created by gigimoi on 8/8/2014. */ public abstract class TileZTC extends TileEntity implements IListenerZTC { @Override public void updateEntity() { super.updateEntity(); if(!ZombieTC.gameManager.isRegisteredListener(this)) { ZombieTC.gameManager.registerListener(this); } } @Override public Packet getDescriptionPacket() { NBTTagCompound tagCompound = new NBTTagCompound(); writeToNBT(tagCompound); return new S35PacketUpdateTileEntity(xCoord, yCoord, zCoord, 1, tagCompound); } @Override public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity pkt) { super.onDataPacket(net, pkt); readFromNBT(pkt.func_148857_g()); } }
Java
FROM registry.access.redhat.com/rhel7:latest MAINTAINER cevich@redhat.com RUN yum install -y deltarpm yum-utils &&\ yum update -y && \ yum install avahi -y && \ yum clean all ADD avahi-daemon.conf /etc/avahi/ ADD ssh.service /etc/avahi/services/ ADD avahi-daemon.service /etc/systemd/system/ LABEL RUN /usr/bin/docker run --rm --name NAME --net=host --volume /etc/localtime:/etc/localtime:r IMAGE /usr/sbin/avahi-daemon --debug LABEL INSTALL /usr/bin/docker run --privileged --rm --volume /:/host --name NAME IMAGE cp -v /etc/systemd/system/avahi-daemon.service /host/etc/systemd/system/ LABEL UNINSTALL /usr/bin/docker run --privileged --rm --volume /:/host --name NAME IMAGE rm /host/etc/systemd/system/avahi-daemon.service
Java
package net.minecraft.server; import java.util.Iterator; import java.util.List; import net.minecraft.src.BiomeGenBase; import cpw.mods.fml.common.registry.IMinecraftRegistry; import cpw.mods.fml.server.FMLBukkitHandler; public class BukkitRegistry implements IMinecraftRegistry { @Override public void addRecipe(net.minecraft.src.ItemStack output, Object... params) { CraftingManager.getInstance().registerShapedRecipe((ItemStack) output, params); } @Override public void addShapelessRecipe(net.minecraft.src.ItemStack output, Object... params) { CraftingManager.getInstance().registerShapelessRecipe((ItemStack) output, params); } @SuppressWarnings("unchecked") @Override public void addRecipe(net.minecraft.src.IRecipe recipe) { CraftingManager.getInstance().getRecipies().add(recipe); } @Override public void addSmelting(int input, net.minecraft.src.ItemStack output) { FurnaceRecipes.getInstance().registerRecipe(input, (ItemStack) output); } @Override public void registerBlock(net.minecraft.src.Block block) { registerBlock(block, ItemBlock.class); } @Override public void registerBlock(net.minecraft.src.Block block, Class <? extends net.minecraft.src.ItemBlock > itemclass) { try { assert block != null : "registerBlock: block cannot be null"; assert itemclass != null : "registerBlock: itemclass cannot be null"; int blockItemId = ((Block)block).id - 256; itemclass.getConstructor(int.class).newInstance(blockItemId); } catch (Exception e) { //HMMM } } @SuppressWarnings("unchecked") @Override public void registerEntityID(Class <? extends net.minecraft.src.Entity > entityClass, String entityName, int id) { EntityTypes.addNewEntityListMapping((Class<? extends Entity>) entityClass, entityName, id); } @SuppressWarnings("unchecked") @Override public void registerEntityID(Class <? extends net.minecraft.src.Entity > entityClass, String entityName, int id, int backgroundEggColour, int foregroundEggColour) { EntityTypes.addNewEntityListMapping((Class<? extends Entity>) entityClass, entityName, id, backgroundEggColour, foregroundEggColour); } @SuppressWarnings("unchecked") @Override public void registerTileEntity(Class <? extends net.minecraft.src.TileEntity > tileEntityClass, String id) { TileEntity.addNewTileEntityMapping((Class<? extends TileEntity>) tileEntityClass, id); } @Override public void addBiome(BiomeGenBase biome) { FMLBukkitHandler.instance().addBiomeToDefaultWorldGenerator((BiomeBase) biome); } @Override public void addSpawn(Class <? extends net.minecraft.src.EntityLiving > entityClass, int weightedProb, int min, int max, net.minecraft.src.EnumCreatureType typeOfCreature, BiomeGenBase... biomes) { BiomeBase[] realBiomes=(BiomeBase[]) biomes; for (BiomeBase biome : realBiomes) { @SuppressWarnings("unchecked") List<BiomeMeta> spawns = ((BiomeBase)biome).getMobs((EnumCreatureType)typeOfCreature); for (BiomeMeta entry : spawns) { //Adjusting an existing spawn entry if (entry.a == entityClass) { entry.d = weightedProb; entry.b = min; entry.c = max; break; } } spawns.add(new BiomeMeta(entityClass, weightedProb, min, max)); } } @Override @SuppressWarnings("unchecked") public void addSpawn(String entityName, int weightedProb, int min, int max, net.minecraft.src.EnumCreatureType spawnList, BiomeGenBase... biomes) { Class <? extends Entity > entityClazz = EntityTypes.getEntityToClassMapping().get(entityName); if (EntityLiving.class.isAssignableFrom(entityClazz)) { addSpawn((Class <? extends net.minecraft.src.EntityLiving >) entityClazz, weightedProb, min, max, spawnList, biomes); } } @Override public void removeBiome(BiomeGenBase biome) { FMLBukkitHandler.instance().removeBiomeFromDefaultWorldGenerator((BiomeBase)biome); } @Override public void removeSpawn(Class <? extends net.minecraft.src.EntityLiving > entityClass, net.minecraft.src.EnumCreatureType typeOfCreature, BiomeGenBase... biomesO) { BiomeBase[] biomes=(BiomeBase[]) biomesO; for (BiomeBase biome : biomes) { @SuppressWarnings("unchecked") List<BiomeMeta> spawns = ((BiomeBase)biome).getMobs((EnumCreatureType) typeOfCreature); Iterator<BiomeMeta> entries = spawns.iterator(); while (entries.hasNext()) { BiomeMeta entry = entries.next(); if (entry.a == entityClass) { entries.remove(); } } } } @Override @SuppressWarnings("unchecked") public void removeSpawn(String entityName, net.minecraft.src.EnumCreatureType spawnList, BiomeGenBase... biomes) { Class <? extends Entity > entityClazz = EntityTypes.getEntityToClassMapping().get(entityName); if (EntityLiving.class.isAssignableFrom(entityClazz)) { removeSpawn((Class <? extends net.minecraft.src.EntityLiving >) entityClazz, spawnList, biomes); } } }
Java
#define OMPI_SKIP_MPICXX 1 #define MPICH_SKIP_MPICXX 1 #include "comm.h" #include <stdio.h> #include "cmdLineOptions.h" #include "h5test.h" #include "parallel_io.h" #include "t3pio.h" Comm P; void outputResults(CmdLineOptions& cmd, ParallelIO& pio); int main(int argc, char* argv[]) { P.init(&argc, &argv, MPI_COMM_WORLD); CmdLineOptions cmd(argc, argv); CmdLineOptions::state_t state = cmd.state(); if (state != CmdLineOptions::iGOOD) { MPI_Finalize(); return (state == CmdLineOptions::iBAD); } ParallelIO pio; if (cmd.h5slab || cmd.h5chunk) pio.h5writer(cmd); if (cmd.romio) pio.MPIIOwriter(cmd); if (P.myProc == 0) outputResults(cmd, pio); P.fini(); return 0; } void outputResults(CmdLineOptions& cmd, ParallelIO& pio) { double fileSz = pio.totalSz()/(1024.0 * 1024.0 * 1024.0); const char* t3pioV = t3pio_version(); if (cmd.luaStyleOutput) { printf("%%%% { t3pioV = \"%s\", nprocs = %d, lSz = %ld, wrtStyle = \"%s\"," " xferStyle = \"%s\", iounits = %d, aggregators = %d, nstripes = %d, " " stripeSzMB = %d, fileSzGB = %15.7g, time = %15.7g, totalTime = %15.7g," " rate = %15.7g },\n", t3pioV, P.nProcs, cmd.localSz, cmd.wrtStyle.c_str(), cmd.xferStyle.c_str(), pio.nIOUnits(), pio.aggregators(), pio.nStripes(), pio.stripeSzMB(), fileSz, pio.time(), pio.totalTime(), pio.rate()); } if (cmd.tableStyleOutput) { printf("\nunstructTest:\n" "-------------------\n\n" " Nprocs: %12d\n" " lSz: %12ld\n" " Numvar: %12d\n" " iounits: %12d\n" " aggregators: %12d\n" " nstripes: %12d\n" " stripeSz (MB): %12d\n" " fileSz (GB): %12.3f\n" " time (sec): %12.3f\n" " totalTime (sec): %12.3f\n" " rate (MB/s): %12.3f\n" " wrtStyle: %12s\n" " xferStyle: %12s\n" " S_dne: %12d\n" " S_auto_max: %12d\n" " nStripesT3: %12d\n" " t3pioV: %12s\n", P.nProcs, cmd.localSz, pio.numvar(), pio.nIOUnits(), pio.aggregators(), pio.nStripes(), pio.stripeSzMB(), fileSz, pio.time(), pio.totalTime(), pio.rate(), cmd.wrtStyle.c_str(), cmd.xferStyle.c_str(), pio.dne_stripes(), pio.auto_max_stripes(), pio.nStripesT3(), t3pioV); } }
Java
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package com.xpn.xwiki.web; /** * Enumeration of supported object policy types. A object policy type is an * implementation on how to manage parameters in the query string that wants to * modify objects in page. They are usually on the form of * 'Space.PageClass_0_prop. In the default implementation of XWiki, these * parameters will initialize values of properties of existing object (see * 'UPDATE'). * * The second implementation, called 'UDPATE_OR_CREATE' will also create objects * if they don't exist. For example, let's take a page that contains one object * Space.PageClass. Given the following parameters: * <ul> * <li>Space.PageClass_0_prop=abc</li> * <li>Space.PageClass_1_prop=def</li> * <li>Space.PageClass_2_prop=ghi</li> * <li>Space.PageClass_6_prop=jkl</li> * </ul> * * The object number 0 will have it's property initialized with 'abc'. The * objects number 1 and 2 will be created and respectively initialized with * 'def' and 'ghi'. The final parameter will be ignored since the number doesn't * refer to a following number. * * @version $Id$ * @since 7.0RC1 */ public enum ObjectPolicyType { /** Only update objects. */ UPDATE("update"), /** Update and/or create objects. */ UPDATE_OR_CREATE("updateOrCreate"); /** Name that is used in HTTP parameters to specify the object policy. */ private final String name; /** * @param name The string name corresponding to the object policy type. */ ObjectPolicyType(String name) { this.name = name; } /** * @return The string name corresponding to the object policy type. */ public String getName() { return this.name; } /** * @param name The string name corresponding to the object policy type. * @return The ObjectPolicyType corresponding to the parameter 'name'. */ public static ObjectPolicyType forName(String name) { for (ObjectPolicyType type : values()) { if (type.getName().equals(name)) { return type; } } return null; } }
Java
-- Copyright (C) 2016-2017 Red Hat, Inc. -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- This library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this library; if not, see <http://www.gnu.org/licenses/>. {-# LANGUAGE OverloadedStrings #-} module BDCS.RPM.Sources(mkSource) where import Database.Esqueleto(Key) import qualified Data.Text as T import BDCS.DB(Projects, Sources(..)) import BDCS.Exceptions(DBException(..), throwIfNothing) import RPM.Tags(Tag, findStringTag) mkSource :: [Tag] -> Key Projects -> Sources mkSource tags projectId = let license = T.pack $ findStringTag "License" tags `throwIfNothing` MissingRPMTag "License" version = T.pack $ findStringTag "Version" tags `throwIfNothing` MissingRPMTag "Version" -- FIXME: Where to get this from? source_ref = "SOURCE_REF" in Sources projectId license version source_ref
Java
#if USE_SDL_BACKEND #include "../test/SDLBackend.h" #else #include "../test/OgreBackend.h" #endif #include <GG/StyleFactory.h> #include <GG/dialogs/ThreeButtonDlg.h> #include <GG/dialogs/FileDlg.h> #include <iostream> // Tutorial 1: Minimal // This contains the minimal interesting GG application. It contains 3D as // well as GUI elements in the same scene, and demonstrates how to use the // default SDL and Ogre input drivers. void CustomRender() { const double RPM = 4; const double DEGREES_PER_MS = 360.0 * RPM / 60000.0; // DeltaT() returns the time in whole milliseconds since the last frame // was rendered (in other words, since this method was last invoked). glRotated(GG::GUI::GetGUI()->DeltaT() * DEGREES_PER_MS, 0.0, 1.0, 0.0); glBegin(GL_QUADS); glColor3d(0.0, 1.0, 0.0); glVertex3d(1.0, 1.0, -1.0); glVertex3d(-1.0, 1.0, -1.0); glVertex3d(-1.0, 1.0, 1.0); glVertex3d(1.0, 1.0, 1.0); glColor3d(1.0, 0.5, 0.0); glVertex3d(1.0, -1.0, 1.0); glVertex3d(-1.0, -1.0, 1.0); glVertex3d(-1.0, -1.0,-1.0); glVertex3d(1.0, -1.0,-1.0); glColor3d(1.0, 0.0, 0.0); glVertex3d(1.0, 1.0, 1.0); glVertex3d(-1.0, 1.0, 1.0); glVertex3d(-1.0, -1.0, 1.0); glVertex3d(1.0, -1.0, 1.0); glColor3d(1.0, 1.0, 0.0); glVertex3d(1.0, -1.0, -1.0); glVertex3d(-1.0, -1.0, -1.0); glVertex3d(-1.0, 1.0, -1.0); glVertex3d(1.0, 1.0, -1.0); glColor3d(0.0, 0.0, 1.0); glVertex3d(-1.0, 1.0, 1.0); glVertex3d(-1.0, 1.0, -1.0); glVertex3d(-1.0, -1.0, -1.0); glVertex3d(-1.0, -1.0, 1.0); glColor3d(1.0, 0.0, 1.0); glVertex3d(1.0, 1.0, -1.0); glVertex3d(1.0, 1.0, 1.0); glVertex3d(1.0, -1.0, 1.0); glVertex3d(1.0, -1.0, -1.0); glEnd(); } // This is the launch point for your GG app. This is where you should place // your main GG::Wnd(s) that should appear when the application starts, if // any. void CustomInit() { // Create a modal dialog and execute it. This will show GG operating on // top of a "real 3D" scene. Note that if you want "real" 3D objects // (i.e. drawn in a non-orthographic space) inside of GG windows, you can // add whatever OpenGL calls you like to a GG::Wnd's Render() method, // sandwiched between Exit2DMode() and Enter2DMode(). const std::string message = "Are we Готово yet?"; // That Russian word means "Done", ha. const std::set<GG::UnicodeCharset> charsets_ = GG::UnicodeCharsetsToRender(message); const std::vector<GG::UnicodeCharset> charsets(charsets_.begin(), charsets_.end()); const boost::shared_ptr<GG::Font> font = GG::GUI::GetGUI()->GetStyleFactory()->DefaultFont(12, &charsets[0], &charsets[0] + charsets.size()); GG::Wnd* quit_dlg = new GG::ThreeButtonDlg(GG::X(200), GG::Y(100), message, font, GG::CLR_SHADOW, GG::CLR_SHADOW, GG::CLR_SHADOW, GG::CLR_WHITE, 1); quit_dlg->Run(); // Now that we're back from the modal dialog, we can exit normally, since // that's what closing the dialog indicates. Exit() calls all the cleanup // methods for GG::SDLGUI. GG::GUI::GetGUI()->Exit(0); } extern "C" // Note the use of C-linkage, as required by SDL. int main(int argc, char* argv[]) { // The try-catch block is not strictly necessary, but it sure helps to see // what exception crashed your app in the log file. try { #if USE_SDL_BACKEND MinimalSDLGUI::CustomInit = &CustomInit; MinimalSDLGUI::CustomRender = &CustomRender; MinimalSDLMain(); #else MinimalOgreGUI::CustomInit = &CustomInit; MinimalOgreGUI::CustomRender = &CustomRender; MinimalOgreMain(); #endif } catch (const std::invalid_argument& e) { std::cerr << "main() caught exception(std::invalid_arg): " << e.what(); } catch (const std::runtime_error& e) { std::cerr << "main() caught exception(std::runtime_error): " << e.what(); } catch (const std::exception& e) { std::cerr << "main() caught exception(std::exception): " << e.what(); } return 0; }
Java
#include "longlong_pre.h" #include <longlong_inc.h> /* longlong.h -- definitions for mixed size 32/64 bit arithmetic. Copyright 1991, 1992, 1993, 1994, 1996, 1997, 1999, 2000, 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc. This file is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This file is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this file; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* You have to define the following before including this file: UWtype -- An unsigned type, default type for operations (typically a "word") UHWtype -- An unsigned type, at least half the size of UWtype. UDWtype -- An unsigned type, at least twice as large a UWtype W_TYPE_SIZE -- size in bits of UWtype SItype, USItype -- Signed and unsigned 32 bit types. DItype, UDItype -- Signed and unsigned 64 bit types. On a 32 bit machine UWtype should typically be USItype; on a 64 bit machine, UWtype should typically be UDItype. */ /* Use mpn_umul_ppmm or mpn_udiv_qrnnd functions, if they exist. The "_r" forms have "reversed" arguments, meaning the pointer is last, which sometimes allows better parameter passing, in particular on 64-bit hppa. */ #define mpn_umul_ppmm __MPN(umul_ppmm) extern UWtype mpn_umul_ppmm _PROTO ((UWtype *, UWtype, UWtype)); #if ! defined (umul_ppmm) && HAVE_NATIVE_mpn_umul_ppmm \ && ! defined (LONGLONG_STANDALONE) #define umul_ppmm(wh, wl, u, v) \ do { \ UWtype __umul_ppmm__p0; \ (wh) = mpn_umul_ppmm (&__umul_ppmm__p0, (UWtype) (u), (UWtype) (v)); \ (wl) = __umul_ppmm__p0; \ } while (0) #endif #define mpn_umul_ppmm_r __MPN(umul_ppmm_r) extern UWtype mpn_umul_ppmm_r _PROTO ((UWtype, UWtype, UWtype *)); #if ! defined (umul_ppmm) && HAVE_NATIVE_mpn_umul_ppmm_r \ && ! defined (LONGLONG_STANDALONE) #define umul_ppmm(wh, wl, u, v) \ do { \ UWtype __umul_ppmm__p0; \ (wh) = mpn_umul_ppmm_r ((UWtype) (u), (UWtype) (v), &__umul_ppmm__p0); \ (wl) = __umul_ppmm__p0; \ } while (0) #endif #define mpn_udiv_qrnnd __MPN(udiv_qrnnd) extern UWtype mpn_udiv_qrnnd _PROTO ((UWtype *, UWtype, UWtype, UWtype)); #if ! defined (udiv_qrnnd) && HAVE_NATIVE_mpn_udiv_qrnnd \ && ! defined (LONGLONG_STANDALONE) #define udiv_qrnnd(q, r, n1, n0, d) \ do { \ UWtype __udiv_qrnnd__r; \ (q) = mpn_udiv_qrnnd (&__udiv_qrnnd__r, \ (UWtype) (n1), (UWtype) (n0), (UWtype) d); \ (r) = __udiv_qrnnd__r; \ } while (0) #endif #define mpn_udiv_qrnnd_r __MPN(udiv_qrnnd_r) extern UWtype mpn_udiv_qrnnd_r _PROTO ((UWtype, UWtype, UWtype, UWtype *)); #if ! defined (udiv_qrnnd) && HAVE_NATIVE_mpn_udiv_qrnnd_r \ && ! defined (LONGLONG_STANDALONE) #define udiv_qrnnd(q, r, n1, n0, d) \ do { \ UWtype __udiv_qrnnd__r; \ (q) = mpn_udiv_qrnnd_r ((UWtype) (n1), (UWtype) (n0), (UWtype) d, \ &__udiv_qrnnd__r); \ (r) = __udiv_qrnnd__r; \ } while (0) #endif /* If this machine has no inline assembler, use C macros. */ #if !defined (add_ssaaaa) #define add_ssaaaa(sh, sl, ah, al, bh, bl) \ do { \ UWtype __x; \ __x = (al) + (bl); \ (sh) = (ah) + (bh) + (__x < (al)); \ (sl) = __x; \ } while (0) #endif #if !defined (sub_ddmmss) #define sub_ddmmss(sh, sl, ah, al, bh, bl) \ do { \ UWtype __x; \ __x = (al) - (bl); \ (sh) = (ah) - (bh) - ((al) < (bl)); \ (sl) = __x; \ } while (0) #endif /* If we lack umul_ppmm but have smul_ppmm, define umul_ppmm in terms of smul_ppmm. */ #if !defined (umul_ppmm) && defined (smul_ppmm) #define umul_ppmm(w1, w0, u, v) \ do { \ UWtype __w1; \ UWtype __xm0 = (u), __xm1 = (v); \ smul_ppmm (__w1, w0, __xm0, __xm1); \ (w1) = __w1 + (-(__xm0 >> (W_TYPE_SIZE - 1)) & __xm1) \ + (-(__xm1 >> (W_TYPE_SIZE - 1)) & __xm0); \ } while (0) #endif /* If we still don't have umul_ppmm, define it using plain C. For reference, when this code is used for squaring (ie. u and v identical expressions), gcc recognises __x1 and __x2 are the same and generates 3 multiplies, not 4. The subsequent additions could be optimized a bit, but the only place GMP currently uses such a square is mpn_sqr_basecase, and chips obliged to use this generic C umul will have plenty of worse performance problems than a couple of extra instructions on the diagonal of sqr_basecase. */ #if !defined (umul_ppmm) #define umul_ppmm(w1, w0, u, v) \ do { \ UWtype __x0, __x1, __x2, __x3; \ UHWtype __ul, __vl, __uh, __vh; \ UWtype __u = (u), __v = (v); \ \ __ul = __ll_lowpart (__u); \ __uh = __ll_highpart (__u); \ __vl = __ll_lowpart (__v); \ __vh = __ll_highpart (__v); \ \ __x0 = (UWtype) __ul * __vl; \ __x1 = (UWtype) __ul * __vh; \ __x2 = (UWtype) __uh * __vl; \ __x3 = (UWtype) __uh * __vh; \ \ __x1 += __ll_highpart (__x0);/* this can't give carry */ \ __x1 += __x2; /* but this indeed can */ \ if (__x1 < __x2) /* did we get it? */ \ __x3 += __ll_B; /* yes, add it in the proper pos. */ \ \ (w1) = __x3 + __ll_highpart (__x1); \ (w0) = (__x1 << W_TYPE_SIZE/2) + __ll_lowpart (__x0); \ } while (0) #endif /* If we don't have smul_ppmm, define it using umul_ppmm (which surely will exist in one form or another. */ #if !defined (smul_ppmm) #define smul_ppmm(w1, w0, u, v) \ do { \ UWtype __w1; \ UWtype __xm0 = (u), __xm1 = (v); \ umul_ppmm (__w1, w0, __xm0, __xm1); \ (w1) = __w1 - (-(__xm0 >> (W_TYPE_SIZE - 1)) & __xm1) \ - (-(__xm1 >> (W_TYPE_SIZE - 1)) & __xm0); \ } while (0) #endif /* Define this unconditionally, so it can be used for debugging. */ #define __udiv_qrnnd_c(q, r, n1, n0, d) \ do { \ UWtype __d1, __d0, __q1, __q0, __r1, __r0, __m; \ \ ASSERT ((d) != 0); \ ASSERT ((n1) < (d)); \ \ __d1 = __ll_highpart (d); \ __d0 = __ll_lowpart (d); \ \ __q1 = (n1) / __d1; \ __r1 = (n1) - __q1 * __d1; \ __m = __q1 * __d0; \ __r1 = __r1 * __ll_B | __ll_highpart (n0); \ if (__r1 < __m) \ { \ __q1--, __r1 += (d); \ if (__r1 >= (d)) /* i.e. we didn't get carry when adding to __r1 */\ if (__r1 < __m) \ __q1--, __r1 += (d); \ } \ __r1 -= __m; \ \ __q0 = __r1 / __d1; \ __r0 = __r1 - __q0 * __d1; \ __m = __q0 * __d0; \ __r0 = __r0 * __ll_B | __ll_lowpart (n0); \ if (__r0 < __m) \ { \ __q0--, __r0 += (d); \ if (__r0 >= (d)) \ if (__r0 < __m) \ __q0--, __r0 += (d); \ } \ __r0 -= __m; \ \ (q) = __q1 * __ll_B | __q0; \ (r) = __r0; \ } while (0) /* If the processor has no udiv_qrnnd but sdiv_qrnnd, go through __udiv_w_sdiv (defined in libgcc or elsewhere). */ #if !defined (udiv_qrnnd) && defined (sdiv_qrnnd) #define udiv_qrnnd(q, r, nh, nl, d) \ do { \ UWtype __r; \ (q) = __MPN(udiv_w_sdiv) (&__r, nh, nl, d); \ (r) = __r; \ } while (0) #endif /* If udiv_qrnnd was not defined for this processor, use __udiv_qrnnd_c. */ #if !defined (udiv_qrnnd) #define UDIV_NEEDS_NORMALIZATION 1 #define udiv_qrnnd __udiv_qrnnd_c #endif #if !defined (count_leading_zeros) #define count_leading_zeros(count, x) \ do { \ UWtype __xr = (x); \ UWtype __a; \ \ if (W_TYPE_SIZE == 32) \ { \ __a = __xr < ((UWtype) 1 << 2*__BITS4) \ ? (__xr < ((UWtype) 1 << __BITS4) ? 1 : __BITS4 + 1) \ : (__xr < ((UWtype) 1 << 3*__BITS4) ? 2*__BITS4 + 1 \ : 3*__BITS4 + 1); \ } \ else \ { \ for (__a = W_TYPE_SIZE - 8; __a > 0; __a -= 8) \ if (((__xr >> __a) & 0xff) != 0) \ break; \ ++__a; \ } \ \ (count) = W_TYPE_SIZE + 1 - __a - __clz_tab[__xr >> __a]; \ } while (0) /* This version gives a well-defined value for zero. */ #define COUNT_LEADING_ZEROS_0 (W_TYPE_SIZE - 1) #define COUNT_LEADING_ZEROS_NEED_CLZ_TAB #endif #ifdef COUNT_LEADING_ZEROS_NEED_CLZ_TAB extern const unsigned char __GMP_DECLSPEC __clz_tab[128]; #endif #if !defined (count_trailing_zeros) /* Define count_trailing_zeros using count_leading_zeros. The latter might be defined in asm, but if it is not, the C version above is good enough. */ #define count_trailing_zeros(count, x) \ do { \ UWtype __ctz_x = (x); \ UWtype __ctz_c; \ ASSERT (__ctz_x != 0); \ count_leading_zeros (__ctz_c, __ctz_x & -__ctz_x); \ (count) = W_TYPE_SIZE - 1 - __ctz_c; \ } while (0) #endif #ifndef UDIV_NEEDS_NORMALIZATION #define UDIV_NEEDS_NORMALIZATION 0 #endif /* Whether udiv_qrnnd is actually implemented with udiv_qrnnd_preinv, and that hence the latter should always be used. */ #ifndef UDIV_PREINV_ALWAYS #define UDIV_PREINV_ALWAYS 0 #endif #ifdef _MSC_VER//!!!P #define sub_333(sh, sm, sl, ah, am, al, bh, bm, bl) \ do { \ UWtype _bw; \ (sl) = (al) - (bl); \ _bw = (sl) > (al) ? 1 : 0; \ (sm) = (am) - (bm) - _bw; \ _bw = (sm) > (am) ? 1 : (sm) < (am) ? 0 : _bw; \ (sh) = (ah) - (bh) - _bw; \ } while (0) #endif
Java
/** * DSS - Digital Signature Services * Copyright (C) 2015 European Commission, provided under the CEF programme * * This file is part of the "DSS - Digital Signature Services" project. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package eu.europa.esig.dss.asic.cades.signature.asics; import eu.europa.esig.dss.asic.cades.ASiCWithCAdESContainerExtractor; import eu.europa.esig.dss.asic.cades.ASiCWithCAdESSignatureParameters; import eu.europa.esig.dss.asic.cades.ASiCWithCAdESTimestampParameters; import eu.europa.esig.dss.asic.cades.signature.ASiCWithCAdESService; import eu.europa.esig.dss.asic.common.ASiCContent; import eu.europa.esig.dss.diagnostic.DiagnosticData; import eu.europa.esig.dss.diagnostic.SignatureWrapper; import eu.europa.esig.dss.diagnostic.jaxb.XmlDigestMatcher; import eu.europa.esig.dss.enumerations.ASiCContainerType; import eu.europa.esig.dss.enumerations.SignatureLevel; import eu.europa.esig.dss.model.DSSDocument; import eu.europa.esig.dss.model.InMemoryDocument; import eu.europa.esig.dss.signature.DocumentSignatureService; import eu.europa.esig.dss.utils.Utils; import eu.europa.esig.dss.validation.SignedDocumentValidator; import eu.europa.esig.dss.validation.reports.Reports; import org.junit.jupiter.api.BeforeEach; import java.util.Arrays; import java.util.Date; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; public class ASiCSCAdESLevelLTTest extends AbstractASiCSCAdESTestSignature { private DocumentSignatureService<ASiCWithCAdESSignatureParameters, ASiCWithCAdESTimestampParameters> service; private ASiCWithCAdESSignatureParameters signatureParameters; private DSSDocument documentToSign; @BeforeEach public void init() throws Exception { documentToSign = new InMemoryDocument("Hello World !".getBytes(), "test.text"); signatureParameters = new ASiCWithCAdESSignatureParameters(); signatureParameters.bLevel().setSigningDate(new Date()); signatureParameters.setSigningCertificate(getSigningCert()); signatureParameters.setCertificateChain(getCertificateChain()); signatureParameters.setSignatureLevel(SignatureLevel.CAdES_BASELINE_LT); signatureParameters.aSiC().setContainerType(ASiCContainerType.ASiC_S); service = new ASiCWithCAdESService(getCompleteCertificateVerifier()); service.setTspSource(getGoodTsa()); } @Override protected void onDocumentSigned(byte[] byteArray) { super.onDocumentSigned(byteArray); ASiCWithCAdESContainerExtractor containerExtractor = new ASiCWithCAdESContainerExtractor(new InMemoryDocument(byteArray)); ASiCContent result = containerExtractor.extract(); List<DSSDocument> signatureDocuments = result.getSignatureDocuments(); assertTrue(Utils.isCollectionNotEmpty(signatureDocuments)); for (DSSDocument signatureDocument : signatureDocuments) { // validate with no detached content DiagnosticData diagnosticData = validateDocument(signatureDocument); SignatureWrapper signature = diagnosticData.getSignatureById(diagnosticData.getFirstSignatureId()); List<XmlDigestMatcher> digestMatchers = signature.getDigestMatchers(); assertEquals(1, digestMatchers.size()); assertFalse(digestMatchers.get(0).isDataFound()); assertFalse(digestMatchers.get(0).isDataIntact()); // with detached content diagnosticData = validateDocument(signatureDocument, Arrays.asList(getSignedData(result))); signature = diagnosticData.getSignatureById(diagnosticData.getFirstSignatureId()); digestMatchers = signature.getDigestMatchers(); assertEquals(1, digestMatchers.size()); assertTrue(digestMatchers.get(0).isDataFound()); assertTrue(digestMatchers.get(0).isDataIntact()); } } private DiagnosticData validateDocument(DSSDocument signatureDocument) { return validateDocument(signatureDocument, null); } private DiagnosticData validateDocument(DSSDocument signatureDocument, List<DSSDocument> detachedContents) { SignedDocumentValidator validator = SignedDocumentValidator.fromDocument(signatureDocument); validator.setCertificateVerifier(getOfflineCertificateVerifier()); if (Utils.isCollectionNotEmpty(detachedContents)) { validator.setDetachedContents(detachedContents); } Reports reports = validator.validateDocument(); return reports.getDiagnosticData(); } @Override protected DocumentSignatureService<ASiCWithCAdESSignatureParameters, ASiCWithCAdESTimestampParameters> getService() { return service; } @Override protected ASiCWithCAdESSignatureParameters getSignatureParameters() { return signatureParameters; } @Override protected DSSDocument getDocumentToSign() { return documentToSign; } @Override protected String getSigningAlias() { return GOOD_USER; } }
Java
#!/usr/bin/env kjscmd5 function Calculator(ui) { // Setup entry functions var display = ui.findChild('display'); this.display = display; this.one = function() { display.intValue = display.intValue*10+1; } this.two = function() { display.intValue = display.intValue*10+2; } this.three = function() { display.intValue = display.intValue*10+3; } this.four = function() { display.intValue = display.intValue*10+4; } this.five = function() { display.intValue = display.intValue*10+5; } this.six = function() { display.intValue = display.intValue*10+6; } this.seven = function() { display.intValue = display.intValue*10+7; } this.eight = function() { display.intValue = display.intValue*10+8; } this.nine = function() { display.intValue = display.intValue*10+9; } this.zero = function() { display.intValue = display.intValue*10+0; } ui.connect( ui.findChild('one'), 'clicked()', this, 'one()' ); ui.connect( ui.findChild('two'), 'clicked()', this, 'two()' ); ui.connect( ui.findChild('three'), 'clicked()', this, 'three()' ); ui.connect( ui.findChild('four'), 'clicked()', this, 'four()' ); ui.connect( ui.findChild('five'), 'clicked()', this, 'five()' ); ui.connect( ui.findChild('six'), 'clicked()', this, 'six()' ); ui.connect( ui.findChild('seven'), 'clicked()', this, 'seven()' ); ui.connect( ui.findChild('eight'), 'clicked()', this, 'eight()' ); ui.connect( ui.findChild('nine'), 'clicked()', this, 'nine()' ); ui.connect( ui.findChild('zero'), 'clicked()', this, 'zero()' ); this.val = 0; this.display.intValue = 0; this.lastop = function() {} this.plus = function() { this.val = display.intValue+this.val; display.intValue = 0; this.lastop=this.plus } this.minus = function() { this.val = display.intValue-this.val; display.intValue = 0; this.lastop=this.minus; } ui.connect( ui.findChild('plus'), 'clicked()', this, 'plus()' ); ui.connect( ui.findChild('minus'), 'clicked()', this, 'minus()' ); this.equals = function() { this.lastop(); display.intValue = this.val; } this.clear = function() { this.lastop=function(){}; display.intValue = 0; this.val = 0; } ui.connect( ui.findChild('equals'), 'clicked()', this, 'equals()' ); ui.connect( ui.findChild('clear'), 'clicked()', this, 'clear()' ); } var loader = new QUiLoader(); var ui = loader.load('calc.ui', this); var calc = new Calculator(ui); ui.show(); exec();
Java
import { Keys } from '@ephox/agar'; import { describe, it } from '@ephox/bedrock-client'; import { TinyAssertions, TinyContentActions, TinyHooks, TinySelections } from '@ephox/mcagar'; import Editor from 'tinymce/core/api/Editor'; import Theme from 'tinymce/themes/silver/Theme'; describe('browser.tinymce.core.keyboard.TypeTextAtCef', () => { const hook = TinyHooks.bddSetupLight<Editor>({ add_unload_trigger: false, base_url: '/project/tinymce/js/tinymce' }, [ Theme ], true); it('Type text before cef inline element', () => { const editor = hook.editor(); editor.setContent('<p><span contenteditable="false">a</span></p>'); TinySelections.select(editor, 'p', [ 1 ]); TinyContentActions.keystroke(editor, Keys.left()); TinyContentActions.type(editor, 'bc'); TinyAssertions.assertCursor(editor, [ 0, 0 ], 2); TinyAssertions.assertContent(editor, '<p>bc<span contenteditable="false">a</span></p>'); }); it('Type after cef inline element', () => { const editor = hook.editor(); editor.setContent('<p><span contenteditable="false">a</span></p>'); TinySelections.select(editor, 'p', [ 1 ]); TinyContentActions.keystroke(editor, Keys.right()); TinyContentActions.type(editor, 'bc'); TinyAssertions.assertCursor(editor, [ 0, 1 ], 3); TinyAssertions.assertContent(editor, '<p><span contenteditable="false">a</span>bc</p>'); }); it('Type between cef inline elements', () => { const editor = hook.editor(); editor.setContent('<p><span contenteditable="false">a</span>&nbsp;<span contenteditable="false">b</span></p>'); TinySelections.select(editor, 'p', [ 3 ]); TinyContentActions.keystroke(editor, Keys.left()); TinyContentActions.keystroke(editor, Keys.left()); TinyContentActions.type(editor, 'bc'); TinyAssertions.assertSelection(editor, [ 0, 1 ], 3, [ 0, 1 ], 3); TinyAssertions.assertContent(editor, '<p><span contenteditable="false">a</span>bc&nbsp;<span contenteditable="false">b</span></p>'); }); });
Java
<?php namespace wcf\acp\form; use wcf\data\contact\option\ContactOption; use wcf\data\contact\option\ContactOptionAction; use wcf\data\contact\option\ContactOptionEditor; /** * Shows the contact option add form. * * @author Alexander Ebert * @copyright 2001-2019 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\Core\Acp\Form * @since 3.1 */ class ContactOptionAddForm extends AbstractCustomOptionForm { /** * @inheritDoc */ public $action = 'add'; /** * @inheritDoc */ public $activeMenuItem = 'wcf.acp.menu.link.contact.settings'; /** * @inheritDoc */ public $neededModules = ['MODULE_CONTACT_FORM']; /** * @inheritDoc */ public $neededPermissions = ['admin.contact.canManageContactForm']; /** * action class name * @var string */ public $actionClass = ContactOptionAction::class; /** * base class name * @var string */ public $baseClass = ContactOption::class; /** * editor class name * @var string */ public $editorClass = ContactOptionEditor::class; /** * @inheritDoc */ public function readParameters() { parent::readParameters(); $this->getI18nValue('optionTitle')->setLanguageItem('wcf.contact.option', 'wcf.contact', 'com.woltlab.wcf'); $this->getI18nValue('optionDescription')->setLanguageItem('wcf.contact.optionDescription', 'wcf.contact', 'com.woltlab.wcf'); } }
Java
/** * Copyright 2006-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.solmix.generator.plugin; import static org.solmix.commons.util.StringUtils.stringHasValue; import static org.solmix.generator.util.Messages.getString; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.solmix.generator.api.IntrospectedTable; import org.solmix.generator.api.PluginAdapter; /** * This plugin demonstrates overriding the initialized() method to rename the * generated example classes. Instead of xxxExample, the classes will be named * xxxCriteria. * * <p>This plugin accepts two properties: * * <ul> * <li><tt>searchString</tt> (required) the regular expression of the name * search.</li> * <li><tt>replaceString</tt> (required) the replacement String.</li> * </ul> * * <p>For example, to change the name of the generated Example classes from * xxxExample to xxxCriteria, specify the following: * * <dl> * <dt>searchString</dt> * <dd>Example$</dd> * <dt>replaceString</dt> * <dd>Criteria</dd> * </dl> * * * @author Jeff Butler * */ public class RenameExampleClassPlugin extends PluginAdapter { private String searchString; private String replaceString; private Pattern pattern; public RenameExampleClassPlugin() { } @Override public boolean validate(List<String> warnings) { searchString = properties.getProperty("searchString"); replaceString = properties.getProperty("replaceString"); boolean valid = stringHasValue(searchString) && stringHasValue(replaceString); if (valid) { pattern = Pattern.compile(searchString); } else { if (!stringHasValue(searchString)) { warnings.add(getString("ValidationError.18", "RenameExampleClassPlugin", "searchString")); } if (!stringHasValue(replaceString)) { warnings.add(getString("ValidationError.18", "RenameExampleClassPlugin", "replaceString")); } } return valid; } @Override public void initialized(IntrospectedTable introspectedTable) { String oldType = introspectedTable.getExampleType(); Matcher matcher = pattern.matcher(oldType); oldType = matcher.replaceAll(replaceString); introspectedTable.setExampleType(oldType); } }
Java
/****************************************************************************** * Copyright (C) 2010-2016 CERN. All rights not expressly granted are reserved. * * This file is part of the CERN Control and Monitoring Platform 'C2MON'. * C2MON is free software: you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free * Software Foundation, either version 3 of the license. * * C2MON 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 C2MON. If not, see <http://www.gnu.org/licenses/>. *****************************************************************************/ package cern.c2mon.client.ext.history.common; import java.sql.Timestamp; import cern.c2mon.client.ext.history.common.id.HistoryUpdateId; /** * This interface is used to keep track of the data which is from the history. * It have a function to get the execution time of the update so the player will know * when to execute the update. And it also have an identifier. * * @author vdeila * */ public interface HistoryUpdate { /** * * @return the id of the update */ HistoryUpdateId getUpdateId(); /** * * @return the time of when this update should execute */ Timestamp getExecutionTimestamp(); }
Java
from __future__ import absolute_import import json class JSONRenderer: """ Renders a mystery as JSON """ def render(self, mystery): return json.dumps(mystery.encode(), indent=4)
Java
/* * SonarQube Java * Copyright (C) 2012-2017 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.maven.model; import javax.xml.bind.annotation.adapters.XmlAdapter; import javax.xml.stream.XMLStreamReader; /** * Adapter in charge of converting attributes from XML object, being String, to located attribute, * storing information related to the location of the attribute. */ public class LocatedAttributeAdapter extends XmlAdapter<String, LocatedAttribute> { private final XMLStreamReader reader; public LocatedAttributeAdapter(XMLStreamReader reader) { this.reader = reader; } @Override public LocatedAttribute unmarshal(String value) throws Exception { LocatedAttribute result = new LocatedAttribute(value); result.setEndLocation(XmlLocation.getLocation(reader.getLocation())); result.setStartLocation(XmlLocation.getStartLocation(value, reader.getLocation())); return result; } @Override public String marshal(LocatedAttribute attribute) throws Exception { return attribute.getValue(); } }
Java
package com.silicolife.textmining.core.datastructures.dataaccess.database.dataaccess.implementation.model.core.entities; // Generated 23/Mar/2015 16:36:00 by Hibernate Tools 4.3.1 import javax.persistence.Column; import javax.persistence.Embeddable; /** * ClusterProcessHasLabelsId generated by hbm2java */ @Embeddable public class ClusterProcessHasLabelsId implements java.io.Serializable { private long cphClusterProcessId; private long cphClusterLabelId; public ClusterProcessHasLabelsId() { } public ClusterProcessHasLabelsId(long cphClusterProcessId, long cphClusterLabelId) { this.cphClusterProcessId = cphClusterProcessId; this.cphClusterLabelId = cphClusterLabelId; } @Column(name = "cph_cluster_process_id", nullable = false) public long getCphClusterProcessId() { return this.cphClusterProcessId; } public void setCphClusterProcessId(long cphClusterProcessId) { this.cphClusterProcessId = cphClusterProcessId; } @Column(name = "cph_cluster_label_id", nullable = false) public long getCphClusterLabelId() { return this.cphClusterLabelId; } public void setCphClusterLabelId(long cphClusterLabelId) { this.cphClusterLabelId = cphClusterLabelId; } public boolean equals(Object other) { if ((this == other)) return true; if ((other == null)) return false; if (!(other instanceof ClusterProcessHasLabelsId)) return false; ClusterProcessHasLabelsId castOther = (ClusterProcessHasLabelsId) other; return (this.getCphClusterProcessId() == castOther.getCphClusterProcessId()) && (this.getCphClusterLabelId() == castOther.getCphClusterLabelId()); } public int hashCode() { int result = 17; result = 37 * result + (int) this.getCphClusterProcessId(); result = 37 * result + (int) this.getCphClusterLabelId(); return result; } }
Java
/* * Library signature type test program * * Copyright (C) 2014-2022, Joachim Metz <joachim.metz@gmail.com> * * Refer to AUTHORS for acknowledgements. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <common.h> #include <file_stream.h> #include <types.h> #if defined( HAVE_STDLIB_H ) || defined( WINAPI ) #include <stdlib.h> #endif #include "sigscan_test_libcerror.h" #include "sigscan_test_libsigscan.h" #include "sigscan_test_macros.h" #include "sigscan_test_memory.h" #include "sigscan_test_unused.h" #include "../libsigscan/libsigscan_signature.h" #if defined( __GNUC__ ) && !defined( LIBSIGSCAN_DLL_IMPORT ) /* Tests the libsigscan_signature_initialize function * Returns 1 if successful or 0 if not */ int sigscan_test_signature_initialize( void ) { libcerror_error_t *error = NULL; libsigscan_signature_t *signature = NULL; int result = 0; #if defined( HAVE_SIGSCAN_TEST_MEMORY ) int number_of_malloc_fail_tests = 1; int number_of_memset_fail_tests = 1; int test_number = 0; #endif /* Test regular cases */ result = libsigscan_signature_initialize( &signature, &error ); SIGSCAN_TEST_ASSERT_EQUAL_INT( "result", result, 1 ); SIGSCAN_TEST_ASSERT_IS_NOT_NULL( "signature", signature ); SIGSCAN_TEST_ASSERT_IS_NULL( "error", error ); result = libsigscan_signature_free( &signature, &error ); SIGSCAN_TEST_ASSERT_EQUAL_INT( "result", result, 1 ); SIGSCAN_TEST_ASSERT_IS_NULL( "signature", signature ); SIGSCAN_TEST_ASSERT_IS_NULL( "error", error ); /* Test error cases */ result = libsigscan_signature_initialize( NULL, &error ); SIGSCAN_TEST_ASSERT_EQUAL_INT( "result", result, -1 ); SIGSCAN_TEST_ASSERT_IS_NOT_NULL( "error", error ); libcerror_error_free( &error ); signature = (libsigscan_signature_t *) 0x12345678UL; result = libsigscan_signature_initialize( &signature, &error ); SIGSCAN_TEST_ASSERT_EQUAL_INT( "result", result, -1 ); SIGSCAN_TEST_ASSERT_IS_NOT_NULL( "error", error ); libcerror_error_free( &error ); signature = NULL; #if defined( HAVE_SIGSCAN_TEST_MEMORY ) for( test_number = 0; test_number < number_of_malloc_fail_tests; test_number++ ) { /* Test libsigscan_signature_initialize with malloc failing */ sigscan_test_malloc_attempts_before_fail = test_number; result = libsigscan_signature_initialize( &signature, &error ); if( sigscan_test_malloc_attempts_before_fail != -1 ) { sigscan_test_malloc_attempts_before_fail = -1; if( signature != NULL ) { libsigscan_signature_free( &signature, NULL ); } } else { SIGSCAN_TEST_ASSERT_EQUAL_INT( "result", result, -1 ); SIGSCAN_TEST_ASSERT_IS_NULL( "signature", signature ); SIGSCAN_TEST_ASSERT_IS_NOT_NULL( "error", error ); libcerror_error_free( &error ); } } for( test_number = 0; test_number < number_of_memset_fail_tests; test_number++ ) { /* Test libsigscan_signature_initialize with memset failing */ sigscan_test_memset_attempts_before_fail = test_number; result = libsigscan_signature_initialize( &signature, &error ); if( sigscan_test_memset_attempts_before_fail != -1 ) { sigscan_test_memset_attempts_before_fail = -1; if( signature != NULL ) { libsigscan_signature_free( &signature, NULL ); } } else { SIGSCAN_TEST_ASSERT_EQUAL_INT( "result", result, -1 ); SIGSCAN_TEST_ASSERT_IS_NULL( "signature", signature ); SIGSCAN_TEST_ASSERT_IS_NOT_NULL( "error", error ); libcerror_error_free( &error ); } } #endif /* defined( HAVE_SIGSCAN_TEST_MEMORY ) */ return( 1 ); on_error: if( error != NULL ) { libcerror_error_free( &error ); } if( signature != NULL ) { libsigscan_signature_free( &signature, NULL ); } return( 0 ); } /* Tests the libsigscan_signature_free function * Returns 1 if successful or 0 if not */ int sigscan_test_signature_free( void ) { libcerror_error_t *error = NULL; int result = 0; /* Test error cases */ result = libsigscan_signature_free( NULL, &error ); SIGSCAN_TEST_ASSERT_EQUAL_INT( "result", result, -1 ); SIGSCAN_TEST_ASSERT_IS_NOT_NULL( "error", error ); libcerror_error_free( &error ); return( 1 ); on_error: if( error != NULL ) { libcerror_error_free( &error ); } return( 0 ); } /* Tests the libsigscan_signature_clone function * Returns 1 if successful or 0 if not */ int sigscan_test_signature_clone( void ) { libcerror_error_t *error = NULL; libsigscan_signature_t *destination_signature = NULL; libsigscan_signature_t *source_signature = NULL; int result = 0; /* Initialize test */ result = libsigscan_signature_initialize( &source_signature, &error ); SIGSCAN_TEST_ASSERT_EQUAL_INT( "result", result, 1 ); SIGSCAN_TEST_ASSERT_IS_NOT_NULL( "source_signature", source_signature ); SIGSCAN_TEST_ASSERT_IS_NULL( "error", error ); /* Test regular cases */ result = libsigscan_signature_clone( &destination_signature, source_signature, &error ); SIGSCAN_TEST_ASSERT_EQUAL_INT( "result", result, 1 ); SIGSCAN_TEST_ASSERT_IS_NOT_NULL( "destination_signature", destination_signature ); SIGSCAN_TEST_ASSERT_IS_NULL( "error", error ); /* TODO: move handling clones into the signature code */ result = libsigscan_signature_free_clone( &destination_signature, &error ); SIGSCAN_TEST_ASSERT_EQUAL_INT( "result", result, 1 ); SIGSCAN_TEST_ASSERT_IS_NULL( "destination_signature", destination_signature ); SIGSCAN_TEST_ASSERT_IS_NULL( "error", error ); result = libsigscan_signature_clone( &destination_signature, NULL, &error ); SIGSCAN_TEST_ASSERT_EQUAL_INT( "result", result, 1 ); SIGSCAN_TEST_ASSERT_IS_NULL( "destination_signature", destination_signature ); SIGSCAN_TEST_ASSERT_IS_NULL( "error", error ); /* Test error cases */ result = libsigscan_signature_clone( NULL, source_signature, &error ); SIGSCAN_TEST_ASSERT_EQUAL_INT( "result", result, -1 ); SIGSCAN_TEST_ASSERT_IS_NOT_NULL( "error", error ); libcerror_error_free( &error ); /* Clean up */ result = libsigscan_signature_free( &source_signature, &error ); SIGSCAN_TEST_ASSERT_EQUAL_INT( "result", result, 1 ); SIGSCAN_TEST_ASSERT_IS_NULL( "source_signature", source_signature ); SIGSCAN_TEST_ASSERT_IS_NULL( "error", error ); return( 1 ); on_error: if( error != NULL ) { libcerror_error_free( &error ); } if( destination_signature != NULL ) { /* TODO: move handling clones into the signature code */ libsigscan_signature_free_clone( &destination_signature, NULL ); } if( source_signature != NULL ) { libsigscan_signature_free( &source_signature, NULL ); } return( 0 ); } /* Tests the libsigscan_signature_get_identifier_size function * Returns 1 if successful or 0 if not */ int sigscan_test_signature_get_identifier_size( void ) { libcerror_error_t *error = NULL; libsigscan_signature_t *signature = NULL; size_t identifier_size = 0; int identifier_size_is_set = 0; int result = 0; /* Initialize test */ result = libsigscan_signature_initialize( &signature, &error ); SIGSCAN_TEST_ASSERT_EQUAL_INT( "result", result, 1 ); SIGSCAN_TEST_ASSERT_IS_NOT_NULL( "signature", signature ); SIGSCAN_TEST_ASSERT_IS_NULL( "error", error ); /* Test regular cases */ result = libsigscan_signature_get_identifier_size( signature, &identifier_size, &error ); SIGSCAN_TEST_ASSERT_NOT_EQUAL_INT( "result", result, -1 ); SIGSCAN_TEST_ASSERT_IS_NULL( "error", error ); identifier_size_is_set = result; /* Test error cases */ result = libsigscan_signature_get_identifier_size( NULL, &identifier_size, &error ); SIGSCAN_TEST_ASSERT_EQUAL_INT( "result", result, -1 ); SIGSCAN_TEST_ASSERT_IS_NOT_NULL( "error", error ); libcerror_error_free( &error ); if( identifier_size_is_set != 0 ) { result = libsigscan_signature_get_identifier_size( signature, NULL, &error ); SIGSCAN_TEST_ASSERT_EQUAL_INT( "result", result, -1 ); SIGSCAN_TEST_ASSERT_IS_NOT_NULL( "error", error ); libcerror_error_free( &error ); } /* Clean up */ result = libsigscan_signature_free( &signature, &error ); SIGSCAN_TEST_ASSERT_EQUAL_INT( "result", result, 1 ); SIGSCAN_TEST_ASSERT_IS_NULL( "signature", signature ); SIGSCAN_TEST_ASSERT_IS_NULL( "error", error ); return( 1 ); on_error: if( error != NULL ) { libcerror_error_free( &error ); } if( signature != NULL ) { libsigscan_signature_free( &signature, NULL ); } return( 0 ); } #endif /* defined( __GNUC__ ) && !defined( LIBSIGSCAN_DLL_IMPORT ) */ /* The main program */ #if defined( HAVE_WIDE_SYSTEM_CHARACTER ) int wmain( int argc SIGSCAN_TEST_ATTRIBUTE_UNUSED, wchar_t * const argv[] SIGSCAN_TEST_ATTRIBUTE_UNUSED ) #else int main( int argc SIGSCAN_TEST_ATTRIBUTE_UNUSED, char * const argv[] SIGSCAN_TEST_ATTRIBUTE_UNUSED ) #endif { SIGSCAN_TEST_UNREFERENCED_PARAMETER( argc ) SIGSCAN_TEST_UNREFERENCED_PARAMETER( argv ) #if defined( __GNUC__ ) && !defined( LIBSIGSCAN_DLL_IMPORT ) SIGSCAN_TEST_RUN( "libsigscan_signature_initialize", sigscan_test_signature_initialize ); SIGSCAN_TEST_RUN( "libsigscan_signature_free", sigscan_test_signature_free ); /* TODO: add tests for libsigscan_signature_free_clone */ SIGSCAN_TEST_RUN( "libsigscan_signature_clone", sigscan_test_signature_clone ); SIGSCAN_TEST_RUN( "libsigscan_signature_get_identifier_size", sigscan_test_signature_get_identifier_size ); /* TODO: add tests for libsigscan_signature_get_identifier */ /* TODO: add tests for libsigscan_signature_set */ #endif /* defined( __GNUC__ ) && !defined( LIBSIGSCAN_DLL_IMPORT ) */ return( EXIT_SUCCESS ); on_error: return( EXIT_FAILURE ); }
Java
var namespaces = [ [ "shyft", "namespaceshyft.html", "namespaceshyft" ] ];
Java
// Created file "Lib\src\Uuid\oledbdat" typedef struct _GUID { unsigned long Data1; unsigned short Data2; unsigned short Data3; unsigned char Data4[8]; } GUID; #define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ extern const GUID name = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } } DEFINE_GUID(DBROWCOL_ISROOT, 0x0c733ab6, 0x2a1c, 0x11ce, 0xad, 0xe5, 0x00, 0xaa, 0x00, 0x44, 0x77, 0x3d);
Java
/** * Copyright (C) 2010-2012 Regis Montoya (aka r3gis - www.r3gis.fr) * This file is part of CSipSimple. * * CSipSimple is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * If you own a pjsip commercial license you can also redistribute it * and/or modify it under the terms of the GNU Lesser General Public License * as an android library. * * CSipSimple 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 CSipSimple. If not, see <http://www.gnu.org/licenses/>. */ package com.csipsimple.ui.outgoingcall; import android.app.PendingIntent; import android.app.PendingIntent.CanceledException; import android.database.Cursor; import android.os.Bundle; import android.os.RemoteException; import android.support.v4.content.Loader; import android.view.View; import android.widget.ListView; import com.csipsimple.api.ISipService; import com.csipsimple.api.SipProfile; import com.csipsimple.ui.account.AccountsLoader; import com.csipsimple.utils.CallHandlerPlugin; import com.csipsimple.utils.Log; import com.csipsimple.widgets.CSSListFragment; public class OutgoingCallListFragment extends CSSListFragment { private static final String THIS_FILE = "OutgoingCallListFragment"; private OutgoingAccountsAdapter mAdapter; private AccountsLoader accLoader; private long startDate; private boolean callMade = false; @Override public void onCreate(Bundle state) { super.onCreate(state); setHasOptionsMenu(true); } @Override public void onResume() { super.onResume(); callMade = false; attachAdapter(); getLoaderManager().initLoader(0, null, this); startDate = System.currentTimeMillis(); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } private void attachAdapter() { if(getListAdapter() == null) { if(mAdapter == null) { mAdapter = new OutgoingAccountsAdapter(this, null); } setListAdapter(mAdapter); } } @Override public Loader<Cursor> onCreateLoader(int loader, Bundle args) { OutgoingCallChooser superActivity = ((OutgoingCallChooser) getActivity()); accLoader = new AccountsLoader(getActivity(), superActivity.getPhoneNumber(), superActivity.shouldIgnoreRewritingRules()); return accLoader; } final long MOBILE_CALL_DELAY_MS = 600; /** * Place the call for a given cursor positionned at right index in list * @param c The cursor pointing the entry we'd like to call * @return true if call performed, false else */ private boolean placeCall(Cursor c) { OutgoingCallChooser superActivity = ((OutgoingCallChooser)getActivity()); ISipService service = superActivity.getConnectedService(); long accountId = c.getLong(c.getColumnIndex(SipProfile.FIELD_ID)); if(accountId > SipProfile.INVALID_ID) { // Extra check for the account id. if(service == null) { return false; } boolean canCall = c.getInt(c.getColumnIndex(AccountsLoader.FIELD_STATUS_OUTGOING)) == 1; if(!canCall) { return false; } try { String toCall = c.getString(c.getColumnIndex(AccountsLoader.FIELD_NBR_TO_CALL)); service.makeCall(toCall, (int) accountId); superActivity.finishServiceIfNeeded(true); return true; } catch (RemoteException e) { Log.e(THIS_FILE, "Unable to make the call", e); } }else if(accountId < SipProfile.INVALID_ID) { // This is a plugin row. if(accLoader != null) { CallHandlerPlugin ch = accLoader.getCallHandlerWithAccountId(accountId); if(ch == null) { Log.w(THIS_FILE, "Call handler not anymore available in loader... something gone wrong"); return false; } String nextExclude = ch.getNextExcludeTelNumber(); long delay = 0; if (nextExclude != null && service != null) { try { service.ignoreNextOutgoingCallFor(nextExclude); } catch (RemoteException e) { Log.e(THIS_FILE, "Ignore next outgoing number failed"); } delay = MOBILE_CALL_DELAY_MS - (System.currentTimeMillis() - startDate); } if(ch.getIntent() != null) { PluginCallRunnable pendingTask = new PluginCallRunnable(ch.getIntent(), delay); Log.d(THIS_FILE, "Deferring call task of " + delay); pendingTask.start(); } return true; } } return false; } private class PluginCallRunnable extends Thread { private PendingIntent pendingIntent; private long delay; public PluginCallRunnable(PendingIntent pi, long d) { pendingIntent = pi; delay = d; } @Override public void run() { if(delay > 0) { try { sleep(delay); } catch (InterruptedException e) { Log.e(THIS_FILE, "Thread that fires outgoing call has been interrupted"); } } OutgoingCallChooser superActivity = ((OutgoingCallChooser)getActivity()); try { pendingIntent.send(); } catch (CanceledException e) { Log.e(THIS_FILE, "Pending intent cancelled", e); } superActivity.finishServiceIfNeeded(false); } } @Override public synchronized void changeCursor(Cursor c) { if(c != null && callMade == false) { OutgoingCallChooser superActivity = ((OutgoingCallChooser)getActivity()); Long accountToCall = superActivity.getAccountToCallTo(); // Move to first to search in this cursor c.moveToFirst(); // First of all, if only one is available... try call with it if(c.getCount() == 1) { if(placeCall(c)) { c.close(); callMade = true; return; } }else { // Now lets search for one in for call mode if service is ready do { if(c.getInt(c.getColumnIndex(AccountsLoader.FIELD_FORCE_CALL)) == 1) { if(placeCall(c)) { c.close(); callMade = true; return; } } if(accountToCall != SipProfile.INVALID_ID) { if(accountToCall == c.getLong(c.getColumnIndex(SipProfile.FIELD_ID))) { if(placeCall(c)) { c.close(); callMade = true; return; } } } } while(c.moveToNext()); } } // Set adapter content if nothing to force was found if(mAdapter != null) { mAdapter.changeCursor(c); } } @Override public synchronized void onListItemClick(ListView l, View v, int position, long id) { if(mAdapter != null) { placeCall((Cursor) mAdapter.getItem(position)); } } public AccountsLoader getAccountLoader() { return accLoader; } }
Java
package fun.guruqu.portal.structures; public class BlockStructure { /** * @param args */ public static void main(String[] args) { } }
Java
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Profile.cs" company="Allors bvba"> // Copyright 2002-2012 Allors bvba. // Dual Licensed under // a) the Lesser General Public Licence v3 (LGPL) // b) the Allors License // The LGPL License is included in the file lgpl.txt. // The Allors License is an addendum to your contract. // Allors Platform 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. // For more information visit http://www.allors.com/legal // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Allors.Adapters.Object.SqlClient.ReadCommitted { using System; using System.Collections.Generic; using Allors.Meta; using Adapters; using Allors.Adapters.Object.SqlClient.Caching.Debugging; using Allors.Adapters.Object.SqlClient.Debug; public class Profile : SqlClient.Profile { private readonly Prefetchers prefetchers = new Prefetchers(); private readonly DebugConnectionFactory connectionFactory; private readonly DebugCacheFactory cacheFactory; public Profile() { } public Profile(DebugConnectionFactory connectionFactory, DebugCacheFactory cacheFactory) { this.connectionFactory = connectionFactory; this.cacheFactory = cacheFactory; } public override Action[] Markers { get { var markers = new List<Action> { () => { }, () => this.Session.Commit(), }; if (Settings.ExtraMarkers) { markers.Add( () => { foreach (var @class in this.Session.Database.MetaPopulation.Classes) { var prefetchPolicy = this.prefetchers[@class]; this.Session.Prefetch(prefetchPolicy, this.Session.Extent(@class)); } }); } return markers.ToArray(); } } protected override string ConnectionString => System.Configuration.ConfigurationManager.ConnectionStrings["sqlclientobject"].ConnectionString; public IDatabase CreateDatabase(IMetaPopulation metaPopulation, bool init) { var configuration = new SqlClient.Configuration { ObjectFactory = this.CreateObjectFactory(metaPopulation), ConnectionString = this.ConnectionString, ConnectionFactory = this.connectionFactory, CacheFactory = this.cacheFactory }; var database = new Database(configuration); if (init) { database.Init(); } return database; } public override IDatabase CreatePopulation() { return new Memory.Database(new Memory.Configuration { ObjectFactory = this.ObjectFactory }); } public override IDatabase CreateDatabase() { var configuration = new SqlClient.Configuration { ObjectFactory = this.ObjectFactory, ConnectionString = this.ConnectionString, ConnectionFactory = this.connectionFactory, CacheFactory = this.cacheFactory }; var database = new Database(configuration); return database; } protected override bool Match(ColumnTypes columnType, string dataType) { dataType = dataType.Trim().ToLowerInvariant(); switch (columnType) { case ColumnTypes.ObjectId: return dataType.Equals("int"); case ColumnTypes.TypeId: return dataType.Equals("uniqueidentifier"); case ColumnTypes.CacheId: return dataType.Equals("int"); case ColumnTypes.Binary: return dataType.Equals("varbinary"); case ColumnTypes.Boolean: return dataType.Equals("bit"); case ColumnTypes.Decimal: return dataType.Equals("decimal"); case ColumnTypes.Float: return dataType.Equals("float"); case ColumnTypes.Integer: return dataType.Equals("int"); case ColumnTypes.String: return dataType.Equals("nvarchar"); case ColumnTypes.Unique: return dataType.Equals("uniqueidentifier"); default: throw new Exception("Unsupported columntype " + columnType); } } } }
Java
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QtAws 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 the QtAws. If not, see <http://www.gnu.org/licenses/>. */ #ifndef QTAWS_DESCRIBEAPPINSTANCEUSERREQUEST_H #define QTAWS_DESCRIBEAPPINSTANCEUSERREQUEST_H #include "chimerequest.h" namespace QtAws { namespace Chime { class DescribeAppInstanceUserRequestPrivate; class QTAWSCHIME_EXPORT DescribeAppInstanceUserRequest : public ChimeRequest { public: DescribeAppInstanceUserRequest(const DescribeAppInstanceUserRequest &other); DescribeAppInstanceUserRequest(); virtual bool isValid() const Q_DECL_OVERRIDE; protected: virtual QtAws::Core::AwsAbstractResponse * response(QNetworkReply * const reply) const Q_DECL_OVERRIDE; private: Q_DECLARE_PRIVATE(DescribeAppInstanceUserRequest) }; } // namespace Chime } // namespace QtAws #endif
Java
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SphericalHarmonicAnalyze { class LUDenceMatrix:MathNet.Numerics.LinearAlgebra.Double.Factorization.LU { MathNet.Numerics.LinearAlgebra.Double.DenseMatrix dm { get; set; } } }
Java